blob: cb035d39c58926dd1f647de8297c65ec911f2442 [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;
Reid Klecknerd7857f02014-10-24 17:42:17 +000050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000053 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000054 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
55 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000056 }
57}
58
John McCall8ee376f2010-02-24 07:14:12 +000059/// Derives the 'this' type for codegen purposes, i.e. ignoring method
60/// qualification.
61/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000062static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
63 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
64 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000065}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000068static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
69 return MD->getType()->getCanonicalTypeUnqualified()
70 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000071}
72
73/// Returns the "extra-canonicalized" return type, which discards
74/// qualifiers on the return type. Codegen doesn't care about them,
75/// and it makes ABI code a little easier to be able to assume that
76/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000077static CanQualType GetReturnType(QualType RetTy) {
78 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
John McCall8dda7b22012-07-07 06:41:13 +000081/// Arrange the argument and result information for a value of the given
82/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000083const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000084CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000085 // When translating an unprototyped function type, always use a
86 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000087 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000088 /*instanceMethod=*/false,
89 /*chainCall=*/false, None,
90 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000091}
92
John McCall8dda7b22012-07-07 06:41:13 +000093/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000094/// type, on top of any implicit parameters already stored.
95static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +000096arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000097 SmallVectorImpl<CanQualType> &prefix,
98 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000099 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000100 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +0000101 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
102 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +0000103 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000104 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
105 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000106 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000107}
108
John McCalla729c622012-02-17 03:33:10 +0000109/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000110/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000111const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000112CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000113 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000114 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
115 FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000116}
117
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000118static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000119 // Set the appropriate calling convention for the Function.
120 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000121 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000122
123 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000124 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000125
Douglas Gregora941dca2010-05-18 16:57:00 +0000126 if (D->hasAttr<ThisCallAttr>())
127 return CC_X86ThisCall;
128
Reid Klecknerd7857f02014-10-24 17:42:17 +0000129 if (D->hasAttr<VectorCallAttr>())
130 return CC_X86VectorCall;
131
Dawn Perchik335e16b2010-09-03 01:29:35 +0000132 if (D->hasAttr<PascalAttr>())
133 return CC_X86Pascal;
134
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000135 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
136 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
137
Derek Schuffa2020962012-10-16 22:30:41 +0000138 if (D->hasAttr<PnaclCallAttr>())
139 return CC_PnaclCall;
140
Guy Benyeif0a014b2012-12-25 08:53:55 +0000141 if (D->hasAttr<IntelOclBiccAttr>())
142 return CC_IntelOclBicc;
143
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000144 if (D->hasAttr<MSABIAttr>())
145 return IsWindows ? CC_C : CC_X86_64Win64;
146
147 if (D->hasAttr<SysVABIAttr>())
148 return IsWindows ? CC_X86_64SysV : CC_C;
149
John McCallab26cfa2010-02-05 21:31:56 +0000150 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000151}
152
John McCalla729c622012-02-17 03:33:10 +0000153/// Arrange the argument and result information for a call to an
154/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000155/// (Zero value of RD means we don't have any meaningful "this" argument type,
156/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000157/// The member function must be an ordinary function, i.e. not a
158/// constructor or destructor.
159const CGFunctionInfo &
160CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
161 const FunctionProtoType *FTP) {
162 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000163
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000164 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000165 if (RD)
166 argTypes.push_back(GetThisType(Context, RD));
167 else
168 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000169
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000170 return ::arrangeLLVMFunctionInfo(
171 *this, true, argTypes,
172 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000173}
174
John McCalla729c622012-02-17 03:33:10 +0000175/// Arrange the argument and result information for a declaration or
176/// definition of the given C++ non-static member function. The
177/// member function must be an ordinary function, i.e. not a
178/// constructor or destructor.
179const CGFunctionInfo &
180CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000181 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000182 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
183
John McCalla729c622012-02-17 03:33:10 +0000184 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000185
John McCalla729c622012-02-17 03:33:10 +0000186 if (MD->isInstance()) {
187 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000188 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000190 }
191
John McCall8dda7b22012-07-07 06:41:13 +0000192 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000193}
194
John McCalla729c622012-02-17 03:33:10 +0000195const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000196CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
197 StructorType Type) {
198
John McCalla729c622012-02-17 03:33:10 +0000199 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000200 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000201
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000202 GlobalDecl GD;
203 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
204 GD = GlobalDecl(CD, toCXXCtorType(Type));
205 } else {
206 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
207 GD = GlobalDecl(DD, toCXXDtorType(Type));
208 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000209
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000210 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000211
212 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000213 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
214 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000215
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000216 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000217
218 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000219 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000220
John McCall8dda7b22012-07-07 06:41:13 +0000221 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000222 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
223 ? argTypes.front()
224 : TheCXXABI.hasMostDerivedReturn(GD)
225 ? CGM.getContext().VoidPtrTy
226 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000227 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
228 /*chainCall=*/false, argTypes, extInfo,
229 required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000230}
231
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000232/// Arrange a call to a C++ method, passing the given arguments.
233const CGFunctionInfo &
234CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
235 const CXXConstructorDecl *D,
236 CXXCtorType CtorKind,
237 unsigned ExtraArgs) {
238 // FIXME: Kill copy.
239 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000240 for (const auto &Arg : args)
241 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000242
243 CanQual<FunctionProtoType> FPT = GetFormalType(D);
244 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
245 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000246 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
247 ? ArgTypes.front()
248 : TheCXXABI.hasMostDerivedReturn(GD)
249 ? CGM.getContext().VoidPtrTy
250 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000251
252 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000253 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
254 /*chainCall=*/false, ArgTypes, Info,
255 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000256}
257
John McCalla729c622012-02-17 03:33:10 +0000258/// Arrange the argument and result information for the declaration or
259/// definition of the given function.
260const CGFunctionInfo &
261CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000262 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000263 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000264 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000265
John McCall2da83a32010-02-26 00:48:12 +0000266 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000267
John McCall2da83a32010-02-26 00:48:12 +0000268 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000269
270 // When declaring a function without a prototype, always use a
271 // non-variadic type.
272 if (isa<FunctionNoProtoType>(FTy)) {
273 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000274 return arrangeLLVMFunctionInfo(
275 noProto->getReturnType(), /*instanceMethod=*/false,
276 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000277 }
278
John McCall2da83a32010-02-26 00:48:12 +0000279 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000280 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000281}
282
John McCalla729c622012-02-17 03:33:10 +0000283/// Arrange the argument and result information for the declaration or
284/// definition of an Objective-C method.
285const CGFunctionInfo &
286CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
287 // It happens that this is the same as a call with no optional
288 // arguments, except also using the formal 'self' type.
289 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
290}
291
292/// Arrange the argument and result information for the function type
293/// through which to perform a send to the given Objective-C method,
294/// using the given receiver type. The receiver type is not always
295/// the 'self' type of the method or even an Objective-C pointer type.
296/// This is *not* the right method for actually performing such a
297/// message send, due to the possibility of optional arguments.
298const CGFunctionInfo &
299CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
300 QualType receiverType) {
301 SmallVector<CanQualType, 16> argTys;
302 argTys.push_back(Context.getCanonicalParamType(receiverType));
303 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000304 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000305 for (const auto *I : MD->params()) {
306 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000307 }
John McCall31168b02011-06-15 23:02:42 +0000308
309 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000310 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
311 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000312
David Blaikiebbafb8a2012-03-11 07:00:24 +0000313 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000314 MD->hasAttr<NSReturnsRetainedAttr>())
315 einfo = einfo.withProducesResult(true);
316
John McCalla729c622012-02-17 03:33:10 +0000317 RequiredArgs required =
318 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
319
Peter Collingbournef7706832014-12-12 23:41:25 +0000320 return arrangeLLVMFunctionInfo(
321 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
322 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000323}
324
John McCalla729c622012-02-17 03:33:10 +0000325const CGFunctionInfo &
326CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000327 // FIXME: Do we need to handle ObjCMethodDecl?
328 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000329
Anders Carlsson6710c532010-02-06 02:44:09 +0000330 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000331 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000332
333 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000334 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000335
John McCalla729c622012-02-17 03:33:10 +0000336 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000337}
338
Reid Klecknerc3473512014-08-29 21:43:29 +0000339/// Arrange a thunk that takes 'this' as the first parameter followed by
340/// varargs. Return a void pointer, regardless of the actual return type.
341/// The body of the thunk will end in a musttail call to a function of the
342/// correct type, and the caller will bitcast the function to the correct
343/// prototype.
344const CGFunctionInfo &
345CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
346 assert(MD->isVirtual() && "only virtual memptrs have thunks");
347 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
348 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000349 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
350 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000351 FTP->getExtInfo(), RequiredArgs(1));
352}
353
John McCallc818bbb2012-12-07 07:03:17 +0000354/// Arrange a call as unto a free function, except possibly with an
355/// additional number of formal parameters considered required.
356static const CGFunctionInfo &
357arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000358 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000359 const CallArgList &args,
360 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000361 unsigned numExtraRequiredArgs,
362 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000363 assert(args.size() >= numExtraRequiredArgs);
364
365 // In most cases, there are no optional arguments.
366 RequiredArgs required = RequiredArgs::All;
367
368 // If we have a variadic prototype, the required arguments are the
369 // extra prefix plus the arguments in the prototype.
370 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
371 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000372 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000373
374 // If we don't have a prototype at all, but we're supposed to
375 // explicitly use the variadic convention for unprototyped calls,
376 // treat all of the arguments as required but preserve the nominal
377 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000378 } else if (CGM.getTargetCodeGenInfo()
379 .isNoProtoCallVariadic(args,
380 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000381 required = RequiredArgs(args.size());
382 }
383
Peter Collingbournef7706832014-12-12 23:41:25 +0000384 // FIXME: Kill copy.
385 SmallVector<CanQualType, 16> argTypes;
386 for (const auto &arg : args)
387 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
388 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
389 /*instanceMethod=*/false, chainCall,
390 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000391}
392
John McCalla729c622012-02-17 03:33:10 +0000393/// Figure out the rules for calling a function with the given formal
394/// type using the given arguments. The arguments are necessary
395/// because the function might be unprototyped, in which case it's
396/// target-dependent in crazy ways.
397const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000398CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000399 const FunctionType *fnType,
400 bool chainCall) {
401 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
402 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000403}
John McCalla729c622012-02-17 03:33:10 +0000404
John McCallc818bbb2012-12-07 07:03:17 +0000405/// A block function call is essentially a free-function call with an
406/// extra implicit argument.
407const CGFunctionInfo &
408CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
409 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000410 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
411 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000412}
413
414const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000415CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
416 const CallArgList &args,
417 FunctionType::ExtInfo info,
418 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000419 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000420 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000421 for (const auto &Arg : args)
422 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000423 return arrangeLLVMFunctionInfo(
424 GetReturnType(resultType), /*instanceMethod=*/false,
425 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000426}
427
428/// Arrange a call to a C++ method, passing the given arguments.
429const CGFunctionInfo &
430CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
431 const FunctionProtoType *FPT,
432 RequiredArgs required) {
433 // FIXME: Kill copy.
434 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000435 for (const auto &Arg : args)
436 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000437
438 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000439 return arrangeLLVMFunctionInfo(
440 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
441 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000442}
443
Reid Kleckner4982b822014-01-31 22:54:50 +0000444const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
445 QualType resultType, const FunctionArgList &args,
446 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000447 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000448 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000449 for (auto Arg : args)
450 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000451
452 RequiredArgs required =
453 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000454 return arrangeLLVMFunctionInfo(
455 GetReturnType(resultType), /*instanceMethod=*/false,
456 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000457}
458
John McCalla729c622012-02-17 03:33:10 +0000459const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000460 return arrangeLLVMFunctionInfo(
461 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
462 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000463}
464
John McCalla729c622012-02-17 03:33:10 +0000465/// Arrange the argument and result information for an abstract value
466/// of a given function type. This is the method which all of the
467/// above functions ultimately defer to.
468const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000469CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000470 bool instanceMethod,
471 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000472 ArrayRef<CanQualType> argTypes,
473 FunctionType::ExtInfo info,
474 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000475 assert(std::all_of(argTypes.begin(), argTypes.end(),
476 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000477
John McCalla729c622012-02-17 03:33:10 +0000478 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000479
Daniel Dunbare0be8292009-02-03 00:07:12 +0000480 // Lookup or create unique function info.
481 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000482 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
483 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000484
Craig Topper8a13c412014-05-21 05:09:00 +0000485 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000486 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000487 if (FI)
488 return *FI;
489
John McCalla729c622012-02-17 03:33:10 +0000490 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000491 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
492 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000493 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000494
David Blaikie82e95a32014-11-19 07:49:47 +0000495 bool inserted = FunctionsBeingProcessed.insert(FI).second;
496 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000497 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000498
Daniel Dunbar313321e2009-02-03 05:31:23 +0000499 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000500 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000501
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000502 // Loop over all of the computed argument and return value info. If any of
503 // them are direct or extend without a specified coerce type, specify the
504 // default now.
John McCalla729c622012-02-17 03:33:10 +0000505 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000506 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000507 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000508
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000509 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000510 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000511 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000512
John McCalla729c622012-02-17 03:33:10 +0000513 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
514 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000515
Daniel Dunbare0be8292009-02-03 00:07:12 +0000516 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000517}
518
John McCalla729c622012-02-17 03:33:10 +0000519CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000520 bool instanceMethod,
521 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000522 const FunctionType::ExtInfo &info,
523 CanQualType resultType,
524 ArrayRef<CanQualType> argTypes,
525 RequiredArgs required) {
526 void *buffer = operator new(sizeof(CGFunctionInfo) +
527 sizeof(ArgInfo) * (argTypes.size() + 1));
528 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
529 FI->CallingConvention = llvmCC;
530 FI->EffectiveCallingConvention = llvmCC;
531 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000532 FI->InstanceMethod = instanceMethod;
533 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000534 FI->NoReturn = info.getNoReturn();
535 FI->ReturnsRetained = info.getProducesResult();
536 FI->Required = required;
537 FI->HasRegParm = info.getHasRegParm();
538 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000539 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000540 FI->NumArgs = argTypes.size();
541 FI->getArgsBuffer()[0].type = resultType;
542 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
543 FI->getArgsBuffer()[i + 1].type = argTypes[i];
544 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000545}
546
547/***/
548
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000549namespace {
550// ABIArgInfo::Expand implementation.
551
552// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
553struct TypeExpansion {
554 enum TypeExpansionKind {
555 // Elements of constant arrays are expanded recursively.
556 TEK_ConstantArray,
557 // Record fields are expanded recursively (but if record is a union, only
558 // the field with the largest size is expanded).
559 TEK_Record,
560 // For complex types, real and imaginary parts are expanded recursively.
561 TEK_Complex,
562 // All other types are not expandable.
563 TEK_None
564 };
565
566 const TypeExpansionKind Kind;
567
568 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
569 virtual ~TypeExpansion() {}
570};
571
572struct ConstantArrayExpansion : TypeExpansion {
573 QualType EltTy;
574 uint64_t NumElts;
575
576 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
577 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
578 static bool classof(const TypeExpansion *TE) {
579 return TE->Kind == TEK_ConstantArray;
580 }
581};
582
583struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000584 SmallVector<const CXXBaseSpecifier *, 1> Bases;
585
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000586 SmallVector<const FieldDecl *, 1> Fields;
587
Reid Klecknere9f6a712014-10-31 17:10:41 +0000588 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
589 SmallVector<const FieldDecl *, 1> &&Fields)
590 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000591 static bool classof(const TypeExpansion *TE) {
592 return TE->Kind == TEK_Record;
593 }
594};
595
596struct ComplexExpansion : TypeExpansion {
597 QualType EltTy;
598
599 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
600 static bool classof(const TypeExpansion *TE) {
601 return TE->Kind == TEK_Complex;
602 }
603};
604
605struct NoExpansion : TypeExpansion {
606 NoExpansion() : TypeExpansion(TEK_None) {}
607 static bool classof(const TypeExpansion *TE) {
608 return TE->Kind == TEK_None;
609 }
610};
611} // namespace
612
613static std::unique_ptr<TypeExpansion>
614getTypeExpansion(QualType Ty, const ASTContext &Context) {
615 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
616 return llvm::make_unique<ConstantArrayExpansion>(
617 AT->getElementType(), AT->getSize().getZExtValue());
618 }
619 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000620 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000621 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000622 const RecordDecl *RD = RT->getDecl();
623 assert(!RD->hasFlexibleArrayMember() &&
624 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000625 if (RD->isUnion()) {
626 // Unions can be here only in degenerative cases - all the fields are same
627 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000628 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000629 CharUnits UnionSize = CharUnits::Zero();
630
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000631 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000632 // Skip zero length bitfields.
633 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
634 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000635 assert(!FD->isBitField() &&
636 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000637 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000638 if (UnionSize < FieldSize) {
639 UnionSize = FieldSize;
640 LargestFD = FD;
641 }
642 }
643 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000644 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000645 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000646 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
647 assert(!CXXRD->isDynamicClass() &&
648 "cannot expand vtable pointers in dynamic classes");
649 for (const CXXBaseSpecifier &BS : CXXRD->bases())
650 Bases.push_back(&BS);
651 }
652
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000653 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000654 // Skip zero length bitfields.
655 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
656 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000657 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000658 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000659 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000660 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000661 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000662 return llvm::make_unique<RecordExpansion>(std::move(Bases),
663 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000664 }
665 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
666 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
667 }
668 return llvm::make_unique<NoExpansion>();
669}
670
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000671static int getExpansionSize(QualType Ty, const ASTContext &Context) {
672 auto Exp = getTypeExpansion(Ty, Context);
673 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
674 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
675 }
676 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
677 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000678 for (auto BS : RExp->Bases)
679 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000680 for (auto FD : RExp->Fields)
681 Res += getExpansionSize(FD->getType(), Context);
682 return Res;
683 }
684 if (isa<ComplexExpansion>(Exp.get()))
685 return 2;
686 assert(isa<NoExpansion>(Exp.get()));
687 return 1;
688}
689
Alexey Samsonov153004f2014-09-29 22:08:00 +0000690void
691CodeGenTypes::getExpandedTypes(QualType Ty,
692 SmallVectorImpl<llvm::Type *>::iterator &TI) {
693 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000694 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
695 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000696 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000697 }
698 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000699 for (auto BS : RExp->Bases)
700 getExpandedTypes(BS->getType(), TI);
701 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000702 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000703 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
704 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000705 *TI++ = EltTy;
706 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000707 } else {
708 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000709 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000710 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000711}
712
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000713void CodeGenFunction::ExpandTypeFromArgs(
714 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000715 assert(LV.isSimple() &&
716 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000717
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000718 auto Exp = getTypeExpansion(Ty, getContext());
719 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
720 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
721 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
722 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
723 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000724 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000725 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000726 llvm::Value *This = LV.getAddress();
727 for (const CXXBaseSpecifier *BS : RExp->Bases) {
728 // Perform a single step derived-to-base conversion.
729 llvm::Value *Base =
730 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
731 /*NullCheckValue=*/false, SourceLocation());
732 LValue SubLV = MakeAddrLValue(Base, BS->getType());
733
734 // Recurse onto bases.
735 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
736 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000737 for (auto FD : RExp->Fields) {
738 // FIXME: What are the right qualifiers here?
739 LValue SubLV = EmitLValueForField(LV, FD);
740 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000741 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000742 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000743 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000744 EmitStoreThroughLValue(RValue::get(*AI++),
745 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000746 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000747 EmitStoreThroughLValue(RValue::get(*AI++),
748 MakeAddrLValue(ImagAddr, CExp->EltTy));
749 } else {
750 assert(isa<NoExpansion>(Exp.get()));
751 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000752 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000753}
754
755void CodeGenFunction::ExpandTypeToArgs(
756 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
757 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
758 auto Exp = getTypeExpansion(Ty, getContext());
759 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
760 llvm::Value *Addr = RV.getAggregateAddr();
761 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
762 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
763 RValue EltRV =
764 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
765 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
766 }
767 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000768 llvm::Value *This = RV.getAggregateAddr();
769 for (const CXXBaseSpecifier *BS : RExp->Bases) {
770 // Perform a single step derived-to-base conversion.
771 llvm::Value *Base =
772 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
773 /*NullCheckValue=*/false, SourceLocation());
774 RValue BaseRV = RValue::getAggregate(Base);
775
776 // Recurse onto bases.
777 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
778 IRCallArgPos);
779 }
780
781 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000782 for (auto FD : RExp->Fields) {
783 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
784 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
785 IRCallArgPos);
786 }
787 } else if (isa<ComplexExpansion>(Exp.get())) {
788 ComplexPairTy CV = RV.getComplexVal();
789 IRCallArgs[IRCallArgPos++] = CV.first;
790 IRCallArgs[IRCallArgPos++] = CV.second;
791 } else {
792 assert(isa<NoExpansion>(Exp.get()));
793 assert(RV.isScalar() &&
794 "Unexpected non-scalar rvalue during struct expansion.");
795
796 // Insert a bitcast as needed.
797 llvm::Value *V = RV.getScalarVal();
798 if (IRCallArgPos < IRFuncTy->getNumParams() &&
799 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
800 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
801
802 IRCallArgs[IRCallArgPos++] = V;
803 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000804}
805
Chris Lattner895c52b2010-06-27 06:04:18 +0000806/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000807/// accessing some number of bytes out of it, try to gep into the struct to get
808/// at its inner goodness. Dive as deep as possible without entering an element
809/// with an in-memory size smaller than DstSize.
810static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000811EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000812 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000813 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000814 // We can't dive into a zero-element struct.
815 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000816
Chris Lattner2192fe52011-07-18 04:24:23 +0000817 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000818
Chris Lattner1cd66982010-06-27 05:56:15 +0000819 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +0000820 // first element is the same size as the whole struct, we can enter it. The
821 // comparison must be made on the store size and not the alloca size. Using
822 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000823 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000824 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000825 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000826 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000827 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000828
Chris Lattner1cd66982010-06-27 05:56:15 +0000829 // GEP into the first element.
830 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000831
Chris Lattner1cd66982010-06-27 05:56:15 +0000832 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000833 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000834 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000835 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000836 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000837
838 return SrcPtr;
839}
840
Chris Lattner055097f2010-06-27 06:26:04 +0000841/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
842/// are either integers or pointers. This does a truncation of the value if it
843/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000844///
845/// This behaves as if the value were coerced through memory, so on big-endian
846/// targets the high bits are preserved in a truncation, while little-endian
847/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000848static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000849 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000850 CodeGenFunction &CGF) {
851 if (Val->getType() == Ty)
852 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000853
Chris Lattner055097f2010-06-27 06:26:04 +0000854 if (isa<llvm::PointerType>(Val->getType())) {
855 // If this is Pointer->Pointer avoid conversion to and from int.
856 if (isa<llvm::PointerType>(Ty))
857 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000858
Chris Lattner055097f2010-06-27 06:26:04 +0000859 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000860 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000861 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000862
Chris Lattner2192fe52011-07-18 04:24:23 +0000863 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000864 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000865 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000866
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000867 if (Val->getType() != DestIntTy) {
868 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
869 if (DL.isBigEndian()) {
870 // Preserve the high bits on big-endian targets.
871 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000872 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
873 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
874
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000875 if (SrcSize > DstSize) {
876 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
877 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
878 } else {
879 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
880 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
881 }
882 } else {
883 // Little-endian targets preserve the low bits. No shifts required.
884 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
885 }
886 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000887
Chris Lattner055097f2010-06-27 06:26:04 +0000888 if (isa<llvm::PointerType>(Ty))
889 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
890 return Val;
891}
892
Chris Lattner1cd66982010-06-27 05:56:15 +0000893
894
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000895/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
896/// a pointer to an object of type \arg Ty.
897///
898/// This safely handles the case when the src type is smaller than the
899/// destination type; in this situation the values of bits which not
900/// present in the src are undefined.
901static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000902 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000903 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000904 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000905 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000906
Chris Lattnerd200eda2010-06-28 22:51:39 +0000907 // If SrcTy and Ty are the same, just do a load.
908 if (SrcTy == Ty)
909 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000910
Micah Villmowdd31ca12012-10-08 16:25:52 +0000911 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000912
Chris Lattner2192fe52011-07-18 04:24:23 +0000913 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000914 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000915 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
916 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000917
Micah Villmowdd31ca12012-10-08 16:25:52 +0000918 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000919
Chris Lattner055097f2010-06-27 06:26:04 +0000920 // If the source and destination are integer or pointer types, just do an
921 // extension or truncation to the desired type.
922 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
923 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
924 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
925 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
926 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000927
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000928 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000929 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000930 // Generally SrcSize is never greater than DstSize, since this means we are
931 // losing bits. However, this can happen in cases where the structure has
932 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000933 //
Mike Stump18bb9282009-05-16 07:57:57 +0000934 // FIXME: Assert that we aren't truncating non-padding bits when have access
935 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000936 llvm::Value *Casted =
937 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000938 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
939 // FIXME: Use better alignment / avoid requiring aligned load.
940 Load->setAlignment(1);
941 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000942 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000943
Chris Lattner3fcc7902010-06-27 01:06:27 +0000944 // Otherwise do coercion through memory. This is stupid, but
945 // simple.
946 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000947 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
948 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
949 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000950 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000951 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
952 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
953 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000954 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000955}
956
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000957// Function to store a first-class aggregate into memory. We prefer to
958// store the elements rather than the aggregate to be more friendly to
959// fast-isel.
960// FIXME: Do we need to recurse here?
961static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
962 llvm::Value *DestPtr, bool DestIsVolatile,
963 bool LowAlignment) {
964 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000965 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000966 dyn_cast<llvm::StructType>(Val->getType())) {
967 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
968 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
969 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
970 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
971 DestIsVolatile);
972 if (LowAlignment)
973 SI->setAlignment(1);
974 }
975 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000976 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
977 if (LowAlignment)
978 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000979 }
980}
981
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000982/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
983/// where the source and destination may have different types.
984///
985/// This safely handles the case when the src type is larger than the
986/// destination type; the upper bits of the src will be lost.
987static void CreateCoercedStore(llvm::Value *Src,
988 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000989 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000990 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000991 llvm::Type *SrcTy = Src->getType();
992 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000993 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000994 if (SrcTy == DstTy) {
995 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
996 return;
997 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000998
Micah Villmowdd31ca12012-10-08 16:25:52 +0000999 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001000
Chris Lattner2192fe52011-07-18 04:24:23 +00001001 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +00001002 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1003 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1004 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001005
Chris Lattner055097f2010-06-27 06:26:04 +00001006 // If the source and destination are integer or pointer types, just do an
1007 // extension or truncation to the desired type.
1008 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1009 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1010 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1011 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1012 return;
1013 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001014
Micah Villmowdd31ca12012-10-08 16:25:52 +00001015 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001016
Daniel Dunbar313321e2009-02-03 05:31:23 +00001017 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001018 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001019 llvm::Value *Casted =
1020 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +00001021 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001022 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001023 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001024 // Otherwise do coercion through memory. This is stupid, but
1025 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001026
1027 // Generally SrcSize is never greater than DstSize, since this means we are
1028 // losing bits. However, this can happen in cases where the structure has
1029 // additional padding, for example due to a user specified alignment.
1030 //
1031 // FIXME: Assert that we aren't truncating non-padding bits when have access
1032 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001033 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1034 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001035 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1036 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1037 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001038 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001039 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1040 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1041 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001042 }
1043}
1044
Alexey Samsonov153004f2014-09-29 22:08:00 +00001045namespace {
1046
1047/// Encapsulates information about the way function arguments from
1048/// CGFunctionInfo should be passed to actual LLVM IR function.
1049class ClangToLLVMArgMapping {
1050 static const unsigned InvalidIndex = ~0U;
1051 unsigned InallocaArgNo;
1052 unsigned SRetArgNo;
1053 unsigned TotalIRArgs;
1054
1055 /// Arguments of LLVM IR function corresponding to single Clang argument.
1056 struct IRArgs {
1057 unsigned PaddingArgIndex;
1058 // Argument is expanded to IR arguments at positions
1059 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1060 unsigned FirstArgIndex;
1061 unsigned NumberOfArgs;
1062
1063 IRArgs()
1064 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1065 NumberOfArgs(0) {}
1066 };
1067
1068 SmallVector<IRArgs, 8> ArgInfo;
1069
1070public:
1071 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1072 bool OnlyRequiredArgs = false)
1073 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1074 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1075 construct(Context, FI, OnlyRequiredArgs);
1076 }
1077
1078 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1079 unsigned getInallocaArgNo() const {
1080 assert(hasInallocaArg());
1081 return InallocaArgNo;
1082 }
1083
1084 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1085 unsigned getSRetArgNo() const {
1086 assert(hasSRetArg());
1087 return SRetArgNo;
1088 }
1089
1090 unsigned totalIRArgs() const { return TotalIRArgs; }
1091
1092 bool hasPaddingArg(unsigned ArgNo) const {
1093 assert(ArgNo < ArgInfo.size());
1094 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1095 }
1096 unsigned getPaddingArgNo(unsigned ArgNo) const {
1097 assert(hasPaddingArg(ArgNo));
1098 return ArgInfo[ArgNo].PaddingArgIndex;
1099 }
1100
1101 /// Returns index of first IR argument corresponding to ArgNo, and their
1102 /// quantity.
1103 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1104 assert(ArgNo < ArgInfo.size());
1105 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1106 ArgInfo[ArgNo].NumberOfArgs);
1107 }
1108
1109private:
1110 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1111 bool OnlyRequiredArgs);
1112};
1113
1114void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1115 const CGFunctionInfo &FI,
1116 bool OnlyRequiredArgs) {
1117 unsigned IRArgNo = 0;
1118 bool SwapThisWithSRet = false;
1119 const ABIArgInfo &RetAI = FI.getReturnInfo();
1120
1121 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1122 SwapThisWithSRet = RetAI.isSRetAfterThis();
1123 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1124 }
1125
1126 unsigned ArgNo = 0;
1127 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1128 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1129 ++I, ++ArgNo) {
1130 assert(I != FI.arg_end());
1131 QualType ArgType = I->type;
1132 const ABIArgInfo &AI = I->info;
1133 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1134 auto &IRArgs = ArgInfo[ArgNo];
1135
1136 if (AI.getPaddingType())
1137 IRArgs.PaddingArgIndex = IRArgNo++;
1138
1139 switch (AI.getKind()) {
1140 case ABIArgInfo::Extend:
1141 case ABIArgInfo::Direct: {
1142 // FIXME: handle sseregparm someday...
1143 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1144 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1145 IRArgs.NumberOfArgs = STy->getNumElements();
1146 } else {
1147 IRArgs.NumberOfArgs = 1;
1148 }
1149 break;
1150 }
1151 case ABIArgInfo::Indirect:
1152 IRArgs.NumberOfArgs = 1;
1153 break;
1154 case ABIArgInfo::Ignore:
1155 case ABIArgInfo::InAlloca:
1156 // ignore and inalloca doesn't have matching LLVM parameters.
1157 IRArgs.NumberOfArgs = 0;
1158 break;
1159 case ABIArgInfo::Expand: {
1160 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1161 break;
1162 }
1163 }
1164
1165 if (IRArgs.NumberOfArgs > 0) {
1166 IRArgs.FirstArgIndex = IRArgNo;
1167 IRArgNo += IRArgs.NumberOfArgs;
1168 }
1169
1170 // Skip over the sret parameter when it comes second. We already handled it
1171 // above.
1172 if (IRArgNo == 1 && SwapThisWithSRet)
1173 IRArgNo++;
1174 }
1175 assert(ArgNo == ArgInfo.size());
1176
1177 if (FI.usesInAlloca())
1178 InallocaArgNo = IRArgNo++;
1179
1180 TotalIRArgs = IRArgNo;
1181}
1182} // namespace
1183
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001184/***/
1185
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001186bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001187 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001188}
1189
Tim Northovere77cc392014-03-29 13:28:05 +00001190bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1191 return ReturnTypeUsesSRet(FI) &&
1192 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1193}
1194
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001195bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1196 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1197 switch (BT->getKind()) {
1198 default:
1199 return false;
1200 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001201 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001202 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001203 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001204 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001205 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001206 }
1207 }
1208
1209 return false;
1210}
1211
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001212bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1213 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1214 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1215 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001216 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001217 }
1218 }
1219
1220 return false;
1221}
1222
Chris Lattnera5f58b02011-07-09 17:41:47 +00001223llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001224 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1225 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001226}
1227
Chris Lattnera5f58b02011-07-09 17:41:47 +00001228llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001229CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001230
David Blaikie82e95a32014-11-19 07:49:47 +00001231 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1232 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001233 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001234
Alexey Samsonov153004f2014-09-29 22:08:00 +00001235 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001236 const ABIArgInfo &retAI = FI.getReturnInfo();
1237 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001238 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001239 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001240
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001241 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001242 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001243 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001244 break;
1245
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001246 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001247 if (retAI.getInAllocaSRet()) {
1248 // sret things on win32 aren't void, they return the sret pointer.
1249 QualType ret = FI.getReturnType();
1250 llvm::Type *ty = ConvertType(ret);
1251 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1252 resultType = llvm::PointerType::get(ty, addressSpace);
1253 } else {
1254 resultType = llvm::Type::getVoidTy(getLLVMContext());
1255 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001256 break;
1257
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001258 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001259 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1260 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001261 break;
1262 }
1263
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001264 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001265 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001266 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001267 }
Mike Stump11289f42009-09-09 15:08:12 +00001268
Alexey Samsonov153004f2014-09-29 22:08:00 +00001269 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1270 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1271
1272 // Add type for sret argument.
1273 if (IRFunctionArgs.hasSRetArg()) {
1274 QualType Ret = FI.getReturnType();
1275 llvm::Type *Ty = ConvertType(Ret);
1276 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1277 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1278 llvm::PointerType::get(Ty, AddressSpace);
1279 }
1280
1281 // Add type for inalloca argument.
1282 if (IRFunctionArgs.hasInallocaArg()) {
1283 auto ArgStruct = FI.getArgStruct();
1284 assert(ArgStruct);
1285 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1286 }
1287
John McCallc818bbb2012-12-07 07:03:17 +00001288 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001289 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001290 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1291 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001292 for (; it != ie; ++it, ++ArgNo) {
1293 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001294
Rafael Espindolafad28de2012-10-24 01:59:00 +00001295 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001296 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1297 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1298 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001299
Alexey Samsonov153004f2014-09-29 22:08:00 +00001300 unsigned FirstIRArg, NumIRArgs;
1301 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1302
1303 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001304 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001305 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001306 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001307 break;
1308
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001309 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001310 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001311 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001312 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001313 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001314 break;
1315 }
1316
1317 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001318 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001319 // Fast-isel and the optimizer generally like scalar values better than
1320 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001321 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001322 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001323 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1324 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001325 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001326 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001327 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001328 assert(NumIRArgs == 1);
1329 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001330 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001331 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Daniel Dunbard3674e62008-09-11 01:48:57 +00001334 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001335 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1336 getExpandedTypes(it->type, ArgTypesIter);
1337 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001338 break;
1339 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001340 }
1341
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001342 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1343 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001344
1345 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001346}
1347
Chris Lattner2192fe52011-07-18 04:24:23 +00001348llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001349 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001350 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001351
Chris Lattner8806e322011-07-10 00:18:59 +00001352 if (!isFuncTypeConvertible(FPT))
1353 return llvm::StructType::get(getLLVMContext());
1354
1355 const CGFunctionInfo *Info;
1356 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001357 Info =
1358 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001359 else
John McCalla729c622012-02-17 03:33:10 +00001360 Info = &arrangeCXXMethodDeclaration(MD);
1361 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001362}
1363
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001364void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001365 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001366 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001367 unsigned &CallingConv,
1368 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001369 llvm::AttrBuilder FuncAttrs;
1370 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001371 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001372
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001373 CallingConv = FI.getEffectiveCallingConvention();
1374
John McCallab26cfa2010-02-05 21:31:56 +00001375 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001376 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001377
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001378 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001379 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001380 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001381 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001382 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001383 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001384 if (TargetDecl->hasAttr<NoReturnAttr>())
1385 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001386 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1387 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001388
1389 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001390 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001391 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001392 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001393 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1394 // These attributes are not inherited by overloads.
1395 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1396 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001397 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001398 }
1399
Eric Christopherbf005ec2011-08-15 22:38:22 +00001400 // 'const' and 'pure' attribute functions are also nounwind.
1401 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001402 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1403 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001404 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001405 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1406 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001407 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001408 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001409 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001410 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1411 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001412
1413 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001414 }
1415
Paul Robinson08556952014-12-11 20:14:04 +00001416 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1417 if (!HasOptnone) {
1418 if (CodeGenOpts.OptimizeSize)
1419 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1420 if (CodeGenOpts.OptimizeSize == 2)
1421 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1422 }
1423
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001424 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001425 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001426 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001427 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001428 if (CodeGenOpts.EnableSegmentedStacks &&
1429 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001430 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001431
Bill Wendling2f81db62013-02-22 20:53:29 +00001432 if (AttrOnCallSite) {
1433 // Attributes that should go on the call site only.
1434 if (!CodeGenOpts.SimplifyLibCalls)
1435 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001436 } else {
1437 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001438 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001439 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001440 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001441 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001442 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001443 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001444 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001445 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001446 }
1447
Bill Wendlingdabafea2013-03-13 22:24:33 +00001448 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001449 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001450 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001451 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001452 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001453 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001454 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001455 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001456 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001457 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001458 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001459 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001460
Bill Wendlingd8f49502013-08-01 21:41:02 +00001461 if (!CodeGenOpts.StackRealignment)
1462 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001463 }
1464
Alexey Samsonov153004f2014-09-29 22:08:00 +00001465 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001466
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001467 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001468 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001469 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001470 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001471 if (RetTy->hasSignedIntegerRepresentation())
1472 RetAttrs.addAttribute(llvm::Attribute::SExt);
1473 else if (RetTy->hasUnsignedIntegerRepresentation())
1474 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001475 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001476 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001477 if (RetAI.getInReg())
1478 RetAttrs.addAttribute(llvm::Attribute::InReg);
1479 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001480 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001481 break;
1482
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001483 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001484 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001485 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001486 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1487 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001488 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001489 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001490
Daniel Dunbard3674e62008-09-11 01:48:57 +00001491 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001492 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001493 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001494
Hal Finkela2347ba2014-07-18 15:52:10 +00001495 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1496 QualType PTy = RefTy->getPointeeType();
1497 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1498 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1499 .getQuantity());
1500 else if (getContext().getTargetAddressSpace(PTy) == 0)
1501 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1502 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001503
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001504 // Attach return attributes.
1505 if (RetAttrs.hasAttributes()) {
1506 PAL.push_back(llvm::AttributeSet::get(
1507 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1508 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001509
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001510 // Attach attributes to sret.
1511 if (IRFunctionArgs.hasSRetArg()) {
1512 llvm::AttrBuilder SRETAttrs;
1513 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1514 if (RetAI.getInReg())
1515 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1516 PAL.push_back(llvm::AttributeSet::get(
1517 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1518 }
1519
1520 // Attach attributes to inalloca argument.
1521 if (IRFunctionArgs.hasInallocaArg()) {
1522 llvm::AttrBuilder Attrs;
1523 Attrs.addAttribute(llvm::Attribute::InAlloca);
1524 PAL.push_back(llvm::AttributeSet::get(
1525 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1526 }
1527
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001528 unsigned ArgNo = 0;
1529 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1530 E = FI.arg_end();
1531 I != E; ++I, ++ArgNo) {
1532 QualType ParamType = I->type;
1533 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001534 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001535
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001536 // Add attribute for padding argument, if necessary.
1537 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001538 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001539 PAL.push_back(llvm::AttributeSet::get(
1540 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1541 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001542 }
1543
John McCall39ec71f2010-03-27 00:47:27 +00001544 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1545 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001546 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001547 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001548 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001549 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001550 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001551 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001552 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001553 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001554 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001555 if (ArgNo == 0 && FI.isChainCall())
1556 Attrs.addAttribute(llvm::Attribute::Nest);
1557 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001558 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001559 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001560
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001561 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001562 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001563 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001564
Anders Carlsson20759ad2009-09-16 15:53:40 +00001565 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001566 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001567
Bill Wendlinga7912f82012-10-10 07:36:56 +00001568 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1569
Daniel Dunbarc2304432009-03-18 19:51:01 +00001570 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001571 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1572 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001573 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001574
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001575 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001576 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001577 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001578
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001579 case ABIArgInfo::InAlloca:
1580 // inalloca disables readnone and readonly.
1581 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1582 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001583 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001584 }
Mike Stump11289f42009-09-09 15:08:12 +00001585
Hal Finkela2347ba2014-07-18 15:52:10 +00001586 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1587 QualType PTy = RefTy->getPointeeType();
1588 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1589 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1590 .getQuantity());
1591 else if (getContext().getTargetAddressSpace(PTy) == 0)
1592 Attrs.addAttribute(llvm::Attribute::NonNull);
1593 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001594
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001595 if (Attrs.hasAttributes()) {
1596 unsigned FirstIRArg, NumIRArgs;
1597 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1598 for (unsigned i = 0; i < NumIRArgs; i++)
1599 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1600 FirstIRArg + i + 1, Attrs));
1601 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001602 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001603 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001604
Bill Wendlinga7912f82012-10-10 07:36:56 +00001605 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001606 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001607 AttributeSet::get(getLLVMContext(),
1608 llvm::AttributeSet::FunctionIndex,
1609 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001610}
1611
John McCalla738c252011-03-09 04:27:21 +00001612/// An argument came in as a promoted argument; demote it back to its
1613/// declared type.
1614static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1615 const VarDecl *var,
1616 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001617 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001618
1619 // This can happen with promotions that actually don't change the
1620 // underlying type, like the enum promotions.
1621 if (value->getType() == varType) return value;
1622
1623 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1624 && "unexpected promotion type");
1625
1626 if (isa<llvm::IntegerType>(varType))
1627 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1628
1629 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1630}
1631
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001632/// Returns the attribute (either parameter attribute, or function
1633/// attribute), which declares argument ArgNo to be non-null.
1634static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1635 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001636 // FIXME: __attribute__((nonnull)) can also be applied to:
1637 // - references to pointers, where the pointee is known to be
1638 // nonnull (apparently a Clang extension)
1639 // - transparent unions containing pointers
1640 // In the former case, LLVM IR cannot represent the constraint. In
1641 // the latter case, we have no guarantee that the transparent union
1642 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001643 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1644 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001645 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001646 if (PVD) {
1647 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1648 return ParmNNAttr;
1649 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001650 // Check function attributes.
1651 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001652 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001653 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001654 if (NNAttr->isNonNull(ArgNo))
1655 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001656 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001657 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001658}
1659
Daniel Dunbard931a872009-02-02 22:03:45 +00001660void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1661 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001662 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001663 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1664 // Naked functions don't have prologues.
1665 return;
1666
John McCallcaa19452009-07-28 01:00:58 +00001667 // If this is an implicit-return-zero function, go ahead and
1668 // initialize the return value. TODO: it might be nice to have
1669 // a more general mechanism for this that didn't require synthesized
1670 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001671 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001672 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001673 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001674 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001675 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001676 Builder.CreateStore(Zero, ReturnValue);
1677 }
1678 }
1679
Mike Stump18bb9282009-05-16 07:57:57 +00001680 // FIXME: We no longer need the types from FunctionArgList; lift up and
1681 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001682
Alexey Samsonov153004f2014-09-29 22:08:00 +00001683 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001684 // Flattened function arguments.
1685 SmallVector<llvm::Argument *, 16> FnArgs;
1686 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1687 for (auto &Arg : Fn->args()) {
1688 FnArgs.push_back(&Arg);
1689 }
1690 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001691
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001692 // If we're using inalloca, all the memory arguments are GEPs off of the last
1693 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001694 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001695 if (IRFunctionArgs.hasInallocaArg()) {
1696 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001697 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1698 }
1699
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001700 // Name the struct return parameter.
1701 if (IRFunctionArgs.hasSRetArg()) {
1702 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001703 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001704 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001705 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 // Track if we received the parameter as a pointer (indirect, byval, or
1709 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1710 // into a local alloca for us.
1711 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001712 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001713 SmallVector<ValueAndIsPtr, 16> ArgVals;
1714 ArgVals.reserve(Args.size());
1715
Reid Kleckner739756c2013-12-04 19:23:12 +00001716 // Create a pointer value for every parameter declaration. This usually
1717 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1718 // any cleanups or do anything that might unwind. We do that separately, so
1719 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001720 assert(FI.arg_size() == Args.size() &&
1721 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001722 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001723 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001724 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001725 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001726 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001727 QualType Ty = info_it->type;
1728 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001729
John McCalla738c252011-03-09 04:27:21 +00001730 bool isPromoted =
1731 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1732
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001733 unsigned FirstIRArg, NumIRArgs;
1734 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001735
Daniel Dunbard3674e62008-09-11 01:48:57 +00001736 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001737 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001738 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001739 llvm::Value *V = Builder.CreateStructGEP(
1740 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1741 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001742 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001743 }
1744
Daniel Dunbar747865a2009-02-05 09:16:39 +00001745 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001746 assert(NumIRArgs == 1);
1747 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001748
John McCall47fb9502013-03-07 21:37:08 +00001749 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001750 // Aggregates and complex variables are accessed by reference. All we
1751 // need to do is realign the value, if requested
1752 if (ArgI.getIndirectRealign()) {
1753 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1754
1755 // Copy from the incoming argument pointer to the temporary with the
1756 // appropriate alignment.
1757 //
1758 // FIXME: We should have a common utility for generating an aggregate
1759 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001760 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001761 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001762 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1763 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1764 Builder.CreateMemCpy(Dst,
1765 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001766 llvm::ConstantInt::get(IntPtrTy,
1767 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001768 ArgI.getIndirectAlign(),
1769 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001770 V = AlignedTemp;
1771 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001772 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001773 } else {
1774 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001775 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001776 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1777 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001778
1779 if (isPromoted)
1780 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001781 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001782 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001783 break;
1784 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001785
1786 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001787 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001788
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001789 // If we have the trivial case, handle it with no muss and fuss.
1790 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001791 ArgI.getCoerceToType() == ConvertType(Ty) &&
1792 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001793 assert(NumIRArgs == 1);
1794 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001795 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001796
Hal Finkel48d53e22014-07-19 01:41:07 +00001797 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001798 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1799 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001800 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1801 AI->getArgNo() + 1,
1802 llvm::Attribute::NonNull));
1803
Hal Finkel48d53e22014-07-19 01:41:07 +00001804 QualType OTy = PVD->getOriginalType();
1805 if (const auto *ArrTy =
1806 getContext().getAsConstantArrayType(OTy)) {
1807 // A C99 array parameter declaration with the static keyword also
1808 // indicates dereferenceability, and if the size is constant we can
1809 // use the dereferenceable attribute (which requires the size in
1810 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001811 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001812 QualType ETy = ArrTy->getElementType();
1813 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1814 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1815 ArrSize) {
1816 llvm::AttrBuilder Attrs;
1817 Attrs.addDereferenceableAttr(
1818 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1819 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1820 AI->getArgNo() + 1, Attrs));
1821 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1822 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1823 AI->getArgNo() + 1,
1824 llvm::Attribute::NonNull));
1825 }
1826 }
1827 } else if (const auto *ArrTy =
1828 getContext().getAsVariableArrayType(OTy)) {
1829 // For C99 VLAs with the static keyword, we don't know the size so
1830 // we can't use the dereferenceable attribute, but in addrspace(0)
1831 // we know that it must be nonnull.
1832 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1833 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1834 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1835 AI->getArgNo() + 1,
1836 llvm::Attribute::NonNull));
1837 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001838
1839 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1840 if (!AVAttr)
1841 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1842 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1843 if (AVAttr) {
1844 llvm::Value *AlignmentValue =
1845 EmitScalarExpr(AVAttr->getAlignment());
1846 llvm::ConstantInt *AlignmentCI =
1847 cast<llvm::ConstantInt>(AlignmentValue);
1848 unsigned Alignment =
1849 std::min((unsigned) AlignmentCI->getZExtValue(),
1850 +llvm::Value::MaximumAlignment);
1851
1852 llvm::AttrBuilder Attrs;
1853 Attrs.addAlignmentAttr(Alignment);
1854 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1855 AI->getArgNo() + 1, Attrs));
1856 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001857 }
1858
Bill Wendling507c3512012-10-16 05:23:44 +00001859 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001860 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1861 AI->getArgNo() + 1,
1862 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001863
Chris Lattner7369c142011-07-20 06:29:00 +00001864 // Ensure the argument is the correct type.
1865 if (V->getType() != ArgI.getCoerceToType())
1866 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1867
John McCalla738c252011-03-09 04:27:21 +00001868 if (isPromoted)
1869 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001870
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001871 if (const CXXMethodDecl *MD =
1872 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001873 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001874 V = CGM.getCXXABI().
1875 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001876 }
1877
Rafael Espindola8778c282012-11-29 16:09:03 +00001878 // Because of merging of function types from multiple decls it is
1879 // possible for the type of an argument to not match the corresponding
1880 // type in the function type. Since we are codegening the callee
1881 // in here, add a cast to the argument type.
1882 llvm::Type *LTy = ConvertType(Arg->getType());
1883 if (V->getType() != LTy)
1884 V = Builder.CreateBitCast(V, LTy);
1885
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001886 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001887 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001890 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001891
Chris Lattnerff941a62010-07-28 18:24:28 +00001892 // The alignment we need to use is the max of the requested alignment for
1893 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001894 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001895 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001896 AlignmentToUse = std::max(AlignmentToUse,
1897 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001898
Chris Lattnerff941a62010-07-28 18:24:28 +00001899 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001900 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001901 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001902
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001903 // If the value is offset in memory, apply the offset now.
1904 if (unsigned Offs = ArgI.getDirectOffset()) {
1905 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1906 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001907 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001908 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1909 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001910
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001911 // Fast-isel and the optimizer generally like scalar values better than
1912 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001913 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001914 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1915 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001916 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001917 llvm::Type *DstTy =
1918 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001919 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001920
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001921 if (SrcSize <= DstSize) {
1922 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1923
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001924 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001925 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001926 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001927 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1928 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001929 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001930 }
1931 } else {
1932 llvm::AllocaInst *TempAlloca =
1933 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1934 TempAlloca->setAlignment(AlignmentToUse);
1935 llvm::Value *TempV = TempAlloca;
1936
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001937 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001938 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001939 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001940 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1941 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001942 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001943 }
1944
1945 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001946 }
1947 } else {
1948 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001949 assert(NumIRArgs == 1);
1950 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001951 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001952 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001953 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001954
1955
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001956 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001957 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001958 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001959 if (isPromoted)
1960 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001961 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1962 } else {
1963 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001964 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001965 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001966 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001967
1968 case ABIArgInfo::Expand: {
1969 // If this structure was expanded into multiple arguments then
1970 // we need to create a temporary and reconstruct it from the
1971 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001972 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001973 CharUnits Align = getContext().getDeclAlign(Arg);
1974 Alloca->setAlignment(Align.getQuantity());
1975 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001976 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001977
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001978 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1979 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1980 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1981 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1982 auto AI = FnArgs[FirstIRArg + i];
1983 AI->setName(Arg->getName() + "." + Twine(i));
1984 }
1985 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001986 }
1987
1988 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001989 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001990 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001991 if (!hasScalarEvaluationKind(Ty)) {
1992 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1993 } else {
1994 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1995 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1996 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001997 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001998 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001999 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002000
Reid Kleckner739756c2013-12-04 19:23:12 +00002001 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2002 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002003 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2004 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002005 } else {
2006 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002007 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2008 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002009 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002010}
2011
John McCallffa2c1a2012-01-29 07:46:59 +00002012static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2013 while (insn->use_empty()) {
2014 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2015 if (!bitcast) return;
2016
2017 // This is "safe" because we would have used a ConstantExpr otherwise.
2018 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2019 bitcast->eraseFromParent();
2020 }
2021}
2022
John McCall31168b02011-06-15 23:02:42 +00002023/// Try to emit a fused autorelease of a return result.
2024static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2025 llvm::Value *result) {
2026 // We must be immediately followed the cast.
2027 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002028 if (BB->empty()) return nullptr;
2029 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002030
Chris Lattner2192fe52011-07-18 04:24:23 +00002031 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002032
2033 // result is in a BasicBlock and is therefore an Instruction.
2034 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2035
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002036 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002037
2038 // Look for:
2039 // %generator = bitcast %type1* %generator2 to %type2*
2040 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2041 // We would have emitted this as a constant if the operand weren't
2042 // an Instruction.
2043 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2044
2045 // Require the generator to be immediately followed by the cast.
2046 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002047 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002048
2049 insnsToKill.push_back(bitcast);
2050 }
2051
2052 // Look for:
2053 // %generator = call i8* @objc_retain(i8* %originalResult)
2054 // or
2055 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2056 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002057 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002058
2059 bool doRetainAutorelease;
2060
2061 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2062 doRetainAutorelease = true;
2063 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2064 .objc_retainAutoreleasedReturnValue) {
2065 doRetainAutorelease = false;
2066
John McCallcfa4e9b2012-09-07 23:30:50 +00002067 // If we emitted an assembly marker for this call (and the
2068 // ARCEntrypoints field should have been set if so), go looking
2069 // for that call. If we can't find it, we can't do this
2070 // optimization. But it should always be the immediately previous
2071 // instruction, unless we needed bitcasts around the call.
2072 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2073 llvm::Instruction *prev = call->getPrevNode();
2074 assert(prev);
2075 if (isa<llvm::BitCastInst>(prev)) {
2076 prev = prev->getPrevNode();
2077 assert(prev);
2078 }
2079 assert(isa<llvm::CallInst>(prev));
2080 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2081 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2082 insnsToKill.push_back(prev);
2083 }
John McCall31168b02011-06-15 23:02:42 +00002084 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002085 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002086 }
2087
2088 result = call->getArgOperand(0);
2089 insnsToKill.push_back(call);
2090
2091 // Keep killing bitcasts, for sanity. Note that we no longer care
2092 // about precise ordering as long as there's exactly one use.
2093 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2094 if (!bitcast->hasOneUse()) break;
2095 insnsToKill.push_back(bitcast);
2096 result = bitcast->getOperand(0);
2097 }
2098
2099 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002100 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002101 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2102 (*i)->eraseFromParent();
2103
2104 // Do the fused retain/autorelease if we were asked to.
2105 if (doRetainAutorelease)
2106 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2107
2108 // Cast back to the result type.
2109 return CGF.Builder.CreateBitCast(result, resultType);
2110}
2111
John McCallffa2c1a2012-01-29 07:46:59 +00002112/// If this is a +1 of the value of an immutable 'self', remove it.
2113static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2114 llvm::Value *result) {
2115 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002116 const ObjCMethodDecl *method =
2117 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002118 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002119 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002120 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002121
2122 // Look for a retain call.
2123 llvm::CallInst *retainCall =
2124 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2125 if (!retainCall ||
2126 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002127 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002128
2129 // Look for an ordinary load of 'self'.
2130 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2131 llvm::LoadInst *load =
2132 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2133 if (!load || load->isAtomic() || load->isVolatile() ||
2134 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002135 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002136
2137 // Okay! Burn it all down. This relies for correctness on the
2138 // assumption that the retain is emitted as part of the return and
2139 // that thereafter everything is used "linearly".
2140 llvm::Type *resultType = result->getType();
2141 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2142 assert(retainCall->use_empty());
2143 retainCall->eraseFromParent();
2144 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2145
2146 return CGF.Builder.CreateBitCast(load, resultType);
2147}
2148
John McCall31168b02011-06-15 23:02:42 +00002149/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002150///
2151/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002152static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2153 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002154 // If we're returning 'self', kill the initial retain. This is a
2155 // heuristic attempt to "encourage correctness" in the really unfortunate
2156 // case where we have a return of self during a dealloc and we desperately
2157 // need to avoid the possible autorelease.
2158 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2159 return self;
2160
John McCall31168b02011-06-15 23:02:42 +00002161 // At -O0, try to emit a fused retain/autorelease.
2162 if (CGF.shouldUseFusedARCCalls())
2163 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2164 return fused;
2165
2166 return CGF.EmitARCAutoreleaseReturnValue(result);
2167}
2168
John McCall6e1c0122012-01-29 02:35:02 +00002169/// Heuristically search for a dominating store to the return-value slot.
2170static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2171 // If there are multiple uses of the return-value slot, just check
2172 // for something immediately preceding the IP. Sometimes this can
2173 // happen with how we generate implicit-returns; it can also happen
2174 // with noreturn cleanups.
2175 if (!CGF.ReturnValue->hasOneUse()) {
2176 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002177 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002178 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002179 if (!store) return nullptr;
2180 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002181 assert(!store->isAtomic() && !store->isVolatile()); // see below
2182 return store;
2183 }
2184
2185 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002186 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002187 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002188
2189 // These aren't actually possible for non-coerced returns, and we
2190 // only care about non-coerced returns on this code path.
2191 assert(!store->isAtomic() && !store->isVolatile());
2192
2193 // Now do a first-and-dirty dominance check: just walk up the
2194 // single-predecessors chain from the current insertion point.
2195 llvm::BasicBlock *StoreBB = store->getParent();
2196 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2197 while (IP != StoreBB) {
2198 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002199 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002200 }
2201
2202 // Okay, the store's basic block dominates the insertion point; we
2203 // can do our thing.
2204 return store;
2205}
2206
Adrian Prantl3be10542013-05-02 17:30:20 +00002207void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002208 bool EmitRetDbgLoc,
2209 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002210 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2211 // Naked functions don't have epilogues.
2212 Builder.CreateUnreachable();
2213 return;
2214 }
2215
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002216 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002217 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002218 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002219 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002220 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002221
Dan Gohman481e40c2010-07-20 20:13:52 +00002222 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002223 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002224 QualType RetTy = FI.getReturnType();
2225 const ABIArgInfo &RetAI = FI.getReturnInfo();
2226
2227 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002228 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002229 // Aggregrates get evaluated directly into the destination. Sometimes we
2230 // need to return the sret value in a register, though.
2231 assert(hasAggregateEvaluationKind(RetTy));
2232 if (RetAI.getInAllocaSRet()) {
2233 llvm::Function::arg_iterator EI = CurFn->arg_end();
2234 --EI;
2235 llvm::Value *ArgStruct = EI;
2236 llvm::Value *SRet =
2237 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2238 RV = Builder.CreateLoad(SRet, "sret");
2239 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002240 break;
2241
Daniel Dunbar03816342010-08-21 02:24:36 +00002242 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002243 auto AI = CurFn->arg_begin();
2244 if (RetAI.isSRetAfterThis())
2245 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002246 switch (getEvaluationKind(RetTy)) {
2247 case TEK_Complex: {
2248 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002249 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2250 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002251 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002252 /*isInit*/ true);
2253 break;
2254 }
2255 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002256 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002257 break;
2258 case TEK_Scalar:
2259 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002260 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002261 /*isInit*/ true);
2262 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002263 }
2264 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002265 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002266
2267 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002268 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002269 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2270 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002271 // The internal return value temp always will have pointer-to-return-type
2272 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002273
John McCall6e1c0122012-01-29 02:35:02 +00002274 // If there is a dominating store to ReturnValue, we can elide
2275 // the load, zap the store, and usually zap the alloca.
2276 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002277 // Reuse the debug location from the store unless there is
2278 // cleanup code to be emitted between the store and return
2279 // instruction.
2280 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002281 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002282 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002283 RV = SI->getValueOperand();
2284 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002285
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002286 // If that was the only use of the return value, nuke it as well now.
2287 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2288 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002289 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002290 }
John McCall6e1c0122012-01-29 02:35:02 +00002291
2292 // Otherwise, we have to do a simple load.
2293 } else {
2294 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002295 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002296 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002297 llvm::Value *V = ReturnValue;
2298 // If the value is offset in memory, apply the offset now.
2299 if (unsigned Offs = RetAI.getDirectOffset()) {
2300 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2301 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002302 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002303 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2304 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002305
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002306 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002307 }
John McCall31168b02011-06-15 23:02:42 +00002308
2309 // In ARC, end functions that return a retainable type with a call
2310 // to objc_autoreleaseReturnValue.
2311 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002312 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002313 !FI.isReturnsRetained() &&
2314 RetTy->isObjCRetainableType());
2315 RV = emitAutoreleaseOfResult(*this, RV);
2316 }
2317
Chris Lattner726b3d02010-06-26 23:13:19 +00002318 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002319
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002320 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002321 break;
2322
2323 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002324 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002325 }
2326
Alexey Samsonovde443c52014-08-13 00:26:40 +00002327 llvm::Instruction *Ret;
2328 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002329 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002330 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2331 SanitizerScope SanScope(this);
2332 llvm::Value *Cond = Builder.CreateICmpNE(
2333 RV, llvm::Constant::getNullValue(RV->getType()));
2334 llvm::Constant *StaticData[] = {
2335 EmitCheckSourceLocation(EndLoc),
2336 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2337 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002338 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2339 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002340 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002341 }
2342 Ret = Builder.CreateRet(RV);
2343 } else {
2344 Ret = Builder.CreateRetVoid();
2345 }
2346
Devang Patel65497582010-07-21 18:08:50 +00002347 if (!RetDbgLoc.isUnknown())
2348 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002349}
2350
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002351static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2352 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2353 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2354}
2355
2356static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2357 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2358 // placeholders.
2359 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2360 llvm::Value *Placeholder =
2361 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2362 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2363 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2364 Ty.getQualifiers(),
2365 AggValueSlot::IsNotDestructed,
2366 AggValueSlot::DoesNotNeedGCBarriers,
2367 AggValueSlot::IsNotAliased);
2368}
2369
John McCall32ea9692011-03-11 20:59:21 +00002370void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002371 const VarDecl *param,
2372 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002373 // StartFunction converted the ABI-lowered parameter(s) into a
2374 // local alloca. We need to turn that into an r-value suitable
2375 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002376 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002377
John McCall32ea9692011-03-11 20:59:21 +00002378 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002379
John McCall23f66262010-05-26 22:34:26 +00002380 // For the most part, we just need to load the alloca, except:
2381 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002382 // 2) references to non-scalars are pointers directly to the aggregate.
2383 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002384 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002385 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002386 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002387
2388 // Locals which are references to scalars are represented
2389 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002390 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002391 }
2392
Reid Klecknerab2090d2014-07-26 01:34:32 +00002393 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2394 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002395
Nick Lewycky2d84e842013-10-02 02:29:49 +00002396 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002397}
2398
John McCall31168b02011-06-15 23:02:42 +00002399static bool isProvablyNull(llvm::Value *addr) {
2400 return isa<llvm::ConstantPointerNull>(addr);
2401}
2402
2403static bool isProvablyNonNull(llvm::Value *addr) {
2404 return isa<llvm::AllocaInst>(addr);
2405}
2406
2407/// Emit the actual writing-back of a writeback.
2408static void emitWriteback(CodeGenFunction &CGF,
2409 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002410 const LValue &srcLV = writeback.Source;
2411 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002412 assert(!isProvablyNull(srcAddr) &&
2413 "shouldn't have writeback for provably null argument");
2414
Craig Topper8a13c412014-05-21 05:09:00 +00002415 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002416
2417 // If the argument wasn't provably non-null, we need to null check
2418 // before doing the store.
2419 bool provablyNonNull = isProvablyNonNull(srcAddr);
2420 if (!provablyNonNull) {
2421 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2422 contBB = CGF.createBasicBlock("icr.done");
2423
2424 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2425 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2426 CGF.EmitBlock(writebackBB);
2427 }
2428
2429 // Load the value to writeback.
2430 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2431
2432 // Cast it back, in case we're writing an id to a Foo* or something.
2433 value = CGF.Builder.CreateBitCast(value,
2434 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2435 "icr.writeback-cast");
2436
2437 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002438
2439 // If we have a "to use" value, it's something we need to emit a use
2440 // of. This has to be carefully threaded in: if it's done after the
2441 // release it's potentially undefined behavior (and the optimizer
2442 // will ignore it), and if it happens before the retain then the
2443 // optimizer could move the release there.
2444 if (writeback.ToUse) {
2445 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2446
2447 // Retain the new value. No need to block-copy here: the block's
2448 // being passed up the stack.
2449 value = CGF.EmitARCRetainNonBlock(value);
2450
2451 // Emit the intrinsic use here.
2452 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2453
2454 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002455 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002456
2457 // Put the new value in place (primitively).
2458 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2459
2460 // Release the old value.
2461 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2462
2463 // Otherwise, we can just do a normal lvalue store.
2464 } else {
2465 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2466 }
John McCall31168b02011-06-15 23:02:42 +00002467
2468 // Jump to the continuation block.
2469 if (!provablyNonNull)
2470 CGF.EmitBlock(contBB);
2471}
2472
2473static void emitWritebacks(CodeGenFunction &CGF,
2474 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002475 for (const auto &I : args.writebacks())
2476 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002477}
2478
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002479static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2480 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002481 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002482 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2483 CallArgs.getCleanupsToDeactivate();
2484 // Iterate in reverse to increase the likelihood of popping the cleanup.
2485 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2486 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2487 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2488 I->IsActiveIP->eraseFromParent();
2489 }
2490}
2491
John McCalleff18842013-03-23 02:35:54 +00002492static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2493 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2494 if (uop->getOpcode() == UO_AddrOf)
2495 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002496 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002497}
2498
John McCall31168b02011-06-15 23:02:42 +00002499/// Emit an argument that's being passed call-by-writeback. That is,
2500/// we are passing the address of
2501static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2502 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002503 LValue srcLV;
2504
2505 // Make an optimistic effort to emit the address as an l-value.
2506 // This can fail if the the argument expression is more complicated.
2507 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2508 srcLV = CGF.EmitLValue(lvExpr);
2509
2510 // Otherwise, just emit it as a scalar.
2511 } else {
2512 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2513
2514 QualType srcAddrType =
2515 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2516 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2517 }
2518 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002519
2520 // The dest and src types don't necessarily match in LLVM terms
2521 // because of the crazy ObjC compatibility rules.
2522
Chris Lattner2192fe52011-07-18 04:24:23 +00002523 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002524 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2525
2526 // If the address is a constant null, just pass the appropriate null.
2527 if (isProvablyNull(srcAddr)) {
2528 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2529 CRE->getType());
2530 return;
2531 }
2532
John McCall31168b02011-06-15 23:02:42 +00002533 // Create the temporary.
2534 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2535 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002536 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2537 // and that cleanup will be conditional if we can't prove that the l-value
2538 // isn't null, so we need to register a dominating point so that the cleanups
2539 // system will make valid IR.
2540 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2541
John McCall31168b02011-06-15 23:02:42 +00002542 // Zero-initialize it if we're not doing a copy-initialization.
2543 bool shouldCopy = CRE->shouldCopy();
2544 if (!shouldCopy) {
2545 llvm::Value *null =
2546 llvm::ConstantPointerNull::get(
2547 cast<llvm::PointerType>(destType->getElementType()));
2548 CGF.Builder.CreateStore(null, temp);
2549 }
Craig Topper8a13c412014-05-21 05:09:00 +00002550
2551 llvm::BasicBlock *contBB = nullptr;
2552 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002553
2554 // If the address is *not* known to be non-null, we need to switch.
2555 llvm::Value *finalArgument;
2556
2557 bool provablyNonNull = isProvablyNonNull(srcAddr);
2558 if (provablyNonNull) {
2559 finalArgument = temp;
2560 } else {
2561 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2562
2563 finalArgument = CGF.Builder.CreateSelect(isNull,
2564 llvm::ConstantPointerNull::get(destType),
2565 temp, "icr.argument");
2566
2567 // If we need to copy, then the load has to be conditional, which
2568 // means we need control flow.
2569 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002570 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002571 contBB = CGF.createBasicBlock("icr.cont");
2572 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2573 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2574 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002575 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002576 }
2577 }
2578
Craig Topper8a13c412014-05-21 05:09:00 +00002579 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002580
John McCall31168b02011-06-15 23:02:42 +00002581 // Perform a copy if necessary.
2582 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002583 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002584 assert(srcRV.isScalar());
2585
2586 llvm::Value *src = srcRV.getScalarVal();
2587 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2588 "icr.cast");
2589
2590 // Use an ordinary store, not a store-to-lvalue.
2591 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002592
2593 // If optimization is enabled, and the value was held in a
2594 // __strong variable, we need to tell the optimizer that this
2595 // value has to stay alive until we're doing the store back.
2596 // This is because the temporary is effectively unretained,
2597 // and so otherwise we can violate the high-level semantics.
2598 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2599 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2600 valueToUse = src;
2601 }
John McCall31168b02011-06-15 23:02:42 +00002602 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002603
John McCall31168b02011-06-15 23:02:42 +00002604 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002605 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002606 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002607 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002608
2609 // Make a phi for the value to intrinsically use.
2610 if (valueToUse) {
2611 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2612 "icr.to-use");
2613 phiToUse->addIncoming(valueToUse, copyBB);
2614 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2615 originBB);
2616 valueToUse = phiToUse;
2617 }
2618
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002619 condEval.end(CGF);
2620 }
John McCall31168b02011-06-15 23:02:42 +00002621
John McCalleff18842013-03-23 02:35:54 +00002622 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002623 args.add(RValue::get(finalArgument), CRE->getType());
2624}
2625
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002626void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2627 assert(!StackBase && !StackCleanup.isValid());
2628
2629 // Save the stack.
2630 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2631 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2632
2633 // Control gets really tied up in landing pads, so we have to spill the
2634 // stacksave to an alloca to avoid violating SSA form.
2635 // TODO: This is dead if we never emit the cleanup. We should create the
2636 // alloca and store lazily on the first cleanup emission.
2637 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2638 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2639 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2640 StackCleanup = CGF.EHStack.getInnermostEHScope();
2641 assert(StackCleanup.isValid());
2642}
2643
2644void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2645 if (StackBase) {
2646 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2647 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2648 // We could load StackBase from StackBaseMem, but in the non-exceptional
2649 // case we can skip it.
2650 CGF.Builder.CreateCall(F, StackBase);
2651 }
2652}
2653
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002654static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2655 QualType ArgType, SourceLocation ArgLoc,
2656 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002657 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002658 return;
2659 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2660 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2661 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2662 if (!NNAttr)
2663 return;
2664 CodeGenFunction::SanitizerScope SanScope(&CGF);
2665 assert(RV.isScalar());
2666 llvm::Value *V = RV.getScalarVal();
2667 llvm::Value *Cond =
2668 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2669 llvm::Constant *StaticData[] = {
2670 CGF.EmitCheckSourceLocation(ArgLoc),
2671 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2672 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2673 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002674 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2675 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002676}
2677
Reid Kleckner739756c2013-12-04 19:23:12 +00002678void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2679 ArrayRef<QualType> ArgTypes,
2680 CallExpr::const_arg_iterator ArgBeg,
2681 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002682 const FunctionDecl *CalleeDecl,
2683 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002684 bool ForceColumnInfo) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002685 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2686 // because arguments are destroyed left to right in the callee.
2687 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002688 // Insert a stack save if we're going to need any inalloca args.
2689 bool HasInAllocaArgs = false;
2690 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2691 I != E && !HasInAllocaArgs; ++I)
2692 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2693 if (HasInAllocaArgs) {
2694 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2695 Args.allocateArgumentMemory(*this);
2696 }
2697
2698 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002699 size_t CallArgsStart = Args.size();
2700 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2701 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2702 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002703 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2704 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002705 }
2706
2707 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2708 // IR function.
2709 std::reverse(Args.begin() + CallArgsStart, Args.end());
2710 return;
2711 }
2712
2713 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2714 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2715 assert(Arg != ArgEnd);
2716 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002717 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2718 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002719 }
2720}
2721
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002722namespace {
2723
2724struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2725 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2726 : Addr(Addr), Ty(Ty) {}
2727
2728 llvm::Value *Addr;
2729 QualType Ty;
2730
Craig Topper4f12f102014-03-12 06:41:41 +00002731 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002732 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2733 assert(!Dtor->isTrivial());
2734 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2735 /*Delegating=*/false, Addr);
2736 }
2737};
2738
2739}
2740
John McCall32ea9692011-03-11 20:59:21 +00002741void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2742 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002743 if (const ObjCIndirectCopyRestoreExpr *CRE
2744 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002745 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002746 assert(getContext().hasSameType(E->getType(), type));
2747 return emitWritebackArg(*this, args, CRE);
2748 }
2749
John McCall0a76c0c2011-08-26 18:42:59 +00002750 assert(type->isReferenceType() == E->isGLValue() &&
2751 "reference binding to unmaterialized r-value!");
2752
John McCall17054bd62011-08-26 21:08:13 +00002753 if (E->isGLValue()) {
2754 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002755 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002758 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2759
2760 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2761 // However, we still have to push an EH-only cleanup in case we unwind before
2762 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002763 if (HasAggregateEvalKind &&
2764 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2765 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002766 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002767 AggValueSlot Slot;
2768 if (args.isUsingInAlloca())
2769 Slot = createPlaceholderSlot(*this, type);
2770 else
2771 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002772
2773 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2774 bool DestroyedInCallee =
2775 RD && RD->hasNonTrivialDestructor() &&
2776 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2777 if (DestroyedInCallee)
2778 Slot.setExternallyDestructed();
2779
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002780 EmitAggExpr(E, Slot);
2781 RValue RV = Slot.asRValue();
2782 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002783
Reid Klecknere39ee212014-05-03 00:33:28 +00002784 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002785 // Create a no-op GEP between the placeholder and the cleanup so we can
2786 // RAUW it successfully. It also serves as a marker of the first
2787 // instruction where the cleanup is active.
2788 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002789 // This unreachable is a temporary marker which will be removed later.
2790 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2791 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002792 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002793 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002794 }
2795
2796 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002797 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2798 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2799 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002800 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2801 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2802 } else {
2803 // We can't represent a misaligned lvalue in the CallArgList, so copy
2804 // to an aligned temporary now.
2805 llvm::Value *tmp = CreateMemTemp(type);
2806 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2807 L.getAlignment());
2808 args.add(RValue::getAggregate(tmp), type);
2809 }
Eli Friedmandf968192011-05-26 00:10:27 +00002810 return;
2811 }
2812
John McCall32ea9692011-03-11 20:59:21 +00002813 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002814}
2815
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002816QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2817 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2818 // implicitly widens null pointer constants that are arguments to varargs
2819 // functions to pointer-sized ints.
2820 if (!getTarget().getTriple().isOSWindows())
2821 return Arg->getType();
2822
2823 if (Arg->getType()->isIntegerType() &&
2824 getContext().getTypeSize(Arg->getType()) <
2825 getContext().getTargetInfo().getPointerWidth(0) &&
2826 Arg->isNullPointerConstant(getContext(),
2827 Expr::NPC_ValueDependentIsNotNull)) {
2828 return getContext().getIntPtrType();
2829 }
2830
2831 return Arg->getType();
2832}
2833
Dan Gohman515a60d2012-02-16 00:57:37 +00002834// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2835// optimizer it can aggressively ignore unwind edges.
2836void
2837CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2838 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2839 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2840 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2841 CGM.getNoObjCARCExceptionsMetadata());
2842}
2843
John McCall882987f2013-02-28 19:01:20 +00002844/// Emits a call to the given no-arguments nounwind runtime function.
2845llvm::CallInst *
2846CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2847 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002848 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002849}
2850
2851/// Emits a call to the given nounwind runtime function.
2852llvm::CallInst *
2853CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2854 ArrayRef<llvm::Value*> args,
2855 const llvm::Twine &name) {
2856 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2857 call->setDoesNotThrow();
2858 return call;
2859}
2860
2861/// Emits a simple call (never an invoke) to the given no-arguments
2862/// runtime function.
2863llvm::CallInst *
2864CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2865 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002866 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002867}
2868
2869/// Emits a simple call (never an invoke) to the given runtime
2870/// function.
2871llvm::CallInst *
2872CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2873 ArrayRef<llvm::Value*> args,
2874 const llvm::Twine &name) {
2875 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2876 call->setCallingConv(getRuntimeCC());
2877 return call;
2878}
2879
2880/// Emits a call or invoke to the given noreturn runtime function.
2881void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2882 ArrayRef<llvm::Value*> args) {
2883 if (getInvokeDest()) {
2884 llvm::InvokeInst *invoke =
2885 Builder.CreateInvoke(callee,
2886 getUnreachableBlock(),
2887 getInvokeDest(),
2888 args);
2889 invoke->setDoesNotReturn();
2890 invoke->setCallingConv(getRuntimeCC());
2891 } else {
2892 llvm::CallInst *call = Builder.CreateCall(callee, args);
2893 call->setDoesNotReturn();
2894 call->setCallingConv(getRuntimeCC());
2895 Builder.CreateUnreachable();
2896 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002897 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002898}
2899
2900/// Emits a call or invoke instruction to the given nullary runtime
2901/// function.
2902llvm::CallSite
2903CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2904 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002905 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002906}
2907
2908/// Emits a call or invoke instruction to the given runtime function.
2909llvm::CallSite
2910CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2911 ArrayRef<llvm::Value*> args,
2912 const Twine &name) {
2913 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2914 callSite.setCallingConv(getRuntimeCC());
2915 return callSite;
2916}
2917
2918llvm::CallSite
2919CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2920 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002921 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002922}
2923
John McCallbd309292010-07-06 01:34:17 +00002924/// Emits a call or invoke instruction to the given function, depending
2925/// on the current state of the EH stack.
2926llvm::CallSite
2927CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002928 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002929 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002930 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002931
Dan Gohman515a60d2012-02-16 00:57:37 +00002932 llvm::Instruction *Inst;
2933 if (!InvokeDest)
2934 Inst = Builder.CreateCall(Callee, Args, Name);
2935 else {
2936 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2937 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2938 EmitBlock(ContBB);
2939 }
2940
2941 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2942 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002943 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002944 AddObjCARCExceptionMetadata(Inst);
2945
2946 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002947}
2948
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002949/// \brief Store a non-aggregate value to an address to initialize it. For
2950/// initialization, a non-atomic store will be used.
2951static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2952 LValue Dst) {
2953 if (Src.isScalar())
2954 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2955 else
2956 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2957}
2958
2959void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2960 llvm::Value *New) {
2961 DeferredReplacements.push_back(std::make_pair(Old, New));
2962}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002963
Daniel Dunbard931a872009-02-02 22:03:45 +00002964RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002965 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002966 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002967 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002968 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002969 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002970 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002971
2972 // Handle struct-return functions by passing a pointer to the
2973 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002974 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002975 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002976
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002977 llvm::FunctionType *IRFuncTy =
2978 cast<llvm::FunctionType>(
2979 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002980
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002981 // If we're using inalloca, insert the allocation after the stack save.
2982 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002983 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002984 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002985 llvm::Instruction *IP = CallArgs.getStackBase();
2986 llvm::AllocaInst *AI;
2987 if (IP) {
2988 IP = IP->getNextNode();
2989 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2990 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002991 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002992 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002993 AI->setUsedWithInAlloca(true);
2994 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2995 ArgMemory = AI;
2996 }
2997
Alexey Samsonov153004f2014-09-29 22:08:00 +00002998 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002999 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3000
Chris Lattner4ca97c32009-06-13 00:26:38 +00003001 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003002 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00003003 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003004 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003005 SRetPtr = ReturnValue.getValue();
3006 if (!SRetPtr)
3007 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003008 if (IRFunctionArgs.hasSRetArg()) {
3009 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003010 } else {
3011 llvm::Value *Addr =
3012 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3013 Builder.CreateStore(SRetPtr, Addr);
3014 }
Anders Carlsson17490832009-12-24 20:40:36 +00003015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003017 assert(CallInfo.arg_size() == CallArgs.size() &&
3018 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003019 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003020 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003021 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003022 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003023 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003024 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003025
John McCall47fb9502013-03-07 21:37:08 +00003026 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003027
3028 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003029 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3030 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3031 llvm::UndefValue::get(ArgInfo.getPaddingType());
3032
3033 unsigned FirstIRArg, NumIRArgs;
3034 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003035
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003036 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003037 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003038 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003039 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3040 if (RV.isAggregate()) {
3041 // Replace the placeholder with the appropriate argument slot GEP.
3042 llvm::Instruction *Placeholder =
3043 cast<llvm::Instruction>(RV.getAggregateAddr());
3044 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3045 Builder.SetInsertPoint(Placeholder);
3046 llvm::Value *Addr = Builder.CreateStructGEP(
3047 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3048 Builder.restoreIP(IP);
3049 deferPlaceholderReplacement(Placeholder, Addr);
3050 } else {
3051 // Store the RValue into the argument struct.
3052 llvm::Value *Addr =
3053 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003054 unsigned AS = Addr->getType()->getPointerAddressSpace();
3055 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3056 // There are some cases where a trivial bitcast is not avoidable. The
3057 // definition of a type later in a translation unit may change it's type
3058 // from {}* to (%struct.foo*)*.
3059 if (Addr->getType() != MemType)
3060 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003061 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3062 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3063 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003064 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003065 }
3066
Daniel Dunbar03816342010-08-21 02:24:36 +00003067 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003068 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003069 if (RV.isScalar() || RV.isComplex()) {
3070 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003071 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3072 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3073 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003074 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003075
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003076 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003077 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003078 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003079 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003080 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003081 // 1. If the argument is not byval, and we are required to copy the
3082 // source. (This case doesn't occur on any common architecture.)
3083 // 2. If the argument is byval, RV is not sufficiently aligned, and
3084 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003085 // 3. If the argument is byval, but RV is located in an address space
3086 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003087 llvm::Value *Addr = RV.getAggregateAddr();
3088 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003089 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003090 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003091 const unsigned ArgAddrSpace =
3092 (FirstIRArg < IRFuncTy->getNumParams()
3093 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3094 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003095 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003096 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00003097 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3098 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003099 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003100 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3101 if (Align > AI->getAlignment())
3102 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003103 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003104 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003105 } else {
3106 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003107 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003108 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003109 }
3110 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003111 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003112
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003113 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003114 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003115 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003116
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003117 case ABIArgInfo::Extend:
3118 case ABIArgInfo::Direct: {
3119 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003120 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3121 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003122 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003123 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003124 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003125 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003126 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003127 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003128
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003129 // We might have to widen integers, but we should never truncate.
3130 if (ArgInfo.getCoerceToType() != V->getType() &&
3131 V->getType()->isIntegerTy())
3132 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3133
Chris Lattner3ce86682011-07-12 04:53:39 +00003134 // If the argument doesn't match, perform a bitcast to coerce it. This
3135 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003136 if (FirstIRArg < IRFuncTy->getNumParams() &&
3137 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3138 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3139 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003140 break;
3141 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003142
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003143 // FIXME: Avoid the conversion through memory if possible.
3144 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003145 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003146 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003147 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003148 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003149 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003150 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003151
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003152 // If the value is offset in memory, apply the offset now.
3153 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3154 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3155 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003156 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003157 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3158
3159 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003160
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003161 // Fast-isel and the optimizer generally like scalar values better than
3162 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003163 llvm::StructType *STy =
3164 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003165 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003166 llvm::Type *SrcTy =
3167 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3168 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3169 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3170
3171 // If the source type is smaller than the destination type of the
3172 // coerce-to logic, copy the source value into a temp alloca the size
3173 // of the destination type to allow loading all of it. The bits past
3174 // the source value are left undef.
3175 if (SrcSize < DstSize) {
3176 llvm::AllocaInst *TempAlloca
3177 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3178 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3179 SrcPtr = TempAlloca;
3180 } else {
3181 SrcPtr = Builder.CreateBitCast(SrcPtr,
3182 llvm::PointerType::getUnqual(STy));
3183 }
3184
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003185 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003186 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3187 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003188 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3189 // We don't know what we're loading from.
3190 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003191 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003192 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003193 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003194 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003195 assert(NumIRArgs == 1);
3196 IRCallArgs[FirstIRArg] =
3197 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003198 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003199
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003200 break;
3201 }
3202
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003203 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003204 unsigned IRArgPos = FirstIRArg;
3205 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3206 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003207 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003208 }
3209 }
Mike Stump11289f42009-09-09 15:08:12 +00003210
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003211 if (ArgMemory) {
3212 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003213 if (CallInfo.isVariadic()) {
3214 // When passing non-POD arguments by value to variadic functions, we will
3215 // end up with a variadic prototype and an inalloca call site. In such
3216 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3217 // the callee.
3218 unsigned CalleeAS =
3219 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3220 Callee = Builder.CreateBitCast(
3221 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3222 } else {
3223 llvm::Type *LastParamTy =
3224 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3225 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003226#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003227 // Assert that these structs have equivalent element types.
3228 llvm::StructType *FullTy = CallInfo.getArgStruct();
3229 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3230 cast<llvm::PointerType>(LastParamTy)->getElementType());
3231 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3232 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3233 DE = DeclaredTy->element_end(),
3234 FI = FullTy->element_begin();
3235 DI != DE; ++DI, ++FI)
3236 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003237#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003238 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3239 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003240 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003241 assert(IRFunctionArgs.hasInallocaArg());
3242 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003243 }
3244
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003245 if (!CallArgs.getCleanupsToDeactivate().empty())
3246 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3247
Chris Lattner4ca97c32009-06-13 00:26:38 +00003248 // If the callee is a bitcast of a function to a varargs pointer to function
3249 // type, check to see if we can remove the bitcast. This handles some cases
3250 // with unprototyped functions.
3251 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3252 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003253 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3254 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003255 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003256 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003257
Chris Lattner4ca97c32009-06-13 00:26:38 +00003258 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3259 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003260 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003261 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003262 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003263 bool ArgsMatch = true;
3264 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3265 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3266 ArgsMatch = false;
3267 break;
3268 }
Mike Stump11289f42009-09-09 15:08:12 +00003269
Chris Lattner4ca97c32009-06-13 00:26:38 +00003270 // Strip the cast if we can get away with it. This is a nice cleanup,
3271 // but also allows us to inline the function at -O0 if it is marked
3272 // always_inline.
3273 if (ArgsMatch)
3274 Callee = CalleeF;
3275 }
3276 }
Mike Stump11289f42009-09-09 15:08:12 +00003277
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003278 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3279 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3280 // Inalloca argument can have different type.
3281 if (IRFunctionArgs.hasInallocaArg() &&
3282 i == IRFunctionArgs.getInallocaArgNo())
3283 continue;
3284 if (i < IRFuncTy->getNumParams())
3285 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3286 }
3287
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003288 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003289 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003290 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3291 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003292 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003293 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003294
Craig Topper8a13c412014-05-21 05:09:00 +00003295 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003296 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3297 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003298 InvokeDest = getInvokeDest();
3299
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003300 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003301 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003302 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003303 } else {
3304 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003305 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003306 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003307 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003308 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003309 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003310
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003311 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3312 !CS.hasFnAttr(llvm::Attribute::NoInline))
3313 Attrs =
3314 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3315 llvm::Attribute::AlwaysInline);
3316
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003317 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003318 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003319
Dan Gohman515a60d2012-02-16 00:57:37 +00003320 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3321 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003322 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003323 AddObjCARCExceptionMetadata(CS.getInstruction());
3324
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003325 // If the call doesn't return, finish the basic block and clear the
3326 // insertion point; this allows the rest of IRgen to discard
3327 // unreachable code.
3328 if (CS.doesNotReturn()) {
3329 Builder.CreateUnreachable();
3330 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003331
Mike Stump18bb9282009-05-16 07:57:57 +00003332 // FIXME: For now, emit a dummy basic block because expr emitters in
3333 // generally are not ready to handle emitting expressions at unreachable
3334 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003335 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003336
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003337 // Return a reasonable RValue.
3338 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003339 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003340
3341 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003342 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003343 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003344
John McCall31168b02011-06-15 23:02:42 +00003345 // Emit any writebacks immediately. Arguably this should happen
3346 // after any return-value munging.
3347 if (CallArgs.hasWritebacks())
3348 emitWritebacks(*this, CallArgs);
3349
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003350 // The stack cleanup for inalloca arguments has to run out of the normal
3351 // lexical order, so deactivate it and run it manually here.
3352 CallArgs.freeArgumentMemory(*this);
3353
Hal Finkelee90a222014-09-26 05:04:30 +00003354 RValue Ret = [&] {
3355 switch (RetAI.getKind()) {
3356 case ABIArgInfo::InAlloca:
3357 case ABIArgInfo::Indirect:
3358 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003359
Hal Finkelee90a222014-09-26 05:04:30 +00003360 case ABIArgInfo::Ignore:
3361 // If we are ignoring an argument that had a result, make sure to
3362 // construct the appropriate return value for our caller.
3363 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003364
Hal Finkelee90a222014-09-26 05:04:30 +00003365 case ABIArgInfo::Extend:
3366 case ABIArgInfo::Direct: {
3367 llvm::Type *RetIRTy = ConvertType(RetTy);
3368 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3369 switch (getEvaluationKind(RetTy)) {
3370 case TEK_Complex: {
3371 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3372 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3373 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003374 }
Hal Finkelee90a222014-09-26 05:04:30 +00003375 case TEK_Aggregate: {
3376 llvm::Value *DestPtr = ReturnValue.getValue();
3377 bool DestIsVolatile = ReturnValue.isVolatile();
3378
3379 if (!DestPtr) {
3380 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3381 DestIsVolatile = false;
3382 }
3383 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3384 return RValue::getAggregate(DestPtr);
3385 }
3386 case TEK_Scalar: {
3387 // If the argument doesn't match, perform a bitcast to coerce it. This
3388 // can happen due to trivial type mismatches.
3389 llvm::Value *V = CI;
3390 if (V->getType() != RetIRTy)
3391 V = Builder.CreateBitCast(V, RetIRTy);
3392 return RValue::get(V);
3393 }
3394 }
3395 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003396 }
Hal Finkelee90a222014-09-26 05:04:30 +00003397
3398 llvm::Value *DestPtr = ReturnValue.getValue();
3399 bool DestIsVolatile = ReturnValue.isVolatile();
3400
3401 if (!DestPtr) {
3402 DestPtr = CreateMemTemp(RetTy, "coerce");
3403 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003404 }
Hal Finkelee90a222014-09-26 05:04:30 +00003405
3406 // If the value is offset in memory, apply the offset now.
3407 llvm::Value *StorePtr = DestPtr;
3408 if (unsigned Offs = RetAI.getDirectOffset()) {
3409 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3410 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3411 StorePtr = Builder.CreateBitCast(StorePtr,
3412 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003413 }
Hal Finkelee90a222014-09-26 05:04:30 +00003414 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3415
3416 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003417 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003418
Hal Finkelee90a222014-09-26 05:04:30 +00003419 case ABIArgInfo::Expand:
3420 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003421 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003422
Hal Finkelee90a222014-09-26 05:04:30 +00003423 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3424 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003425
Hal Finkelee90a222014-09-26 05:04:30 +00003426 if (Ret.isScalar() && TargetDecl) {
3427 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3428 llvm::Value *OffsetValue = nullptr;
3429 if (const auto *Offset = AA->getOffset())
3430 OffsetValue = EmitScalarExpr(Offset);
3431
3432 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3433 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3434 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3435 OffsetValue);
3436 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003437 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003438
Hal Finkelee90a222014-09-26 05:04:30 +00003439 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003440}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003441
3442/* VarArg handling */
3443
3444llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3445 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3446}