blob: ecb2baddeeafb78f80a2a86c34b1bbf6197d03fb [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
88/// type, on top of any implicit parameters already stored. Use the
89/// given ExtInfo instead of the ExtInfo from the function type.
90static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
Reid Kleckner4982b822014-01-31 22:54:50 +000091 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +000092 SmallVectorImpl<CanQualType> &prefix,
93 CanQual<FunctionProtoType> FTP,
94 FunctionType::ExtInfo extInfo) {
95 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000096 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000097 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
98 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +000099 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +0000100 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
101 extInfo, required);
John McCall8dda7b22012-07-07 06:41:13 +0000102}
103
104/// Arrange the argument and result information for a free function (i.e.
105/// not a C++ or ObjC instance method) of the given type.
106static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
108 CanQual<FunctionProtoType> FTP) {
Reid Kleckner4982b822014-01-31 22:54:50 +0000109 return arrangeLLVMFunctionInfo(CGT, false, prefix, FTP, FTP->getExtInfo());
John McCall8dda7b22012-07-07 06:41:13 +0000110}
111
John McCall8dda7b22012-07-07 06:41:13 +0000112/// Arrange the argument and result information for a free function (i.e.
113/// not a C++ or ObjC instance method) of the given type.
114static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
115 SmallVectorImpl<CanQualType> &prefix,
116 CanQual<FunctionProtoType> FTP) {
117 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000118 return arrangeLLVMFunctionInfo(CGT, true, prefix, FTP, extInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000119}
120
John McCalla729c622012-02-17 03:33:10 +0000121/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000122/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000123const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000124CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000125 SmallVector<CanQualType, 16> argTypes;
John McCall8dda7b22012-07-07 06:41:13 +0000126 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000127}
128
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000129static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000130 // Set the appropriate calling convention for the Function.
131 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000132 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000133
134 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000135 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000136
Douglas Gregora941dca2010-05-18 16:57:00 +0000137 if (D->hasAttr<ThisCallAttr>())
138 return CC_X86ThisCall;
139
Dawn Perchik335e16b2010-09-03 01:29:35 +0000140 if (D->hasAttr<PascalAttr>())
141 return CC_X86Pascal;
142
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000143 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
144 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
145
Derek Schuffa2020962012-10-16 22:30:41 +0000146 if (D->hasAttr<PnaclCallAttr>())
147 return CC_PnaclCall;
148
Guy Benyeif0a014b2012-12-25 08:53:55 +0000149 if (D->hasAttr<IntelOclBiccAttr>())
150 return CC_IntelOclBicc;
151
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000152 if (D->hasAttr<MSABIAttr>())
153 return IsWindows ? CC_C : CC_X86_64Win64;
154
155 if (D->hasAttr<SysVABIAttr>())
156 return IsWindows ? CC_X86_64SysV : CC_C;
157
John McCallab26cfa2010-02-05 21:31:56 +0000158 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000159}
160
James Molloy6f244b62014-05-09 16:21:39 +0000161static bool isAAPCSVFP(const CGFunctionInfo &FI, const TargetInfo &Target) {
162 switch (FI.getEffectiveCallingConvention()) {
163 case llvm::CallingConv::C:
164 switch (Target.getTriple().getEnvironment()) {
165 case llvm::Triple::EABIHF:
166 case llvm::Triple::GNUEABIHF:
167 return true;
168 default:
169 return false;
170 }
171 case llvm::CallingConv::ARM_AAPCS_VFP:
172 return true;
173 default:
174 return false;
175 }
176}
177
John McCalla729c622012-02-17 03:33:10 +0000178/// Arrange the argument and result information for a call to an
179/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000180/// (Zero value of RD means we don't have any meaningful "this" argument type,
181/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000182/// The member function must be an ordinary function, i.e. not a
183/// constructor or destructor.
184const CGFunctionInfo &
185CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
186 const FunctionProtoType *FTP) {
187 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000188
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000189 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000190 if (RD)
191 argTypes.push_back(GetThisType(Context, RD));
192 else
193 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000194
John McCall8dda7b22012-07-07 06:41:13 +0000195 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000196 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000197}
198
John McCalla729c622012-02-17 03:33:10 +0000199/// Arrange the argument and result information for a declaration or
200/// definition of the given C++ non-static member function. The
201/// member function must be an ordinary function, i.e. not a
202/// constructor or destructor.
203const CGFunctionInfo &
204CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000205 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000206 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
207
John McCalla729c622012-02-17 03:33:10 +0000208 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000209
John McCalla729c622012-02-17 03:33:10 +0000210 if (MD->isInstance()) {
211 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000212 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000213 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000214 }
215
John McCall8dda7b22012-07-07 06:41:13 +0000216 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000217}
218
John McCalla729c622012-02-17 03:33:10 +0000219/// Arrange the argument and result information for a declaration
220/// or definition to the given constructor variant.
221const CGFunctionInfo &
222CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
223 CXXCtorType ctorKind) {
224 SmallVector<CanQualType, 16> argTypes;
225 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000226
227 GlobalDecl GD(D, ctorKind);
228 CanQualType resultType =
229 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000230
John McCall5d865c322010-08-31 07:33:07 +0000231 CanQual<FunctionProtoType> FTP = GetFormalType(D);
232
233 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000234 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
235 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000236
Reid Kleckner89077a12013-12-17 19:46:40 +0000237 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
238
239 RequiredArgs required =
240 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
241
John McCall8dda7b22012-07-07 06:41:13 +0000242 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000243 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000244}
245
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000246/// Arrange a call to a C++ method, passing the given arguments.
247const CGFunctionInfo &
248CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
249 const CXXConstructorDecl *D,
250 CXXCtorType CtorKind,
251 unsigned ExtraArgs) {
252 // FIXME: Kill copy.
253 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000254 for (const auto &Arg : args)
255 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000256
257 CanQual<FunctionProtoType> FPT = GetFormalType(D);
258 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
259 GlobalDecl GD(D, CtorKind);
260 CanQualType ResultType =
261 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
262
263 FunctionType::ExtInfo Info = FPT->getExtInfo();
264 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
265}
266
John McCalla729c622012-02-17 03:33:10 +0000267/// Arrange the argument and result information for a declaration,
268/// definition, or call to the given destructor variant. It so
269/// happens that all three cases produce the same information.
270const CGFunctionInfo &
271CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
272 CXXDtorType dtorKind) {
273 SmallVector<CanQualType, 2> argTypes;
274 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000275
276 GlobalDecl GD(D, dtorKind);
277 CanQualType resultType =
278 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000279
John McCalla729c622012-02-17 03:33:10 +0000280 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000281
282 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Alp Toker9cacbab2014-01-20 20:26:09 +0000283 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000284 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000285
John McCall8dda7b22012-07-07 06:41:13 +0000286 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000287 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
John McCall8dda7b22012-07-07 06:41:13 +0000288 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000289}
290
John McCalla729c622012-02-17 03:33:10 +0000291/// Arrange the argument and result information for the declaration or
292/// definition of the given function.
293const CGFunctionInfo &
294CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000295 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000296 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000297 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000298
John McCall2da83a32010-02-26 00:48:12 +0000299 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000300
John McCall2da83a32010-02-26 00:48:12 +0000301 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000302
303 // When declaring a function without a prototype, always use a
304 // non-variadic type.
305 if (isa<FunctionNoProtoType>(FTy)) {
306 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000307 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000308 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000309 }
310
John McCall2da83a32010-02-26 00:48:12 +0000311 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000312 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000313}
314
John McCalla729c622012-02-17 03:33:10 +0000315/// Arrange the argument and result information for the declaration or
316/// definition of an Objective-C method.
317const CGFunctionInfo &
318CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
319 // It happens that this is the same as a call with no optional
320 // arguments, except also using the formal 'self' type.
321 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
322}
323
324/// Arrange the argument and result information for the function type
325/// through which to perform a send to the given Objective-C method,
326/// using the given receiver type. The receiver type is not always
327/// the 'self' type of the method or even an Objective-C pointer type.
328/// This is *not* the right method for actually performing such a
329/// message send, due to the possibility of optional arguments.
330const CGFunctionInfo &
331CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
332 QualType receiverType) {
333 SmallVector<CanQualType, 16> argTys;
334 argTys.push_back(Context.getCanonicalParamType(receiverType));
335 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000336 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000337 for (const auto *I : MD->params()) {
338 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000339 }
John McCall31168b02011-06-15 23:02:42 +0000340
341 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000342 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
343 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000344
David Blaikiebbafb8a2012-03-11 07:00:24 +0000345 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000346 MD->hasAttr<NSReturnsRetainedAttr>())
347 einfo = einfo.withProducesResult(true);
348
John McCalla729c622012-02-17 03:33:10 +0000349 RequiredArgs required =
350 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
351
Reid Kleckner4982b822014-01-31 22:54:50 +0000352 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
353 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000354}
355
John McCalla729c622012-02-17 03:33:10 +0000356const CGFunctionInfo &
357CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000358 // FIXME: Do we need to handle ObjCMethodDecl?
359 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000360
Anders Carlsson6710c532010-02-06 02:44:09 +0000361 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000362 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000363
364 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000365 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000366
John McCalla729c622012-02-17 03:33:10 +0000367 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000368}
369
John McCallc818bbb2012-12-07 07:03:17 +0000370/// Arrange a call as unto a free function, except possibly with an
371/// additional number of formal parameters considered required.
372static const CGFunctionInfo &
373arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000374 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000375 const CallArgList &args,
376 const FunctionType *fnType,
377 unsigned numExtraRequiredArgs) {
378 assert(args.size() >= numExtraRequiredArgs);
379
380 // In most cases, there are no optional arguments.
381 RequiredArgs required = RequiredArgs::All;
382
383 // If we have a variadic prototype, the required arguments are the
384 // extra prefix plus the arguments in the prototype.
385 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
386 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000387 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000388
389 // If we don't have a prototype at all, but we're supposed to
390 // explicitly use the variadic convention for unprototyped calls,
391 // treat all of the arguments as required but preserve the nominal
392 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000393 } else if (CGM.getTargetCodeGenInfo()
394 .isNoProtoCallVariadic(args,
395 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000396 required = RequiredArgs(args.size());
397 }
398
Alp Toker314cc812014-01-25 16:55:45 +0000399 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000400 fnType->getExtInfo(), required);
401}
402
John McCalla729c622012-02-17 03:33:10 +0000403/// Figure out the rules for calling a function with the given formal
404/// type using the given arguments. The arguments are necessary
405/// because the function might be unprototyped, in which case it's
406/// target-dependent in crazy ways.
407const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000408CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
409 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000410 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000411}
John McCalla729c622012-02-17 03:33:10 +0000412
John McCallc818bbb2012-12-07 07:03:17 +0000413/// A block function call is essentially a free-function call with an
414/// extra implicit argument.
415const CGFunctionInfo &
416CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
417 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000418 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000419}
420
421const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000422CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
423 const CallArgList &args,
424 FunctionType::ExtInfo info,
425 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000426 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000427 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000428 for (const auto &Arg : args)
429 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000430 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
431 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000432}
433
434/// Arrange a call to a C++ method, passing the given arguments.
435const CGFunctionInfo &
436CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
437 const FunctionProtoType *FPT,
438 RequiredArgs required) {
439 // FIXME: Kill copy.
440 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000441 for (const auto &Arg : args)
442 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000443
444 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000445 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
446 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000447}
448
Reid Kleckner4982b822014-01-31 22:54:50 +0000449const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
450 QualType resultType, const FunctionArgList &args,
451 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000452 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000453 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000454 for (auto Arg : args)
455 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000456
457 RequiredArgs required =
458 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000459 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000460 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000461}
462
John McCalla729c622012-02-17 03:33:10 +0000463const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000464 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000465 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000466}
467
John McCalla729c622012-02-17 03:33:10 +0000468/// Arrange the argument and result information for an abstract value
469/// of a given function type. This is the method which all of the
470/// above functions ultimately defer to.
471const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000472CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000473 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000474 ArrayRef<CanQualType> argTypes,
475 FunctionType::ExtInfo info,
476 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000477#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000478 for (ArrayRef<CanQualType>::const_iterator
479 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000480 assert(I->isCanonicalAsParam());
481#endif
482
John McCalla729c622012-02-17 03:33:10 +0000483 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000484
Daniel Dunbare0be8292009-02-03 00:07:12 +0000485 // Lookup or create unique function info.
486 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000487 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
488 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000489
Craig Topper8a13c412014-05-21 05:09:00 +0000490 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000491 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000492 if (FI)
493 return *FI;
494
John McCalla729c622012-02-17 03:33:10 +0000495 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000496 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
497 required);
John McCalla729c622012-02-17 03:33:10 +0000498 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000499
John McCalla729c622012-02-17 03:33:10 +0000500 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
501 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000502
Daniel Dunbar313321e2009-02-03 05:31:23 +0000503 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000504 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000505
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000506 // Loop over all of the computed argument and return value info. If any of
507 // them are direct or extend without a specified coerce type, specify the
508 // default now.
John McCalla729c622012-02-17 03:33:10 +0000509 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000510 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000511 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000512
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000513 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000514 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000515 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000516
John McCalla729c622012-02-17 03:33:10 +0000517 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
518 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000519
Daniel Dunbare0be8292009-02-03 00:07:12 +0000520 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000521}
522
John McCalla729c622012-02-17 03:33:10 +0000523CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000524 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000525 const FunctionType::ExtInfo &info,
526 CanQualType resultType,
527 ArrayRef<CanQualType> argTypes,
528 RequiredArgs required) {
529 void *buffer = operator new(sizeof(CGFunctionInfo) +
530 sizeof(ArgInfo) * (argTypes.size() + 1));
531 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
532 FI->CallingConvention = llvmCC;
533 FI->EffectiveCallingConvention = llvmCC;
534 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000535 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000536 FI->NoReturn = info.getNoReturn();
537 FI->ReturnsRetained = info.getProducesResult();
538 FI->Required = required;
539 FI->HasRegParm = info.getHasRegParm();
540 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000541 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000542 FI->NumArgs = argTypes.size();
543 FI->getArgsBuffer()[0].type = resultType;
544 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
545 FI->getArgsBuffer()[i + 1].type = argTypes[i];
546 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000547}
548
549/***/
550
John McCall85dd2c52011-05-15 02:19:42 +0000551void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000552 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000553 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
554 uint64_t NumElts = AT->getSize().getZExtValue();
555 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
556 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000557 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000558 const RecordDecl *RD = RT->getDecl();
559 assert(!RD->hasFlexibleArrayMember() &&
560 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000561 if (RD->isUnion()) {
562 // Unions can be here only in degenerative cases - all the fields are same
563 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000564 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000565 CharUnits UnionSize = CharUnits::Zero();
566
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000567 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000568 assert(!FD->isBitField() &&
569 "Cannot expand structure with bit-field members.");
570 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
571 if (UnionSize < FieldSize) {
572 UnionSize = FieldSize;
573 LargestFD = FD;
574 }
575 }
576 if (LargestFD)
577 GetExpandedTypes(LargestFD->getType(), expandedTypes);
578 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000579 for (const auto *I : RD->fields()) {
580 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000581 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000582 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000583 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000584 }
585 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
586 llvm::Type *EltTy = ConvertType(CT->getElementType());
587 expandedTypes.push_back(EltTy);
588 expandedTypes.push_back(EltTy);
589 } else
590 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000591}
592
Mike Stump11289f42009-09-09 15:08:12 +0000593llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000594CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
595 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 assert(LV.isSimple() &&
597 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000598
Bob Wilsone826a2a2011-08-03 05:58:22 +0000599 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
600 unsigned NumElts = AT->getSize().getZExtValue();
601 QualType EltTy = AT->getElementType();
602 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000603 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000604 LValue LV = MakeAddrLValue(EltAddr, EltTy);
605 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000606 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000607 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000608 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000609 if (RD->isUnion()) {
610 // Unions can be here only in degenerative cases - all the fields are same
611 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000612 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000613 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000614
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000615 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000616 assert(!FD->isBitField() &&
617 "Cannot expand structure with bit-field members.");
618 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
619 if (UnionSize < FieldSize) {
620 UnionSize = FieldSize;
621 LargestFD = FD;
622 }
623 }
624 if (LargestFD) {
625 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000626 LValue SubLV = EmitLValueForField(LV, LargestFD);
627 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000628 }
629 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000630 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000631 QualType FT = FD->getType();
632
633 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000634 LValue SubLV = EmitLValueForField(LV, FD);
635 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000636 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000637 }
638 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
639 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000640 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000641 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000642 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000643 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
644 } else {
645 EmitStoreThroughLValue(RValue::get(AI), LV);
646 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000647 }
648
649 return AI;
650}
651
Chris Lattner895c52b2010-06-27 06:04:18 +0000652/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000653/// accessing some number of bytes out of it, try to gep into the struct to get
654/// at its inner goodness. Dive as deep as possible without entering an element
655/// with an in-memory size smaller than DstSize.
656static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000657EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000658 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000659 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000660 // We can't dive into a zero-element struct.
661 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000662
Chris Lattner2192fe52011-07-18 04:24:23 +0000663 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000664
Chris Lattner1cd66982010-06-27 05:56:15 +0000665 // If the first elt is at least as large as what we're looking for, or if the
666 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000667 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000668 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000669 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000670 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000671 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000672
Chris Lattner1cd66982010-06-27 05:56:15 +0000673 // GEP into the first element.
674 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000675
Chris Lattner1cd66982010-06-27 05:56:15 +0000676 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000677 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000678 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000679 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000680 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000681
682 return SrcPtr;
683}
684
Chris Lattner055097f2010-06-27 06:26:04 +0000685/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
686/// are either integers or pointers. This does a truncation of the value if it
687/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000688///
689/// This behaves as if the value were coerced through memory, so on big-endian
690/// targets the high bits are preserved in a truncation, while little-endian
691/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000692static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000693 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000694 CodeGenFunction &CGF) {
695 if (Val->getType() == Ty)
696 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000697
Chris Lattner055097f2010-06-27 06:26:04 +0000698 if (isa<llvm::PointerType>(Val->getType())) {
699 // If this is Pointer->Pointer avoid conversion to and from int.
700 if (isa<llvm::PointerType>(Ty))
701 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000702
Chris Lattner055097f2010-06-27 06:26:04 +0000703 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000704 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000705 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000706
Chris Lattner2192fe52011-07-18 04:24:23 +0000707 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000708 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000709 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000710
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000711 if (Val->getType() != DestIntTy) {
712 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
713 if (DL.isBigEndian()) {
714 // Preserve the high bits on big-endian targets.
715 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000716 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
717 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
718
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000719 if (SrcSize > DstSize) {
720 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
721 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
722 } else {
723 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
724 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
725 }
726 } else {
727 // Little-endian targets preserve the low bits. No shifts required.
728 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
729 }
730 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000731
Chris Lattner055097f2010-06-27 06:26:04 +0000732 if (isa<llvm::PointerType>(Ty))
733 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
734 return Val;
735}
736
Chris Lattner1cd66982010-06-27 05:56:15 +0000737
738
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000739/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
740/// a pointer to an object of type \arg Ty.
741///
742/// This safely handles the case when the src type is smaller than the
743/// destination type; in this situation the values of bits which not
744/// present in the src are undefined.
745static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000746 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000747 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000748 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000749 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000750
Chris Lattnerd200eda2010-06-28 22:51:39 +0000751 // If SrcTy and Ty are the same, just do a load.
752 if (SrcTy == Ty)
753 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000754
Micah Villmowdd31ca12012-10-08 16:25:52 +0000755 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000756
Chris Lattner2192fe52011-07-18 04:24:23 +0000757 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000758 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000759 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
760 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000761
Micah Villmowdd31ca12012-10-08 16:25:52 +0000762 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000763
Chris Lattner055097f2010-06-27 06:26:04 +0000764 // If the source and destination are integer or pointer types, just do an
765 // extension or truncation to the desired type.
766 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
767 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
768 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
769 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
770 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000771
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000772 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000773 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000774 // Generally SrcSize is never greater than DstSize, since this means we are
775 // losing bits. However, this can happen in cases where the structure has
776 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000777 //
Mike Stump18bb9282009-05-16 07:57:57 +0000778 // FIXME: Assert that we aren't truncating non-padding bits when have access
779 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000780 llvm::Value *Casted =
781 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000782 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
783 // FIXME: Use better alignment / avoid requiring aligned load.
784 Load->setAlignment(1);
785 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000786 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000787
Chris Lattner3fcc7902010-06-27 01:06:27 +0000788 // Otherwise do coercion through memory. This is stupid, but
789 // simple.
790 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000791 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
792 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
793 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000794 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000795 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
796 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
797 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000798 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000799}
800
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000801// Function to store a first-class aggregate into memory. We prefer to
802// store the elements rather than the aggregate to be more friendly to
803// fast-isel.
804// FIXME: Do we need to recurse here?
805static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
806 llvm::Value *DestPtr, bool DestIsVolatile,
807 bool LowAlignment) {
808 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000809 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000810 dyn_cast<llvm::StructType>(Val->getType())) {
811 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
812 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
813 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
814 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
815 DestIsVolatile);
816 if (LowAlignment)
817 SI->setAlignment(1);
818 }
819 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000820 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
821 if (LowAlignment)
822 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000823 }
824}
825
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000826/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
827/// where the source and destination may have different types.
828///
829/// This safely handles the case when the src type is larger than the
830/// destination type; the upper bits of the src will be lost.
831static void CreateCoercedStore(llvm::Value *Src,
832 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000833 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000834 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000835 llvm::Type *SrcTy = Src->getType();
836 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000837 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000838 if (SrcTy == DstTy) {
839 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
840 return;
841 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000842
Micah Villmowdd31ca12012-10-08 16:25:52 +0000843 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000844
Chris Lattner2192fe52011-07-18 04:24:23 +0000845 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000846 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
847 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
848 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000849
Chris Lattner055097f2010-06-27 06:26:04 +0000850 // If the source and destination are integer or pointer types, just do an
851 // extension or truncation to the desired type.
852 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
853 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
854 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
855 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
856 return;
857 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000858
Micah Villmowdd31ca12012-10-08 16:25:52 +0000859 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000860
Daniel Dunbar313321e2009-02-03 05:31:23 +0000861 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000862 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000863 llvm::Value *Casted =
864 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000865 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000866 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000867 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000868 // Otherwise do coercion through memory. This is stupid, but
869 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000870
871 // Generally SrcSize is never greater than DstSize, since this means we are
872 // losing bits. However, this can happen in cases where the structure has
873 // additional padding, for example due to a user specified alignment.
874 //
875 // FIXME: Assert that we aren't truncating non-padding bits when have access
876 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000877 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
878 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000879 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
880 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
881 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000882 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000883 CGF.Builder.CreateMemCpy(DstCasted, Casted,
884 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
885 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000886 }
887}
888
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000889/***/
890
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000891bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000892 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000893}
894
Tim Northovere77cc392014-03-29 13:28:05 +0000895bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
896 return ReturnTypeUsesSRet(FI) &&
897 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
898}
899
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000900bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
901 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
902 switch (BT->getKind()) {
903 default:
904 return false;
905 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000906 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000907 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000908 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000909 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000910 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000911 }
912 }
913
914 return false;
915}
916
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000917bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
918 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
919 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
920 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000921 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000922 }
923 }
924
925 return false;
926}
927
Chris Lattnera5f58b02011-07-09 17:41:47 +0000928llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000929 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
930 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000931}
932
Chris Lattnera5f58b02011-07-09 17:41:47 +0000933llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000934CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000935
936 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
937 assert(Inserted && "Recursively being processed?");
938
Reid Kleckner37abaca2014-05-09 22:46:15 +0000939 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000940 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000941 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000942
John McCall85dd2c52011-05-15 02:19:42 +0000943 const ABIArgInfo &retAI = FI.getReturnInfo();
944 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000945 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000946 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000947
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000948 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000949 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000950 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000951 break;
952
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000953 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000954 if (retAI.getInAllocaSRet()) {
955 // sret things on win32 aren't void, they return the sret pointer.
956 QualType ret = FI.getReturnType();
957 llvm::Type *ty = ConvertType(ret);
958 unsigned addressSpace = Context.getTargetAddressSpace(ret);
959 resultType = llvm::PointerType::get(ty, addressSpace);
960 } else {
961 resultType = llvm::Type::getVoidTy(getLLVMContext());
962 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000963 break;
964
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000965 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000966 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
967 resultType = llvm::Type::getVoidTy(getLLVMContext());
968
969 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000970 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000971 unsigned addressSpace = Context.getTargetAddressSpace(ret);
972 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000973
974 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000975 break;
976 }
977
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000978 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000979 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000980 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCallc818bbb2012-12-07 07:03:17 +0000983 // Add in all of the required arguments.
984 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
985 if (FI.isVariadic()) {
986 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
987 } else {
988 ie = FI.arg_end();
989 }
990 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000991 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000992
Rafael Espindolafad28de2012-10-24 01:59:00 +0000993 // Insert a padding type to ensure proper alignment.
994 if (llvm::Type *PaddingType = argAI.getPaddingType())
995 argTypes.push_back(PaddingType);
996
John McCall85dd2c52011-05-15 02:19:42 +0000997 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000998 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000999 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001000 break;
1001
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001002 case ABIArgInfo::Indirect: {
1003 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001004 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +00001005 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001006 break;
1007 }
1008
1009 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001010 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001011 // If the coerce-to type is a first class aggregate, flatten it. Either
1012 // way is semantically identical, but fast-isel and the optimizer
1013 // generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00001014 // We cannot do this for functions using the AAPCS calling convention,
1015 // as structures are treated differently by that calling convention.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001016 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001017 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1018 if (st && !isAAPCSVFP(FI, getTarget())) {
John McCall85dd2c52011-05-15 02:19:42 +00001019 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1020 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +00001021 } else {
John McCall85dd2c52011-05-15 02:19:42 +00001022 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001023 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001024 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Daniel Dunbard3674e62008-09-11 01:48:57 +00001027 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +00001028 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001029 break;
1030 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001031 }
1032
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001033 // Add the inalloca struct as the last parameter type.
1034 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1035 argTypes.push_back(ArgStruct->getPointerTo());
1036
Reid Kleckner37abaca2014-05-09 22:46:15 +00001037 if (SwapThisWithSRet)
1038 std::swap(argTypes[0], argTypes[1]);
1039
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001040 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1041 assert(Erased && "Not in set?");
1042
John McCalla729c622012-02-17 03:33:10 +00001043 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001044}
1045
Chris Lattner2192fe52011-07-18 04:24:23 +00001046llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001047 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001048 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001049
Chris Lattner8806e322011-07-10 00:18:59 +00001050 if (!isFuncTypeConvertible(FPT))
1051 return llvm::StructType::get(getLLVMContext());
1052
1053 const CGFunctionInfo *Info;
1054 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001055 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001056 else
John McCalla729c622012-02-17 03:33:10 +00001057 Info = &arrangeCXXMethodDeclaration(MD);
1058 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001059}
1060
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001061void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001062 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001063 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001064 unsigned &CallingConv,
1065 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001066 llvm::AttrBuilder FuncAttrs;
1067 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001068
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001069 CallingConv = FI.getEffectiveCallingConvention();
1070
John McCallab26cfa2010-02-05 21:31:56 +00001071 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001072 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001073
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001074 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001075 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001076 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001077 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001078 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001079 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001080 if (TargetDecl->hasAttr<NoReturnAttr>())
1081 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001082 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1083 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001084
1085 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001086 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001087 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001088 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001089 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1090 // These attributes are not inherited by overloads.
1091 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1092 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001093 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001094 }
1095
Eric Christopherbf005ec2011-08-15 22:38:22 +00001096 // 'const' and 'pure' attribute functions are also nounwind.
1097 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001098 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1099 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001100 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001101 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1102 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001103 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001104 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001105 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001106 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1107 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001108 }
1109
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001110 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001111 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001112 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001113 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001114 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001115 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001116 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001117 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001118 if (CodeGenOpts.EnableSegmentedStacks &&
1119 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001120 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001121
Bill Wendling2f81db62013-02-22 20:53:29 +00001122 if (AttrOnCallSite) {
1123 // Attributes that should go on the call site only.
1124 if (!CodeGenOpts.SimplifyLibCalls)
1125 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001126 } else {
1127 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001128 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001129 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001130 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001131 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001132 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001133 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001134 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001135 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001136 }
1137
Bill Wendlingdabafea2013-03-13 22:24:33 +00001138 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001139 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001140 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001141 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001142 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001143 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001144 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001145 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001146 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001147 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001148 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001149 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001150
Bill Wendlingd8f49502013-08-01 21:41:02 +00001151 if (!CodeGenOpts.StackRealignment)
1152 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001153 }
1154
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001155 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001156 unsigned Index = 1;
Reid Kleckner37abaca2014-05-09 22:46:15 +00001157 bool SwapThisWithSRet = false;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001158 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001159 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001160 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001161 if (RetTy->hasSignedIntegerRepresentation())
1162 RetAttrs.addAttribute(llvm::Attribute::SExt);
1163 else if (RetTy->hasUnsignedIntegerRepresentation())
1164 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001165 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001166 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001167 if (RetAI.getInReg())
1168 RetAttrs.addAttribute(llvm::Attribute::InReg);
1169 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001170 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001171 break;
1172
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001173 case ABIArgInfo::InAlloca: {
1174 // inalloca disables readnone and readonly
1175 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1176 .removeAttribute(llvm::Attribute::ReadNone);
1177 break;
1178 }
1179
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001180 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001181 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001182 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001183 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001184 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Reid Kleckner37abaca2014-05-09 22:46:15 +00001185 SwapThisWithSRet = RetAI.isSRetAfterThis();
1186 PAL.push_back(llvm::AttributeSet::get(
1187 getLLVMContext(), SwapThisWithSRet ? 2 : Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001188
Reid Kleckner37abaca2014-05-09 22:46:15 +00001189 if (!SwapThisWithSRet)
1190 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001191 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001192 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1193 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001194 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001195 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001196
Daniel Dunbard3674e62008-09-11 01:48:57 +00001197 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001198 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001199 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001200
Hal Finkela2347ba2014-07-18 15:52:10 +00001201 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1202 QualType PTy = RefTy->getPointeeType();
1203 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1204 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1205 .getQuantity());
1206 else if (getContext().getTargetAddressSpace(PTy) == 0)
1207 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1208 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001209
Bill Wendlinga7912f82012-10-10 07:36:56 +00001210 if (RetAttrs.hasAttributes())
1211 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001212 AttributeSet::get(getLLVMContext(),
1213 llvm::AttributeSet::ReturnIndex,
1214 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001215
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001216 for (const auto &I : FI.arguments()) {
1217 QualType ParamType = I.type;
1218 const ABIArgInfo &AI = I.info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001219 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001220
Reid Kleckner37abaca2014-05-09 22:46:15 +00001221 // Skip over the sret parameter when it comes second. We already handled it
1222 // above.
1223 if (Index == 2 && SwapThisWithSRet)
1224 ++Index;
1225
Rafael Espindolafad28de2012-10-24 01:59:00 +00001226 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001227 if (AI.getPaddingInReg())
1228 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1229 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001230 // Increment Index if there is padding.
1231 ++Index;
1232 }
1233
John McCall39ec71f2010-03-27 00:47:27 +00001234 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1235 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001236 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001237 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001238 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001239 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001240 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001241 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001242 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001243 // FALL THROUGH
James Molloy6f244b62014-05-09 16:21:39 +00001244 case ABIArgInfo::Direct: {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001245 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001246 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001247
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001248 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001249
James Molloy6f244b62014-05-09 16:21:39 +00001250 llvm::StructType *STy =
1251 dyn_cast<llvm::StructType>(AI.getCoerceToType());
1252 if (!isAAPCSVFP(FI, getTarget()) && STy) {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001253 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001254 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001255 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001256 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1257 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001258 Index += Extra;
1259 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001260 break;
James Molloy6f244b62014-05-09 16:21:39 +00001261 }
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001262 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001263 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001264 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001265
Anders Carlsson20759ad2009-09-16 15:53:40 +00001266 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001267 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001268
Bill Wendlinga7912f82012-10-10 07:36:56 +00001269 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1270
Daniel Dunbarc2304432009-03-18 19:51:01 +00001271 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001272 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1273 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001274 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001275
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001276 case ABIArgInfo::Ignore:
1277 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001278 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001279
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001280 case ABIArgInfo::InAlloca:
1281 // inalloca disables readnone and readonly.
1282 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1283 .removeAttribute(llvm::Attribute::ReadNone);
1284 // Skip increment, no matching LLVM parameter.
1285 continue;
1286
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001287 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001288 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001289 // FIXME: This is rather inefficient. Do we ever actually need to do
1290 // anything here? The result should be just reconstructed on the other
1291 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001292 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001293 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001294 continue;
1295 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Hal Finkela2347ba2014-07-18 15:52:10 +00001298 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1299 QualType PTy = RefTy->getPointeeType();
1300 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1301 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1302 .getQuantity());
1303 else if (getContext().getTargetAddressSpace(PTy) == 0)
1304 Attrs.addAttribute(llvm::Attribute::NonNull);
1305 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001306
Bill Wendlinga7912f82012-10-10 07:36:56 +00001307 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001308 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001309 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001310 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001311
1312 // Add the inalloca attribute to the trailing inalloca parameter if present.
1313 if (FI.usesInAlloca()) {
1314 llvm::AttrBuilder Attrs;
1315 Attrs.addAttribute(llvm::Attribute::InAlloca);
1316 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1317 }
1318
Bill Wendlinga7912f82012-10-10 07:36:56 +00001319 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001320 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001321 AttributeSet::get(getLLVMContext(),
1322 llvm::AttributeSet::FunctionIndex,
1323 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001324}
1325
John McCalla738c252011-03-09 04:27:21 +00001326/// An argument came in as a promoted argument; demote it back to its
1327/// declared type.
1328static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1329 const VarDecl *var,
1330 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001331 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001332
1333 // This can happen with promotions that actually don't change the
1334 // underlying type, like the enum promotions.
1335 if (value->getType() == varType) return value;
1336
1337 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1338 && "unexpected promotion type");
1339
1340 if (isa<llvm::IntegerType>(varType))
1341 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1342
1343 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1344}
1345
Daniel Dunbard931a872009-02-02 22:03:45 +00001346void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1347 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001348 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001349 // If this is an implicit-return-zero function, go ahead and
1350 // initialize the return value. TODO: it might be nice to have
1351 // a more general mechanism for this that didn't require synthesized
1352 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001354 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001355 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001356 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001357 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001358 Builder.CreateStore(Zero, ReturnValue);
1359 }
1360 }
1361
Mike Stump18bb9282009-05-16 07:57:57 +00001362 // FIXME: We no longer need the types from FunctionArgList; lift up and
1363 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001364
Daniel Dunbar613855c2008-09-09 23:27:19 +00001365 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1366 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001367
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001368 // If we're using inalloca, all the memory arguments are GEPs off of the last
1369 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001370 llvm::Value *ArgStruct = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001371 if (FI.usesInAlloca()) {
1372 llvm::Function::arg_iterator EI = Fn->arg_end();
1373 --EI;
1374 ArgStruct = EI;
1375 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1376 }
1377
Reid Kleckner37abaca2014-05-09 22:46:15 +00001378 // Name the struct return parameter, which can come first or second.
1379 const ABIArgInfo &RetAI = FI.getReturnInfo();
1380 bool SwapThisWithSRet = false;
1381 if (RetAI.isIndirect()) {
1382 SwapThisWithSRet = RetAI.isSRetAfterThis();
1383 if (SwapThisWithSRet)
1384 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001385 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001386 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001387 llvm::Attribute::NoAlias));
Reid Kleckner37abaca2014-05-09 22:46:15 +00001388 if (SwapThisWithSRet)
1389 --AI; // Go back to the beginning for 'this'.
1390 else
1391 ++AI; // Skip the sret parameter.
Daniel Dunbar613855c2008-09-09 23:27:19 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Hal Finkel82504f02014-07-11 17:35:21 +00001394 // Get the function-level nonnull attribute if it exists.
1395 const NonNullAttr *NNAtt =
1396 CurCodeDecl ? CurCodeDecl->getAttr<NonNullAttr>() : nullptr;
1397
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001398 // Track if we received the parameter as a pointer (indirect, byval, or
1399 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1400 // into a local alloca for us.
1401 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001402 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001403 SmallVector<ValueAndIsPtr, 16> ArgVals;
1404 ArgVals.reserve(Args.size());
1405
Reid Kleckner739756c2013-12-04 19:23:12 +00001406 // Create a pointer value for every parameter declaration. This usually
1407 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1408 // any cleanups or do anything that might unwind. We do that separately, so
1409 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001410 assert(FI.arg_size() == Args.size() &&
1411 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001412 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001413 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001414 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1415 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001416 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001417 QualType Ty = info_it->type;
1418 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001419
John McCalla738c252011-03-09 04:27:21 +00001420 bool isPromoted =
1421 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1422
Rafael Espindolafad28de2012-10-24 01:59:00 +00001423 // Skip the dummy padding argument.
1424 if (ArgI.getPaddingType())
1425 ++AI;
1426
Daniel Dunbard3674e62008-09-11 01:48:57 +00001427 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001428 case ABIArgInfo::InAlloca: {
1429 llvm::Value *V = Builder.CreateStructGEP(
1430 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1431 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1432 continue; // Don't increment AI!
1433 }
1434
Daniel Dunbar747865a2009-02-05 09:16:39 +00001435 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001436 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001437
John McCall47fb9502013-03-07 21:37:08 +00001438 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001439 // Aggregates and complex variables are accessed by reference. All we
1440 // need to do is realign the value, if requested
1441 if (ArgI.getIndirectRealign()) {
1442 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1443
1444 // Copy from the incoming argument pointer to the temporary with the
1445 // appropriate alignment.
1446 //
1447 // FIXME: We should have a common utility for generating an aggregate
1448 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001449 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001450 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001451 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1452 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1453 Builder.CreateMemCpy(Dst,
1454 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001455 llvm::ConstantInt::get(IntPtrTy,
1456 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001457 ArgI.getIndirectAlign(),
1458 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001459 V = AlignedTemp;
1460 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001461 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001462 } else {
1463 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001464 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001465 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1466 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001467
1468 if (isPromoted)
1469 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001470 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001471 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001472 break;
1473 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001474
1475 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001476 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001477
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001478 // If we have the trivial case, handle it with no muss and fuss.
1479 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001480 ArgI.getCoerceToType() == ConvertType(Ty) &&
1481 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001482 assert(AI != Fn->arg_end() && "Argument mismatch!");
1483 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001484
Hal Finkel48d53e22014-07-19 01:41:07 +00001485 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Hal Finkel82504f02014-07-11 17:35:21 +00001486 if ((NNAtt && NNAtt->isNonNull(PVD->getFunctionScopeIndex())) ||
1487 PVD->hasAttr<NonNullAttr>())
1488 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1489 AI->getArgNo() + 1,
1490 llvm::Attribute::NonNull));
1491
Hal Finkel48d53e22014-07-19 01:41:07 +00001492 QualType OTy = PVD->getOriginalType();
1493 if (const auto *ArrTy =
1494 getContext().getAsConstantArrayType(OTy)) {
1495 // A C99 array parameter declaration with the static keyword also
1496 // indicates dereferenceability, and if the size is constant we can
1497 // use the dereferenceable attribute (which requires the size in
1498 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001499 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001500 QualType ETy = ArrTy->getElementType();
1501 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1502 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1503 ArrSize) {
1504 llvm::AttrBuilder Attrs;
1505 Attrs.addDereferenceableAttr(
1506 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1507 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1508 AI->getArgNo() + 1, Attrs));
1509 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1510 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1511 AI->getArgNo() + 1,
1512 llvm::Attribute::NonNull));
1513 }
1514 }
1515 } else if (const auto *ArrTy =
1516 getContext().getAsVariableArrayType(OTy)) {
1517 // For C99 VLAs with the static keyword, we don't know the size so
1518 // we can't use the dereferenceable attribute, but in addrspace(0)
1519 // we know that it must be nonnull.
1520 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1521 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1522 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1523 AI->getArgNo() + 1,
1524 llvm::Attribute::NonNull));
1525 }
1526 }
1527
Bill Wendling507c3512012-10-16 05:23:44 +00001528 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001529 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1530 AI->getArgNo() + 1,
1531 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001532
Chris Lattner7369c142011-07-20 06:29:00 +00001533 // Ensure the argument is the correct type.
1534 if (V->getType() != ArgI.getCoerceToType())
1535 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1536
John McCalla738c252011-03-09 04:27:21 +00001537 if (isPromoted)
1538 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001539
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001540 if (const CXXMethodDecl *MD =
1541 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001542 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001543 V = CGM.getCXXABI().
1544 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001545 }
1546
Rafael Espindola8778c282012-11-29 16:09:03 +00001547 // Because of merging of function types from multiple decls it is
1548 // possible for the type of an argument to not match the corresponding
1549 // type in the function type. Since we are codegening the callee
1550 // in here, add a cast to the argument type.
1551 llvm::Type *LTy = ConvertType(Arg->getType());
1552 if (V->getType() != LTy)
1553 V = Builder.CreateBitCast(V, LTy);
1554
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001555 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001556 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001559 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001560
Chris Lattnerff941a62010-07-28 18:24:28 +00001561 // The alignment we need to use is the max of the requested alignment for
1562 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001563 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001564 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001565 AlignmentToUse = std::max(AlignmentToUse,
1566 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001567
Chris Lattnerff941a62010-07-28 18:24:28 +00001568 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001569 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001570 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001571
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001572 // If the value is offset in memory, apply the offset now.
1573 if (unsigned Offs = ArgI.getDirectOffset()) {
1574 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1575 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001576 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001577 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1578 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001579
Chris Lattner15ec3612010-06-29 00:06:42 +00001580 // If the coerce-to type is a first class aggregate, we flatten it and
1581 // pass the elements. Either way is semantically identical, but fast-isel
1582 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00001583 // We cannot do this for functions using the AAPCS calling convention,
1584 // as structures are treated differently by that calling convention.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001585 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
James Molloy6f244b62014-05-09 16:21:39 +00001586 if (!isAAPCSVFP(FI, getTarget()) && STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001587 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001588 llvm::Type *DstTy =
1589 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001590 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001591
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001592 if (SrcSize <= DstSize) {
1593 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1594
1595 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1596 assert(AI != Fn->arg_end() && "Argument mismatch!");
1597 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1598 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1599 Builder.CreateStore(AI++, EltPtr);
1600 }
1601 } else {
1602 llvm::AllocaInst *TempAlloca =
1603 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1604 TempAlloca->setAlignment(AlignmentToUse);
1605 llvm::Value *TempV = TempAlloca;
1606
1607 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1608 assert(AI != Fn->arg_end() && "Argument mismatch!");
1609 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1610 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1611 Builder.CreateStore(AI++, EltPtr);
1612 }
1613
1614 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001615 }
1616 } else {
1617 // Simple case, just do a coerced store of the argument into the alloca.
1618 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001619 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001620 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001621 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001622
1623
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001624 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001625 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001626 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001627 if (isPromoted)
1628 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001629 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1630 } else {
1631 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001632 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00001633 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001634 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001635
1636 case ABIArgInfo::Expand: {
1637 // If this structure was expanded into multiple arguments then
1638 // we need to create a temporary and reconstruct it from the
1639 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001640 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001641 CharUnits Align = getContext().getDeclAlign(Arg);
1642 Alloca->setAlignment(Align.getQuantity());
1643 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001644 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001645 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001646
1647 // Name the arguments used in expansion and increment AI.
1648 unsigned Index = 0;
1649 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001650 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001651 continue;
1652 }
1653
1654 case ABIArgInfo::Ignore:
1655 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001656 if (!hasScalarEvaluationKind(Ty)) {
1657 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1658 } else {
1659 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1660 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1661 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001662
1663 // Skip increment, no matching LLVM parameter.
1664 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001665 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001666
1667 ++AI;
Reid Kleckner37abaca2014-05-09 22:46:15 +00001668
1669 if (ArgNo == 1 && SwapThisWithSRet)
1670 ++AI; // Skip the sret parameter.
Daniel Dunbar613855c2008-09-09 23:27:19 +00001671 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001672
1673 if (FI.usesInAlloca())
1674 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001675 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001676
1677 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1678 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001679 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1680 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001681 } else {
1682 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001683 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1684 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001685 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001686}
1687
John McCallffa2c1a2012-01-29 07:46:59 +00001688static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1689 while (insn->use_empty()) {
1690 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1691 if (!bitcast) return;
1692
1693 // This is "safe" because we would have used a ConstantExpr otherwise.
1694 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1695 bitcast->eraseFromParent();
1696 }
1697}
1698
John McCall31168b02011-06-15 23:02:42 +00001699/// Try to emit a fused autorelease of a return result.
1700static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1701 llvm::Value *result) {
1702 // We must be immediately followed the cast.
1703 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001704 if (BB->empty()) return nullptr;
1705 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001706
Chris Lattner2192fe52011-07-18 04:24:23 +00001707 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001708
1709 // result is in a BasicBlock and is therefore an Instruction.
1710 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1711
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001712 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001713
1714 // Look for:
1715 // %generator = bitcast %type1* %generator2 to %type2*
1716 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1717 // We would have emitted this as a constant if the operand weren't
1718 // an Instruction.
1719 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1720
1721 // Require the generator to be immediately followed by the cast.
1722 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001723 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001724
1725 insnsToKill.push_back(bitcast);
1726 }
1727
1728 // Look for:
1729 // %generator = call i8* @objc_retain(i8* %originalResult)
1730 // or
1731 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1732 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001733 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001734
1735 bool doRetainAutorelease;
1736
1737 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1738 doRetainAutorelease = true;
1739 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1740 .objc_retainAutoreleasedReturnValue) {
1741 doRetainAutorelease = false;
1742
John McCallcfa4e9b2012-09-07 23:30:50 +00001743 // If we emitted an assembly marker for this call (and the
1744 // ARCEntrypoints field should have been set if so), go looking
1745 // for that call. If we can't find it, we can't do this
1746 // optimization. But it should always be the immediately previous
1747 // instruction, unless we needed bitcasts around the call.
1748 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1749 llvm::Instruction *prev = call->getPrevNode();
1750 assert(prev);
1751 if (isa<llvm::BitCastInst>(prev)) {
1752 prev = prev->getPrevNode();
1753 assert(prev);
1754 }
1755 assert(isa<llvm::CallInst>(prev));
1756 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1757 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1758 insnsToKill.push_back(prev);
1759 }
John McCall31168b02011-06-15 23:02:42 +00001760 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001761 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001762 }
1763
1764 result = call->getArgOperand(0);
1765 insnsToKill.push_back(call);
1766
1767 // Keep killing bitcasts, for sanity. Note that we no longer care
1768 // about precise ordering as long as there's exactly one use.
1769 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1770 if (!bitcast->hasOneUse()) break;
1771 insnsToKill.push_back(bitcast);
1772 result = bitcast->getOperand(0);
1773 }
1774
1775 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001776 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001777 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1778 (*i)->eraseFromParent();
1779
1780 // Do the fused retain/autorelease if we were asked to.
1781 if (doRetainAutorelease)
1782 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1783
1784 // Cast back to the result type.
1785 return CGF.Builder.CreateBitCast(result, resultType);
1786}
1787
John McCallffa2c1a2012-01-29 07:46:59 +00001788/// If this is a +1 of the value of an immutable 'self', remove it.
1789static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1790 llvm::Value *result) {
1791 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001792 const ObjCMethodDecl *method =
1793 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001794 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001795 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001796 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001797
1798 // Look for a retain call.
1799 llvm::CallInst *retainCall =
1800 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1801 if (!retainCall ||
1802 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001803 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001804
1805 // Look for an ordinary load of 'self'.
1806 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1807 llvm::LoadInst *load =
1808 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1809 if (!load || load->isAtomic() || load->isVolatile() ||
1810 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001811 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001812
1813 // Okay! Burn it all down. This relies for correctness on the
1814 // assumption that the retain is emitted as part of the return and
1815 // that thereafter everything is used "linearly".
1816 llvm::Type *resultType = result->getType();
1817 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1818 assert(retainCall->use_empty());
1819 retainCall->eraseFromParent();
1820 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1821
1822 return CGF.Builder.CreateBitCast(load, resultType);
1823}
1824
John McCall31168b02011-06-15 23:02:42 +00001825/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001826///
1827/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001828static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1829 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001830 // If we're returning 'self', kill the initial retain. This is a
1831 // heuristic attempt to "encourage correctness" in the really unfortunate
1832 // case where we have a return of self during a dealloc and we desperately
1833 // need to avoid the possible autorelease.
1834 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1835 return self;
1836
John McCall31168b02011-06-15 23:02:42 +00001837 // At -O0, try to emit a fused retain/autorelease.
1838 if (CGF.shouldUseFusedARCCalls())
1839 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1840 return fused;
1841
1842 return CGF.EmitARCAutoreleaseReturnValue(result);
1843}
1844
John McCall6e1c0122012-01-29 02:35:02 +00001845/// Heuristically search for a dominating store to the return-value slot.
1846static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1847 // If there are multiple uses of the return-value slot, just check
1848 // for something immediately preceding the IP. Sometimes this can
1849 // happen with how we generate implicit-returns; it can also happen
1850 // with noreturn cleanups.
1851 if (!CGF.ReturnValue->hasOneUse()) {
1852 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001853 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001854 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001855 if (!store) return nullptr;
1856 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001857 assert(!store->isAtomic() && !store->isVolatile()); // see below
1858 return store;
1859 }
1860
1861 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001862 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001863 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001864
1865 // These aren't actually possible for non-coerced returns, and we
1866 // only care about non-coerced returns on this code path.
1867 assert(!store->isAtomic() && !store->isVolatile());
1868
1869 // Now do a first-and-dirty dominance check: just walk up the
1870 // single-predecessors chain from the current insertion point.
1871 llvm::BasicBlock *StoreBB = store->getParent();
1872 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1873 while (IP != StoreBB) {
1874 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001875 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001876 }
1877
1878 // Okay, the store's basic block dominates the insertion point; we
1879 // can do our thing.
1880 return store;
1881}
1882
Adrian Prantl3be10542013-05-02 17:30:20 +00001883void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001884 bool EmitRetDbgLoc,
1885 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001886 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001887 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001888 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001889 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001890 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001891
Dan Gohman481e40c2010-07-20 20:13:52 +00001892 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00001893 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00001894 QualType RetTy = FI.getReturnType();
1895 const ABIArgInfo &RetAI = FI.getReturnInfo();
1896
1897 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001898 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001899 // Aggregrates get evaluated directly into the destination. Sometimes we
1900 // need to return the sret value in a register, though.
1901 assert(hasAggregateEvaluationKind(RetTy));
1902 if (RetAI.getInAllocaSRet()) {
1903 llvm::Function::arg_iterator EI = CurFn->arg_end();
1904 --EI;
1905 llvm::Value *ArgStruct = EI;
1906 llvm::Value *SRet =
1907 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1908 RV = Builder.CreateLoad(SRet, "sret");
1909 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001910 break;
1911
Daniel Dunbar03816342010-08-21 02:24:36 +00001912 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00001913 auto AI = CurFn->arg_begin();
1914 if (RetAI.isSRetAfterThis())
1915 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00001916 switch (getEvaluationKind(RetTy)) {
1917 case TEK_Complex: {
1918 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001919 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1920 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00001921 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00001922 /*isInit*/ true);
1923 break;
1924 }
1925 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001926 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001927 break;
1928 case TEK_Scalar:
1929 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00001930 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00001931 /*isInit*/ true);
1932 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001933 }
1934 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001935 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001936
1937 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001938 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001939 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1940 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001941 // The internal return value temp always will have pointer-to-return-type
1942 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001943
John McCall6e1c0122012-01-29 02:35:02 +00001944 // If there is a dominating store to ReturnValue, we can elide
1945 // the load, zap the store, and usually zap the alloca.
1946 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001947 // Reuse the debug location from the store unless there is
1948 // cleanup code to be emitted between the store and return
1949 // instruction.
1950 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001951 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001952 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001953 RV = SI->getValueOperand();
1954 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001955
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001956 // If that was the only use of the return value, nuke it as well now.
1957 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1958 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00001959 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001960 }
John McCall6e1c0122012-01-29 02:35:02 +00001961
1962 // Otherwise, we have to do a simple load.
1963 } else {
1964 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001965 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001966 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001967 llvm::Value *V = ReturnValue;
1968 // If the value is offset in memory, apply the offset now.
1969 if (unsigned Offs = RetAI.getDirectOffset()) {
1970 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1971 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001972 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001973 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1974 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001975
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001976 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001977 }
John McCall31168b02011-06-15 23:02:42 +00001978
1979 // In ARC, end functions that return a retainable type with a call
1980 // to objc_autoreleaseReturnValue.
1981 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001982 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001983 !FI.isReturnsRetained() &&
1984 RetTy->isObjCRetainableType());
1985 RV = emitAutoreleaseOfResult(*this, RV);
1986 }
1987
Chris Lattner726b3d02010-06-26 23:13:19 +00001988 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001989
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001990 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001991 break;
1992
1993 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001994 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001995 }
1996
Alexey Samsonovde443c52014-08-13 00:26:40 +00001997 llvm::Instruction *Ret;
1998 if (RV) {
1999 if (SanOpts->ReturnsNonnullAttribute &&
2000 CurGD.getDecl()->hasAttr<ReturnsNonNullAttr>()) {
2001 SanitizerScope SanScope(this);
2002 llvm::Value *Cond =
2003 Builder.CreateICmpNE(RV, llvm::Constant::getNullValue(RV->getType()));
2004 llvm::Constant *StaticData[] = {
2005 EmitCheckSourceLocation(EndLoc)
2006 };
2007 EmitCheck(Cond, "nonnull_return", StaticData, ArrayRef<llvm::Value *>(),
2008 CRK_Recoverable);
2009 }
2010 Ret = Builder.CreateRet(RV);
2011 } else {
2012 Ret = Builder.CreateRetVoid();
2013 }
2014
Devang Patel65497582010-07-21 18:08:50 +00002015 if (!RetDbgLoc.isUnknown())
2016 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002017}
2018
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002019static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2020 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2021 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2022}
2023
2024static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2025 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2026 // placeholders.
2027 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2028 llvm::Value *Placeholder =
2029 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2030 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2031 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2032 Ty.getQualifiers(),
2033 AggValueSlot::IsNotDestructed,
2034 AggValueSlot::DoesNotNeedGCBarriers,
2035 AggValueSlot::IsNotAliased);
2036}
2037
John McCall32ea9692011-03-11 20:59:21 +00002038void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002039 const VarDecl *param,
2040 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002041 // StartFunction converted the ABI-lowered parameter(s) into a
2042 // local alloca. We need to turn that into an r-value suitable
2043 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002044 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002045
John McCall32ea9692011-03-11 20:59:21 +00002046 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002047
John McCall23f66262010-05-26 22:34:26 +00002048 // For the most part, we just need to load the alloca, except:
2049 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002050 // 2) references to non-scalars are pointers directly to the aggregate.
2051 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002052 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002053 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002054 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002055
2056 // Locals which are references to scalars are represented
2057 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002058 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002059 }
2060
Reid Klecknerab2090d2014-07-26 01:34:32 +00002061 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2062 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002063
Nick Lewycky2d84e842013-10-02 02:29:49 +00002064 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002065}
2066
John McCall31168b02011-06-15 23:02:42 +00002067static bool isProvablyNull(llvm::Value *addr) {
2068 return isa<llvm::ConstantPointerNull>(addr);
2069}
2070
2071static bool isProvablyNonNull(llvm::Value *addr) {
2072 return isa<llvm::AllocaInst>(addr);
2073}
2074
2075/// Emit the actual writing-back of a writeback.
2076static void emitWriteback(CodeGenFunction &CGF,
2077 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002078 const LValue &srcLV = writeback.Source;
2079 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002080 assert(!isProvablyNull(srcAddr) &&
2081 "shouldn't have writeback for provably null argument");
2082
Craig Topper8a13c412014-05-21 05:09:00 +00002083 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002084
2085 // If the argument wasn't provably non-null, we need to null check
2086 // before doing the store.
2087 bool provablyNonNull = isProvablyNonNull(srcAddr);
2088 if (!provablyNonNull) {
2089 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2090 contBB = CGF.createBasicBlock("icr.done");
2091
2092 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2093 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2094 CGF.EmitBlock(writebackBB);
2095 }
2096
2097 // Load the value to writeback.
2098 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2099
2100 // Cast it back, in case we're writing an id to a Foo* or something.
2101 value = CGF.Builder.CreateBitCast(value,
2102 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2103 "icr.writeback-cast");
2104
2105 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002106
2107 // If we have a "to use" value, it's something we need to emit a use
2108 // of. This has to be carefully threaded in: if it's done after the
2109 // release it's potentially undefined behavior (and the optimizer
2110 // will ignore it), and if it happens before the retain then the
2111 // optimizer could move the release there.
2112 if (writeback.ToUse) {
2113 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2114
2115 // Retain the new value. No need to block-copy here: the block's
2116 // being passed up the stack.
2117 value = CGF.EmitARCRetainNonBlock(value);
2118
2119 // Emit the intrinsic use here.
2120 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2121
2122 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002123 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002124
2125 // Put the new value in place (primitively).
2126 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2127
2128 // Release the old value.
2129 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2130
2131 // Otherwise, we can just do a normal lvalue store.
2132 } else {
2133 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2134 }
John McCall31168b02011-06-15 23:02:42 +00002135
2136 // Jump to the continuation block.
2137 if (!provablyNonNull)
2138 CGF.EmitBlock(contBB);
2139}
2140
2141static void emitWritebacks(CodeGenFunction &CGF,
2142 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002143 for (const auto &I : args.writebacks())
2144 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002145}
2146
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002147static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2148 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002149 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002150 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2151 CallArgs.getCleanupsToDeactivate();
2152 // Iterate in reverse to increase the likelihood of popping the cleanup.
2153 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2154 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2155 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2156 I->IsActiveIP->eraseFromParent();
2157 }
2158}
2159
John McCalleff18842013-03-23 02:35:54 +00002160static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2161 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2162 if (uop->getOpcode() == UO_AddrOf)
2163 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002164 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002165}
2166
John McCall31168b02011-06-15 23:02:42 +00002167/// Emit an argument that's being passed call-by-writeback. That is,
2168/// we are passing the address of
2169static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2170 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002171 LValue srcLV;
2172
2173 // Make an optimistic effort to emit the address as an l-value.
2174 // This can fail if the the argument expression is more complicated.
2175 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2176 srcLV = CGF.EmitLValue(lvExpr);
2177
2178 // Otherwise, just emit it as a scalar.
2179 } else {
2180 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2181
2182 QualType srcAddrType =
2183 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2184 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2185 }
2186 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002187
2188 // The dest and src types don't necessarily match in LLVM terms
2189 // because of the crazy ObjC compatibility rules.
2190
Chris Lattner2192fe52011-07-18 04:24:23 +00002191 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002192 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2193
2194 // If the address is a constant null, just pass the appropriate null.
2195 if (isProvablyNull(srcAddr)) {
2196 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2197 CRE->getType());
2198 return;
2199 }
2200
John McCall31168b02011-06-15 23:02:42 +00002201 // Create the temporary.
2202 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2203 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002204 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2205 // and that cleanup will be conditional if we can't prove that the l-value
2206 // isn't null, so we need to register a dominating point so that the cleanups
2207 // system will make valid IR.
2208 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2209
John McCall31168b02011-06-15 23:02:42 +00002210 // Zero-initialize it if we're not doing a copy-initialization.
2211 bool shouldCopy = CRE->shouldCopy();
2212 if (!shouldCopy) {
2213 llvm::Value *null =
2214 llvm::ConstantPointerNull::get(
2215 cast<llvm::PointerType>(destType->getElementType()));
2216 CGF.Builder.CreateStore(null, temp);
2217 }
Craig Topper8a13c412014-05-21 05:09:00 +00002218
2219 llvm::BasicBlock *contBB = nullptr;
2220 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002221
2222 // If the address is *not* known to be non-null, we need to switch.
2223 llvm::Value *finalArgument;
2224
2225 bool provablyNonNull = isProvablyNonNull(srcAddr);
2226 if (provablyNonNull) {
2227 finalArgument = temp;
2228 } else {
2229 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2230
2231 finalArgument = CGF.Builder.CreateSelect(isNull,
2232 llvm::ConstantPointerNull::get(destType),
2233 temp, "icr.argument");
2234
2235 // If we need to copy, then the load has to be conditional, which
2236 // means we need control flow.
2237 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002238 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002239 contBB = CGF.createBasicBlock("icr.cont");
2240 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2241 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2242 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002243 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002244 }
2245 }
2246
Craig Topper8a13c412014-05-21 05:09:00 +00002247 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002248
John McCall31168b02011-06-15 23:02:42 +00002249 // Perform a copy if necessary.
2250 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002251 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002252 assert(srcRV.isScalar());
2253
2254 llvm::Value *src = srcRV.getScalarVal();
2255 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2256 "icr.cast");
2257
2258 // Use an ordinary store, not a store-to-lvalue.
2259 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002260
2261 // If optimization is enabled, and the value was held in a
2262 // __strong variable, we need to tell the optimizer that this
2263 // value has to stay alive until we're doing the store back.
2264 // This is because the temporary is effectively unretained,
2265 // and so otherwise we can violate the high-level semantics.
2266 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2267 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2268 valueToUse = src;
2269 }
John McCall31168b02011-06-15 23:02:42 +00002270 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002271
John McCall31168b02011-06-15 23:02:42 +00002272 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002273 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002274 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002275 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002276
2277 // Make a phi for the value to intrinsically use.
2278 if (valueToUse) {
2279 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2280 "icr.to-use");
2281 phiToUse->addIncoming(valueToUse, copyBB);
2282 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2283 originBB);
2284 valueToUse = phiToUse;
2285 }
2286
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002287 condEval.end(CGF);
2288 }
John McCall31168b02011-06-15 23:02:42 +00002289
John McCalleff18842013-03-23 02:35:54 +00002290 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002291 args.add(RValue::get(finalArgument), CRE->getType());
2292}
2293
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002294void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2295 assert(!StackBase && !StackCleanup.isValid());
2296
2297 // Save the stack.
2298 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2299 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2300
2301 // Control gets really tied up in landing pads, so we have to spill the
2302 // stacksave to an alloca to avoid violating SSA form.
2303 // TODO: This is dead if we never emit the cleanup. We should create the
2304 // alloca and store lazily on the first cleanup emission.
2305 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2306 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2307 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2308 StackCleanup = CGF.EHStack.getInnermostEHScope();
2309 assert(StackCleanup.isValid());
2310}
2311
2312void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2313 if (StackBase) {
2314 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2315 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2316 // We could load StackBase from StackBaseMem, but in the non-exceptional
2317 // case we can skip it.
2318 CGF.Builder.CreateCall(F, StackBase);
2319 }
2320}
2321
Reid Kleckner739756c2013-12-04 19:23:12 +00002322void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2323 ArrayRef<QualType> ArgTypes,
2324 CallExpr::const_arg_iterator ArgBeg,
2325 CallExpr::const_arg_iterator ArgEnd,
2326 bool ForceColumnInfo) {
2327 CGDebugInfo *DI = getDebugInfo();
2328 SourceLocation CallLoc;
2329 if (DI) CallLoc = DI->getLocation();
2330
2331 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2332 // because arguments are destroyed left to right in the callee.
2333 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002334 // Insert a stack save if we're going to need any inalloca args.
2335 bool HasInAllocaArgs = false;
2336 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2337 I != E && !HasInAllocaArgs; ++I)
2338 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2339 if (HasInAllocaArgs) {
2340 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2341 Args.allocateArgumentMemory(*this);
2342 }
2343
2344 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002345 size_t CallArgsStart = Args.size();
2346 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2347 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2348 EmitCallArg(Args, *Arg, ArgTypes[I]);
2349 // Restore the debug location.
2350 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2351 }
2352
2353 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2354 // IR function.
2355 std::reverse(Args.begin() + CallArgsStart, Args.end());
2356 return;
2357 }
2358
2359 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2360 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2361 assert(Arg != ArgEnd);
2362 EmitCallArg(Args, *Arg, ArgTypes[I]);
2363 // Restore the debug location.
2364 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2365 }
2366}
2367
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002368namespace {
2369
2370struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2371 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2372 : Addr(Addr), Ty(Ty) {}
2373
2374 llvm::Value *Addr;
2375 QualType Ty;
2376
Craig Topper4f12f102014-03-12 06:41:41 +00002377 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002378 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2379 assert(!Dtor->isTrivial());
2380 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2381 /*Delegating=*/false, Addr);
2382 }
2383};
2384
2385}
2386
John McCall32ea9692011-03-11 20:59:21 +00002387void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2388 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002389 if (const ObjCIndirectCopyRestoreExpr *CRE
2390 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002391 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002392 assert(getContext().hasSameType(E->getType(), type));
2393 return emitWritebackArg(*this, args, CRE);
2394 }
2395
John McCall0a76c0c2011-08-26 18:42:59 +00002396 assert(type->isReferenceType() == E->isGLValue() &&
2397 "reference binding to unmaterialized r-value!");
2398
John McCall17054bd62011-08-26 21:08:13 +00002399 if (E->isGLValue()) {
2400 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002401 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002402 }
Mike Stump11289f42009-09-09 15:08:12 +00002403
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002404 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2405
2406 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2407 // However, we still have to push an EH-only cleanup in case we unwind before
2408 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002409 if (HasAggregateEvalKind &&
2410 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2411 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002412 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002413 AggValueSlot Slot;
2414 if (args.isUsingInAlloca())
2415 Slot = createPlaceholderSlot(*this, type);
2416 else
2417 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002418
2419 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2420 bool DestroyedInCallee =
2421 RD && RD->hasNonTrivialDestructor() &&
2422 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2423 if (DestroyedInCallee)
2424 Slot.setExternallyDestructed();
2425
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002426 EmitAggExpr(E, Slot);
2427 RValue RV = Slot.asRValue();
2428 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002429
Reid Klecknere39ee212014-05-03 00:33:28 +00002430 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002431 // Create a no-op GEP between the placeholder and the cleanup so we can
2432 // RAUW it successfully. It also serves as a marker of the first
2433 // instruction where the cleanup is active.
2434 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002435 // This unreachable is a temporary marker which will be removed later.
2436 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2437 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002438 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002439 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002440 }
2441
2442 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002443 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2444 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2445 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002446 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2447 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2448 } else {
2449 // We can't represent a misaligned lvalue in the CallArgList, so copy
2450 // to an aligned temporary now.
2451 llvm::Value *tmp = CreateMemTemp(type);
2452 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2453 L.getAlignment());
2454 args.add(RValue::getAggregate(tmp), type);
2455 }
Eli Friedmandf968192011-05-26 00:10:27 +00002456 return;
2457 }
2458
John McCall32ea9692011-03-11 20:59:21 +00002459 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002460}
2461
Dan Gohman515a60d2012-02-16 00:57:37 +00002462// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2463// optimizer it can aggressively ignore unwind edges.
2464void
2465CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2466 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2467 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2468 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2469 CGM.getNoObjCARCExceptionsMetadata());
2470}
2471
John McCall882987f2013-02-28 19:01:20 +00002472/// Emits a call to the given no-arguments nounwind runtime function.
2473llvm::CallInst *
2474CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2475 const llvm::Twine &name) {
2476 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2477}
2478
2479/// Emits a call to the given nounwind runtime function.
2480llvm::CallInst *
2481CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2482 ArrayRef<llvm::Value*> args,
2483 const llvm::Twine &name) {
2484 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2485 call->setDoesNotThrow();
2486 return call;
2487}
2488
2489/// Emits a simple call (never an invoke) to the given no-arguments
2490/// runtime function.
2491llvm::CallInst *
2492CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2493 const llvm::Twine &name) {
2494 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2495}
2496
2497/// Emits a simple call (never an invoke) to the given runtime
2498/// function.
2499llvm::CallInst *
2500CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2501 ArrayRef<llvm::Value*> args,
2502 const llvm::Twine &name) {
2503 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2504 call->setCallingConv(getRuntimeCC());
2505 return call;
2506}
2507
2508/// Emits a call or invoke to the given noreturn runtime function.
2509void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2510 ArrayRef<llvm::Value*> args) {
2511 if (getInvokeDest()) {
2512 llvm::InvokeInst *invoke =
2513 Builder.CreateInvoke(callee,
2514 getUnreachableBlock(),
2515 getInvokeDest(),
2516 args);
2517 invoke->setDoesNotReturn();
2518 invoke->setCallingConv(getRuntimeCC());
2519 } else {
2520 llvm::CallInst *call = Builder.CreateCall(callee, args);
2521 call->setDoesNotReturn();
2522 call->setCallingConv(getRuntimeCC());
2523 Builder.CreateUnreachable();
2524 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002525 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002526}
2527
2528/// Emits a call or invoke instruction to the given nullary runtime
2529/// function.
2530llvm::CallSite
2531CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2532 const Twine &name) {
2533 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2534}
2535
2536/// Emits a call or invoke instruction to the given runtime function.
2537llvm::CallSite
2538CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2539 ArrayRef<llvm::Value*> args,
2540 const Twine &name) {
2541 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2542 callSite.setCallingConv(getRuntimeCC());
2543 return callSite;
2544}
2545
2546llvm::CallSite
2547CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2548 const Twine &Name) {
2549 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2550}
2551
John McCallbd309292010-07-06 01:34:17 +00002552/// Emits a call or invoke instruction to the given function, depending
2553/// on the current state of the EH stack.
2554llvm::CallSite
2555CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002556 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002557 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002558 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002559
Dan Gohman515a60d2012-02-16 00:57:37 +00002560 llvm::Instruction *Inst;
2561 if (!InvokeDest)
2562 Inst = Builder.CreateCall(Callee, Args, Name);
2563 else {
2564 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2565 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2566 EmitBlock(ContBB);
2567 }
2568
2569 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2570 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002571 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002572 AddObjCARCExceptionMetadata(Inst);
2573
2574 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002575}
2576
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002577static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2578 llvm::FunctionType *FTy) {
2579 if (ArgNo < FTy->getNumParams())
2580 assert(Elt->getType() == FTy->getParamType(ArgNo));
2581 else
2582 assert(FTy->isVarArg());
2583 ++ArgNo;
2584}
2585
Chris Lattnerd59d8672011-07-12 06:29:11 +00002586void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002587 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002588 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002589 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2590 unsigned NumElts = AT->getSize().getZExtValue();
2591 QualType EltTy = AT->getElementType();
2592 llvm::Value *Addr = RV.getAggregateAddr();
2593 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2594 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002595 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002596 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002597 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002598 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002599 RecordDecl *RD = RT->getDecl();
2600 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002601 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002602
2603 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002604 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002605 CharUnits UnionSize = CharUnits::Zero();
2606
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002607 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002608 assert(!FD->isBitField() &&
2609 "Cannot expand structure with bit-field members.");
2610 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2611 if (UnionSize < FieldSize) {
2612 UnionSize = FieldSize;
2613 LargestFD = FD;
2614 }
2615 }
2616 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002617 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002618 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2619 }
2620 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002621 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002622 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002623 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2624 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002625 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002626 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002627 ComplexPairTy CV = RV.getComplexVal();
2628 Args.push_back(CV.first);
2629 Args.push_back(CV.second);
2630 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002631 assert(RV.isScalar() &&
2632 "Unexpected non-scalar rvalue during struct expansion.");
2633
2634 // Insert a bitcast as needed.
2635 llvm::Value *V = RV.getScalarVal();
2636 if (Args.size() < IRFuncTy->getNumParams() &&
2637 V->getType() != IRFuncTy->getParamType(Args.size()))
2638 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2639
2640 Args.push_back(V);
2641 }
2642}
2643
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002644/// \brief Store a non-aggregate value to an address to initialize it. For
2645/// initialization, a non-atomic store will be used.
2646static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2647 LValue Dst) {
2648 if (Src.isScalar())
2649 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2650 else
2651 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2652}
2653
2654void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2655 llvm::Value *New) {
2656 DeferredReplacements.push_back(std::make_pair(Old, New));
2657}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002658
Daniel Dunbard931a872009-02-02 22:03:45 +00002659RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002660 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002661 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002662 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002663 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002664 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002665 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002666 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002667
2668 // Handle struct-return functions by passing a pointer to the
2669 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002670 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002671 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002672
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002673 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2674 unsigned IRArgNo = 0;
2675 llvm::FunctionType *IRFuncTy =
2676 cast<llvm::FunctionType>(
2677 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002678
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002679 // If we're using inalloca, insert the allocation after the stack save.
2680 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002681 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002682 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002683 llvm::Instruction *IP = CallArgs.getStackBase();
2684 llvm::AllocaInst *AI;
2685 if (IP) {
2686 IP = IP->getNextNode();
2687 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2688 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002689 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002690 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002691 AI->setUsedWithInAlloca(true);
2692 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2693 ArgMemory = AI;
2694 }
2695
Chris Lattner4ca97c32009-06-13 00:26:38 +00002696 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002697 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002698 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002699 bool SwapThisWithSRet = false;
2700 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002701 SRetPtr = ReturnValue.getValue();
2702 if (!SRetPtr)
2703 SRetPtr = CreateMemTemp(RetTy);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002704 if (RetAI.isIndirect()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002705 Args.push_back(SRetPtr);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002706 SwapThisWithSRet = RetAI.isSRetAfterThis();
2707 if (SwapThisWithSRet)
2708 IRArgNo = 1;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002709 checkArgMatches(SRetPtr, IRArgNo, IRFuncTy);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002710 if (SwapThisWithSRet)
2711 IRArgNo = 0;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002712 } else {
2713 llvm::Value *Addr =
2714 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2715 Builder.CreateStore(SRetPtr, Addr);
2716 }
Anders Carlsson17490832009-12-24 20:40:36 +00002717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002719 assert(CallInfo.arg_size() == CallArgs.size() &&
2720 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002721 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002722 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002723 I != E; ++I, ++info_it) {
2724 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002725 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002726
Reid Kleckner37abaca2014-05-09 22:46:15 +00002727 // Skip 'sret' if it came second.
2728 if (IRArgNo == 1 && SwapThisWithSRet)
2729 ++IRArgNo;
2730
John McCall47fb9502013-03-07 21:37:08 +00002731 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002732
2733 // Insert a padding argument to ensure proper alignment.
2734 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2735 Args.push_back(llvm::UndefValue::get(PaddingType));
2736 ++IRArgNo;
2737 }
2738
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002739 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002740 case ABIArgInfo::InAlloca: {
2741 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2742 if (RV.isAggregate()) {
2743 // Replace the placeholder with the appropriate argument slot GEP.
2744 llvm::Instruction *Placeholder =
2745 cast<llvm::Instruction>(RV.getAggregateAddr());
2746 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2747 Builder.SetInsertPoint(Placeholder);
2748 llvm::Value *Addr = Builder.CreateStructGEP(
2749 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2750 Builder.restoreIP(IP);
2751 deferPlaceholderReplacement(Placeholder, Addr);
2752 } else {
2753 // Store the RValue into the argument struct.
2754 llvm::Value *Addr =
2755 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002756 unsigned AS = Addr->getType()->getPointerAddressSpace();
2757 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2758 // There are some cases where a trivial bitcast is not avoidable. The
2759 // definition of a type later in a translation unit may change it's type
2760 // from {}* to (%struct.foo*)*.
2761 if (Addr->getType() != MemType)
2762 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002763 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2764 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2765 }
2766 break; // Don't increment IRArgNo!
2767 }
2768
Daniel Dunbar03816342010-08-21 02:24:36 +00002769 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002770 if (RV.isScalar() || RV.isComplex()) {
2771 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002772 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2773 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2774 AI->setAlignment(ArgInfo.getIndirectAlign());
2775 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002776
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002777 LValue argLV = MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
2778 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002779
2780 // Validate argument match.
2781 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002782 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002783 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002784 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002785 // 1. If the argument is not byval, and we are required to copy the
2786 // source. (This case doesn't occur on any common architecture.)
2787 // 2. If the argument is byval, RV is not sufficiently aligned, and
2788 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002789 // 3. If the argument is byval, but RV is located in an address space
2790 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002791 llvm::Value *Addr = RV.getAggregateAddr();
2792 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002793 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002794 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2795 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2796 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002797 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002798 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002799 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2800 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002801 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002802 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2803 if (Align > AI->getAlignment())
2804 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002805 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002806 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002807
2808 // Validate argument match.
2809 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002810 } else {
2811 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002812 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002813
2814 // Validate argument match.
2815 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002816 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002817 }
2818 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002819 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002820
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002821 case ABIArgInfo::Ignore:
2822 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002823
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002824 case ABIArgInfo::Extend:
2825 case ABIArgInfo::Direct: {
2826 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002827 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2828 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002829 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002830 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002831 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002832 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002833 V = Builder.CreateLoad(RV.getAggregateAddr());
2834
Chris Lattner3ce86682011-07-12 04:53:39 +00002835 // If the argument doesn't match, perform a bitcast to coerce it. This
2836 // can happen due to trivial type mismatches.
2837 if (IRArgNo < IRFuncTy->getNumParams() &&
2838 V->getType() != IRFuncTy->getParamType(IRArgNo))
2839 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002840 Args.push_back(V);
2841
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002842 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002843 break;
2844 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002845
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002846 // FIXME: Avoid the conversion through memory if possible.
2847 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002848 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002849 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002850 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002851 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002852 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002853 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002854
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002855 // If the value is offset in memory, apply the offset now.
2856 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2857 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2858 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002859 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002860 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2861
2862 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002863
Chris Lattner3dd716c2010-06-28 23:44:11 +00002864 // If the coerce-to type is a first class aggregate, we flatten it and
2865 // pass the elements. Either way is semantically identical, but fast-isel
2866 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00002867 // We cannot do this for functions using the AAPCS calling convention,
2868 // as structures are treated differently by that calling convention.
2869 llvm::StructType *STy =
2870 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
2871 if (STy && !isAAPCSVFP(CallInfo, getTarget())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002872 llvm::Type *SrcTy =
2873 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2874 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2875 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2876
2877 // If the source type is smaller than the destination type of the
2878 // coerce-to logic, copy the source value into a temp alloca the size
2879 // of the destination type to allow loading all of it. The bits past
2880 // the source value are left undef.
2881 if (SrcSize < DstSize) {
2882 llvm::AllocaInst *TempAlloca
2883 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2884 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2885 SrcPtr = TempAlloca;
2886 } else {
2887 SrcPtr = Builder.CreateBitCast(SrcPtr,
2888 llvm::PointerType::getUnqual(STy));
2889 }
2890
Chris Lattnerceddafb2010-07-05 20:41:41 +00002891 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2892 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002893 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2894 // We don't know what we're loading from.
2895 LI->setAlignment(1);
2896 Args.push_back(LI);
Alexey Samsonov3551e312014-08-13 20:06:24 +00002897
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002898 // Validate argument match.
2899 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002900 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002901 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002902 // In the simple case, just pass the coerced loaded value.
2903 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2904 *this));
Alexey Samsonov3551e312014-08-13 20:06:24 +00002905
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002906 // Validate argument match.
2907 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002908 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002909
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002910 break;
2911 }
2912
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002913 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002914 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002915 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002916 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002917 }
2918 }
Mike Stump11289f42009-09-09 15:08:12 +00002919
Reid Kleckner37abaca2014-05-09 22:46:15 +00002920 if (SwapThisWithSRet)
2921 std::swap(Args[0], Args[1]);
2922
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002923 if (ArgMemory) {
2924 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00002925 if (CallInfo.isVariadic()) {
2926 // When passing non-POD arguments by value to variadic functions, we will
2927 // end up with a variadic prototype and an inalloca call site. In such
2928 // cases, we can't do any parameter mismatch checks. Give up and bitcast
2929 // the callee.
2930 unsigned CalleeAS =
2931 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
2932 Callee = Builder.CreateBitCast(
2933 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
2934 } else {
2935 llvm::Type *LastParamTy =
2936 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2937 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002938#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00002939 // Assert that these structs have equivalent element types.
2940 llvm::StructType *FullTy = CallInfo.getArgStruct();
2941 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
2942 cast<llvm::PointerType>(LastParamTy)->getElementType());
2943 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
2944 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
2945 DE = DeclaredTy->element_end(),
2946 FI = FullTy->element_begin();
2947 DI != DE; ++DI, ++FI)
2948 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002949#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00002950 Arg = Builder.CreateBitCast(Arg, LastParamTy);
2951 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002952 }
2953 Args.push_back(Arg);
2954 }
2955
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002956 if (!CallArgs.getCleanupsToDeactivate().empty())
2957 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2958
Chris Lattner4ca97c32009-06-13 00:26:38 +00002959 // If the callee is a bitcast of a function to a varargs pointer to function
2960 // type, check to see if we can remove the bitcast. This handles some cases
2961 // with unprototyped functions.
2962 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2963 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002964 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2965 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002966 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002967 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002968
Chris Lattner4ca97c32009-06-13 00:26:38 +00002969 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2970 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002971 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002972 ActualFT->getNumParams() == Args.size() &&
2973 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002974 bool ArgsMatch = true;
2975 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2976 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2977 ArgsMatch = false;
2978 break;
2979 }
Mike Stump11289f42009-09-09 15:08:12 +00002980
Chris Lattner4ca97c32009-06-13 00:26:38 +00002981 // Strip the cast if we can get away with it. This is a nice cleanup,
2982 // but also allows us to inline the function at -O0 if it is marked
2983 // always_inline.
2984 if (ArgsMatch)
2985 Callee = CalleeF;
2986 }
2987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002989 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002990 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002991 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2992 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002993 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002994 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002995
Craig Topper8a13c412014-05-21 05:09:00 +00002996 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00002997 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2998 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002999 InvokeDest = getInvokeDest();
3000
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003001 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003002 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00003003 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00003004 } else {
3005 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00003006 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00003007 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003008 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003009 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003010 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003011
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003012 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3013 !CS.hasFnAttr(llvm::Attribute::NoInline))
3014 Attrs =
3015 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3016 llvm::Attribute::AlwaysInline);
3017
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003018 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003019 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003020
Dan Gohman515a60d2012-02-16 00:57:37 +00003021 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3022 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003023 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003024 AddObjCARCExceptionMetadata(CS.getInstruction());
3025
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003026 // If the call doesn't return, finish the basic block and clear the
3027 // insertion point; this allows the rest of IRgen to discard
3028 // unreachable code.
3029 if (CS.doesNotReturn()) {
3030 Builder.CreateUnreachable();
3031 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003032
Mike Stump18bb9282009-05-16 07:57:57 +00003033 // FIXME: For now, emit a dummy basic block because expr emitters in
3034 // generally are not ready to handle emitting expressions at unreachable
3035 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003036 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003037
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003038 // Return a reasonable RValue.
3039 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003040 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003041
3042 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003043 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003044 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003045
John McCall31168b02011-06-15 23:02:42 +00003046 // Emit any writebacks immediately. Arguably this should happen
3047 // after any return-value munging.
3048 if (CallArgs.hasWritebacks())
3049 emitWritebacks(*this, CallArgs);
3050
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003051 // The stack cleanup for inalloca arguments has to run out of the normal
3052 // lexical order, so deactivate it and run it manually here.
3053 CallArgs.freeArgumentMemory(*this);
3054
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003055 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003056 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00003057 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003058 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003059
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003060 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00003061 // If we are ignoring an argument that had a result, make sure to
3062 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00003063 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003064
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003065 case ABIArgInfo::Extend:
3066 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00003067 llvm::Type *RetIRTy = ConvertType(RetTy);
3068 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00003069 switch (getEvaluationKind(RetTy)) {
3070 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003071 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3072 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3073 return RValue::getComplex(std::make_pair(Real, Imag));
3074 }
John McCall47fb9502013-03-07 21:37:08 +00003075 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003076 llvm::Value *DestPtr = ReturnValue.getValue();
3077 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003078
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003079 if (!DestPtr) {
3080 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3081 DestIsVolatile = false;
3082 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00003083 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003084 return RValue::getAggregate(DestPtr);
3085 }
John McCall47fb9502013-03-07 21:37:08 +00003086 case TEK_Scalar: {
3087 // If the argument doesn't match, perform a bitcast to coerce it. This
3088 // can happen due to trivial type mismatches.
3089 llvm::Value *V = CI;
3090 if (V->getType() != RetIRTy)
3091 V = Builder.CreateBitCast(V, RetIRTy);
3092 return RValue::get(V);
3093 }
3094 }
3095 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003096 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003097
Anders Carlsson17490832009-12-24 20:40:36 +00003098 llvm::Value *DestPtr = ReturnValue.getValue();
3099 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003100
Anders Carlsson17490832009-12-24 20:40:36 +00003101 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00003102 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00003103 DestIsVolatile = false;
3104 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003105
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003106 // If the value is offset in memory, apply the offset now.
3107 llvm::Value *StorePtr = DestPtr;
3108 if (unsigned Offs = RetAI.getDirectOffset()) {
3109 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3110 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003111 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003112 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3113 }
3114 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003115
Nick Lewycky2d84e842013-10-02 02:29:49 +00003116 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00003117 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003118
Daniel Dunbard3674e62008-09-11 01:48:57 +00003119 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00003120 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003121 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003122
David Blaikie83d382b2011-09-23 05:06:16 +00003123 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003124}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003125
3126/* VarArg handling */
3127
3128llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3129 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3130}