blob: b31cdf3a909001f3a6a41294d4bc74dc34187f7e [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.
53 case CC_X86VectorCall: return llvm::CallingConv::C;
John McCallab26cfa2010-02-05 21:31:56 +000054 }
55}
56
John McCall8ee376f2010-02-24 07:14:12 +000057/// Derives the 'this' type for codegen purposes, i.e. ignoring method
58/// qualification.
59/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000060static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
61 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
62 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000063}
64
John McCall8ee376f2010-02-24 07:14:12 +000065/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000066static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
67 return MD->getType()->getCanonicalTypeUnqualified()
68 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000069}
70
71/// Returns the "extra-canonicalized" return type, which discards
72/// qualifiers on the return type. Codegen doesn't care about them,
73/// and it makes ABI code a little easier to be able to assume that
74/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000075static CanQualType GetReturnType(QualType RetTy) {
76 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000077}
78
John McCall8dda7b22012-07-07 06:41:13 +000079/// Arrange the argument and result information for a value of the given
80/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000081const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000082CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000083 // When translating an unprototyped function type, always use a
84 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000085 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000086 false, None, FTNP->getExtInfo(),
87 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000088}
89
John McCall8dda7b22012-07-07 06:41:13 +000090/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000091/// type, on top of any implicit parameters already stored.
92static const CGFunctionInfo &
93arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
94 SmallVectorImpl<CanQualType> &prefix,
95 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000096 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000097 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000098 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
99 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +0000100 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +0000101 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000102 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000103}
104
John McCalla729c622012-02-17 03:33:10 +0000105/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000106/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000107const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000108CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000109 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000110 return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000111}
112
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000113static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000114 // Set the appropriate calling convention for the Function.
115 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000116 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117
118 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000119 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000120
Douglas Gregora941dca2010-05-18 16:57:00 +0000121 if (D->hasAttr<ThisCallAttr>())
122 return CC_X86ThisCall;
123
Reid Klecknerd7857f02014-10-24 17:42:17 +0000124 if (D->hasAttr<VectorCallAttr>())
125 return CC_X86VectorCall;
126
Dawn Perchik335e16b2010-09-03 01:29:35 +0000127 if (D->hasAttr<PascalAttr>())
128 return CC_X86Pascal;
129
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000130 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
131 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
132
Derek Schuffa2020962012-10-16 22:30:41 +0000133 if (D->hasAttr<PnaclCallAttr>())
134 return CC_PnaclCall;
135
Guy Benyeif0a014b2012-12-25 08:53:55 +0000136 if (D->hasAttr<IntelOclBiccAttr>())
137 return CC_IntelOclBicc;
138
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000139 if (D->hasAttr<MSABIAttr>())
140 return IsWindows ? CC_C : CC_X86_64Win64;
141
142 if (D->hasAttr<SysVABIAttr>())
143 return IsWindows ? CC_X86_64SysV : CC_C;
144
John McCallab26cfa2010-02-05 21:31:56 +0000145 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000146}
147
John McCalla729c622012-02-17 03:33:10 +0000148/// Arrange the argument and result information for a call to an
149/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000150/// (Zero value of RD means we don't have any meaningful "this" argument type,
151/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000152/// The member function must be an ordinary function, i.e. not a
153/// constructor or destructor.
154const CGFunctionInfo &
155CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
156 const FunctionProtoType *FTP) {
157 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000158
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000159 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000160 if (RD)
161 argTypes.push_back(GetThisType(Context, RD));
162 else
163 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000164
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000165 return ::arrangeLLVMFunctionInfo(
166 *this, true, argTypes,
167 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000168}
169
John McCalla729c622012-02-17 03:33:10 +0000170/// Arrange the argument and result information for a declaration or
171/// definition of the given C++ non-static member function. The
172/// member function must be an ordinary function, i.e. not a
173/// constructor or destructor.
174const CGFunctionInfo &
175CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000176 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000177 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
178
John McCalla729c622012-02-17 03:33:10 +0000179 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000180
John McCalla729c622012-02-17 03:33:10 +0000181 if (MD->isInstance()) {
182 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000183 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000184 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000185 }
186
John McCall8dda7b22012-07-07 06:41:13 +0000187 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000188}
189
John McCalla729c622012-02-17 03:33:10 +0000190const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000191CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
192 StructorType Type) {
193
John McCalla729c622012-02-17 03:33:10 +0000194 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000195 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000196
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000197 GlobalDecl GD;
198 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
199 GD = GlobalDecl(CD, toCXXCtorType(Type));
200 } else {
201 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
202 GD = GlobalDecl(DD, toCXXDtorType(Type));
203 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000204
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000205 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000206
207 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000208 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
209 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000210
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000212
213 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000214 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000215
John McCall8dda7b22012-07-07 06:41:13 +0000216 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000217 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
218 ? argTypes.front()
219 : TheCXXABI.hasMostDerivedReturn(GD)
220 ? CGM.getContext().VoidPtrTy
221 : Context.VoidTy;
Reid Kleckner4982b822014-01-31 22:54:50 +0000222 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000223}
224
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000225/// Arrange a call to a C++ method, passing the given arguments.
226const CGFunctionInfo &
227CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
228 const CXXConstructorDecl *D,
229 CXXCtorType CtorKind,
230 unsigned ExtraArgs) {
231 // FIXME: Kill copy.
232 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000233 for (const auto &Arg : args)
234 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000235
236 CanQual<FunctionProtoType> FPT = GetFormalType(D);
237 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
238 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000239 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
240 ? ArgTypes.front()
241 : TheCXXABI.hasMostDerivedReturn(GD)
242 ? CGM.getContext().VoidPtrTy
243 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000244
245 FunctionType::ExtInfo Info = FPT->getExtInfo();
246 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
247}
248
John McCalla729c622012-02-17 03:33:10 +0000249/// Arrange the argument and result information for the declaration or
250/// definition of the given function.
251const CGFunctionInfo &
252CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000253 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000254 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000255 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000256
John McCall2da83a32010-02-26 00:48:12 +0000257 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000258
John McCall2da83a32010-02-26 00:48:12 +0000259 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000260
261 // When declaring a function without a prototype, always use a
262 // non-variadic type.
263 if (isa<FunctionNoProtoType>(FTy)) {
264 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000265 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000266 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000267 }
268
John McCall2da83a32010-02-26 00:48:12 +0000269 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000270 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000271}
272
John McCalla729c622012-02-17 03:33:10 +0000273/// Arrange the argument and result information for the declaration or
274/// definition of an Objective-C method.
275const CGFunctionInfo &
276CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
277 // It happens that this is the same as a call with no optional
278 // arguments, except also using the formal 'self' type.
279 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
280}
281
282/// Arrange the argument and result information for the function type
283/// through which to perform a send to the given Objective-C method,
284/// using the given receiver type. The receiver type is not always
285/// the 'self' type of the method or even an Objective-C pointer type.
286/// This is *not* the right method for actually performing such a
287/// message send, due to the possibility of optional arguments.
288const CGFunctionInfo &
289CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
290 QualType receiverType) {
291 SmallVector<CanQualType, 16> argTys;
292 argTys.push_back(Context.getCanonicalParamType(receiverType));
293 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000294 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000295 for (const auto *I : MD->params()) {
296 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000297 }
John McCall31168b02011-06-15 23:02:42 +0000298
299 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000300 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
301 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000302
David Blaikiebbafb8a2012-03-11 07:00:24 +0000303 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000304 MD->hasAttr<NSReturnsRetainedAttr>())
305 einfo = einfo.withProducesResult(true);
306
John McCalla729c622012-02-17 03:33:10 +0000307 RequiredArgs required =
308 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
309
Reid Kleckner4982b822014-01-31 22:54:50 +0000310 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
311 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000312}
313
John McCalla729c622012-02-17 03:33:10 +0000314const CGFunctionInfo &
315CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000316 // FIXME: Do we need to handle ObjCMethodDecl?
317 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000318
Anders Carlsson6710c532010-02-06 02:44:09 +0000319 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000320 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000321
322 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000323 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000324
John McCalla729c622012-02-17 03:33:10 +0000325 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000326}
327
Reid Klecknerc3473512014-08-29 21:43:29 +0000328/// Arrange a thunk that takes 'this' as the first parameter followed by
329/// varargs. Return a void pointer, regardless of the actual return type.
330/// The body of the thunk will end in a musttail call to a function of the
331/// correct type, and the caller will bitcast the function to the correct
332/// prototype.
333const CGFunctionInfo &
334CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
335 assert(MD->isVirtual() && "only virtual memptrs have thunks");
336 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
337 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
338 return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
339 FTP->getExtInfo(), RequiredArgs(1));
340}
341
John McCallc818bbb2012-12-07 07:03:17 +0000342/// Arrange a call as unto a free function, except possibly with an
343/// additional number of formal parameters considered required.
344static const CGFunctionInfo &
345arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000346 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000347 const CallArgList &args,
348 const FunctionType *fnType,
349 unsigned numExtraRequiredArgs) {
350 assert(args.size() >= numExtraRequiredArgs);
351
352 // In most cases, there are no optional arguments.
353 RequiredArgs required = RequiredArgs::All;
354
355 // If we have a variadic prototype, the required arguments are the
356 // extra prefix plus the arguments in the prototype.
357 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
358 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000359 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000360
361 // If we don't have a prototype at all, but we're supposed to
362 // explicitly use the variadic convention for unprototyped calls,
363 // treat all of the arguments as required but preserve the nominal
364 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000365 } else if (CGM.getTargetCodeGenInfo()
366 .isNoProtoCallVariadic(args,
367 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000368 required = RequiredArgs(args.size());
369 }
370
Alp Toker314cc812014-01-25 16:55:45 +0000371 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000372 fnType->getExtInfo(), required);
373}
374
John McCalla729c622012-02-17 03:33:10 +0000375/// Figure out the rules for calling a function with the given formal
376/// type using the given arguments. The arguments are necessary
377/// because the function might be unprototyped, in which case it's
378/// target-dependent in crazy ways.
379const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000380CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
381 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000382 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000383}
John McCalla729c622012-02-17 03:33:10 +0000384
John McCallc818bbb2012-12-07 07:03:17 +0000385/// A block function call is essentially a free-function call with an
386/// extra implicit argument.
387const CGFunctionInfo &
388CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
389 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000390 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000391}
392
393const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000394CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
395 const CallArgList &args,
396 FunctionType::ExtInfo info,
397 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000398 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000399 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000400 for (const auto &Arg : args)
401 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000402 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
403 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000404}
405
406/// Arrange a call to a C++ method, passing the given arguments.
407const CGFunctionInfo &
408CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
409 const FunctionProtoType *FPT,
410 RequiredArgs required) {
411 // FIXME: Kill copy.
412 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000413 for (const auto &Arg : args)
414 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000415
416 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000417 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
418 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000419}
420
Reid Kleckner4982b822014-01-31 22:54:50 +0000421const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
422 QualType resultType, const FunctionArgList &args,
423 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000424 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000425 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000426 for (auto Arg : args)
427 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000428
429 RequiredArgs required =
430 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000431 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000432 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000433}
434
John McCalla729c622012-02-17 03:33:10 +0000435const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000436 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000437 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000438}
439
John McCalla729c622012-02-17 03:33:10 +0000440/// Arrange the argument and result information for an abstract value
441/// of a given function type. This is the method which all of the
442/// above functions ultimately defer to.
443const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000444CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000445 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000446 ArrayRef<CanQualType> argTypes,
447 FunctionType::ExtInfo info,
448 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000449#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000450 for (ArrayRef<CanQualType>::const_iterator
451 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000452 assert(I->isCanonicalAsParam());
453#endif
454
John McCalla729c622012-02-17 03:33:10 +0000455 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000456
Daniel Dunbare0be8292009-02-03 00:07:12 +0000457 // Lookup or create unique function info.
458 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000459 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
460 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000461
Craig Topper8a13c412014-05-21 05:09:00 +0000462 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000463 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000464 if (FI)
465 return *FI;
466
John McCalla729c622012-02-17 03:33:10 +0000467 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000468 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
469 required);
John McCalla729c622012-02-17 03:33:10 +0000470 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000471
John McCalla729c622012-02-17 03:33:10 +0000472 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
473 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000474
Daniel Dunbar313321e2009-02-03 05:31:23 +0000475 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000476 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000477
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000478 // Loop over all of the computed argument and return value info. If any of
479 // them are direct or extend without a specified coerce type, specify the
480 // default now.
John McCalla729c622012-02-17 03:33:10 +0000481 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000482 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000483 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000484
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000485 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000486 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000487 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000488
John McCalla729c622012-02-17 03:33:10 +0000489 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
490 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000491
Daniel Dunbare0be8292009-02-03 00:07:12 +0000492 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000493}
494
John McCalla729c622012-02-17 03:33:10 +0000495CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000496 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000497 const FunctionType::ExtInfo &info,
498 CanQualType resultType,
499 ArrayRef<CanQualType> argTypes,
500 RequiredArgs required) {
501 void *buffer = operator new(sizeof(CGFunctionInfo) +
502 sizeof(ArgInfo) * (argTypes.size() + 1));
503 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
504 FI->CallingConvention = llvmCC;
505 FI->EffectiveCallingConvention = llvmCC;
506 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000507 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000508 FI->NoReturn = info.getNoReturn();
509 FI->ReturnsRetained = info.getProducesResult();
510 FI->Required = required;
511 FI->HasRegParm = info.getHasRegParm();
512 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000513 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000514 FI->NumArgs = argTypes.size();
515 FI->getArgsBuffer()[0].type = resultType;
516 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
517 FI->getArgsBuffer()[i + 1].type = argTypes[i];
518 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000519}
520
521/***/
522
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000523namespace {
524// ABIArgInfo::Expand implementation.
525
526// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
527struct TypeExpansion {
528 enum TypeExpansionKind {
529 // Elements of constant arrays are expanded recursively.
530 TEK_ConstantArray,
531 // Record fields are expanded recursively (but if record is a union, only
532 // the field with the largest size is expanded).
533 TEK_Record,
534 // For complex types, real and imaginary parts are expanded recursively.
535 TEK_Complex,
536 // All other types are not expandable.
537 TEK_None
538 };
539
540 const TypeExpansionKind Kind;
541
542 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
543 virtual ~TypeExpansion() {}
544};
545
546struct ConstantArrayExpansion : TypeExpansion {
547 QualType EltTy;
548 uint64_t NumElts;
549
550 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
551 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
552 static bool classof(const TypeExpansion *TE) {
553 return TE->Kind == TEK_ConstantArray;
554 }
555};
556
557struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000558 SmallVector<const CXXBaseSpecifier *, 1> Bases;
559
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000560 SmallVector<const FieldDecl *, 1> Fields;
561
Reid Klecknere9f6a712014-10-31 17:10:41 +0000562 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
563 SmallVector<const FieldDecl *, 1> &&Fields)
564 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000565 static bool classof(const TypeExpansion *TE) {
566 return TE->Kind == TEK_Record;
567 }
568};
569
570struct ComplexExpansion : TypeExpansion {
571 QualType EltTy;
572
573 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
574 static bool classof(const TypeExpansion *TE) {
575 return TE->Kind == TEK_Complex;
576 }
577};
578
579struct NoExpansion : TypeExpansion {
580 NoExpansion() : TypeExpansion(TEK_None) {}
581 static bool classof(const TypeExpansion *TE) {
582 return TE->Kind == TEK_None;
583 }
584};
585} // namespace
586
587static std::unique_ptr<TypeExpansion>
588getTypeExpansion(QualType Ty, const ASTContext &Context) {
589 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
590 return llvm::make_unique<ConstantArrayExpansion>(
591 AT->getElementType(), AT->getSize().getZExtValue());
592 }
593 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000594 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000595 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000596 const RecordDecl *RD = RT->getDecl();
597 assert(!RD->hasFlexibleArrayMember() &&
598 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000599 if (RD->isUnion()) {
600 // Unions can be here only in degenerative cases - all the fields are same
601 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000602 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000603 CharUnits UnionSize = CharUnits::Zero();
604
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000605 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000606 assert(!FD->isBitField() &&
607 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000608 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000609 if (UnionSize < FieldSize) {
610 UnionSize = FieldSize;
611 LargestFD = FD;
612 }
613 }
614 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000615 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000616 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000617 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
618 assert(!CXXRD->isDynamicClass() &&
619 "cannot expand vtable pointers in dynamic classes");
620 for (const CXXBaseSpecifier &BS : CXXRD->bases())
621 Bases.push_back(&BS);
622 }
623
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000624 for (const auto *FD : RD->fields()) {
625 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000626 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000627 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000628 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000629 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000630 return llvm::make_unique<RecordExpansion>(std::move(Bases),
631 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000632 }
633 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
634 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
635 }
636 return llvm::make_unique<NoExpansion>();
637}
638
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000639static int getExpansionSize(QualType Ty, const ASTContext &Context) {
640 auto Exp = getTypeExpansion(Ty, Context);
641 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
642 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
643 }
644 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
645 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000646 for (auto BS : RExp->Bases)
647 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000648 for (auto FD : RExp->Fields)
649 Res += getExpansionSize(FD->getType(), Context);
650 return Res;
651 }
652 if (isa<ComplexExpansion>(Exp.get()))
653 return 2;
654 assert(isa<NoExpansion>(Exp.get()));
655 return 1;
656}
657
Alexey Samsonov153004f2014-09-29 22:08:00 +0000658void
659CodeGenTypes::getExpandedTypes(QualType Ty,
660 SmallVectorImpl<llvm::Type *>::iterator &TI) {
661 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000662 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
663 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000664 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000665 }
666 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000667 for (auto BS : RExp->Bases)
668 getExpandedTypes(BS->getType(), TI);
669 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000670 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000671 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
672 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000673 *TI++ = EltTy;
674 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000675 } else {
676 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000677 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000678 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000679}
680
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000681void CodeGenFunction::ExpandTypeFromArgs(
682 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000683 assert(LV.isSimple() &&
684 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000685
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000686 auto Exp = getTypeExpansion(Ty, getContext());
687 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
688 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
689 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
690 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
691 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000692 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000693 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000694 llvm::Value *This = LV.getAddress();
695 for (const CXXBaseSpecifier *BS : RExp->Bases) {
696 // Perform a single step derived-to-base conversion.
697 llvm::Value *Base =
698 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
699 /*NullCheckValue=*/false, SourceLocation());
700 LValue SubLV = MakeAddrLValue(Base, BS->getType());
701
702 // Recurse onto bases.
703 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
704 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000705 for (auto FD : RExp->Fields) {
706 // FIXME: What are the right qualifiers here?
707 LValue SubLV = EmitLValueForField(LV, FD);
708 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000709 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000710 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000711 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000712 EmitStoreThroughLValue(RValue::get(*AI++),
713 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000714 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000715 EmitStoreThroughLValue(RValue::get(*AI++),
716 MakeAddrLValue(ImagAddr, CExp->EltTy));
717 } else {
718 assert(isa<NoExpansion>(Exp.get()));
719 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000720 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000721}
722
723void CodeGenFunction::ExpandTypeToArgs(
724 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
725 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
726 auto Exp = getTypeExpansion(Ty, getContext());
727 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
728 llvm::Value *Addr = RV.getAggregateAddr();
729 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
730 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
731 RValue EltRV =
732 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
733 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
734 }
735 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000736 llvm::Value *This = RV.getAggregateAddr();
737 for (const CXXBaseSpecifier *BS : RExp->Bases) {
738 // Perform a single step derived-to-base conversion.
739 llvm::Value *Base =
740 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
741 /*NullCheckValue=*/false, SourceLocation());
742 RValue BaseRV = RValue::getAggregate(Base);
743
744 // Recurse onto bases.
745 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
746 IRCallArgPos);
747 }
748
749 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000750 for (auto FD : RExp->Fields) {
751 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
752 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
753 IRCallArgPos);
754 }
755 } else if (isa<ComplexExpansion>(Exp.get())) {
756 ComplexPairTy CV = RV.getComplexVal();
757 IRCallArgs[IRCallArgPos++] = CV.first;
758 IRCallArgs[IRCallArgPos++] = CV.second;
759 } else {
760 assert(isa<NoExpansion>(Exp.get()));
761 assert(RV.isScalar() &&
762 "Unexpected non-scalar rvalue during struct expansion.");
763
764 // Insert a bitcast as needed.
765 llvm::Value *V = RV.getScalarVal();
766 if (IRCallArgPos < IRFuncTy->getNumParams() &&
767 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
768 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
769
770 IRCallArgs[IRCallArgPos++] = V;
771 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000772}
773
Chris Lattner895c52b2010-06-27 06:04:18 +0000774/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000775/// accessing some number of bytes out of it, try to gep into the struct to get
776/// at its inner goodness. Dive as deep as possible without entering an element
777/// with an in-memory size smaller than DstSize.
778static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000779EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000780 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000781 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000782 // We can't dive into a zero-element struct.
783 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000784
Chris Lattner2192fe52011-07-18 04:24:23 +0000785 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000786
Chris Lattner1cd66982010-06-27 05:56:15 +0000787 // 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 +0000788 // first element is the same size as the whole struct, we can enter it. The
789 // comparison must be made on the store size and not the alloca size. Using
790 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000791 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000792 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000793 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000794 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000795 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000796
Chris Lattner1cd66982010-06-27 05:56:15 +0000797 // GEP into the first element.
798 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000799
Chris Lattner1cd66982010-06-27 05:56:15 +0000800 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000801 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000802 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000803 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000804 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000805
806 return SrcPtr;
807}
808
Chris Lattner055097f2010-06-27 06:26:04 +0000809/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
810/// are either integers or pointers. This does a truncation of the value if it
811/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000812///
813/// This behaves as if the value were coerced through memory, so on big-endian
814/// targets the high bits are preserved in a truncation, while little-endian
815/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000816static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000817 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000818 CodeGenFunction &CGF) {
819 if (Val->getType() == Ty)
820 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000821
Chris Lattner055097f2010-06-27 06:26:04 +0000822 if (isa<llvm::PointerType>(Val->getType())) {
823 // If this is Pointer->Pointer avoid conversion to and from int.
824 if (isa<llvm::PointerType>(Ty))
825 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000826
Chris Lattner055097f2010-06-27 06:26:04 +0000827 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000828 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000829 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000830
Chris Lattner2192fe52011-07-18 04:24:23 +0000831 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000832 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000833 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000834
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000835 if (Val->getType() != DestIntTy) {
836 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
837 if (DL.isBigEndian()) {
838 // Preserve the high bits on big-endian targets.
839 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000840 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
841 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
842
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000843 if (SrcSize > DstSize) {
844 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
845 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
846 } else {
847 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
848 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
849 }
850 } else {
851 // Little-endian targets preserve the low bits. No shifts required.
852 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
853 }
854 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000855
Chris Lattner055097f2010-06-27 06:26:04 +0000856 if (isa<llvm::PointerType>(Ty))
857 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
858 return Val;
859}
860
Chris Lattner1cd66982010-06-27 05:56:15 +0000861
862
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000863/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
864/// a pointer to an object of type \arg Ty.
865///
866/// This safely handles the case when the src type is smaller than the
867/// destination type; in this situation the values of bits which not
868/// present in the src are undefined.
869static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000870 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000871 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000872 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000873 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000874
Chris Lattnerd200eda2010-06-28 22:51:39 +0000875 // If SrcTy and Ty are the same, just do a load.
876 if (SrcTy == Ty)
877 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000878
Micah Villmowdd31ca12012-10-08 16:25:52 +0000879 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000880
Chris Lattner2192fe52011-07-18 04:24:23 +0000881 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000882 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000883 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
884 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000885
Micah Villmowdd31ca12012-10-08 16:25:52 +0000886 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000887
Chris Lattner055097f2010-06-27 06:26:04 +0000888 // If the source and destination are integer or pointer types, just do an
889 // extension or truncation to the desired type.
890 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
891 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
892 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
893 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
894 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000895
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000896 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000897 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000898 // Generally SrcSize is never greater than DstSize, since this means we are
899 // losing bits. However, this can happen in cases where the structure has
900 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000901 //
Mike Stump18bb9282009-05-16 07:57:57 +0000902 // FIXME: Assert that we aren't truncating non-padding bits when have access
903 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000904 llvm::Value *Casted =
905 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000906 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
907 // FIXME: Use better alignment / avoid requiring aligned load.
908 Load->setAlignment(1);
909 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000910 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000911
Chris Lattner3fcc7902010-06-27 01:06:27 +0000912 // Otherwise do coercion through memory. This is stupid, but
913 // simple.
914 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000915 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
916 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
917 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000918 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000919 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
920 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
921 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000922 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000923}
924
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000925// Function to store a first-class aggregate into memory. We prefer to
926// store the elements rather than the aggregate to be more friendly to
927// fast-isel.
928// FIXME: Do we need to recurse here?
929static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
930 llvm::Value *DestPtr, bool DestIsVolatile,
931 bool LowAlignment) {
932 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000933 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000934 dyn_cast<llvm::StructType>(Val->getType())) {
935 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
936 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
937 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
938 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
939 DestIsVolatile);
940 if (LowAlignment)
941 SI->setAlignment(1);
942 }
943 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000944 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
945 if (LowAlignment)
946 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000947 }
948}
949
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000950/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
951/// where the source and destination may have different types.
952///
953/// This safely handles the case when the src type is larger than the
954/// destination type; the upper bits of the src will be lost.
955static void CreateCoercedStore(llvm::Value *Src,
956 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000957 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000958 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000959 llvm::Type *SrcTy = Src->getType();
960 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000961 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000962 if (SrcTy == DstTy) {
963 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
964 return;
965 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000966
Micah Villmowdd31ca12012-10-08 16:25:52 +0000967 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000968
Chris Lattner2192fe52011-07-18 04:24:23 +0000969 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000970 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
971 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
972 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000973
Chris Lattner055097f2010-06-27 06:26:04 +0000974 // If the source and destination are integer or pointer types, just do an
975 // extension or truncation to the desired type.
976 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
977 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
978 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
979 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
980 return;
981 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000982
Micah Villmowdd31ca12012-10-08 16:25:52 +0000983 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000984
Daniel Dunbar313321e2009-02-03 05:31:23 +0000985 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000986 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000987 llvm::Value *Casted =
988 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000989 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000990 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000991 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000992 // Otherwise do coercion through memory. This is stupid, but
993 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000994
995 // Generally SrcSize is never greater than DstSize, since this means we are
996 // losing bits. However, this can happen in cases where the structure has
997 // additional padding, for example due to a user specified alignment.
998 //
999 // FIXME: Assert that we aren't truncating non-padding bits when have access
1000 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001001 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1002 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001003 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1004 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1005 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001006 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001007 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1008 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1009 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001010 }
1011}
1012
Alexey Samsonov153004f2014-09-29 22:08:00 +00001013namespace {
1014
1015/// Encapsulates information about the way function arguments from
1016/// CGFunctionInfo should be passed to actual LLVM IR function.
1017class ClangToLLVMArgMapping {
1018 static const unsigned InvalidIndex = ~0U;
1019 unsigned InallocaArgNo;
1020 unsigned SRetArgNo;
1021 unsigned TotalIRArgs;
1022
1023 /// Arguments of LLVM IR function corresponding to single Clang argument.
1024 struct IRArgs {
1025 unsigned PaddingArgIndex;
1026 // Argument is expanded to IR arguments at positions
1027 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1028 unsigned FirstArgIndex;
1029 unsigned NumberOfArgs;
1030
1031 IRArgs()
1032 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1033 NumberOfArgs(0) {}
1034 };
1035
1036 SmallVector<IRArgs, 8> ArgInfo;
1037
1038public:
1039 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1040 bool OnlyRequiredArgs = false)
1041 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1042 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1043 construct(Context, FI, OnlyRequiredArgs);
1044 }
1045
1046 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1047 unsigned getInallocaArgNo() const {
1048 assert(hasInallocaArg());
1049 return InallocaArgNo;
1050 }
1051
1052 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1053 unsigned getSRetArgNo() const {
1054 assert(hasSRetArg());
1055 return SRetArgNo;
1056 }
1057
1058 unsigned totalIRArgs() const { return TotalIRArgs; }
1059
1060 bool hasPaddingArg(unsigned ArgNo) const {
1061 assert(ArgNo < ArgInfo.size());
1062 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1063 }
1064 unsigned getPaddingArgNo(unsigned ArgNo) const {
1065 assert(hasPaddingArg(ArgNo));
1066 return ArgInfo[ArgNo].PaddingArgIndex;
1067 }
1068
1069 /// Returns index of first IR argument corresponding to ArgNo, and their
1070 /// quantity.
1071 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1072 assert(ArgNo < ArgInfo.size());
1073 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1074 ArgInfo[ArgNo].NumberOfArgs);
1075 }
1076
1077private:
1078 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1079 bool OnlyRequiredArgs);
1080};
1081
1082void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1083 const CGFunctionInfo &FI,
1084 bool OnlyRequiredArgs) {
1085 unsigned IRArgNo = 0;
1086 bool SwapThisWithSRet = false;
1087 const ABIArgInfo &RetAI = FI.getReturnInfo();
1088
1089 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1090 SwapThisWithSRet = RetAI.isSRetAfterThis();
1091 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1092 }
1093
1094 unsigned ArgNo = 0;
1095 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1096 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1097 ++I, ++ArgNo) {
1098 assert(I != FI.arg_end());
1099 QualType ArgType = I->type;
1100 const ABIArgInfo &AI = I->info;
1101 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1102 auto &IRArgs = ArgInfo[ArgNo];
1103
1104 if (AI.getPaddingType())
1105 IRArgs.PaddingArgIndex = IRArgNo++;
1106
1107 switch (AI.getKind()) {
1108 case ABIArgInfo::Extend:
1109 case ABIArgInfo::Direct: {
1110 // FIXME: handle sseregparm someday...
1111 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1112 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1113 IRArgs.NumberOfArgs = STy->getNumElements();
1114 } else {
1115 IRArgs.NumberOfArgs = 1;
1116 }
1117 break;
1118 }
1119 case ABIArgInfo::Indirect:
1120 IRArgs.NumberOfArgs = 1;
1121 break;
1122 case ABIArgInfo::Ignore:
1123 case ABIArgInfo::InAlloca:
1124 // ignore and inalloca doesn't have matching LLVM parameters.
1125 IRArgs.NumberOfArgs = 0;
1126 break;
1127 case ABIArgInfo::Expand: {
1128 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1129 break;
1130 }
1131 }
1132
1133 if (IRArgs.NumberOfArgs > 0) {
1134 IRArgs.FirstArgIndex = IRArgNo;
1135 IRArgNo += IRArgs.NumberOfArgs;
1136 }
1137
1138 // Skip over the sret parameter when it comes second. We already handled it
1139 // above.
1140 if (IRArgNo == 1 && SwapThisWithSRet)
1141 IRArgNo++;
1142 }
1143 assert(ArgNo == ArgInfo.size());
1144
1145 if (FI.usesInAlloca())
1146 InallocaArgNo = IRArgNo++;
1147
1148 TotalIRArgs = IRArgNo;
1149}
1150} // namespace
1151
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001152/***/
1153
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001154bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001155 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001156}
1157
Tim Northovere77cc392014-03-29 13:28:05 +00001158bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1159 return ReturnTypeUsesSRet(FI) &&
1160 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1161}
1162
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001163bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1164 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1165 switch (BT->getKind()) {
1166 default:
1167 return false;
1168 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001169 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001170 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001171 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001172 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001173 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001174 }
1175 }
1176
1177 return false;
1178}
1179
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001180bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1181 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1182 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1183 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001184 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001185 }
1186 }
1187
1188 return false;
1189}
1190
Chris Lattnera5f58b02011-07-09 17:41:47 +00001191llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001192 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1193 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001194}
1195
Chris Lattnera5f58b02011-07-09 17:41:47 +00001196llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001197CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001198
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001199 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
1200 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001201
Alexey Samsonov153004f2014-09-29 22:08:00 +00001202 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001203 const ABIArgInfo &retAI = FI.getReturnInfo();
1204 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001205 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001206 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001207
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001208 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001209 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001210 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001211 break;
1212
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001213 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001214 if (retAI.getInAllocaSRet()) {
1215 // sret things on win32 aren't void, they return the sret pointer.
1216 QualType ret = FI.getReturnType();
1217 llvm::Type *ty = ConvertType(ret);
1218 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1219 resultType = llvm::PointerType::get(ty, addressSpace);
1220 } else {
1221 resultType = llvm::Type::getVoidTy(getLLVMContext());
1222 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001223 break;
1224
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001225 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001226 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1227 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001228 break;
1229 }
1230
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001231 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001232 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001233 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001234 }
Mike Stump11289f42009-09-09 15:08:12 +00001235
Alexey Samsonov153004f2014-09-29 22:08:00 +00001236 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1237 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1238
1239 // Add type for sret argument.
1240 if (IRFunctionArgs.hasSRetArg()) {
1241 QualType Ret = FI.getReturnType();
1242 llvm::Type *Ty = ConvertType(Ret);
1243 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1244 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1245 llvm::PointerType::get(Ty, AddressSpace);
1246 }
1247
1248 // Add type for inalloca argument.
1249 if (IRFunctionArgs.hasInallocaArg()) {
1250 auto ArgStruct = FI.getArgStruct();
1251 assert(ArgStruct);
1252 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1253 }
1254
John McCallc818bbb2012-12-07 07:03:17 +00001255 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001256 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001257 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1258 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001259 for (; it != ie; ++it, ++ArgNo) {
1260 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001261
Rafael Espindolafad28de2012-10-24 01:59:00 +00001262 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001263 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1264 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1265 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001266
Alexey Samsonov153004f2014-09-29 22:08:00 +00001267 unsigned FirstIRArg, NumIRArgs;
1268 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1269
1270 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001271 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001272 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001273 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001274 break;
1275
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001276 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001277 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001278 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001279 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001280 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001281 break;
1282 }
1283
1284 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001285 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001286 // Fast-isel and the optimizer generally like scalar values better than
1287 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001288 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001289 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001290 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1291 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001292 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001293 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001294 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001295 assert(NumIRArgs == 1);
1296 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001297 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001298 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Daniel Dunbard3674e62008-09-11 01:48:57 +00001301 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001302 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1303 getExpandedTypes(it->type, ArgTypesIter);
1304 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001305 break;
1306 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001307 }
1308
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001309 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1310 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001311
1312 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001313}
1314
Chris Lattner2192fe52011-07-18 04:24:23 +00001315llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001316 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001317 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001318
Chris Lattner8806e322011-07-10 00:18:59 +00001319 if (!isFuncTypeConvertible(FPT))
1320 return llvm::StructType::get(getLLVMContext());
1321
1322 const CGFunctionInfo *Info;
1323 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001324 Info =
1325 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001326 else
John McCalla729c622012-02-17 03:33:10 +00001327 Info = &arrangeCXXMethodDeclaration(MD);
1328 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001329}
1330
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001331void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001332 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001333 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001334 unsigned &CallingConv,
1335 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001336 llvm::AttrBuilder FuncAttrs;
1337 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001338
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001339 CallingConv = FI.getEffectiveCallingConvention();
1340
John McCallab26cfa2010-02-05 21:31:56 +00001341 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001342 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001343
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001344 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001345 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001346 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001347 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001348 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001349 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001350 if (TargetDecl->hasAttr<NoReturnAttr>())
1351 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001352 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1353 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001354
1355 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001356 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001357 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001358 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001359 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1360 // These attributes are not inherited by overloads.
1361 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1362 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001363 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001364 }
1365
Eric Christopherbf005ec2011-08-15 22:38:22 +00001366 // 'const' and 'pure' attribute functions are also nounwind.
1367 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001368 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1369 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001370 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001371 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1372 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001373 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001374 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001375 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001376 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1377 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001378 }
1379
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001380 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001381 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001382 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001383 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001384 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001385 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001386 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001387 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001388 if (CodeGenOpts.EnableSegmentedStacks &&
1389 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001390 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001391
Bill Wendling2f81db62013-02-22 20:53:29 +00001392 if (AttrOnCallSite) {
1393 // Attributes that should go on the call site only.
1394 if (!CodeGenOpts.SimplifyLibCalls)
1395 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001396 } else {
1397 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001398 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001399 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001400 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001401 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001402 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001403 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001404 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001405 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001406 }
1407
Bill Wendlingdabafea2013-03-13 22:24:33 +00001408 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001409 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001410 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001411 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001412 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001413 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001414 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001415 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001416 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001417 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001418 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001419 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001420
Bill Wendlingd8f49502013-08-01 21:41:02 +00001421 if (!CodeGenOpts.StackRealignment)
1422 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001423 }
1424
Alexey Samsonov153004f2014-09-29 22:08:00 +00001425 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001426
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001427 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001428 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001429 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001430 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001431 if (RetTy->hasSignedIntegerRepresentation())
1432 RetAttrs.addAttribute(llvm::Attribute::SExt);
1433 else if (RetTy->hasUnsignedIntegerRepresentation())
1434 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001435 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001436 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001437 if (RetAI.getInReg())
1438 RetAttrs.addAttribute(llvm::Attribute::InReg);
1439 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001440 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001441 break;
1442
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001443 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001444 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001445 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001446 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1447 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001448 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001449 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001450
Daniel Dunbard3674e62008-09-11 01:48:57 +00001451 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001452 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001453 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001454
Hal Finkela2347ba2014-07-18 15:52:10 +00001455 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1456 QualType PTy = RefTy->getPointeeType();
1457 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1458 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1459 .getQuantity());
1460 else if (getContext().getTargetAddressSpace(PTy) == 0)
1461 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1462 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001463
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001464 // Attach return attributes.
1465 if (RetAttrs.hasAttributes()) {
1466 PAL.push_back(llvm::AttributeSet::get(
1467 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1468 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001469
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001470 // Attach attributes to sret.
1471 if (IRFunctionArgs.hasSRetArg()) {
1472 llvm::AttrBuilder SRETAttrs;
1473 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1474 if (RetAI.getInReg())
1475 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1476 PAL.push_back(llvm::AttributeSet::get(
1477 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1478 }
1479
1480 // Attach attributes to inalloca argument.
1481 if (IRFunctionArgs.hasInallocaArg()) {
1482 llvm::AttrBuilder Attrs;
1483 Attrs.addAttribute(llvm::Attribute::InAlloca);
1484 PAL.push_back(llvm::AttributeSet::get(
1485 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1486 }
1487
1488
1489 unsigned ArgNo = 0;
1490 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1491 E = FI.arg_end();
1492 I != E; ++I, ++ArgNo) {
1493 QualType ParamType = I->type;
1494 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001495 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001496
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001497 // Add attribute for padding argument, if necessary.
1498 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001499 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001500 PAL.push_back(llvm::AttributeSet::get(
1501 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1502 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001503 }
1504
John McCall39ec71f2010-03-27 00:47:27 +00001505 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1506 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001507 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001508 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001509 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001510 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001511 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001512 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001513 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001514 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001515 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001516 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001517 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001518 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001519
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001520 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001521 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001522 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523
Anders Carlsson20759ad2009-09-16 15:53:40 +00001524 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001525 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001526
Bill Wendlinga7912f82012-10-10 07:36:56 +00001527 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1528
Daniel Dunbarc2304432009-03-18 19:51:01 +00001529 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001530 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1531 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001532 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001533
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001534 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001535 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001536 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001537
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001538 case ABIArgInfo::InAlloca:
1539 // inalloca disables readnone and readonly.
1540 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1541 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001542 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001543 }
Mike Stump11289f42009-09-09 15:08:12 +00001544
Hal Finkela2347ba2014-07-18 15:52:10 +00001545 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1546 QualType PTy = RefTy->getPointeeType();
1547 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1548 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1549 .getQuantity());
1550 else if (getContext().getTargetAddressSpace(PTy) == 0)
1551 Attrs.addAttribute(llvm::Attribute::NonNull);
1552 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001553
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001554 if (Attrs.hasAttributes()) {
1555 unsigned FirstIRArg, NumIRArgs;
1556 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1557 for (unsigned i = 0; i < NumIRArgs; i++)
1558 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1559 FirstIRArg + i + 1, Attrs));
1560 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001561 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001562 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001563
Bill Wendlinga7912f82012-10-10 07:36:56 +00001564 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001565 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001566 AttributeSet::get(getLLVMContext(),
1567 llvm::AttributeSet::FunctionIndex,
1568 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001569}
1570
John McCalla738c252011-03-09 04:27:21 +00001571/// An argument came in as a promoted argument; demote it back to its
1572/// declared type.
1573static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1574 const VarDecl *var,
1575 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001576 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001577
1578 // This can happen with promotions that actually don't change the
1579 // underlying type, like the enum promotions.
1580 if (value->getType() == varType) return value;
1581
1582 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1583 && "unexpected promotion type");
1584
1585 if (isa<llvm::IntegerType>(varType))
1586 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1587
1588 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1589}
1590
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001591/// Returns the attribute (either parameter attribute, or function
1592/// attribute), which declares argument ArgNo to be non-null.
1593static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1594 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001595 // FIXME: __attribute__((nonnull)) can also be applied to:
1596 // - references to pointers, where the pointee is known to be
1597 // nonnull (apparently a Clang extension)
1598 // - transparent unions containing pointers
1599 // In the former case, LLVM IR cannot represent the constraint. In
1600 // the latter case, we have no guarantee that the transparent union
1601 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001602 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1603 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001604 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001605 if (PVD) {
1606 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1607 return ParmNNAttr;
1608 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001609 // Check function attributes.
1610 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001611 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001612 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001613 if (NNAttr->isNonNull(ArgNo))
1614 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001615 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001616 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001617}
1618
Daniel Dunbard931a872009-02-02 22:03:45 +00001619void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1620 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001621 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001622 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1623 // Naked functions don't have prologues.
1624 return;
1625
John McCallcaa19452009-07-28 01:00:58 +00001626 // If this is an implicit-return-zero function, go ahead and
1627 // initialize the return value. TODO: it might be nice to have
1628 // a more general mechanism for this that didn't require synthesized
1629 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001630 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001631 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001632 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001633 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001634 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001635 Builder.CreateStore(Zero, ReturnValue);
1636 }
1637 }
1638
Mike Stump18bb9282009-05-16 07:57:57 +00001639 // FIXME: We no longer need the types from FunctionArgList; lift up and
1640 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001641
Alexey Samsonov153004f2014-09-29 22:08:00 +00001642 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001643 // Flattened function arguments.
1644 SmallVector<llvm::Argument *, 16> FnArgs;
1645 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1646 for (auto &Arg : Fn->args()) {
1647 FnArgs.push_back(&Arg);
1648 }
1649 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001650
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001651 // If we're using inalloca, all the memory arguments are GEPs off of the last
1652 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001653 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001654 if (IRFunctionArgs.hasInallocaArg()) {
1655 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001656 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1657 }
1658
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001659 // Name the struct return parameter.
1660 if (IRFunctionArgs.hasSRetArg()) {
1661 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001662 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001663 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001664 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001665 }
Mike Stump11289f42009-09-09 15:08:12 +00001666
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001667 // Track if we received the parameter as a pointer (indirect, byval, or
1668 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1669 // into a local alloca for us.
1670 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001671 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001672 SmallVector<ValueAndIsPtr, 16> ArgVals;
1673 ArgVals.reserve(Args.size());
1674
Reid Kleckner739756c2013-12-04 19:23:12 +00001675 // Create a pointer value for every parameter declaration. This usually
1676 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1677 // any cleanups or do anything that might unwind. We do that separately, so
1678 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001679 assert(FI.arg_size() == Args.size() &&
1680 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001681 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001682 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001683 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001684 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001685 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001686 QualType Ty = info_it->type;
1687 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001688
John McCalla738c252011-03-09 04:27:21 +00001689 bool isPromoted =
1690 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1691
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001692 unsigned FirstIRArg, NumIRArgs;
1693 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001694
Daniel Dunbard3674e62008-09-11 01:48:57 +00001695 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001696 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001697 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001698 llvm::Value *V = Builder.CreateStructGEP(
1699 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1700 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001701 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001702 }
1703
Daniel Dunbar747865a2009-02-05 09:16:39 +00001704 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001705 assert(NumIRArgs == 1);
1706 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001707
John McCall47fb9502013-03-07 21:37:08 +00001708 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001709 // Aggregates and complex variables are accessed by reference. All we
1710 // need to do is realign the value, if requested
1711 if (ArgI.getIndirectRealign()) {
1712 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1713
1714 // Copy from the incoming argument pointer to the temporary with the
1715 // appropriate alignment.
1716 //
1717 // FIXME: We should have a common utility for generating an aggregate
1718 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001719 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001720 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001721 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1722 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1723 Builder.CreateMemCpy(Dst,
1724 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001725 llvm::ConstantInt::get(IntPtrTy,
1726 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001727 ArgI.getIndirectAlign(),
1728 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001729 V = AlignedTemp;
1730 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001731 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001732 } else {
1733 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001734 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001735 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1736 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001737
1738 if (isPromoted)
1739 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001740 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001741 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001742 break;
1743 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001744
1745 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001746 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001747
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001748 // If we have the trivial case, handle it with no muss and fuss.
1749 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001750 ArgI.getCoerceToType() == ConvertType(Ty) &&
1751 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001752 assert(NumIRArgs == 1);
1753 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001754 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001755
Hal Finkel48d53e22014-07-19 01:41:07 +00001756 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001757 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1758 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001759 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1760 AI->getArgNo() + 1,
1761 llvm::Attribute::NonNull));
1762
Hal Finkel48d53e22014-07-19 01:41:07 +00001763 QualType OTy = PVD->getOriginalType();
1764 if (const auto *ArrTy =
1765 getContext().getAsConstantArrayType(OTy)) {
1766 // A C99 array parameter declaration with the static keyword also
1767 // indicates dereferenceability, and if the size is constant we can
1768 // use the dereferenceable attribute (which requires the size in
1769 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001770 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001771 QualType ETy = ArrTy->getElementType();
1772 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1773 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1774 ArrSize) {
1775 llvm::AttrBuilder Attrs;
1776 Attrs.addDereferenceableAttr(
1777 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1778 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1779 AI->getArgNo() + 1, Attrs));
1780 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1781 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1782 AI->getArgNo() + 1,
1783 llvm::Attribute::NonNull));
1784 }
1785 }
1786 } else if (const auto *ArrTy =
1787 getContext().getAsVariableArrayType(OTy)) {
1788 // For C99 VLAs with the static keyword, we don't know the size so
1789 // we can't use the dereferenceable attribute, but in addrspace(0)
1790 // we know that it must be nonnull.
1791 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1792 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1793 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1794 AI->getArgNo() + 1,
1795 llvm::Attribute::NonNull));
1796 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001797
1798 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1799 if (!AVAttr)
1800 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1801 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1802 if (AVAttr) {
1803 llvm::Value *AlignmentValue =
1804 EmitScalarExpr(AVAttr->getAlignment());
1805 llvm::ConstantInt *AlignmentCI =
1806 cast<llvm::ConstantInt>(AlignmentValue);
1807 unsigned Alignment =
1808 std::min((unsigned) AlignmentCI->getZExtValue(),
1809 +llvm::Value::MaximumAlignment);
1810
1811 llvm::AttrBuilder Attrs;
1812 Attrs.addAlignmentAttr(Alignment);
1813 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1814 AI->getArgNo() + 1, Attrs));
1815 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001816 }
1817
Bill Wendling507c3512012-10-16 05:23:44 +00001818 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001819 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1820 AI->getArgNo() + 1,
1821 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001822
Chris Lattner7369c142011-07-20 06:29:00 +00001823 // Ensure the argument is the correct type.
1824 if (V->getType() != ArgI.getCoerceToType())
1825 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1826
John McCalla738c252011-03-09 04:27:21 +00001827 if (isPromoted)
1828 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001829
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001830 if (const CXXMethodDecl *MD =
1831 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001832 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001833 V = CGM.getCXXABI().
1834 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001835 }
1836
Rafael Espindola8778c282012-11-29 16:09:03 +00001837 // Because of merging of function types from multiple decls it is
1838 // possible for the type of an argument to not match the corresponding
1839 // type in the function type. Since we are codegening the callee
1840 // in here, add a cast to the argument type.
1841 llvm::Type *LTy = ConvertType(Arg->getType());
1842 if (V->getType() != LTy)
1843 V = Builder.CreateBitCast(V, LTy);
1844
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001845 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001846 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001849 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001850
Chris Lattnerff941a62010-07-28 18:24:28 +00001851 // The alignment we need to use is the max of the requested alignment for
1852 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001853 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001854 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001855 AlignmentToUse = std::max(AlignmentToUse,
1856 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001857
Chris Lattnerff941a62010-07-28 18:24:28 +00001858 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001859 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001860 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001861
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001862 // If the value is offset in memory, apply the offset now.
1863 if (unsigned Offs = ArgI.getDirectOffset()) {
1864 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1865 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001866 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001867 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1868 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001869
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001870 // Fast-isel and the optimizer generally like scalar values better than
1871 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001872 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001873 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1874 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001875 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001876 llvm::Type *DstTy =
1877 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001878 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001879
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001880 if (SrcSize <= DstSize) {
1881 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1882
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001883 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001884 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001885 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001886 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1887 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001888 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001889 }
1890 } else {
1891 llvm::AllocaInst *TempAlloca =
1892 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1893 TempAlloca->setAlignment(AlignmentToUse);
1894 llvm::Value *TempV = TempAlloca;
1895
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001896 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001897 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001898 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001899 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1900 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001901 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001902 }
1903
1904 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001905 }
1906 } else {
1907 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001908 assert(NumIRArgs == 1);
1909 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001910 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001911 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001912 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001913
1914
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001915 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001916 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001917 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001918 if (isPromoted)
1919 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001920 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1921 } else {
1922 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001923 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001924 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001925 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001926
1927 case ABIArgInfo::Expand: {
1928 // If this structure was expanded into multiple arguments then
1929 // we need to create a temporary and reconstruct it from the
1930 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001931 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001932 CharUnits Align = getContext().getDeclAlign(Arg);
1933 Alloca->setAlignment(Align.getQuantity());
1934 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001935 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001936
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001937 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1938 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1939 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1940 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1941 auto AI = FnArgs[FirstIRArg + i];
1942 AI->setName(Arg->getName() + "." + Twine(i));
1943 }
1944 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001945 }
1946
1947 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001948 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001949 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001950 if (!hasScalarEvaluationKind(Ty)) {
1951 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1952 } else {
1953 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1954 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1955 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001956 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001957 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001958 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001959
Reid Kleckner739756c2013-12-04 19:23:12 +00001960 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1961 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001962 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1963 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001964 } else {
1965 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001966 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1967 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001968 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001969}
1970
John McCallffa2c1a2012-01-29 07:46:59 +00001971static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1972 while (insn->use_empty()) {
1973 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1974 if (!bitcast) return;
1975
1976 // This is "safe" because we would have used a ConstantExpr otherwise.
1977 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1978 bitcast->eraseFromParent();
1979 }
1980}
1981
John McCall31168b02011-06-15 23:02:42 +00001982/// Try to emit a fused autorelease of a return result.
1983static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1984 llvm::Value *result) {
1985 // We must be immediately followed the cast.
1986 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001987 if (BB->empty()) return nullptr;
1988 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001989
Chris Lattner2192fe52011-07-18 04:24:23 +00001990 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001991
1992 // result is in a BasicBlock and is therefore an Instruction.
1993 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1994
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001995 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001996
1997 // Look for:
1998 // %generator = bitcast %type1* %generator2 to %type2*
1999 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2000 // We would have emitted this as a constant if the operand weren't
2001 // an Instruction.
2002 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2003
2004 // Require the generator to be immediately followed by the cast.
2005 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002006 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002007
2008 insnsToKill.push_back(bitcast);
2009 }
2010
2011 // Look for:
2012 // %generator = call i8* @objc_retain(i8* %originalResult)
2013 // or
2014 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2015 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002016 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002017
2018 bool doRetainAutorelease;
2019
2020 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2021 doRetainAutorelease = true;
2022 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2023 .objc_retainAutoreleasedReturnValue) {
2024 doRetainAutorelease = false;
2025
John McCallcfa4e9b2012-09-07 23:30:50 +00002026 // If we emitted an assembly marker for this call (and the
2027 // ARCEntrypoints field should have been set if so), go looking
2028 // for that call. If we can't find it, we can't do this
2029 // optimization. But it should always be the immediately previous
2030 // instruction, unless we needed bitcasts around the call.
2031 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2032 llvm::Instruction *prev = call->getPrevNode();
2033 assert(prev);
2034 if (isa<llvm::BitCastInst>(prev)) {
2035 prev = prev->getPrevNode();
2036 assert(prev);
2037 }
2038 assert(isa<llvm::CallInst>(prev));
2039 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2040 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2041 insnsToKill.push_back(prev);
2042 }
John McCall31168b02011-06-15 23:02:42 +00002043 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002044 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002045 }
2046
2047 result = call->getArgOperand(0);
2048 insnsToKill.push_back(call);
2049
2050 // Keep killing bitcasts, for sanity. Note that we no longer care
2051 // about precise ordering as long as there's exactly one use.
2052 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2053 if (!bitcast->hasOneUse()) break;
2054 insnsToKill.push_back(bitcast);
2055 result = bitcast->getOperand(0);
2056 }
2057
2058 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002059 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002060 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2061 (*i)->eraseFromParent();
2062
2063 // Do the fused retain/autorelease if we were asked to.
2064 if (doRetainAutorelease)
2065 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2066
2067 // Cast back to the result type.
2068 return CGF.Builder.CreateBitCast(result, resultType);
2069}
2070
John McCallffa2c1a2012-01-29 07:46:59 +00002071/// If this is a +1 of the value of an immutable 'self', remove it.
2072static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2073 llvm::Value *result) {
2074 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002075 const ObjCMethodDecl *method =
2076 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002077 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002078 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002079 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002080
2081 // Look for a retain call.
2082 llvm::CallInst *retainCall =
2083 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2084 if (!retainCall ||
2085 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002086 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002087
2088 // Look for an ordinary load of 'self'.
2089 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2090 llvm::LoadInst *load =
2091 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2092 if (!load || load->isAtomic() || load->isVolatile() ||
2093 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002094 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002095
2096 // Okay! Burn it all down. This relies for correctness on the
2097 // assumption that the retain is emitted as part of the return and
2098 // that thereafter everything is used "linearly".
2099 llvm::Type *resultType = result->getType();
2100 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2101 assert(retainCall->use_empty());
2102 retainCall->eraseFromParent();
2103 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2104
2105 return CGF.Builder.CreateBitCast(load, resultType);
2106}
2107
John McCall31168b02011-06-15 23:02:42 +00002108/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002109///
2110/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002111static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2112 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002113 // If we're returning 'self', kill the initial retain. This is a
2114 // heuristic attempt to "encourage correctness" in the really unfortunate
2115 // case where we have a return of self during a dealloc and we desperately
2116 // need to avoid the possible autorelease.
2117 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2118 return self;
2119
John McCall31168b02011-06-15 23:02:42 +00002120 // At -O0, try to emit a fused retain/autorelease.
2121 if (CGF.shouldUseFusedARCCalls())
2122 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2123 return fused;
2124
2125 return CGF.EmitARCAutoreleaseReturnValue(result);
2126}
2127
John McCall6e1c0122012-01-29 02:35:02 +00002128/// Heuristically search for a dominating store to the return-value slot.
2129static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2130 // If there are multiple uses of the return-value slot, just check
2131 // for something immediately preceding the IP. Sometimes this can
2132 // happen with how we generate implicit-returns; it can also happen
2133 // with noreturn cleanups.
2134 if (!CGF.ReturnValue->hasOneUse()) {
2135 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002136 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002137 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002138 if (!store) return nullptr;
2139 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002140 assert(!store->isAtomic() && !store->isVolatile()); // see below
2141 return store;
2142 }
2143
2144 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002145 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002146 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002147
2148 // These aren't actually possible for non-coerced returns, and we
2149 // only care about non-coerced returns on this code path.
2150 assert(!store->isAtomic() && !store->isVolatile());
2151
2152 // Now do a first-and-dirty dominance check: just walk up the
2153 // single-predecessors chain from the current insertion point.
2154 llvm::BasicBlock *StoreBB = store->getParent();
2155 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2156 while (IP != StoreBB) {
2157 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002158 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002159 }
2160
2161 // Okay, the store's basic block dominates the insertion point; we
2162 // can do our thing.
2163 return store;
2164}
2165
Adrian Prantl3be10542013-05-02 17:30:20 +00002166void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002167 bool EmitRetDbgLoc,
2168 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002169 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2170 // Naked functions don't have epilogues.
2171 Builder.CreateUnreachable();
2172 return;
2173 }
2174
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002175 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002176 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002177 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002178 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002179 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002180
Dan Gohman481e40c2010-07-20 20:13:52 +00002181 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002182 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002183 QualType RetTy = FI.getReturnType();
2184 const ABIArgInfo &RetAI = FI.getReturnInfo();
2185
2186 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002187 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002188 // Aggregrates get evaluated directly into the destination. Sometimes we
2189 // need to return the sret value in a register, though.
2190 assert(hasAggregateEvaluationKind(RetTy));
2191 if (RetAI.getInAllocaSRet()) {
2192 llvm::Function::arg_iterator EI = CurFn->arg_end();
2193 --EI;
2194 llvm::Value *ArgStruct = EI;
2195 llvm::Value *SRet =
2196 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2197 RV = Builder.CreateLoad(SRet, "sret");
2198 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002199 break;
2200
Daniel Dunbar03816342010-08-21 02:24:36 +00002201 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002202 auto AI = CurFn->arg_begin();
2203 if (RetAI.isSRetAfterThis())
2204 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002205 switch (getEvaluationKind(RetTy)) {
2206 case TEK_Complex: {
2207 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002208 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2209 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002210 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002211 /*isInit*/ true);
2212 break;
2213 }
2214 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002215 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002216 break;
2217 case TEK_Scalar:
2218 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002219 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002220 /*isInit*/ true);
2221 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002222 }
2223 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002224 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002225
2226 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002227 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002228 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2229 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002230 // The internal return value temp always will have pointer-to-return-type
2231 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002232
John McCall6e1c0122012-01-29 02:35:02 +00002233 // If there is a dominating store to ReturnValue, we can elide
2234 // the load, zap the store, and usually zap the alloca.
2235 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002236 // Reuse the debug location from the store unless there is
2237 // cleanup code to be emitted between the store and return
2238 // instruction.
2239 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002240 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002241 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002242 RV = SI->getValueOperand();
2243 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002244
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002245 // If that was the only use of the return value, nuke it as well now.
2246 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2247 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002248 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002249 }
John McCall6e1c0122012-01-29 02:35:02 +00002250
2251 // Otherwise, we have to do a simple load.
2252 } else {
2253 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002254 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002255 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002256 llvm::Value *V = ReturnValue;
2257 // If the value is offset in memory, apply the offset now.
2258 if (unsigned Offs = RetAI.getDirectOffset()) {
2259 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2260 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002261 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002262 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2263 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002264
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002265 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002266 }
John McCall31168b02011-06-15 23:02:42 +00002267
2268 // In ARC, end functions that return a retainable type with a call
2269 // to objc_autoreleaseReturnValue.
2270 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002271 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002272 !FI.isReturnsRetained() &&
2273 RetTy->isObjCRetainableType());
2274 RV = emitAutoreleaseOfResult(*this, RV);
2275 }
2276
Chris Lattner726b3d02010-06-26 23:13:19 +00002277 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002278
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002279 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002280 break;
2281
2282 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002283 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002284 }
2285
Alexey Samsonovde443c52014-08-13 00:26:40 +00002286 llvm::Instruction *Ret;
2287 if (RV) {
Alexey Samsonov035462c2014-10-30 19:33:44 +00002288 if (SanOpts.ReturnsNonnullAttribute) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002289 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2290 SanitizerScope SanScope(this);
2291 llvm::Value *Cond = Builder.CreateICmpNE(
2292 RV, llvm::Constant::getNullValue(RV->getType()));
2293 llvm::Constant *StaticData[] = {
2294 EmitCheckSourceLocation(EndLoc),
2295 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2296 };
2297 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
2298 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002299 }
2300 Ret = Builder.CreateRet(RV);
2301 } else {
2302 Ret = Builder.CreateRetVoid();
2303 }
2304
Devang Patel65497582010-07-21 18:08:50 +00002305 if (!RetDbgLoc.isUnknown())
2306 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002307}
2308
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002309static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2310 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2311 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2312}
2313
2314static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2315 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2316 // placeholders.
2317 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2318 llvm::Value *Placeholder =
2319 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2320 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2321 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2322 Ty.getQualifiers(),
2323 AggValueSlot::IsNotDestructed,
2324 AggValueSlot::DoesNotNeedGCBarriers,
2325 AggValueSlot::IsNotAliased);
2326}
2327
John McCall32ea9692011-03-11 20:59:21 +00002328void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002329 const VarDecl *param,
2330 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002331 // StartFunction converted the ABI-lowered parameter(s) into a
2332 // local alloca. We need to turn that into an r-value suitable
2333 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002334 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002335
John McCall32ea9692011-03-11 20:59:21 +00002336 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002337
John McCall23f66262010-05-26 22:34:26 +00002338 // For the most part, we just need to load the alloca, except:
2339 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002340 // 2) references to non-scalars are pointers directly to the aggregate.
2341 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002342 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002343 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002344 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002345
2346 // Locals which are references to scalars are represented
2347 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002348 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002349 }
2350
Reid Klecknerab2090d2014-07-26 01:34:32 +00002351 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2352 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002353
Nick Lewycky2d84e842013-10-02 02:29:49 +00002354 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002355}
2356
John McCall31168b02011-06-15 23:02:42 +00002357static bool isProvablyNull(llvm::Value *addr) {
2358 return isa<llvm::ConstantPointerNull>(addr);
2359}
2360
2361static bool isProvablyNonNull(llvm::Value *addr) {
2362 return isa<llvm::AllocaInst>(addr);
2363}
2364
2365/// Emit the actual writing-back of a writeback.
2366static void emitWriteback(CodeGenFunction &CGF,
2367 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002368 const LValue &srcLV = writeback.Source;
2369 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002370 assert(!isProvablyNull(srcAddr) &&
2371 "shouldn't have writeback for provably null argument");
2372
Craig Topper8a13c412014-05-21 05:09:00 +00002373 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002374
2375 // If the argument wasn't provably non-null, we need to null check
2376 // before doing the store.
2377 bool provablyNonNull = isProvablyNonNull(srcAddr);
2378 if (!provablyNonNull) {
2379 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2380 contBB = CGF.createBasicBlock("icr.done");
2381
2382 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2383 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2384 CGF.EmitBlock(writebackBB);
2385 }
2386
2387 // Load the value to writeback.
2388 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2389
2390 // Cast it back, in case we're writing an id to a Foo* or something.
2391 value = CGF.Builder.CreateBitCast(value,
2392 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2393 "icr.writeback-cast");
2394
2395 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002396
2397 // If we have a "to use" value, it's something we need to emit a use
2398 // of. This has to be carefully threaded in: if it's done after the
2399 // release it's potentially undefined behavior (and the optimizer
2400 // will ignore it), and if it happens before the retain then the
2401 // optimizer could move the release there.
2402 if (writeback.ToUse) {
2403 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2404
2405 // Retain the new value. No need to block-copy here: the block's
2406 // being passed up the stack.
2407 value = CGF.EmitARCRetainNonBlock(value);
2408
2409 // Emit the intrinsic use here.
2410 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2411
2412 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002413 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002414
2415 // Put the new value in place (primitively).
2416 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2417
2418 // Release the old value.
2419 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2420
2421 // Otherwise, we can just do a normal lvalue store.
2422 } else {
2423 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2424 }
John McCall31168b02011-06-15 23:02:42 +00002425
2426 // Jump to the continuation block.
2427 if (!provablyNonNull)
2428 CGF.EmitBlock(contBB);
2429}
2430
2431static void emitWritebacks(CodeGenFunction &CGF,
2432 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002433 for (const auto &I : args.writebacks())
2434 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002435}
2436
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002437static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2438 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002439 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002440 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2441 CallArgs.getCleanupsToDeactivate();
2442 // Iterate in reverse to increase the likelihood of popping the cleanup.
2443 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2444 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2445 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2446 I->IsActiveIP->eraseFromParent();
2447 }
2448}
2449
John McCalleff18842013-03-23 02:35:54 +00002450static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2451 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2452 if (uop->getOpcode() == UO_AddrOf)
2453 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002454 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002455}
2456
John McCall31168b02011-06-15 23:02:42 +00002457/// Emit an argument that's being passed call-by-writeback. That is,
2458/// we are passing the address of
2459static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2460 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002461 LValue srcLV;
2462
2463 // Make an optimistic effort to emit the address as an l-value.
2464 // This can fail if the the argument expression is more complicated.
2465 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2466 srcLV = CGF.EmitLValue(lvExpr);
2467
2468 // Otherwise, just emit it as a scalar.
2469 } else {
2470 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2471
2472 QualType srcAddrType =
2473 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2474 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2475 }
2476 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002477
2478 // The dest and src types don't necessarily match in LLVM terms
2479 // because of the crazy ObjC compatibility rules.
2480
Chris Lattner2192fe52011-07-18 04:24:23 +00002481 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002482 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2483
2484 // If the address is a constant null, just pass the appropriate null.
2485 if (isProvablyNull(srcAddr)) {
2486 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2487 CRE->getType());
2488 return;
2489 }
2490
John McCall31168b02011-06-15 23:02:42 +00002491 // Create the temporary.
2492 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2493 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002494 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2495 // and that cleanup will be conditional if we can't prove that the l-value
2496 // isn't null, so we need to register a dominating point so that the cleanups
2497 // system will make valid IR.
2498 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2499
John McCall31168b02011-06-15 23:02:42 +00002500 // Zero-initialize it if we're not doing a copy-initialization.
2501 bool shouldCopy = CRE->shouldCopy();
2502 if (!shouldCopy) {
2503 llvm::Value *null =
2504 llvm::ConstantPointerNull::get(
2505 cast<llvm::PointerType>(destType->getElementType()));
2506 CGF.Builder.CreateStore(null, temp);
2507 }
Craig Topper8a13c412014-05-21 05:09:00 +00002508
2509 llvm::BasicBlock *contBB = nullptr;
2510 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002511
2512 // If the address is *not* known to be non-null, we need to switch.
2513 llvm::Value *finalArgument;
2514
2515 bool provablyNonNull = isProvablyNonNull(srcAddr);
2516 if (provablyNonNull) {
2517 finalArgument = temp;
2518 } else {
2519 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2520
2521 finalArgument = CGF.Builder.CreateSelect(isNull,
2522 llvm::ConstantPointerNull::get(destType),
2523 temp, "icr.argument");
2524
2525 // If we need to copy, then the load has to be conditional, which
2526 // means we need control flow.
2527 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002528 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002529 contBB = CGF.createBasicBlock("icr.cont");
2530 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2531 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2532 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002533 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002534 }
2535 }
2536
Craig Topper8a13c412014-05-21 05:09:00 +00002537 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002538
John McCall31168b02011-06-15 23:02:42 +00002539 // Perform a copy if necessary.
2540 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002541 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002542 assert(srcRV.isScalar());
2543
2544 llvm::Value *src = srcRV.getScalarVal();
2545 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2546 "icr.cast");
2547
2548 // Use an ordinary store, not a store-to-lvalue.
2549 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002550
2551 // If optimization is enabled, and the value was held in a
2552 // __strong variable, we need to tell the optimizer that this
2553 // value has to stay alive until we're doing the store back.
2554 // This is because the temporary is effectively unretained,
2555 // and so otherwise we can violate the high-level semantics.
2556 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2557 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2558 valueToUse = src;
2559 }
John McCall31168b02011-06-15 23:02:42 +00002560 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002561
John McCall31168b02011-06-15 23:02:42 +00002562 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002563 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002564 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002565 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002566
2567 // Make a phi for the value to intrinsically use.
2568 if (valueToUse) {
2569 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2570 "icr.to-use");
2571 phiToUse->addIncoming(valueToUse, copyBB);
2572 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2573 originBB);
2574 valueToUse = phiToUse;
2575 }
2576
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002577 condEval.end(CGF);
2578 }
John McCall31168b02011-06-15 23:02:42 +00002579
John McCalleff18842013-03-23 02:35:54 +00002580 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002581 args.add(RValue::get(finalArgument), CRE->getType());
2582}
2583
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002584void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2585 assert(!StackBase && !StackCleanup.isValid());
2586
2587 // Save the stack.
2588 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2589 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2590
2591 // Control gets really tied up in landing pads, so we have to spill the
2592 // stacksave to an alloca to avoid violating SSA form.
2593 // TODO: This is dead if we never emit the cleanup. We should create the
2594 // alloca and store lazily on the first cleanup emission.
2595 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2596 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2597 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2598 StackCleanup = CGF.EHStack.getInnermostEHScope();
2599 assert(StackCleanup.isValid());
2600}
2601
2602void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2603 if (StackBase) {
2604 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2605 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2606 // We could load StackBase from StackBaseMem, but in the non-exceptional
2607 // case we can skip it.
2608 CGF.Builder.CreateCall(F, StackBase);
2609 }
2610}
2611
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002612static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2613 QualType ArgType, SourceLocation ArgLoc,
2614 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonov035462c2014-10-30 19:33:44 +00002615 if (!CGF.SanOpts.NonnullAttribute || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002616 return;
2617 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2618 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2619 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2620 if (!NNAttr)
2621 return;
2622 CodeGenFunction::SanitizerScope SanScope(&CGF);
2623 assert(RV.isScalar());
2624 llvm::Value *V = RV.getScalarVal();
2625 llvm::Value *Cond =
2626 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2627 llvm::Constant *StaticData[] = {
2628 CGF.EmitCheckSourceLocation(ArgLoc),
2629 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2630 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2631 };
2632 CGF.EmitCheck(Cond, "nonnull_arg", StaticData, None,
2633 CodeGenFunction::CRK_Recoverable);
2634}
2635
Reid Kleckner739756c2013-12-04 19:23:12 +00002636void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2637 ArrayRef<QualType> ArgTypes,
2638 CallExpr::const_arg_iterator ArgBeg,
2639 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002640 const FunctionDecl *CalleeDecl,
2641 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002642 bool ForceColumnInfo) {
2643 CGDebugInfo *DI = getDebugInfo();
2644 SourceLocation CallLoc;
2645 if (DI) CallLoc = DI->getLocation();
2646
2647 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2648 // because arguments are destroyed left to right in the callee.
2649 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002650 // Insert a stack save if we're going to need any inalloca args.
2651 bool HasInAllocaArgs = false;
2652 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2653 I != E && !HasInAllocaArgs; ++I)
2654 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2655 if (HasInAllocaArgs) {
2656 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2657 Args.allocateArgumentMemory(*this);
2658 }
2659
2660 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002661 size_t CallArgsStart = Args.size();
2662 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2663 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2664 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002665 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2666 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002667 // Restore the debug location.
2668 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2669 }
2670
2671 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2672 // IR function.
2673 std::reverse(Args.begin() + CallArgsStart, Args.end());
2674 return;
2675 }
2676
2677 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2678 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2679 assert(Arg != ArgEnd);
2680 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002681 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2682 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002683 // Restore the debug location.
2684 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2685 }
2686}
2687
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002688namespace {
2689
2690struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2691 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2692 : Addr(Addr), Ty(Ty) {}
2693
2694 llvm::Value *Addr;
2695 QualType Ty;
2696
Craig Topper4f12f102014-03-12 06:41:41 +00002697 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002698 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2699 assert(!Dtor->isTrivial());
2700 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2701 /*Delegating=*/false, Addr);
2702 }
2703};
2704
2705}
2706
John McCall32ea9692011-03-11 20:59:21 +00002707void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2708 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002709 if (const ObjCIndirectCopyRestoreExpr *CRE
2710 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002711 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002712 assert(getContext().hasSameType(E->getType(), type));
2713 return emitWritebackArg(*this, args, CRE);
2714 }
2715
John McCall0a76c0c2011-08-26 18:42:59 +00002716 assert(type->isReferenceType() == E->isGLValue() &&
2717 "reference binding to unmaterialized r-value!");
2718
John McCall17054bd62011-08-26 21:08:13 +00002719 if (E->isGLValue()) {
2720 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002721 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002724 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2725
2726 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2727 // However, we still have to push an EH-only cleanup in case we unwind before
2728 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002729 if (HasAggregateEvalKind &&
2730 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2731 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002732 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002733 AggValueSlot Slot;
2734 if (args.isUsingInAlloca())
2735 Slot = createPlaceholderSlot(*this, type);
2736 else
2737 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002738
2739 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2740 bool DestroyedInCallee =
2741 RD && RD->hasNonTrivialDestructor() &&
2742 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2743 if (DestroyedInCallee)
2744 Slot.setExternallyDestructed();
2745
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002746 EmitAggExpr(E, Slot);
2747 RValue RV = Slot.asRValue();
2748 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002749
Reid Klecknere39ee212014-05-03 00:33:28 +00002750 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002751 // Create a no-op GEP between the placeholder and the cleanup so we can
2752 // RAUW it successfully. It also serves as a marker of the first
2753 // instruction where the cleanup is active.
2754 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002755 // This unreachable is a temporary marker which will be removed later.
2756 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2757 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002758 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002759 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002760 }
2761
2762 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002763 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2764 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2765 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002766 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2767 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2768 } else {
2769 // We can't represent a misaligned lvalue in the CallArgList, so copy
2770 // to an aligned temporary now.
2771 llvm::Value *tmp = CreateMemTemp(type);
2772 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2773 L.getAlignment());
2774 args.add(RValue::getAggregate(tmp), type);
2775 }
Eli Friedmandf968192011-05-26 00:10:27 +00002776 return;
2777 }
2778
John McCall32ea9692011-03-11 20:59:21 +00002779 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002780}
2781
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002782QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2783 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2784 // implicitly widens null pointer constants that are arguments to varargs
2785 // functions to pointer-sized ints.
2786 if (!getTarget().getTriple().isOSWindows())
2787 return Arg->getType();
2788
2789 if (Arg->getType()->isIntegerType() &&
2790 getContext().getTypeSize(Arg->getType()) <
2791 getContext().getTargetInfo().getPointerWidth(0) &&
2792 Arg->isNullPointerConstant(getContext(),
2793 Expr::NPC_ValueDependentIsNotNull)) {
2794 return getContext().getIntPtrType();
2795 }
2796
2797 return Arg->getType();
2798}
2799
Dan Gohman515a60d2012-02-16 00:57:37 +00002800// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2801// optimizer it can aggressively ignore unwind edges.
2802void
2803CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2804 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2805 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2806 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2807 CGM.getNoObjCARCExceptionsMetadata());
2808}
2809
John McCall882987f2013-02-28 19:01:20 +00002810/// Emits a call to the given no-arguments nounwind runtime function.
2811llvm::CallInst *
2812CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2813 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002814 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002815}
2816
2817/// Emits a call to the given nounwind runtime function.
2818llvm::CallInst *
2819CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2820 ArrayRef<llvm::Value*> args,
2821 const llvm::Twine &name) {
2822 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2823 call->setDoesNotThrow();
2824 return call;
2825}
2826
2827/// Emits a simple call (never an invoke) to the given no-arguments
2828/// runtime function.
2829llvm::CallInst *
2830CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2831 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002832 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002833}
2834
2835/// Emits a simple call (never an invoke) to the given runtime
2836/// function.
2837llvm::CallInst *
2838CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2839 ArrayRef<llvm::Value*> args,
2840 const llvm::Twine &name) {
2841 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2842 call->setCallingConv(getRuntimeCC());
2843 return call;
2844}
2845
2846/// Emits a call or invoke to the given noreturn runtime function.
2847void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2848 ArrayRef<llvm::Value*> args) {
2849 if (getInvokeDest()) {
2850 llvm::InvokeInst *invoke =
2851 Builder.CreateInvoke(callee,
2852 getUnreachableBlock(),
2853 getInvokeDest(),
2854 args);
2855 invoke->setDoesNotReturn();
2856 invoke->setCallingConv(getRuntimeCC());
2857 } else {
2858 llvm::CallInst *call = Builder.CreateCall(callee, args);
2859 call->setDoesNotReturn();
2860 call->setCallingConv(getRuntimeCC());
2861 Builder.CreateUnreachable();
2862 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002863 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002864}
2865
2866/// Emits a call or invoke instruction to the given nullary runtime
2867/// function.
2868llvm::CallSite
2869CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2870 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002871 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002872}
2873
2874/// Emits a call or invoke instruction to the given runtime function.
2875llvm::CallSite
2876CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2877 ArrayRef<llvm::Value*> args,
2878 const Twine &name) {
2879 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2880 callSite.setCallingConv(getRuntimeCC());
2881 return callSite;
2882}
2883
2884llvm::CallSite
2885CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2886 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002887 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002888}
2889
John McCallbd309292010-07-06 01:34:17 +00002890/// Emits a call or invoke instruction to the given function, depending
2891/// on the current state of the EH stack.
2892llvm::CallSite
2893CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002894 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002895 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002896 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002897
Dan Gohman515a60d2012-02-16 00:57:37 +00002898 llvm::Instruction *Inst;
2899 if (!InvokeDest)
2900 Inst = Builder.CreateCall(Callee, Args, Name);
2901 else {
2902 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2903 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2904 EmitBlock(ContBB);
2905 }
2906
2907 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2908 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002909 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002910 AddObjCARCExceptionMetadata(Inst);
2911
2912 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002913}
2914
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002915/// \brief Store a non-aggregate value to an address to initialize it. For
2916/// initialization, a non-atomic store will be used.
2917static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2918 LValue Dst) {
2919 if (Src.isScalar())
2920 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2921 else
2922 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2923}
2924
2925void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2926 llvm::Value *New) {
2927 DeferredReplacements.push_back(std::make_pair(Old, New));
2928}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002929
Daniel Dunbard931a872009-02-02 22:03:45 +00002930RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002931 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002932 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002933 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002934 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002935 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002936 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002937
2938 // Handle struct-return functions by passing a pointer to the
2939 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002940 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002941 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002942
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002943 llvm::FunctionType *IRFuncTy =
2944 cast<llvm::FunctionType>(
2945 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002946
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002947 // If we're using inalloca, insert the allocation after the stack save.
2948 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002949 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002950 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002951 llvm::Instruction *IP = CallArgs.getStackBase();
2952 llvm::AllocaInst *AI;
2953 if (IP) {
2954 IP = IP->getNextNode();
2955 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2956 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002957 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002958 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002959 AI->setUsedWithInAlloca(true);
2960 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2961 ArgMemory = AI;
2962 }
2963
Alexey Samsonov153004f2014-09-29 22:08:00 +00002964 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002965 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2966
Chris Lattner4ca97c32009-06-13 00:26:38 +00002967 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002968 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002969 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002970 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002971 SRetPtr = ReturnValue.getValue();
2972 if (!SRetPtr)
2973 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002974 if (IRFunctionArgs.hasSRetArg()) {
2975 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002976 } else {
2977 llvm::Value *Addr =
2978 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2979 Builder.CreateStore(SRetPtr, Addr);
2980 }
Anders Carlsson17490832009-12-24 20:40:36 +00002981 }
Mike Stump11289f42009-09-09 15:08:12 +00002982
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002983 assert(CallInfo.arg_size() == CallArgs.size() &&
2984 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002985 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002986 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002987 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002988 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002989 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002990 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002991
John McCall47fb9502013-03-07 21:37:08 +00002992 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002993
2994 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002995 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2996 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2997 llvm::UndefValue::get(ArgInfo.getPaddingType());
2998
2999 unsigned FirstIRArg, NumIRArgs;
3000 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003001
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003002 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003003 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003004 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003005 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3006 if (RV.isAggregate()) {
3007 // Replace the placeholder with the appropriate argument slot GEP.
3008 llvm::Instruction *Placeholder =
3009 cast<llvm::Instruction>(RV.getAggregateAddr());
3010 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3011 Builder.SetInsertPoint(Placeholder);
3012 llvm::Value *Addr = Builder.CreateStructGEP(
3013 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3014 Builder.restoreIP(IP);
3015 deferPlaceholderReplacement(Placeholder, Addr);
3016 } else {
3017 // Store the RValue into the argument struct.
3018 llvm::Value *Addr =
3019 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003020 unsigned AS = Addr->getType()->getPointerAddressSpace();
3021 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3022 // There are some cases where a trivial bitcast is not avoidable. The
3023 // definition of a type later in a translation unit may change it's type
3024 // from {}* to (%struct.foo*)*.
3025 if (Addr->getType() != MemType)
3026 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003027 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3028 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3029 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003030 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003031 }
3032
Daniel Dunbar03816342010-08-21 02:24:36 +00003033 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003034 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003035 if (RV.isScalar() || RV.isComplex()) {
3036 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003037 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3038 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3039 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003040 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003041
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003042 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003043 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003044 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003045 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003046 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003047 // 1. If the argument is not byval, and we are required to copy the
3048 // source. (This case doesn't occur on any common architecture.)
3049 // 2. If the argument is byval, RV is not sufficiently aligned, and
3050 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003051 // 3. If the argument is byval, but RV is located in an address space
3052 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003053 llvm::Value *Addr = RV.getAggregateAddr();
3054 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003055 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003056 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003057 const unsigned ArgAddrSpace =
3058 (FirstIRArg < IRFuncTy->getNumParams()
3059 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3060 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003061 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003062 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00003063 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3064 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003065 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003066 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3067 if (Align > AI->getAlignment())
3068 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003069 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003070 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003071 } else {
3072 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003073 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003074 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003075 }
3076 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003077 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003078
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003079 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003080 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003081 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003082
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003083 case ABIArgInfo::Extend:
3084 case ABIArgInfo::Direct: {
3085 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003086 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3087 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003088 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003089 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003090 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003091 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003092 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003093 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003094
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003095 // We might have to widen integers, but we should never truncate.
3096 if (ArgInfo.getCoerceToType() != V->getType() &&
3097 V->getType()->isIntegerTy())
3098 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3099
Chris Lattner3ce86682011-07-12 04:53:39 +00003100 // If the argument doesn't match, perform a bitcast to coerce it. This
3101 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003102 if (FirstIRArg < IRFuncTy->getNumParams() &&
3103 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3104 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3105 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003106 break;
3107 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003108
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003109 // FIXME: Avoid the conversion through memory if possible.
3110 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003111 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003112 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003113 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003114 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003115 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003116 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003117
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003118 // If the value is offset in memory, apply the offset now.
3119 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3120 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3121 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003122 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003123 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3124
3125 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003126
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003127 // Fast-isel and the optimizer generally like scalar values better than
3128 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003129 llvm::StructType *STy =
3130 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003131 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003132 llvm::Type *SrcTy =
3133 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3134 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3135 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3136
3137 // If the source type is smaller than the destination type of the
3138 // coerce-to logic, copy the source value into a temp alloca the size
3139 // of the destination type to allow loading all of it. The bits past
3140 // the source value are left undef.
3141 if (SrcSize < DstSize) {
3142 llvm::AllocaInst *TempAlloca
3143 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3144 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3145 SrcPtr = TempAlloca;
3146 } else {
3147 SrcPtr = Builder.CreateBitCast(SrcPtr,
3148 llvm::PointerType::getUnqual(STy));
3149 }
3150
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003151 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003152 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3153 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003154 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3155 // We don't know what we're loading from.
3156 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003157 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003158 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003159 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003160 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003161 assert(NumIRArgs == 1);
3162 IRCallArgs[FirstIRArg] =
3163 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003164 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003165
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003166 break;
3167 }
3168
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003169 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003170 unsigned IRArgPos = FirstIRArg;
3171 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3172 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003173 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003174 }
3175 }
Mike Stump11289f42009-09-09 15:08:12 +00003176
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003177 if (ArgMemory) {
3178 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003179 if (CallInfo.isVariadic()) {
3180 // When passing non-POD arguments by value to variadic functions, we will
3181 // end up with a variadic prototype and an inalloca call site. In such
3182 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3183 // the callee.
3184 unsigned CalleeAS =
3185 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3186 Callee = Builder.CreateBitCast(
3187 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3188 } else {
3189 llvm::Type *LastParamTy =
3190 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3191 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003192#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003193 // Assert that these structs have equivalent element types.
3194 llvm::StructType *FullTy = CallInfo.getArgStruct();
3195 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3196 cast<llvm::PointerType>(LastParamTy)->getElementType());
3197 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3198 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3199 DE = DeclaredTy->element_end(),
3200 FI = FullTy->element_begin();
3201 DI != DE; ++DI, ++FI)
3202 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003203#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003204 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3205 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003206 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003207 assert(IRFunctionArgs.hasInallocaArg());
3208 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003209 }
3210
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003211 if (!CallArgs.getCleanupsToDeactivate().empty())
3212 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3213
Chris Lattner4ca97c32009-06-13 00:26:38 +00003214 // If the callee is a bitcast of a function to a varargs pointer to function
3215 // type, check to see if we can remove the bitcast. This handles some cases
3216 // with unprototyped functions.
3217 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3218 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003219 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3220 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003221 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003222 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003223
Chris Lattner4ca97c32009-06-13 00:26:38 +00003224 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3225 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003226 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003227 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003228 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003229 bool ArgsMatch = true;
3230 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3231 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3232 ArgsMatch = false;
3233 break;
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235
Chris Lattner4ca97c32009-06-13 00:26:38 +00003236 // Strip the cast if we can get away with it. This is a nice cleanup,
3237 // but also allows us to inline the function at -O0 if it is marked
3238 // always_inline.
3239 if (ArgsMatch)
3240 Callee = CalleeF;
3241 }
3242 }
Mike Stump11289f42009-09-09 15:08:12 +00003243
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003244 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3245 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3246 // Inalloca argument can have different type.
3247 if (IRFunctionArgs.hasInallocaArg() &&
3248 i == IRFunctionArgs.getInallocaArgNo())
3249 continue;
3250 if (i < IRFuncTy->getNumParams())
3251 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3252 }
3253
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003254 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003255 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003256 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3257 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003258 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003259 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003260
Craig Topper8a13c412014-05-21 05:09:00 +00003261 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003262 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3263 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003264 InvokeDest = getInvokeDest();
3265
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003266 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003267 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003268 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003269 } else {
3270 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003271 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003272 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003273 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003274 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003275 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003276
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003277 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3278 !CS.hasFnAttr(llvm::Attribute::NoInline))
3279 Attrs =
3280 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3281 llvm::Attribute::AlwaysInline);
3282
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003283 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003284 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003285
Dan Gohman515a60d2012-02-16 00:57:37 +00003286 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3287 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003288 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003289 AddObjCARCExceptionMetadata(CS.getInstruction());
3290
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003291 // If the call doesn't return, finish the basic block and clear the
3292 // insertion point; this allows the rest of IRgen to discard
3293 // unreachable code.
3294 if (CS.doesNotReturn()) {
3295 Builder.CreateUnreachable();
3296 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003297
Mike Stump18bb9282009-05-16 07:57:57 +00003298 // FIXME: For now, emit a dummy basic block because expr emitters in
3299 // generally are not ready to handle emitting expressions at unreachable
3300 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003301 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003302
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003303 // Return a reasonable RValue.
3304 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003305 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003306
3307 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003308 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003309 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003310
John McCall31168b02011-06-15 23:02:42 +00003311 // Emit any writebacks immediately. Arguably this should happen
3312 // after any return-value munging.
3313 if (CallArgs.hasWritebacks())
3314 emitWritebacks(*this, CallArgs);
3315
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003316 // The stack cleanup for inalloca arguments has to run out of the normal
3317 // lexical order, so deactivate it and run it manually here.
3318 CallArgs.freeArgumentMemory(*this);
3319
Hal Finkelee90a222014-09-26 05:04:30 +00003320 RValue Ret = [&] {
3321 switch (RetAI.getKind()) {
3322 case ABIArgInfo::InAlloca:
3323 case ABIArgInfo::Indirect:
3324 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003325
Hal Finkelee90a222014-09-26 05:04:30 +00003326 case ABIArgInfo::Ignore:
3327 // If we are ignoring an argument that had a result, make sure to
3328 // construct the appropriate return value for our caller.
3329 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003330
Hal Finkelee90a222014-09-26 05:04:30 +00003331 case ABIArgInfo::Extend:
3332 case ABIArgInfo::Direct: {
3333 llvm::Type *RetIRTy = ConvertType(RetTy);
3334 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3335 switch (getEvaluationKind(RetTy)) {
3336 case TEK_Complex: {
3337 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3338 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3339 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003340 }
Hal Finkelee90a222014-09-26 05:04:30 +00003341 case TEK_Aggregate: {
3342 llvm::Value *DestPtr = ReturnValue.getValue();
3343 bool DestIsVolatile = ReturnValue.isVolatile();
3344
3345 if (!DestPtr) {
3346 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3347 DestIsVolatile = false;
3348 }
3349 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3350 return RValue::getAggregate(DestPtr);
3351 }
3352 case TEK_Scalar: {
3353 // If the argument doesn't match, perform a bitcast to coerce it. This
3354 // can happen due to trivial type mismatches.
3355 llvm::Value *V = CI;
3356 if (V->getType() != RetIRTy)
3357 V = Builder.CreateBitCast(V, RetIRTy);
3358 return RValue::get(V);
3359 }
3360 }
3361 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003362 }
Hal Finkelee90a222014-09-26 05:04:30 +00003363
3364 llvm::Value *DestPtr = ReturnValue.getValue();
3365 bool DestIsVolatile = ReturnValue.isVolatile();
3366
3367 if (!DestPtr) {
3368 DestPtr = CreateMemTemp(RetTy, "coerce");
3369 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003370 }
Hal Finkelee90a222014-09-26 05:04:30 +00003371
3372 // If the value is offset in memory, apply the offset now.
3373 llvm::Value *StorePtr = DestPtr;
3374 if (unsigned Offs = RetAI.getDirectOffset()) {
3375 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3376 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3377 StorePtr = Builder.CreateBitCast(StorePtr,
3378 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003379 }
Hal Finkelee90a222014-09-26 05:04:30 +00003380 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3381
3382 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003383 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003384
Hal Finkelee90a222014-09-26 05:04:30 +00003385 case ABIArgInfo::Expand:
3386 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003387 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003388
Hal Finkelee90a222014-09-26 05:04:30 +00003389 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3390 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003391
Hal Finkelee90a222014-09-26 05:04:30 +00003392 if (Ret.isScalar() && TargetDecl) {
3393 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3394 llvm::Value *OffsetValue = nullptr;
3395 if (const auto *Offset = AA->getOffset())
3396 OffsetValue = EmitScalarExpr(Offset);
3397
3398 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3399 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3400 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3401 OffsetValue);
3402 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003403 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003404
Hal Finkelee90a222014-09-26 05:04:30 +00003405 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003406}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003407
3408/* VarArg handling */
3409
3410llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3411 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3412}