blob: 526a27903523772380504605cf2a397952a8db16 [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
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000575void CodeGenFunction::ExpandTypeFromArgs(
576 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000577 assert(LV.isSimple() &&
578 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000579
Bob Wilsone826a2a2011-08-03 05:58:22 +0000580 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
581 unsigned NumElts = AT->getSize().getZExtValue();
582 QualType EltTy = AT->getElementType();
583 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000584 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000585 LValue LV = MakeAddrLValue(EltAddr, EltTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000586 ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000587 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000588 return;
589 }
590 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000591 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000592 if (RD->isUnion()) {
593 // Unions can be here only in degenerative cases - all the fields are same
594 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000595 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000597
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000598 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000599 assert(!FD->isBitField() &&
600 "Cannot expand structure with bit-field members.");
601 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
602 if (UnionSize < FieldSize) {
603 UnionSize = FieldSize;
604 LargestFD = FD;
605 }
606 }
607 if (LargestFD) {
608 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000609 LValue SubLV = EmitLValueForField(LV, LargestFD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000610 ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000611 }
612 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000613 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000614 QualType FT = FD->getType();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000615 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000616 LValue SubLV = EmitLValueForField(LV, FD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000617 ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000618 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000619 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000620 return;
621 }
622 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000623 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000624 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000625 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000626 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000627 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(ImagAddr, EltTy));
628 return;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000629 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000630 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000631}
632
Chris Lattner895c52b2010-06-27 06:04:18 +0000633/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000634/// accessing some number of bytes out of it, try to gep into the struct to get
635/// at its inner goodness. Dive as deep as possible without entering an element
636/// with an in-memory size smaller than DstSize.
637static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000638EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000639 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000640 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000641 // We can't dive into a zero-element struct.
642 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000643
Chris Lattner2192fe52011-07-18 04:24:23 +0000644 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000645
Chris Lattner1cd66982010-06-27 05:56:15 +0000646 // If the first elt is at least as large as what we're looking for, or if the
647 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000648 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000649 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000650 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000651 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000652 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000653
Chris Lattner1cd66982010-06-27 05:56:15 +0000654 // GEP into the first element.
655 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000656
Chris Lattner1cd66982010-06-27 05:56:15 +0000657 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000658 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000659 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000660 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000661 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000662
663 return SrcPtr;
664}
665
Chris Lattner055097f2010-06-27 06:26:04 +0000666/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
667/// are either integers or pointers. This does a truncation of the value if it
668/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000669///
670/// This behaves as if the value were coerced through memory, so on big-endian
671/// targets the high bits are preserved in a truncation, while little-endian
672/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000673static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000674 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000675 CodeGenFunction &CGF) {
676 if (Val->getType() == Ty)
677 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000678
Chris Lattner055097f2010-06-27 06:26:04 +0000679 if (isa<llvm::PointerType>(Val->getType())) {
680 // If this is Pointer->Pointer avoid conversion to and from int.
681 if (isa<llvm::PointerType>(Ty))
682 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000683
Chris Lattner055097f2010-06-27 06:26:04 +0000684 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000685 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000686 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000687
Chris Lattner2192fe52011-07-18 04:24:23 +0000688 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000689 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000690 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000691
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000692 if (Val->getType() != DestIntTy) {
693 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
694 if (DL.isBigEndian()) {
695 // Preserve the high bits on big-endian targets.
696 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000697 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
698 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
699
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000700 if (SrcSize > DstSize) {
701 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
702 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
703 } else {
704 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
705 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
706 }
707 } else {
708 // Little-endian targets preserve the low bits. No shifts required.
709 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
710 }
711 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000712
Chris Lattner055097f2010-06-27 06:26:04 +0000713 if (isa<llvm::PointerType>(Ty))
714 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
715 return Val;
716}
717
Chris Lattner1cd66982010-06-27 05:56:15 +0000718
719
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000720/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
721/// a pointer to an object of type \arg Ty.
722///
723/// This safely handles the case when the src type is smaller than the
724/// destination type; in this situation the values of bits which not
725/// present in the src are undefined.
726static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000727 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000728 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000729 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000730 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000731
Chris Lattnerd200eda2010-06-28 22:51:39 +0000732 // If SrcTy and Ty are the same, just do a load.
733 if (SrcTy == Ty)
734 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000735
Micah Villmowdd31ca12012-10-08 16:25:52 +0000736 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000737
Chris Lattner2192fe52011-07-18 04:24:23 +0000738 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000739 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000740 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
741 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000742
Micah Villmowdd31ca12012-10-08 16:25:52 +0000743 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000744
Chris Lattner055097f2010-06-27 06:26:04 +0000745 // If the source and destination are integer or pointer types, just do an
746 // extension or truncation to the desired type.
747 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
748 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
749 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
750 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
751 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000752
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000753 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000754 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000755 // Generally SrcSize is never greater than DstSize, since this means we are
756 // losing bits. However, this can happen in cases where the structure has
757 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000758 //
Mike Stump18bb9282009-05-16 07:57:57 +0000759 // FIXME: Assert that we aren't truncating non-padding bits when have access
760 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000761 llvm::Value *Casted =
762 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000763 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
764 // FIXME: Use better alignment / avoid requiring aligned load.
765 Load->setAlignment(1);
766 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000767 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000768
Chris Lattner3fcc7902010-06-27 01:06:27 +0000769 // Otherwise do coercion through memory. This is stupid, but
770 // simple.
771 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000772 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
773 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
774 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000775 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000776 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
777 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
778 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000779 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000780}
781
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000782// Function to store a first-class aggregate into memory. We prefer to
783// store the elements rather than the aggregate to be more friendly to
784// fast-isel.
785// FIXME: Do we need to recurse here?
786static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
787 llvm::Value *DestPtr, bool DestIsVolatile,
788 bool LowAlignment) {
789 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000790 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000791 dyn_cast<llvm::StructType>(Val->getType())) {
792 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
793 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
794 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
795 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
796 DestIsVolatile);
797 if (LowAlignment)
798 SI->setAlignment(1);
799 }
800 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000801 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
802 if (LowAlignment)
803 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000804 }
805}
806
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000807/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
808/// where the source and destination may have different types.
809///
810/// This safely handles the case when the src type is larger than the
811/// destination type; the upper bits of the src will be lost.
812static void CreateCoercedStore(llvm::Value *Src,
813 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000814 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000815 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000816 llvm::Type *SrcTy = Src->getType();
817 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000818 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000819 if (SrcTy == DstTy) {
820 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
821 return;
822 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000823
Micah Villmowdd31ca12012-10-08 16:25:52 +0000824 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000825
Chris Lattner2192fe52011-07-18 04:24:23 +0000826 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000827 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
828 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
829 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000830
Chris Lattner055097f2010-06-27 06:26:04 +0000831 // If the source and destination are integer or pointer types, just do an
832 // extension or truncation to the desired type.
833 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
834 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
835 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
836 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
837 return;
838 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000839
Micah Villmowdd31ca12012-10-08 16:25:52 +0000840 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000841
Daniel Dunbar313321e2009-02-03 05:31:23 +0000842 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000843 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000844 llvm::Value *Casted =
845 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000846 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000847 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000848 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000849 // Otherwise do coercion through memory. This is stupid, but
850 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000851
852 // Generally SrcSize is never greater than DstSize, since this means we are
853 // losing bits. However, this can happen in cases where the structure has
854 // additional padding, for example due to a user specified alignment.
855 //
856 // FIXME: Assert that we aren't truncating non-padding bits when have access
857 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000858 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
859 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000860 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
861 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
862 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000863 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000864 CGF.Builder.CreateMemCpy(DstCasted, Casted,
865 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
866 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000867 }
868}
869
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000870/***/
871
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000872bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000873 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000874}
875
Tim Northovere77cc392014-03-29 13:28:05 +0000876bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
877 return ReturnTypeUsesSRet(FI) &&
878 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
879}
880
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000881bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
882 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
883 switch (BT->getKind()) {
884 default:
885 return false;
886 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000887 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000888 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000889 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000890 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000891 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000892 }
893 }
894
895 return false;
896}
897
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000898bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
899 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
900 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
901 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000902 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000903 }
904 }
905
906 return false;
907}
908
Chris Lattnera5f58b02011-07-09 17:41:47 +0000909llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000910 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
911 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000912}
913
Chris Lattnera5f58b02011-07-09 17:41:47 +0000914llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000915CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000916
917 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
918 assert(Inserted && "Recursively being processed?");
919
Reid Kleckner37abaca2014-05-09 22:46:15 +0000920 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000921 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000922 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000923
John McCall85dd2c52011-05-15 02:19:42 +0000924 const ABIArgInfo &retAI = FI.getReturnInfo();
925 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000926 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000927 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000928
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000929 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000930 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000931 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000932 break;
933
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000934 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000935 if (retAI.getInAllocaSRet()) {
936 // sret things on win32 aren't void, they return the sret pointer.
937 QualType ret = FI.getReturnType();
938 llvm::Type *ty = ConvertType(ret);
939 unsigned addressSpace = Context.getTargetAddressSpace(ret);
940 resultType = llvm::PointerType::get(ty, addressSpace);
941 } else {
942 resultType = llvm::Type::getVoidTy(getLLVMContext());
943 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000944 break;
945
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000946 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000947 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
948 resultType = llvm::Type::getVoidTy(getLLVMContext());
949
950 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000951 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000952 unsigned addressSpace = Context.getTargetAddressSpace(ret);
953 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000954
955 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000956 break;
957 }
958
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000959 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000960 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000961 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000962 }
Mike Stump11289f42009-09-09 15:08:12 +0000963
John McCallc818bbb2012-12-07 07:03:17 +0000964 // Add in all of the required arguments.
965 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
966 if (FI.isVariadic()) {
967 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
968 } else {
969 ie = FI.arg_end();
970 }
971 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000972 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000973
Rafael Espindolafad28de2012-10-24 01:59:00 +0000974 // Insert a padding type to ensure proper alignment.
975 if (llvm::Type *PaddingType = argAI.getPaddingType())
976 argTypes.push_back(PaddingType);
977
John McCall85dd2c52011-05-15 02:19:42 +0000978 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000979 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000980 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000981 break;
982
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000983 case ABIArgInfo::Indirect: {
984 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000985 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000986 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000987 break;
988 }
989
990 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000991 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000992 // If the coerce-to type is a first class aggregate, flatten it. Either
993 // way is semantically identical, but fast-isel and the optimizer
994 // generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +0000995 // We cannot do this for functions using the AAPCS calling convention,
996 // as structures are treated differently by that calling convention.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000997 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +0000998 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
999 if (st && !isAAPCSVFP(FI, getTarget())) {
John McCall85dd2c52011-05-15 02:19:42 +00001000 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1001 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +00001002 } else {
John McCall85dd2c52011-05-15 02:19:42 +00001003 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001004 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001005 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
Daniel Dunbard3674e62008-09-11 01:48:57 +00001008 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +00001009 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001010 break;
1011 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001012 }
1013
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001014 // Add the inalloca struct as the last parameter type.
1015 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1016 argTypes.push_back(ArgStruct->getPointerTo());
1017
Reid Kleckner37abaca2014-05-09 22:46:15 +00001018 if (SwapThisWithSRet)
1019 std::swap(argTypes[0], argTypes[1]);
1020
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001021 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1022 assert(Erased && "Not in set?");
1023
John McCalla729c622012-02-17 03:33:10 +00001024 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001025}
1026
Chris Lattner2192fe52011-07-18 04:24:23 +00001027llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001028 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001029 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001030
Chris Lattner8806e322011-07-10 00:18:59 +00001031 if (!isFuncTypeConvertible(FPT))
1032 return llvm::StructType::get(getLLVMContext());
1033
1034 const CGFunctionInfo *Info;
1035 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001036 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001037 else
John McCalla729c622012-02-17 03:33:10 +00001038 Info = &arrangeCXXMethodDeclaration(MD);
1039 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001040}
1041
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001042namespace {
1043
1044/// Encapsulates information about the way function arguments from
1045/// CGFunctionInfo should be passed to actual LLVM IR function.
1046class ClangToLLVMArgMapping {
1047 static const unsigned InvalidIndex = ~0U;
1048 unsigned InallocaArgNo;
1049 unsigned SRetArgNo;
1050 unsigned TotalIRArgs;
1051
1052 /// Arguments of LLVM IR function corresponding to single Clang argument.
1053 struct IRArgs {
1054 unsigned PaddingArgIndex;
1055 // Argument is expanded to IR arguments at positions
1056 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1057 unsigned FirstArgIndex;
1058 unsigned NumberOfArgs;
1059
1060 IRArgs()
1061 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1062 NumberOfArgs(0) {}
1063 };
1064
1065 SmallVector<IRArgs, 8> ArgInfo;
1066
1067public:
1068 ClangToLLVMArgMapping(CodeGenModule &CGM, const CGFunctionInfo &FI)
1069 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1070 ArgInfo(FI.arg_size()) {
1071 construct(CGM, FI);
1072 }
1073
1074 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1075 unsigned getInallocaArgNo() const {
1076 assert(hasInallocaArg());
1077 return InallocaArgNo;
1078 }
1079
1080 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1081 unsigned getSRetArgNo() const {
1082 assert(hasSRetArg());
1083 return SRetArgNo;
1084 }
1085
1086 unsigned totalIRArgs() const { return TotalIRArgs; }
1087
1088 bool hasPaddingArg(unsigned ArgNo) const {
1089 assert(ArgNo < ArgInfo.size());
1090 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1091 }
1092 unsigned getPaddingArgNo(unsigned ArgNo) const {
1093 assert(hasPaddingArg(ArgNo));
1094 return ArgInfo[ArgNo].PaddingArgIndex;
1095 }
1096
1097 /// Returns index of first IR argument corresponding to ArgNo, and their
1098 /// quantity.
1099 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1100 assert(ArgNo < ArgInfo.size());
1101 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1102 ArgInfo[ArgNo].NumberOfArgs);
1103 }
1104
1105private:
1106 void construct(CodeGenModule &CGM, const CGFunctionInfo &FI);
1107};
1108
1109void ClangToLLVMArgMapping::construct(CodeGenModule &CGM,
1110 const CGFunctionInfo &FI) {
1111 unsigned IRArgNo = 0;
1112 bool SwapThisWithSRet = false;
1113 const ABIArgInfo &RetAI = FI.getReturnInfo();
1114
1115 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1116 SwapThisWithSRet = RetAI.isSRetAfterThis();
1117 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1118 }
1119
1120 unsigned ArgNo = 0;
1121 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1122 E = FI.arg_end();
1123 I != E; ++I, ++ArgNo) {
1124 QualType ArgType = I->type;
1125 const ABIArgInfo &AI = I->info;
1126 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1127 auto &IRArgs = ArgInfo[ArgNo];
1128
1129 if (AI.getPaddingType())
1130 IRArgs.PaddingArgIndex = IRArgNo++;
1131
1132 switch (AI.getKind()) {
1133 case ABIArgInfo::Extend:
1134 case ABIArgInfo::Direct: {
1135 // FIXME: handle sseregparm someday...
1136 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1137 if (!isAAPCSVFP(FI, CGM.getTarget()) && STy) {
1138 IRArgs.NumberOfArgs = STy->getNumElements();
1139 } else {
1140 IRArgs.NumberOfArgs = 1;
1141 }
1142 break;
1143 }
1144 case ABIArgInfo::Indirect:
1145 IRArgs.NumberOfArgs = 1;
1146 break;
1147 case ABIArgInfo::Ignore:
1148 case ABIArgInfo::InAlloca:
1149 // ignore and inalloca doesn't have matching LLVM parameters.
1150 IRArgs.NumberOfArgs = 0;
1151 break;
1152 case ABIArgInfo::Expand: {
1153 SmallVector<llvm::Type*, 8> Types;
1154 // FIXME: This is rather inefficient. Do we ever actually need to do
1155 // anything here? The result should be just reconstructed on the other
1156 // side, so extension should be a non-issue.
1157 CGM.getTypes().GetExpandedTypes(ArgType, Types);
1158 IRArgs.NumberOfArgs = Types.size();
1159 break;
1160 }
1161 }
1162
1163 if (IRArgs.NumberOfArgs > 0) {
1164 IRArgs.FirstArgIndex = IRArgNo;
1165 IRArgNo += IRArgs.NumberOfArgs;
1166 }
1167
1168 // Skip over the sret parameter when it comes second. We already handled it
1169 // above.
1170 if (IRArgNo == 1 && SwapThisWithSRet)
1171 IRArgNo++;
1172 }
1173 assert(ArgNo == FI.arg_size());
1174
1175 if (FI.usesInAlloca())
1176 InallocaArgNo = IRArgNo++;
1177
1178 TotalIRArgs = IRArgNo;
1179}
1180} // namespace
1181
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001182void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001183 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001184 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001185 unsigned &CallingConv,
1186 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001187 llvm::AttrBuilder FuncAttrs;
1188 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001189
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001190 CallingConv = FI.getEffectiveCallingConvention();
1191
John McCallab26cfa2010-02-05 21:31:56 +00001192 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001193 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001194
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001195 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001196 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001197 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001198 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001199 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001200 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001201 if (TargetDecl->hasAttr<NoReturnAttr>())
1202 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001203 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1204 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001205
1206 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001207 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001208 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001209 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001210 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1211 // These attributes are not inherited by overloads.
1212 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1213 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001214 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001215 }
1216
Eric Christopherbf005ec2011-08-15 22:38:22 +00001217 // 'const' and 'pure' attribute functions are also nounwind.
1218 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001219 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1220 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001221 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001222 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1223 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001224 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001225 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001226 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001227 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1228 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001229 }
1230
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001231 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001232 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001233 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001234 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001235 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001236 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001237 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001238 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001239 if (CodeGenOpts.EnableSegmentedStacks &&
1240 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001241 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001242
Bill Wendling2f81db62013-02-22 20:53:29 +00001243 if (AttrOnCallSite) {
1244 // Attributes that should go on the call site only.
1245 if (!CodeGenOpts.SimplifyLibCalls)
1246 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001247 } else {
1248 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001249 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001250 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001251 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001252 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001253 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001254 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001255 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001256 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001257 }
1258
Bill Wendlingdabafea2013-03-13 22:24:33 +00001259 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001260 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001261 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001262 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001263 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001264 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001265 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001266 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001267 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001268 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001269 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001270 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001271
Bill Wendlingd8f49502013-08-01 21:41:02 +00001272 if (!CodeGenOpts.StackRealignment)
1273 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001274 }
1275
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001276 ClangToLLVMArgMapping IRFunctionArgs(*this, FI);
1277
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001278 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001279 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001280 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001281 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001282 if (RetTy->hasSignedIntegerRepresentation())
1283 RetAttrs.addAttribute(llvm::Attribute::SExt);
1284 else if (RetTy->hasUnsignedIntegerRepresentation())
1285 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001286 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001287 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001288 if (RetAI.getInReg())
1289 RetAttrs.addAttribute(llvm::Attribute::InReg);
1290 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001291 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001292 break;
1293
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001294 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001295 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001296 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001297 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1298 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001299 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001300 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001301
Daniel Dunbard3674e62008-09-11 01:48:57 +00001302 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001303 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001304 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001305
Hal Finkela2347ba2014-07-18 15:52:10 +00001306 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1307 QualType PTy = RefTy->getPointeeType();
1308 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1309 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1310 .getQuantity());
1311 else if (getContext().getTargetAddressSpace(PTy) == 0)
1312 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1313 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001314
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001315 // Attach return attributes.
1316 if (RetAttrs.hasAttributes()) {
1317 PAL.push_back(llvm::AttributeSet::get(
1318 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1319 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001320
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001321 // Attach attributes to sret.
1322 if (IRFunctionArgs.hasSRetArg()) {
1323 llvm::AttrBuilder SRETAttrs;
1324 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1325 if (RetAI.getInReg())
1326 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1327 PAL.push_back(llvm::AttributeSet::get(
1328 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1329 }
1330
1331 // Attach attributes to inalloca argument.
1332 if (IRFunctionArgs.hasInallocaArg()) {
1333 llvm::AttrBuilder Attrs;
1334 Attrs.addAttribute(llvm::Attribute::InAlloca);
1335 PAL.push_back(llvm::AttributeSet::get(
1336 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1337 }
1338
1339
1340 unsigned ArgNo = 0;
1341 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1342 E = FI.arg_end();
1343 I != E; ++I, ++ArgNo) {
1344 QualType ParamType = I->type;
1345 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001346 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001347
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001348 // Add attribute for padding argument, if necessary.
1349 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001350 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001351 PAL.push_back(llvm::AttributeSet::get(
1352 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1353 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001354 }
1355
John McCall39ec71f2010-03-27 00:47:27 +00001356 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1357 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001358 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001359 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001360 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001361 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001362 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001363 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001364 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001365 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001366 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001367 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001368 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001369 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001370
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001371 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001372 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001373 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001374
Anders Carlsson20759ad2009-09-16 15:53:40 +00001375 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001376 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001377
Bill Wendlinga7912f82012-10-10 07:36:56 +00001378 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1379
Daniel Dunbarc2304432009-03-18 19:51:01 +00001380 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001381 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1382 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001383 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001384
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001385 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001386 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001387 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001388
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001389 case ABIArgInfo::InAlloca:
1390 // inalloca disables readnone and readonly.
1391 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1392 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001393 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Hal Finkela2347ba2014-07-18 15:52:10 +00001396 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1397 QualType PTy = RefTy->getPointeeType();
1398 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1399 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1400 .getQuantity());
1401 else if (getContext().getTargetAddressSpace(PTy) == 0)
1402 Attrs.addAttribute(llvm::Attribute::NonNull);
1403 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001404
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001405 if (Attrs.hasAttributes()) {
1406 unsigned FirstIRArg, NumIRArgs;
1407 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1408 for (unsigned i = 0; i < NumIRArgs; i++)
1409 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1410 FirstIRArg + i + 1, Attrs));
1411 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001412 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001413 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001414
Bill Wendlinga7912f82012-10-10 07:36:56 +00001415 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001416 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001417 AttributeSet::get(getLLVMContext(),
1418 llvm::AttributeSet::FunctionIndex,
1419 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001420}
1421
John McCalla738c252011-03-09 04:27:21 +00001422/// An argument came in as a promoted argument; demote it back to its
1423/// declared type.
1424static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1425 const VarDecl *var,
1426 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001427 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001428
1429 // This can happen with promotions that actually don't change the
1430 // underlying type, like the enum promotions.
1431 if (value->getType() == varType) return value;
1432
1433 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1434 && "unexpected promotion type");
1435
1436 if (isa<llvm::IntegerType>(varType))
1437 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1438
1439 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1440}
1441
Daniel Dunbard931a872009-02-02 22:03:45 +00001442void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1443 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001444 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001445 // If this is an implicit-return-zero function, go ahead and
1446 // initialize the return value. TODO: it might be nice to have
1447 // a more general mechanism for this that didn't require synthesized
1448 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001449 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001450 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001451 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001452 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001453 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001454 Builder.CreateStore(Zero, ReturnValue);
1455 }
1456 }
1457
Mike Stump18bb9282009-05-16 07:57:57 +00001458 // FIXME: We no longer need the types from FunctionArgList; lift up and
1459 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001460
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001461 ClangToLLVMArgMapping IRFunctionArgs(CGM, FI);
1462 // Flattened function arguments.
1463 SmallVector<llvm::Argument *, 16> FnArgs;
1464 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1465 for (auto &Arg : Fn->args()) {
1466 FnArgs.push_back(&Arg);
1467 }
1468 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001469
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001470 // If we're using inalloca, all the memory arguments are GEPs off of the last
1471 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001472 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001473 if (IRFunctionArgs.hasInallocaArg()) {
1474 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001475 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1476 }
1477
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001478 // Name the struct return parameter.
1479 if (IRFunctionArgs.hasSRetArg()) {
1480 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001481 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001482 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001483 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Hal Finkel82504f02014-07-11 17:35:21 +00001486 // Get the function-level nonnull attribute if it exists.
1487 const NonNullAttr *NNAtt =
1488 CurCodeDecl ? CurCodeDecl->getAttr<NonNullAttr>() : nullptr;
1489
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001490 // Track if we received the parameter as a pointer (indirect, byval, or
1491 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1492 // into a local alloca for us.
1493 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001494 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001495 SmallVector<ValueAndIsPtr, 16> ArgVals;
1496 ArgVals.reserve(Args.size());
1497
Reid Kleckner739756c2013-12-04 19:23:12 +00001498 // Create a pointer value for every parameter declaration. This usually
1499 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1500 // any cleanups or do anything that might unwind. We do that separately, so
1501 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001502 assert(FI.arg_size() == Args.size() &&
1503 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001504 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001505 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001506 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001507 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001508 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001509 QualType Ty = info_it->type;
1510 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001511
John McCalla738c252011-03-09 04:27:21 +00001512 bool isPromoted =
1513 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1514
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001515 unsigned FirstIRArg, NumIRArgs;
1516 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001517
Daniel Dunbard3674e62008-09-11 01:48:57 +00001518 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001519 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001520 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001521 llvm::Value *V = Builder.CreateStructGEP(
1522 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1523 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001524 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001525 }
1526
Daniel Dunbar747865a2009-02-05 09:16:39 +00001527 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001528 assert(NumIRArgs == 1);
1529 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001530
John McCall47fb9502013-03-07 21:37:08 +00001531 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001532 // Aggregates and complex variables are accessed by reference. All we
1533 // need to do is realign the value, if requested
1534 if (ArgI.getIndirectRealign()) {
1535 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1536
1537 // Copy from the incoming argument pointer to the temporary with the
1538 // appropriate alignment.
1539 //
1540 // FIXME: We should have a common utility for generating an aggregate
1541 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001542 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001543 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001544 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1545 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1546 Builder.CreateMemCpy(Dst,
1547 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001548 llvm::ConstantInt::get(IntPtrTy,
1549 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001550 ArgI.getIndirectAlign(),
1551 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001552 V = AlignedTemp;
1553 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001554 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001555 } else {
1556 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001557 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001558 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1559 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001560
1561 if (isPromoted)
1562 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001563 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001564 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001565 break;
1566 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001567
1568 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001569 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001570
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001571 // If we have the trivial case, handle it with no muss and fuss.
1572 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001573 ArgI.getCoerceToType() == ConvertType(Ty) &&
1574 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001575 assert(NumIRArgs == 1);
1576 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001577 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001578
Hal Finkel48d53e22014-07-19 01:41:07 +00001579 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Hal Finkel82504f02014-07-11 17:35:21 +00001580 if ((NNAtt && NNAtt->isNonNull(PVD->getFunctionScopeIndex())) ||
1581 PVD->hasAttr<NonNullAttr>())
1582 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1583 AI->getArgNo() + 1,
1584 llvm::Attribute::NonNull));
1585
Hal Finkel48d53e22014-07-19 01:41:07 +00001586 QualType OTy = PVD->getOriginalType();
1587 if (const auto *ArrTy =
1588 getContext().getAsConstantArrayType(OTy)) {
1589 // A C99 array parameter declaration with the static keyword also
1590 // indicates dereferenceability, and if the size is constant we can
1591 // use the dereferenceable attribute (which requires the size in
1592 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001593 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001594 QualType ETy = ArrTy->getElementType();
1595 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1596 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1597 ArrSize) {
1598 llvm::AttrBuilder Attrs;
1599 Attrs.addDereferenceableAttr(
1600 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1601 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1602 AI->getArgNo() + 1, Attrs));
1603 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1604 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1605 AI->getArgNo() + 1,
1606 llvm::Attribute::NonNull));
1607 }
1608 }
1609 } else if (const auto *ArrTy =
1610 getContext().getAsVariableArrayType(OTy)) {
1611 // For C99 VLAs with the static keyword, we don't know the size so
1612 // we can't use the dereferenceable attribute, but in addrspace(0)
1613 // we know that it must be nonnull.
1614 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1615 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1616 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1617 AI->getArgNo() + 1,
1618 llvm::Attribute::NonNull));
1619 }
1620 }
1621
Bill Wendling507c3512012-10-16 05:23:44 +00001622 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001623 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1624 AI->getArgNo() + 1,
1625 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001626
Chris Lattner7369c142011-07-20 06:29:00 +00001627 // Ensure the argument is the correct type.
1628 if (V->getType() != ArgI.getCoerceToType())
1629 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1630
John McCalla738c252011-03-09 04:27:21 +00001631 if (isPromoted)
1632 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001633
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001634 if (const CXXMethodDecl *MD =
1635 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001636 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001637 V = CGM.getCXXABI().
1638 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001639 }
1640
Rafael Espindola8778c282012-11-29 16:09:03 +00001641 // Because of merging of function types from multiple decls it is
1642 // possible for the type of an argument to not match the corresponding
1643 // type in the function type. Since we are codegening the callee
1644 // in here, add a cast to the argument type.
1645 llvm::Type *LTy = ConvertType(Arg->getType());
1646 if (V->getType() != LTy)
1647 V = Builder.CreateBitCast(V, LTy);
1648
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001649 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001650 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001651 }
Mike Stump11289f42009-09-09 15:08:12 +00001652
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001653 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001654
Chris Lattnerff941a62010-07-28 18:24:28 +00001655 // The alignment we need to use is the max of the requested alignment for
1656 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001657 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001658 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001659 AlignmentToUse = std::max(AlignmentToUse,
1660 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001661
Chris Lattnerff941a62010-07-28 18:24:28 +00001662 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001663 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001664 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001665
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001666 // If the value is offset in memory, apply the offset now.
1667 if (unsigned Offs = ArgI.getDirectOffset()) {
1668 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1669 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001670 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001671 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1672 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001673
Chris Lattner15ec3612010-06-29 00:06:42 +00001674 // If the coerce-to type is a first class aggregate, we flatten it and
1675 // pass the elements. Either way is semantically identical, but fast-isel
1676 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00001677 // We cannot do this for functions using the AAPCS calling convention,
1678 // as structures are treated differently by that calling convention.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001679 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
James Molloy6f244b62014-05-09 16:21:39 +00001680 if (!isAAPCSVFP(FI, getTarget()) && STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001681 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001682 llvm::Type *DstTy =
1683 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001684 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001685
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001686 if (SrcSize <= DstSize) {
1687 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1688
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001689 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001690 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001691 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001692 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1693 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001694 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001695 }
1696 } else {
1697 llvm::AllocaInst *TempAlloca =
1698 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1699 TempAlloca->setAlignment(AlignmentToUse);
1700 llvm::Value *TempV = TempAlloca;
1701
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001702 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001703 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001704 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001705 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1706 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001707 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001708 }
1709
1710 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001711 }
1712 } else {
1713 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001714 assert(NumIRArgs == 1);
1715 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001716 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001717 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001718 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001719
1720
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001721 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001722 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001723 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001724 if (isPromoted)
1725 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001726 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1727 } else {
1728 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001729 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001730 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001731 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001732
1733 case ABIArgInfo::Expand: {
1734 // If this structure was expanded into multiple arguments then
1735 // we need to create a temporary and reconstruct it from the
1736 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001737 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001738 CharUnits Align = getContext().getDeclAlign(Arg);
1739 Alloca->setAlignment(Align.getQuantity());
1740 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001741 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001742
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001743 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1744 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1745 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1746 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1747 auto AI = FnArgs[FirstIRArg + i];
1748 AI->setName(Arg->getName() + "." + Twine(i));
1749 }
1750 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001751 }
1752
1753 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001754 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001755 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001756 if (!hasScalarEvaluationKind(Ty)) {
1757 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1758 } else {
1759 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1760 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1761 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001762 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001763 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001764 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001765
Reid Kleckner739756c2013-12-04 19:23:12 +00001766 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1767 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001768 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1769 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001770 } else {
1771 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001772 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1773 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001774 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001775}
1776
John McCallffa2c1a2012-01-29 07:46:59 +00001777static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1778 while (insn->use_empty()) {
1779 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1780 if (!bitcast) return;
1781
1782 // This is "safe" because we would have used a ConstantExpr otherwise.
1783 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1784 bitcast->eraseFromParent();
1785 }
1786}
1787
John McCall31168b02011-06-15 23:02:42 +00001788/// Try to emit a fused autorelease of a return result.
1789static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1790 llvm::Value *result) {
1791 // We must be immediately followed the cast.
1792 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001793 if (BB->empty()) return nullptr;
1794 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001795
Chris Lattner2192fe52011-07-18 04:24:23 +00001796 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001797
1798 // result is in a BasicBlock and is therefore an Instruction.
1799 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1800
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001801 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001802
1803 // Look for:
1804 // %generator = bitcast %type1* %generator2 to %type2*
1805 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1806 // We would have emitted this as a constant if the operand weren't
1807 // an Instruction.
1808 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1809
1810 // Require the generator to be immediately followed by the cast.
1811 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001812 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001813
1814 insnsToKill.push_back(bitcast);
1815 }
1816
1817 // Look for:
1818 // %generator = call i8* @objc_retain(i8* %originalResult)
1819 // or
1820 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1821 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001822 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001823
1824 bool doRetainAutorelease;
1825
1826 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1827 doRetainAutorelease = true;
1828 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1829 .objc_retainAutoreleasedReturnValue) {
1830 doRetainAutorelease = false;
1831
John McCallcfa4e9b2012-09-07 23:30:50 +00001832 // If we emitted an assembly marker for this call (and the
1833 // ARCEntrypoints field should have been set if so), go looking
1834 // for that call. If we can't find it, we can't do this
1835 // optimization. But it should always be the immediately previous
1836 // instruction, unless we needed bitcasts around the call.
1837 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1838 llvm::Instruction *prev = call->getPrevNode();
1839 assert(prev);
1840 if (isa<llvm::BitCastInst>(prev)) {
1841 prev = prev->getPrevNode();
1842 assert(prev);
1843 }
1844 assert(isa<llvm::CallInst>(prev));
1845 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1846 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1847 insnsToKill.push_back(prev);
1848 }
John McCall31168b02011-06-15 23:02:42 +00001849 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001850 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001851 }
1852
1853 result = call->getArgOperand(0);
1854 insnsToKill.push_back(call);
1855
1856 // Keep killing bitcasts, for sanity. Note that we no longer care
1857 // about precise ordering as long as there's exactly one use.
1858 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1859 if (!bitcast->hasOneUse()) break;
1860 insnsToKill.push_back(bitcast);
1861 result = bitcast->getOperand(0);
1862 }
1863
1864 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001865 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001866 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1867 (*i)->eraseFromParent();
1868
1869 // Do the fused retain/autorelease if we were asked to.
1870 if (doRetainAutorelease)
1871 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1872
1873 // Cast back to the result type.
1874 return CGF.Builder.CreateBitCast(result, resultType);
1875}
1876
John McCallffa2c1a2012-01-29 07:46:59 +00001877/// If this is a +1 of the value of an immutable 'self', remove it.
1878static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1879 llvm::Value *result) {
1880 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001881 const ObjCMethodDecl *method =
1882 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001883 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001884 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001885 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001886
1887 // Look for a retain call.
1888 llvm::CallInst *retainCall =
1889 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1890 if (!retainCall ||
1891 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001892 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001893
1894 // Look for an ordinary load of 'self'.
1895 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1896 llvm::LoadInst *load =
1897 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1898 if (!load || load->isAtomic() || load->isVolatile() ||
1899 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001900 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001901
1902 // Okay! Burn it all down. This relies for correctness on the
1903 // assumption that the retain is emitted as part of the return and
1904 // that thereafter everything is used "linearly".
1905 llvm::Type *resultType = result->getType();
1906 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1907 assert(retainCall->use_empty());
1908 retainCall->eraseFromParent();
1909 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1910
1911 return CGF.Builder.CreateBitCast(load, resultType);
1912}
1913
John McCall31168b02011-06-15 23:02:42 +00001914/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001915///
1916/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001917static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1918 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001919 // If we're returning 'self', kill the initial retain. This is a
1920 // heuristic attempt to "encourage correctness" in the really unfortunate
1921 // case where we have a return of self during a dealloc and we desperately
1922 // need to avoid the possible autorelease.
1923 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1924 return self;
1925
John McCall31168b02011-06-15 23:02:42 +00001926 // At -O0, try to emit a fused retain/autorelease.
1927 if (CGF.shouldUseFusedARCCalls())
1928 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1929 return fused;
1930
1931 return CGF.EmitARCAutoreleaseReturnValue(result);
1932}
1933
John McCall6e1c0122012-01-29 02:35:02 +00001934/// Heuristically search for a dominating store to the return-value slot.
1935static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1936 // If there are multiple uses of the return-value slot, just check
1937 // for something immediately preceding the IP. Sometimes this can
1938 // happen with how we generate implicit-returns; it can also happen
1939 // with noreturn cleanups.
1940 if (!CGF.ReturnValue->hasOneUse()) {
1941 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001942 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001943 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001944 if (!store) return nullptr;
1945 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001946 assert(!store->isAtomic() && !store->isVolatile()); // see below
1947 return store;
1948 }
1949
1950 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001951 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001952 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001953
1954 // These aren't actually possible for non-coerced returns, and we
1955 // only care about non-coerced returns on this code path.
1956 assert(!store->isAtomic() && !store->isVolatile());
1957
1958 // Now do a first-and-dirty dominance check: just walk up the
1959 // single-predecessors chain from the current insertion point.
1960 llvm::BasicBlock *StoreBB = store->getParent();
1961 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1962 while (IP != StoreBB) {
1963 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001964 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001965 }
1966
1967 // Okay, the store's basic block dominates the insertion point; we
1968 // can do our thing.
1969 return store;
1970}
1971
Adrian Prantl3be10542013-05-02 17:30:20 +00001972void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001973 bool EmitRetDbgLoc,
1974 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001975 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001976 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001977 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001978 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001979 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001980
Dan Gohman481e40c2010-07-20 20:13:52 +00001981 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00001982 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00001983 QualType RetTy = FI.getReturnType();
1984 const ABIArgInfo &RetAI = FI.getReturnInfo();
1985
1986 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001987 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001988 // Aggregrates get evaluated directly into the destination. Sometimes we
1989 // need to return the sret value in a register, though.
1990 assert(hasAggregateEvaluationKind(RetTy));
1991 if (RetAI.getInAllocaSRet()) {
1992 llvm::Function::arg_iterator EI = CurFn->arg_end();
1993 --EI;
1994 llvm::Value *ArgStruct = EI;
1995 llvm::Value *SRet =
1996 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1997 RV = Builder.CreateLoad(SRet, "sret");
1998 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001999 break;
2000
Daniel Dunbar03816342010-08-21 02:24:36 +00002001 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002002 auto AI = CurFn->arg_begin();
2003 if (RetAI.isSRetAfterThis())
2004 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002005 switch (getEvaluationKind(RetTy)) {
2006 case TEK_Complex: {
2007 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002008 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2009 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002010 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002011 /*isInit*/ true);
2012 break;
2013 }
2014 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002015 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002016 break;
2017 case TEK_Scalar:
2018 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002019 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002020 /*isInit*/ true);
2021 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002022 }
2023 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002024 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002025
2026 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002027 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002028 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2029 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002030 // The internal return value temp always will have pointer-to-return-type
2031 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002032
John McCall6e1c0122012-01-29 02:35:02 +00002033 // If there is a dominating store to ReturnValue, we can elide
2034 // the load, zap the store, and usually zap the alloca.
2035 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002036 // Reuse the debug location from the store unless there is
2037 // cleanup code to be emitted between the store and return
2038 // instruction.
2039 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002040 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002041 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002042 RV = SI->getValueOperand();
2043 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002044
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002045 // If that was the only use of the return value, nuke it as well now.
2046 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2047 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002048 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002049 }
John McCall6e1c0122012-01-29 02:35:02 +00002050
2051 // Otherwise, we have to do a simple load.
2052 } else {
2053 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002054 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002055 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002056 llvm::Value *V = ReturnValue;
2057 // If the value is offset in memory, apply the offset now.
2058 if (unsigned Offs = RetAI.getDirectOffset()) {
2059 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2060 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002061 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002062 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2063 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002064
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002065 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002066 }
John McCall31168b02011-06-15 23:02:42 +00002067
2068 // In ARC, end functions that return a retainable type with a call
2069 // to objc_autoreleaseReturnValue.
2070 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002071 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002072 !FI.isReturnsRetained() &&
2073 RetTy->isObjCRetainableType());
2074 RV = emitAutoreleaseOfResult(*this, RV);
2075 }
2076
Chris Lattner726b3d02010-06-26 23:13:19 +00002077 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002078
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002079 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002080 break;
2081
2082 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002083 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002084 }
2085
Alexey Samsonovde443c52014-08-13 00:26:40 +00002086 llvm::Instruction *Ret;
2087 if (RV) {
2088 if (SanOpts->ReturnsNonnullAttribute &&
2089 CurGD.getDecl()->hasAttr<ReturnsNonNullAttr>()) {
2090 SanitizerScope SanScope(this);
2091 llvm::Value *Cond =
2092 Builder.CreateICmpNE(RV, llvm::Constant::getNullValue(RV->getType()));
2093 llvm::Constant *StaticData[] = {
2094 EmitCheckSourceLocation(EndLoc)
2095 };
2096 EmitCheck(Cond, "nonnull_return", StaticData, ArrayRef<llvm::Value *>(),
2097 CRK_Recoverable);
2098 }
2099 Ret = Builder.CreateRet(RV);
2100 } else {
2101 Ret = Builder.CreateRetVoid();
2102 }
2103
Devang Patel65497582010-07-21 18:08:50 +00002104 if (!RetDbgLoc.isUnknown())
2105 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002106}
2107
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002108static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2109 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2110 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2111}
2112
2113static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2114 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2115 // placeholders.
2116 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2117 llvm::Value *Placeholder =
2118 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2119 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2120 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2121 Ty.getQualifiers(),
2122 AggValueSlot::IsNotDestructed,
2123 AggValueSlot::DoesNotNeedGCBarriers,
2124 AggValueSlot::IsNotAliased);
2125}
2126
John McCall32ea9692011-03-11 20:59:21 +00002127void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002128 const VarDecl *param,
2129 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002130 // StartFunction converted the ABI-lowered parameter(s) into a
2131 // local alloca. We need to turn that into an r-value suitable
2132 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002133 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002134
John McCall32ea9692011-03-11 20:59:21 +00002135 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002136
John McCall23f66262010-05-26 22:34:26 +00002137 // For the most part, we just need to load the alloca, except:
2138 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002139 // 2) references to non-scalars are pointers directly to the aggregate.
2140 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002141 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002142 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002143 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002144
2145 // Locals which are references to scalars are represented
2146 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002147 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002148 }
2149
Reid Klecknerab2090d2014-07-26 01:34:32 +00002150 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2151 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002152
Nick Lewycky2d84e842013-10-02 02:29:49 +00002153 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002154}
2155
John McCall31168b02011-06-15 23:02:42 +00002156static bool isProvablyNull(llvm::Value *addr) {
2157 return isa<llvm::ConstantPointerNull>(addr);
2158}
2159
2160static bool isProvablyNonNull(llvm::Value *addr) {
2161 return isa<llvm::AllocaInst>(addr);
2162}
2163
2164/// Emit the actual writing-back of a writeback.
2165static void emitWriteback(CodeGenFunction &CGF,
2166 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002167 const LValue &srcLV = writeback.Source;
2168 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002169 assert(!isProvablyNull(srcAddr) &&
2170 "shouldn't have writeback for provably null argument");
2171
Craig Topper8a13c412014-05-21 05:09:00 +00002172 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002173
2174 // If the argument wasn't provably non-null, we need to null check
2175 // before doing the store.
2176 bool provablyNonNull = isProvablyNonNull(srcAddr);
2177 if (!provablyNonNull) {
2178 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2179 contBB = CGF.createBasicBlock("icr.done");
2180
2181 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2182 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2183 CGF.EmitBlock(writebackBB);
2184 }
2185
2186 // Load the value to writeback.
2187 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2188
2189 // Cast it back, in case we're writing an id to a Foo* or something.
2190 value = CGF.Builder.CreateBitCast(value,
2191 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2192 "icr.writeback-cast");
2193
2194 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002195
2196 // If we have a "to use" value, it's something we need to emit a use
2197 // of. This has to be carefully threaded in: if it's done after the
2198 // release it's potentially undefined behavior (and the optimizer
2199 // will ignore it), and if it happens before the retain then the
2200 // optimizer could move the release there.
2201 if (writeback.ToUse) {
2202 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2203
2204 // Retain the new value. No need to block-copy here: the block's
2205 // being passed up the stack.
2206 value = CGF.EmitARCRetainNonBlock(value);
2207
2208 // Emit the intrinsic use here.
2209 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2210
2211 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002212 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002213
2214 // Put the new value in place (primitively).
2215 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2216
2217 // Release the old value.
2218 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2219
2220 // Otherwise, we can just do a normal lvalue store.
2221 } else {
2222 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2223 }
John McCall31168b02011-06-15 23:02:42 +00002224
2225 // Jump to the continuation block.
2226 if (!provablyNonNull)
2227 CGF.EmitBlock(contBB);
2228}
2229
2230static void emitWritebacks(CodeGenFunction &CGF,
2231 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002232 for (const auto &I : args.writebacks())
2233 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002234}
2235
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002236static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2237 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002238 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002239 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2240 CallArgs.getCleanupsToDeactivate();
2241 // Iterate in reverse to increase the likelihood of popping the cleanup.
2242 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2243 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2244 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2245 I->IsActiveIP->eraseFromParent();
2246 }
2247}
2248
John McCalleff18842013-03-23 02:35:54 +00002249static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2250 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2251 if (uop->getOpcode() == UO_AddrOf)
2252 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002253 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002254}
2255
John McCall31168b02011-06-15 23:02:42 +00002256/// Emit an argument that's being passed call-by-writeback. That is,
2257/// we are passing the address of
2258static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2259 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002260 LValue srcLV;
2261
2262 // Make an optimistic effort to emit the address as an l-value.
2263 // This can fail if the the argument expression is more complicated.
2264 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2265 srcLV = CGF.EmitLValue(lvExpr);
2266
2267 // Otherwise, just emit it as a scalar.
2268 } else {
2269 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2270
2271 QualType srcAddrType =
2272 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2273 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2274 }
2275 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002276
2277 // The dest and src types don't necessarily match in LLVM terms
2278 // because of the crazy ObjC compatibility rules.
2279
Chris Lattner2192fe52011-07-18 04:24:23 +00002280 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002281 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2282
2283 // If the address is a constant null, just pass the appropriate null.
2284 if (isProvablyNull(srcAddr)) {
2285 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2286 CRE->getType());
2287 return;
2288 }
2289
John McCall31168b02011-06-15 23:02:42 +00002290 // Create the temporary.
2291 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2292 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002293 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2294 // and that cleanup will be conditional if we can't prove that the l-value
2295 // isn't null, so we need to register a dominating point so that the cleanups
2296 // system will make valid IR.
2297 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2298
John McCall31168b02011-06-15 23:02:42 +00002299 // Zero-initialize it if we're not doing a copy-initialization.
2300 bool shouldCopy = CRE->shouldCopy();
2301 if (!shouldCopy) {
2302 llvm::Value *null =
2303 llvm::ConstantPointerNull::get(
2304 cast<llvm::PointerType>(destType->getElementType()));
2305 CGF.Builder.CreateStore(null, temp);
2306 }
Craig Topper8a13c412014-05-21 05:09:00 +00002307
2308 llvm::BasicBlock *contBB = nullptr;
2309 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002310
2311 // If the address is *not* known to be non-null, we need to switch.
2312 llvm::Value *finalArgument;
2313
2314 bool provablyNonNull = isProvablyNonNull(srcAddr);
2315 if (provablyNonNull) {
2316 finalArgument = temp;
2317 } else {
2318 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2319
2320 finalArgument = CGF.Builder.CreateSelect(isNull,
2321 llvm::ConstantPointerNull::get(destType),
2322 temp, "icr.argument");
2323
2324 // If we need to copy, then the load has to be conditional, which
2325 // means we need control flow.
2326 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002327 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002328 contBB = CGF.createBasicBlock("icr.cont");
2329 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2330 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2331 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002332 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002333 }
2334 }
2335
Craig Topper8a13c412014-05-21 05:09:00 +00002336 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002337
John McCall31168b02011-06-15 23:02:42 +00002338 // Perform a copy if necessary.
2339 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002340 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002341 assert(srcRV.isScalar());
2342
2343 llvm::Value *src = srcRV.getScalarVal();
2344 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2345 "icr.cast");
2346
2347 // Use an ordinary store, not a store-to-lvalue.
2348 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002349
2350 // If optimization is enabled, and the value was held in a
2351 // __strong variable, we need to tell the optimizer that this
2352 // value has to stay alive until we're doing the store back.
2353 // This is because the temporary is effectively unretained,
2354 // and so otherwise we can violate the high-level semantics.
2355 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2356 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2357 valueToUse = src;
2358 }
John McCall31168b02011-06-15 23:02:42 +00002359 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002360
John McCall31168b02011-06-15 23:02:42 +00002361 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002362 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002363 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002364 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002365
2366 // Make a phi for the value to intrinsically use.
2367 if (valueToUse) {
2368 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2369 "icr.to-use");
2370 phiToUse->addIncoming(valueToUse, copyBB);
2371 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2372 originBB);
2373 valueToUse = phiToUse;
2374 }
2375
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002376 condEval.end(CGF);
2377 }
John McCall31168b02011-06-15 23:02:42 +00002378
John McCalleff18842013-03-23 02:35:54 +00002379 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002380 args.add(RValue::get(finalArgument), CRE->getType());
2381}
2382
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002383void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2384 assert(!StackBase && !StackCleanup.isValid());
2385
2386 // Save the stack.
2387 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2388 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2389
2390 // Control gets really tied up in landing pads, so we have to spill the
2391 // stacksave to an alloca to avoid violating SSA form.
2392 // TODO: This is dead if we never emit the cleanup. We should create the
2393 // alloca and store lazily on the first cleanup emission.
2394 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2395 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2396 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2397 StackCleanup = CGF.EHStack.getInnermostEHScope();
2398 assert(StackCleanup.isValid());
2399}
2400
2401void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2402 if (StackBase) {
2403 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2404 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2405 // We could load StackBase from StackBaseMem, but in the non-exceptional
2406 // case we can skip it.
2407 CGF.Builder.CreateCall(F, StackBase);
2408 }
2409}
2410
Reid Kleckner739756c2013-12-04 19:23:12 +00002411void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2412 ArrayRef<QualType> ArgTypes,
2413 CallExpr::const_arg_iterator ArgBeg,
2414 CallExpr::const_arg_iterator ArgEnd,
2415 bool ForceColumnInfo) {
2416 CGDebugInfo *DI = getDebugInfo();
2417 SourceLocation CallLoc;
2418 if (DI) CallLoc = DI->getLocation();
2419
2420 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2421 // because arguments are destroyed left to right in the callee.
2422 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002423 // Insert a stack save if we're going to need any inalloca args.
2424 bool HasInAllocaArgs = false;
2425 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2426 I != E && !HasInAllocaArgs; ++I)
2427 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2428 if (HasInAllocaArgs) {
2429 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2430 Args.allocateArgumentMemory(*this);
2431 }
2432
2433 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002434 size_t CallArgsStart = Args.size();
2435 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2436 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2437 EmitCallArg(Args, *Arg, ArgTypes[I]);
2438 // Restore the debug location.
2439 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2440 }
2441
2442 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2443 // IR function.
2444 std::reverse(Args.begin() + CallArgsStart, Args.end());
2445 return;
2446 }
2447
2448 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2449 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2450 assert(Arg != ArgEnd);
2451 EmitCallArg(Args, *Arg, ArgTypes[I]);
2452 // Restore the debug location.
2453 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2454 }
2455}
2456
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002457namespace {
2458
2459struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2460 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2461 : Addr(Addr), Ty(Ty) {}
2462
2463 llvm::Value *Addr;
2464 QualType Ty;
2465
Craig Topper4f12f102014-03-12 06:41:41 +00002466 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002467 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2468 assert(!Dtor->isTrivial());
2469 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2470 /*Delegating=*/false, Addr);
2471 }
2472};
2473
2474}
2475
John McCall32ea9692011-03-11 20:59:21 +00002476void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2477 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002478 if (const ObjCIndirectCopyRestoreExpr *CRE
2479 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002480 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002481 assert(getContext().hasSameType(E->getType(), type));
2482 return emitWritebackArg(*this, args, CRE);
2483 }
2484
John McCall0a76c0c2011-08-26 18:42:59 +00002485 assert(type->isReferenceType() == E->isGLValue() &&
2486 "reference binding to unmaterialized r-value!");
2487
John McCall17054bd62011-08-26 21:08:13 +00002488 if (E->isGLValue()) {
2489 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002490 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002491 }
Mike Stump11289f42009-09-09 15:08:12 +00002492
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002493 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2494
2495 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2496 // However, we still have to push an EH-only cleanup in case we unwind before
2497 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002498 if (HasAggregateEvalKind &&
2499 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2500 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002501 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002502 AggValueSlot Slot;
2503 if (args.isUsingInAlloca())
2504 Slot = createPlaceholderSlot(*this, type);
2505 else
2506 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002507
2508 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2509 bool DestroyedInCallee =
2510 RD && RD->hasNonTrivialDestructor() &&
2511 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2512 if (DestroyedInCallee)
2513 Slot.setExternallyDestructed();
2514
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002515 EmitAggExpr(E, Slot);
2516 RValue RV = Slot.asRValue();
2517 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002518
Reid Klecknere39ee212014-05-03 00:33:28 +00002519 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002520 // Create a no-op GEP between the placeholder and the cleanup so we can
2521 // RAUW it successfully. It also serves as a marker of the first
2522 // instruction where the cleanup is active.
2523 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002524 // This unreachable is a temporary marker which will be removed later.
2525 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2526 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002527 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002528 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002529 }
2530
2531 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002532 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2533 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2534 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002535 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2536 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2537 } else {
2538 // We can't represent a misaligned lvalue in the CallArgList, so copy
2539 // to an aligned temporary now.
2540 llvm::Value *tmp = CreateMemTemp(type);
2541 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2542 L.getAlignment());
2543 args.add(RValue::getAggregate(tmp), type);
2544 }
Eli Friedmandf968192011-05-26 00:10:27 +00002545 return;
2546 }
2547
John McCall32ea9692011-03-11 20:59:21 +00002548 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002549}
2550
Dan Gohman515a60d2012-02-16 00:57:37 +00002551// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2552// optimizer it can aggressively ignore unwind edges.
2553void
2554CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2555 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2556 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2557 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2558 CGM.getNoObjCARCExceptionsMetadata());
2559}
2560
John McCall882987f2013-02-28 19:01:20 +00002561/// Emits a call to the given no-arguments nounwind runtime function.
2562llvm::CallInst *
2563CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2564 const llvm::Twine &name) {
2565 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2566}
2567
2568/// Emits a call to the given nounwind runtime function.
2569llvm::CallInst *
2570CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2571 ArrayRef<llvm::Value*> args,
2572 const llvm::Twine &name) {
2573 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2574 call->setDoesNotThrow();
2575 return call;
2576}
2577
2578/// Emits a simple call (never an invoke) to the given no-arguments
2579/// runtime function.
2580llvm::CallInst *
2581CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2582 const llvm::Twine &name) {
2583 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2584}
2585
2586/// Emits a simple call (never an invoke) to the given runtime
2587/// function.
2588llvm::CallInst *
2589CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2590 ArrayRef<llvm::Value*> args,
2591 const llvm::Twine &name) {
2592 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2593 call->setCallingConv(getRuntimeCC());
2594 return call;
2595}
2596
2597/// Emits a call or invoke to the given noreturn runtime function.
2598void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2599 ArrayRef<llvm::Value*> args) {
2600 if (getInvokeDest()) {
2601 llvm::InvokeInst *invoke =
2602 Builder.CreateInvoke(callee,
2603 getUnreachableBlock(),
2604 getInvokeDest(),
2605 args);
2606 invoke->setDoesNotReturn();
2607 invoke->setCallingConv(getRuntimeCC());
2608 } else {
2609 llvm::CallInst *call = Builder.CreateCall(callee, args);
2610 call->setDoesNotReturn();
2611 call->setCallingConv(getRuntimeCC());
2612 Builder.CreateUnreachable();
2613 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002614 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002615}
2616
2617/// Emits a call or invoke instruction to the given nullary runtime
2618/// function.
2619llvm::CallSite
2620CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2621 const Twine &name) {
2622 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2623}
2624
2625/// Emits a call or invoke instruction to the given runtime function.
2626llvm::CallSite
2627CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2628 ArrayRef<llvm::Value*> args,
2629 const Twine &name) {
2630 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2631 callSite.setCallingConv(getRuntimeCC());
2632 return callSite;
2633}
2634
2635llvm::CallSite
2636CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2637 const Twine &Name) {
2638 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2639}
2640
John McCallbd309292010-07-06 01:34:17 +00002641/// Emits a call or invoke instruction to the given function, depending
2642/// on the current state of the EH stack.
2643llvm::CallSite
2644CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002645 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002646 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002647 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002648
Dan Gohman515a60d2012-02-16 00:57:37 +00002649 llvm::Instruction *Inst;
2650 if (!InvokeDest)
2651 Inst = Builder.CreateCall(Callee, Args, Name);
2652 else {
2653 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2654 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2655 EmitBlock(ContBB);
2656 }
2657
2658 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2659 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002660 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002661 AddObjCARCExceptionMetadata(Inst);
2662
2663 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002664}
2665
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002666void CodeGenFunction::ExpandTypeToArgs(
2667 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
2668 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002669 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2670 unsigned NumElts = AT->getSize().getZExtValue();
2671 QualType EltTy = AT->getElementType();
2672 llvm::Value *Addr = RV.getAggregateAddr();
2673 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2674 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002675 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002676 ExpandTypeToArgs(EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002677 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002678 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002679 RecordDecl *RD = RT->getDecl();
2680 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002681 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002682
2683 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002684 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002685 CharUnits UnionSize = CharUnits::Zero();
2686
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002687 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002688 assert(!FD->isBitField() &&
2689 "Cannot expand structure with bit-field members.");
2690 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2691 if (UnionSize < FieldSize) {
2692 UnionSize = FieldSize;
2693 LargestFD = FD;
2694 }
2695 }
2696 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002697 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002698 ExpandTypeToArgs(LargestFD->getType(), FldRV, IRFuncTy, IRCallArgs,
2699 IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002700 }
2701 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002702 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002703 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002704 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002705 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002706 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002707 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002708 ComplexPairTy CV = RV.getComplexVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002709 IRCallArgs[IRCallArgPos++] = CV.first;
2710 IRCallArgs[IRCallArgPos++] = CV.second;
Bob Wilsone826a2a2011-08-03 05:58:22 +00002711 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002712 assert(RV.isScalar() &&
2713 "Unexpected non-scalar rvalue during struct expansion.");
2714
2715 // Insert a bitcast as needed.
2716 llvm::Value *V = RV.getScalarVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002717 if (IRCallArgPos < IRFuncTy->getNumParams() &&
2718 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
2719 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
Chris Lattnerd59d8672011-07-12 06:29:11 +00002720
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002721 IRCallArgs[IRCallArgPos++] = V;
Chris Lattnerd59d8672011-07-12 06:29:11 +00002722 }
2723}
2724
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002725/// \brief Store a non-aggregate value to an address to initialize it. For
2726/// initialization, a non-atomic store will be used.
2727static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2728 LValue Dst) {
2729 if (Src.isScalar())
2730 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2731 else
2732 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2733}
2734
2735void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2736 llvm::Value *New) {
2737 DeferredReplacements.push_back(std::make_pair(Old, New));
2738}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002739
Daniel Dunbard931a872009-02-02 22:03:45 +00002740RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002741 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002742 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002743 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002744 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002745 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002746 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002747
2748 // Handle struct-return functions by passing a pointer to the
2749 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002750 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002751 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002753 llvm::FunctionType *IRFuncTy =
2754 cast<llvm::FunctionType>(
2755 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002756
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002757 // If we're using inalloca, insert the allocation after the stack save.
2758 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002759 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002760 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002761 llvm::Instruction *IP = CallArgs.getStackBase();
2762 llvm::AllocaInst *AI;
2763 if (IP) {
2764 IP = IP->getNextNode();
2765 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2766 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002767 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002768 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002769 AI->setUsedWithInAlloca(true);
2770 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2771 ArgMemory = AI;
2772 }
2773
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002774 ClangToLLVMArgMapping IRFunctionArgs(CGM, CallInfo);
2775 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2776
Chris Lattner4ca97c32009-06-13 00:26:38 +00002777 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002778 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002779 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002780 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002781 SRetPtr = ReturnValue.getValue();
2782 if (!SRetPtr)
2783 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002784 if (IRFunctionArgs.hasSRetArg()) {
2785 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002786 } else {
2787 llvm::Value *Addr =
2788 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2789 Builder.CreateStore(SRetPtr, Addr);
2790 }
Anders Carlsson17490832009-12-24 20:40:36 +00002791 }
Mike Stump11289f42009-09-09 15:08:12 +00002792
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002793 assert(CallInfo.arg_size() == CallArgs.size() &&
2794 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002795 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002796 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002797 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002798 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002799 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002800 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002801
John McCall47fb9502013-03-07 21:37:08 +00002802 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002803
2804 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002805 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2806 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2807 llvm::UndefValue::get(ArgInfo.getPaddingType());
2808
2809 unsigned FirstIRArg, NumIRArgs;
2810 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002811
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002812 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002813 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002814 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002815 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2816 if (RV.isAggregate()) {
2817 // Replace the placeholder with the appropriate argument slot GEP.
2818 llvm::Instruction *Placeholder =
2819 cast<llvm::Instruction>(RV.getAggregateAddr());
2820 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2821 Builder.SetInsertPoint(Placeholder);
2822 llvm::Value *Addr = Builder.CreateStructGEP(
2823 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2824 Builder.restoreIP(IP);
2825 deferPlaceholderReplacement(Placeholder, Addr);
2826 } else {
2827 // Store the RValue into the argument struct.
2828 llvm::Value *Addr =
2829 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002830 unsigned AS = Addr->getType()->getPointerAddressSpace();
2831 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2832 // There are some cases where a trivial bitcast is not avoidable. The
2833 // definition of a type later in a translation unit may change it's type
2834 // from {}* to (%struct.foo*)*.
2835 if (Addr->getType() != MemType)
2836 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002837 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2838 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2839 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002840 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002841 }
2842
Daniel Dunbar03816342010-08-21 02:24:36 +00002843 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002844 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002845 if (RV.isScalar() || RV.isComplex()) {
2846 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002847 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2848 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2849 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002850 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00002851
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002852 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002853 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002854 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002855 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002856 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002857 // 1. If the argument is not byval, and we are required to copy the
2858 // source. (This case doesn't occur on any common architecture.)
2859 // 2. If the argument is byval, RV is not sufficiently aligned, and
2860 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002861 // 3. If the argument is byval, but RV is located in an address space
2862 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002863 llvm::Value *Addr = RV.getAggregateAddr();
2864 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002865 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002866 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002867 const unsigned ArgAddrSpace =
2868 (FirstIRArg < IRFuncTy->getNumParams()
2869 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
2870 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002871 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002872 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002873 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2874 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002875 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002876 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2877 if (Align > AI->getAlignment())
2878 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002879 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00002880 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002881 } else {
2882 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002883 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002884 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002885 }
2886 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002887 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002888
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002889 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002890 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002891 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002892
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002893 case ABIArgInfo::Extend:
2894 case ABIArgInfo::Direct: {
2895 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002896 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2897 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002898 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002899 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002900 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002901 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002902 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002903 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002904
Chris Lattner3ce86682011-07-12 04:53:39 +00002905 // If the argument doesn't match, perform a bitcast to coerce it. This
2906 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002907 if (FirstIRArg < IRFuncTy->getNumParams() &&
2908 V->getType() != IRFuncTy->getParamType(FirstIRArg))
2909 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
2910 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002911 break;
2912 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002913
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002914 // FIXME: Avoid the conversion through memory if possible.
2915 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002916 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002917 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002918 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002919 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002920 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002921 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002922
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002923 // If the value is offset in memory, apply the offset now.
2924 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2925 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2926 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002927 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002928 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2929
2930 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002931
Chris Lattner3dd716c2010-06-28 23:44:11 +00002932 // If the coerce-to type is a first class aggregate, we flatten it and
2933 // pass the elements. Either way is semantically identical, but fast-isel
2934 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00002935 // We cannot do this for functions using the AAPCS calling convention,
2936 // as structures are treated differently by that calling convention.
2937 llvm::StructType *STy =
2938 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
2939 if (STy && !isAAPCSVFP(CallInfo, getTarget())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002940 llvm::Type *SrcTy =
2941 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2942 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2943 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2944
2945 // If the source type is smaller than the destination type of the
2946 // coerce-to logic, copy the source value into a temp alloca the size
2947 // of the destination type to allow loading all of it. The bits past
2948 // the source value are left undef.
2949 if (SrcSize < DstSize) {
2950 llvm::AllocaInst *TempAlloca
2951 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2952 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2953 SrcPtr = TempAlloca;
2954 } else {
2955 SrcPtr = Builder.CreateBitCast(SrcPtr,
2956 llvm::PointerType::getUnqual(STy));
2957 }
2958
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002959 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00002960 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2961 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002962 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2963 // We don't know what we're loading from.
2964 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002965 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00002966 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002967 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002968 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002969 assert(NumIRArgs == 1);
2970 IRCallArgs[FirstIRArg] =
2971 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002972 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002973
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002974 break;
2975 }
2976
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002977 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002978 unsigned IRArgPos = FirstIRArg;
2979 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
2980 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002981 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002982 }
2983 }
Mike Stump11289f42009-09-09 15:08:12 +00002984
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002985 if (ArgMemory) {
2986 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00002987 if (CallInfo.isVariadic()) {
2988 // When passing non-POD arguments by value to variadic functions, we will
2989 // end up with a variadic prototype and an inalloca call site. In such
2990 // cases, we can't do any parameter mismatch checks. Give up and bitcast
2991 // the callee.
2992 unsigned CalleeAS =
2993 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
2994 Callee = Builder.CreateBitCast(
2995 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
2996 } else {
2997 llvm::Type *LastParamTy =
2998 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2999 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003000#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003001 // Assert that these structs have equivalent element types.
3002 llvm::StructType *FullTy = CallInfo.getArgStruct();
3003 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3004 cast<llvm::PointerType>(LastParamTy)->getElementType());
3005 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3006 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3007 DE = DeclaredTy->element_end(),
3008 FI = FullTy->element_begin();
3009 DI != DE; ++DI, ++FI)
3010 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003011#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003012 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3013 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003014 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003015 assert(IRFunctionArgs.hasInallocaArg());
3016 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003017 }
3018
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003019 if (!CallArgs.getCleanupsToDeactivate().empty())
3020 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3021
Chris Lattner4ca97c32009-06-13 00:26:38 +00003022 // If the callee is a bitcast of a function to a varargs pointer to function
3023 // type, check to see if we can remove the bitcast. This handles some cases
3024 // with unprototyped functions.
3025 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3026 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003027 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3028 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003029 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003030 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003031
Chris Lattner4ca97c32009-06-13 00:26:38 +00003032 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3033 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003034 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003035 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003036 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003037 bool ArgsMatch = true;
3038 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3039 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3040 ArgsMatch = false;
3041 break;
3042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043
Chris Lattner4ca97c32009-06-13 00:26:38 +00003044 // Strip the cast if we can get away with it. This is a nice cleanup,
3045 // but also allows us to inline the function at -O0 if it is marked
3046 // always_inline.
3047 if (ArgsMatch)
3048 Callee = CalleeF;
3049 }
3050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003052 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3053 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3054 // Inalloca argument can have different type.
3055 if (IRFunctionArgs.hasInallocaArg() &&
3056 i == IRFunctionArgs.getInallocaArgNo())
3057 continue;
3058 if (i < IRFuncTy->getNumParams())
3059 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3060 }
3061
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003062 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003063 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003064 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3065 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003066 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003067 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Craig Topper8a13c412014-05-21 05:09:00 +00003069 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003070 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3071 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003072 InvokeDest = getInvokeDest();
3073
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003074 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003075 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003076 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003077 } else {
3078 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003079 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003080 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003081 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003082 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003083 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003084
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003085 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3086 !CS.hasFnAttr(llvm::Attribute::NoInline))
3087 Attrs =
3088 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3089 llvm::Attribute::AlwaysInline);
3090
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003091 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003092 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003093
Dan Gohman515a60d2012-02-16 00:57:37 +00003094 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3095 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003096 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003097 AddObjCARCExceptionMetadata(CS.getInstruction());
3098
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003099 // If the call doesn't return, finish the basic block and clear the
3100 // insertion point; this allows the rest of IRgen to discard
3101 // unreachable code.
3102 if (CS.doesNotReturn()) {
3103 Builder.CreateUnreachable();
3104 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003105
Mike Stump18bb9282009-05-16 07:57:57 +00003106 // FIXME: For now, emit a dummy basic block because expr emitters in
3107 // generally are not ready to handle emitting expressions at unreachable
3108 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003109 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003110
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003111 // Return a reasonable RValue.
3112 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003113 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003114
3115 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003116 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003117 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003118
John McCall31168b02011-06-15 23:02:42 +00003119 // Emit any writebacks immediately. Arguably this should happen
3120 // after any return-value munging.
3121 if (CallArgs.hasWritebacks())
3122 emitWritebacks(*this, CallArgs);
3123
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003124 // The stack cleanup for inalloca arguments has to run out of the normal
3125 // lexical order, so deactivate it and run it manually here.
3126 CallArgs.freeArgumentMemory(*this);
3127
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003128 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003129 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00003130 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003131 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003132
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003133 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00003134 // If we are ignoring an argument that had a result, make sure to
3135 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00003136 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003137
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003138 case ABIArgInfo::Extend:
3139 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00003140 llvm::Type *RetIRTy = ConvertType(RetTy);
3141 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00003142 switch (getEvaluationKind(RetTy)) {
3143 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003144 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3145 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3146 return RValue::getComplex(std::make_pair(Real, Imag));
3147 }
John McCall47fb9502013-03-07 21:37:08 +00003148 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003149 llvm::Value *DestPtr = ReturnValue.getValue();
3150 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003151
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003152 if (!DestPtr) {
3153 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3154 DestIsVolatile = false;
3155 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00003156 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003157 return RValue::getAggregate(DestPtr);
3158 }
John McCall47fb9502013-03-07 21:37:08 +00003159 case TEK_Scalar: {
3160 // If the argument doesn't match, perform a bitcast to coerce it. This
3161 // can happen due to trivial type mismatches.
3162 llvm::Value *V = CI;
3163 if (V->getType() != RetIRTy)
3164 V = Builder.CreateBitCast(V, RetIRTy);
3165 return RValue::get(V);
3166 }
3167 }
3168 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003169 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003170
Anders Carlsson17490832009-12-24 20:40:36 +00003171 llvm::Value *DestPtr = ReturnValue.getValue();
3172 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003173
Anders Carlsson17490832009-12-24 20:40:36 +00003174 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00003175 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00003176 DestIsVolatile = false;
3177 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003178
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003179 // If the value is offset in memory, apply the offset now.
3180 llvm::Value *StorePtr = DestPtr;
3181 if (unsigned Offs = RetAI.getDirectOffset()) {
3182 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3183 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003184 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003185 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3186 }
3187 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003188
Nick Lewycky2d84e842013-10-02 02:29:49 +00003189 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00003190 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003191
Daniel Dunbard3674e62008-09-11 01:48:57 +00003192 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00003193 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003194 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003195
David Blaikie83d382b2011-09-23 05:06:16 +00003196 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003197}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003198
3199/* VarArg handling */
3200
3201llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3202 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3203}