blob: 06d02b52c8fdc6238012d3c6ffe069c1d3cb297f [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000053 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
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()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000606 // Skip zero length bitfields.
607 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
608 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000609 assert(!FD->isBitField() &&
610 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000611 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000612 if (UnionSize < FieldSize) {
613 UnionSize = FieldSize;
614 LargestFD = FD;
615 }
616 }
617 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000618 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000619 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000620 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
621 assert(!CXXRD->isDynamicClass() &&
622 "cannot expand vtable pointers in dynamic classes");
623 for (const CXXBaseSpecifier &BS : CXXRD->bases())
624 Bases.push_back(&BS);
625 }
626
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000627 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000628 // Skip zero length bitfields.
629 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
630 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000631 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000632 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000633 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000634 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000635 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000636 return llvm::make_unique<RecordExpansion>(std::move(Bases),
637 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000638 }
639 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
640 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
641 }
642 return llvm::make_unique<NoExpansion>();
643}
644
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000645static int getExpansionSize(QualType Ty, const ASTContext &Context) {
646 auto Exp = getTypeExpansion(Ty, Context);
647 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
648 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
649 }
650 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
651 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000652 for (auto BS : RExp->Bases)
653 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000654 for (auto FD : RExp->Fields)
655 Res += getExpansionSize(FD->getType(), Context);
656 return Res;
657 }
658 if (isa<ComplexExpansion>(Exp.get()))
659 return 2;
660 assert(isa<NoExpansion>(Exp.get()));
661 return 1;
662}
663
Alexey Samsonov153004f2014-09-29 22:08:00 +0000664void
665CodeGenTypes::getExpandedTypes(QualType Ty,
666 SmallVectorImpl<llvm::Type *>::iterator &TI) {
667 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000668 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
669 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000670 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000671 }
672 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000673 for (auto BS : RExp->Bases)
674 getExpandedTypes(BS->getType(), TI);
675 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000676 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000677 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
678 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000679 *TI++ = EltTy;
680 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000681 } else {
682 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000683 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000684 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000685}
686
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000687void CodeGenFunction::ExpandTypeFromArgs(
688 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000689 assert(LV.isSimple() &&
690 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000691
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000692 auto Exp = getTypeExpansion(Ty, getContext());
693 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
694 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
695 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
696 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
697 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000698 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000699 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000700 llvm::Value *This = LV.getAddress();
701 for (const CXXBaseSpecifier *BS : RExp->Bases) {
702 // Perform a single step derived-to-base conversion.
703 llvm::Value *Base =
704 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
705 /*NullCheckValue=*/false, SourceLocation());
706 LValue SubLV = MakeAddrLValue(Base, BS->getType());
707
708 // Recurse onto bases.
709 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
710 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000711 for (auto FD : RExp->Fields) {
712 // FIXME: What are the right qualifiers here?
713 LValue SubLV = EmitLValueForField(LV, FD);
714 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000715 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000716 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000717 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000718 EmitStoreThroughLValue(RValue::get(*AI++),
719 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000720 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000721 EmitStoreThroughLValue(RValue::get(*AI++),
722 MakeAddrLValue(ImagAddr, CExp->EltTy));
723 } else {
724 assert(isa<NoExpansion>(Exp.get()));
725 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000726 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000727}
728
729void CodeGenFunction::ExpandTypeToArgs(
730 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
731 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
732 auto Exp = getTypeExpansion(Ty, getContext());
733 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
734 llvm::Value *Addr = RV.getAggregateAddr();
735 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
736 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
737 RValue EltRV =
738 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
739 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
740 }
741 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000742 llvm::Value *This = RV.getAggregateAddr();
743 for (const CXXBaseSpecifier *BS : RExp->Bases) {
744 // Perform a single step derived-to-base conversion.
745 llvm::Value *Base =
746 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
747 /*NullCheckValue=*/false, SourceLocation());
748 RValue BaseRV = RValue::getAggregate(Base);
749
750 // Recurse onto bases.
751 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
752 IRCallArgPos);
753 }
754
755 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000756 for (auto FD : RExp->Fields) {
757 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
758 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
759 IRCallArgPos);
760 }
761 } else if (isa<ComplexExpansion>(Exp.get())) {
762 ComplexPairTy CV = RV.getComplexVal();
763 IRCallArgs[IRCallArgPos++] = CV.first;
764 IRCallArgs[IRCallArgPos++] = CV.second;
765 } else {
766 assert(isa<NoExpansion>(Exp.get()));
767 assert(RV.isScalar() &&
768 "Unexpected non-scalar rvalue during struct expansion.");
769
770 // Insert a bitcast as needed.
771 llvm::Value *V = RV.getScalarVal();
772 if (IRCallArgPos < IRFuncTy->getNumParams() &&
773 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
774 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
775
776 IRCallArgs[IRCallArgPos++] = V;
777 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000778}
779
Chris Lattner895c52b2010-06-27 06:04:18 +0000780/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000781/// accessing some number of bytes out of it, try to gep into the struct to get
782/// at its inner goodness. Dive as deep as possible without entering an element
783/// with an in-memory size smaller than DstSize.
784static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000785EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000786 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000787 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000788 // We can't dive into a zero-element struct.
789 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000790
Chris Lattner2192fe52011-07-18 04:24:23 +0000791 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000792
Chris Lattner1cd66982010-06-27 05:56:15 +0000793 // 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 +0000794 // first element is the same size as the whole struct, we can enter it. The
795 // comparison must be made on the store size and not the alloca size. Using
796 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000797 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000798 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000799 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000800 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000801 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000802
Chris Lattner1cd66982010-06-27 05:56:15 +0000803 // GEP into the first element.
804 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000805
Chris Lattner1cd66982010-06-27 05:56:15 +0000806 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000807 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000808 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000809 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000810 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000811
812 return SrcPtr;
813}
814
Chris Lattner055097f2010-06-27 06:26:04 +0000815/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
816/// are either integers or pointers. This does a truncation of the value if it
817/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000818///
819/// This behaves as if the value were coerced through memory, so on big-endian
820/// targets the high bits are preserved in a truncation, while little-endian
821/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000822static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000823 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000824 CodeGenFunction &CGF) {
825 if (Val->getType() == Ty)
826 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000827
Chris Lattner055097f2010-06-27 06:26:04 +0000828 if (isa<llvm::PointerType>(Val->getType())) {
829 // If this is Pointer->Pointer avoid conversion to and from int.
830 if (isa<llvm::PointerType>(Ty))
831 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000832
Chris Lattner055097f2010-06-27 06:26:04 +0000833 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000834 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000835 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000836
Chris Lattner2192fe52011-07-18 04:24:23 +0000837 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000838 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000839 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000840
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000841 if (Val->getType() != DestIntTy) {
842 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
843 if (DL.isBigEndian()) {
844 // Preserve the high bits on big-endian targets.
845 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000846 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
847 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
848
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000849 if (SrcSize > DstSize) {
850 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
851 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
852 } else {
853 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
854 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
855 }
856 } else {
857 // Little-endian targets preserve the low bits. No shifts required.
858 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
859 }
860 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000861
Chris Lattner055097f2010-06-27 06:26:04 +0000862 if (isa<llvm::PointerType>(Ty))
863 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
864 return Val;
865}
866
Chris Lattner1cd66982010-06-27 05:56:15 +0000867
868
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000869/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
870/// a pointer to an object of type \arg Ty.
871///
872/// This safely handles the case when the src type is smaller than the
873/// destination type; in this situation the values of bits which not
874/// present in the src are undefined.
875static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000876 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000877 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000878 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000879 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000880
Chris Lattnerd200eda2010-06-28 22:51:39 +0000881 // If SrcTy and Ty are the same, just do a load.
882 if (SrcTy == Ty)
883 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000884
Micah Villmowdd31ca12012-10-08 16:25:52 +0000885 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000886
Chris Lattner2192fe52011-07-18 04:24:23 +0000887 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000888 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000889 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
890 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000891
Micah Villmowdd31ca12012-10-08 16:25:52 +0000892 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000893
Chris Lattner055097f2010-06-27 06:26:04 +0000894 // If the source and destination are integer or pointer types, just do an
895 // extension or truncation to the desired type.
896 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
897 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
898 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
899 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
900 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000901
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000902 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000903 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000904 // Generally SrcSize is never greater than DstSize, since this means we are
905 // losing bits. However, this can happen in cases where the structure has
906 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000907 //
Mike Stump18bb9282009-05-16 07:57:57 +0000908 // FIXME: Assert that we aren't truncating non-padding bits when have access
909 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000910 llvm::Value *Casted =
911 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000912 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
913 // FIXME: Use better alignment / avoid requiring aligned load.
914 Load->setAlignment(1);
915 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000916 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000917
Chris Lattner3fcc7902010-06-27 01:06:27 +0000918 // Otherwise do coercion through memory. This is stupid, but
919 // simple.
920 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000921 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
922 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
923 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000924 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000925 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
926 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
927 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000928 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000929}
930
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000931// Function to store a first-class aggregate into memory. We prefer to
932// store the elements rather than the aggregate to be more friendly to
933// fast-isel.
934// FIXME: Do we need to recurse here?
935static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
936 llvm::Value *DestPtr, bool DestIsVolatile,
937 bool LowAlignment) {
938 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000939 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000940 dyn_cast<llvm::StructType>(Val->getType())) {
941 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
942 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
943 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
944 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
945 DestIsVolatile);
946 if (LowAlignment)
947 SI->setAlignment(1);
948 }
949 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000950 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
951 if (LowAlignment)
952 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000953 }
954}
955
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000956/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
957/// where the source and destination may have different types.
958///
959/// This safely handles the case when the src type is larger than the
960/// destination type; the upper bits of the src will be lost.
961static void CreateCoercedStore(llvm::Value *Src,
962 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000963 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000964 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000965 llvm::Type *SrcTy = Src->getType();
966 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000967 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000968 if (SrcTy == DstTy) {
969 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
970 return;
971 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000972
Micah Villmowdd31ca12012-10-08 16:25:52 +0000973 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000974
Chris Lattner2192fe52011-07-18 04:24:23 +0000975 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000976 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
977 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
978 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000979
Chris Lattner055097f2010-06-27 06:26:04 +0000980 // If the source and destination are integer or pointer types, just do an
981 // extension or truncation to the desired type.
982 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
983 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
984 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
985 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
986 return;
987 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000988
Micah Villmowdd31ca12012-10-08 16:25:52 +0000989 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000990
Daniel Dunbar313321e2009-02-03 05:31:23 +0000991 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000992 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000993 llvm::Value *Casted =
994 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000995 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000996 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000997 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000998 // Otherwise do coercion through memory. This is stupid, but
999 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001000
1001 // Generally SrcSize is never greater than DstSize, since this means we are
1002 // losing bits. However, this can happen in cases where the structure has
1003 // additional padding, for example due to a user specified alignment.
1004 //
1005 // FIXME: Assert that we aren't truncating non-padding bits when have access
1006 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001007 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1008 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001009 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1010 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1011 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001012 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001013 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1014 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1015 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001016 }
1017}
1018
Alexey Samsonov153004f2014-09-29 22:08:00 +00001019namespace {
1020
1021/// Encapsulates information about the way function arguments from
1022/// CGFunctionInfo should be passed to actual LLVM IR function.
1023class ClangToLLVMArgMapping {
1024 static const unsigned InvalidIndex = ~0U;
1025 unsigned InallocaArgNo;
1026 unsigned SRetArgNo;
1027 unsigned TotalIRArgs;
1028
1029 /// Arguments of LLVM IR function corresponding to single Clang argument.
1030 struct IRArgs {
1031 unsigned PaddingArgIndex;
1032 // Argument is expanded to IR arguments at positions
1033 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1034 unsigned FirstArgIndex;
1035 unsigned NumberOfArgs;
1036
1037 IRArgs()
1038 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1039 NumberOfArgs(0) {}
1040 };
1041
1042 SmallVector<IRArgs, 8> ArgInfo;
1043
1044public:
1045 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1046 bool OnlyRequiredArgs = false)
1047 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1048 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1049 construct(Context, FI, OnlyRequiredArgs);
1050 }
1051
1052 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1053 unsigned getInallocaArgNo() const {
1054 assert(hasInallocaArg());
1055 return InallocaArgNo;
1056 }
1057
1058 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1059 unsigned getSRetArgNo() const {
1060 assert(hasSRetArg());
1061 return SRetArgNo;
1062 }
1063
1064 unsigned totalIRArgs() const { return TotalIRArgs; }
1065
1066 bool hasPaddingArg(unsigned ArgNo) const {
1067 assert(ArgNo < ArgInfo.size());
1068 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1069 }
1070 unsigned getPaddingArgNo(unsigned ArgNo) const {
1071 assert(hasPaddingArg(ArgNo));
1072 return ArgInfo[ArgNo].PaddingArgIndex;
1073 }
1074
1075 /// Returns index of first IR argument corresponding to ArgNo, and their
1076 /// quantity.
1077 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1078 assert(ArgNo < ArgInfo.size());
1079 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1080 ArgInfo[ArgNo].NumberOfArgs);
1081 }
1082
1083private:
1084 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1085 bool OnlyRequiredArgs);
1086};
1087
1088void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1089 const CGFunctionInfo &FI,
1090 bool OnlyRequiredArgs) {
1091 unsigned IRArgNo = 0;
1092 bool SwapThisWithSRet = false;
1093 const ABIArgInfo &RetAI = FI.getReturnInfo();
1094
1095 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1096 SwapThisWithSRet = RetAI.isSRetAfterThis();
1097 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1098 }
1099
1100 unsigned ArgNo = 0;
1101 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1102 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1103 ++I, ++ArgNo) {
1104 assert(I != FI.arg_end());
1105 QualType ArgType = I->type;
1106 const ABIArgInfo &AI = I->info;
1107 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1108 auto &IRArgs = ArgInfo[ArgNo];
1109
1110 if (AI.getPaddingType())
1111 IRArgs.PaddingArgIndex = IRArgNo++;
1112
1113 switch (AI.getKind()) {
1114 case ABIArgInfo::Extend:
1115 case ABIArgInfo::Direct: {
1116 // FIXME: handle sseregparm someday...
1117 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1118 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1119 IRArgs.NumberOfArgs = STy->getNumElements();
1120 } else {
1121 IRArgs.NumberOfArgs = 1;
1122 }
1123 break;
1124 }
1125 case ABIArgInfo::Indirect:
1126 IRArgs.NumberOfArgs = 1;
1127 break;
1128 case ABIArgInfo::Ignore:
1129 case ABIArgInfo::InAlloca:
1130 // ignore and inalloca doesn't have matching LLVM parameters.
1131 IRArgs.NumberOfArgs = 0;
1132 break;
1133 case ABIArgInfo::Expand: {
1134 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1135 break;
1136 }
1137 }
1138
1139 if (IRArgs.NumberOfArgs > 0) {
1140 IRArgs.FirstArgIndex = IRArgNo;
1141 IRArgNo += IRArgs.NumberOfArgs;
1142 }
1143
1144 // Skip over the sret parameter when it comes second. We already handled it
1145 // above.
1146 if (IRArgNo == 1 && SwapThisWithSRet)
1147 IRArgNo++;
1148 }
1149 assert(ArgNo == ArgInfo.size());
1150
1151 if (FI.usesInAlloca())
1152 InallocaArgNo = IRArgNo++;
1153
1154 TotalIRArgs = IRArgNo;
1155}
1156} // namespace
1157
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001158/***/
1159
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001160bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001161 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001162}
1163
Tim Northovere77cc392014-03-29 13:28:05 +00001164bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1165 return ReturnTypeUsesSRet(FI) &&
1166 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1167}
1168
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001169bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1170 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1171 switch (BT->getKind()) {
1172 default:
1173 return false;
1174 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001175 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001176 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001177 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001178 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001179 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001180 }
1181 }
1182
1183 return false;
1184}
1185
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001186bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1187 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1188 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1189 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001190 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001191 }
1192 }
1193
1194 return false;
1195}
1196
Chris Lattnera5f58b02011-07-09 17:41:47 +00001197llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001198 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1199 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001200}
1201
Chris Lattnera5f58b02011-07-09 17:41:47 +00001202llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001203CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001204
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001205 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
1206 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001207
Alexey Samsonov153004f2014-09-29 22:08:00 +00001208 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001209 const ABIArgInfo &retAI = FI.getReturnInfo();
1210 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001211 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001212 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001213
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001214 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001215 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001216 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001217 break;
1218
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001219 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001220 if (retAI.getInAllocaSRet()) {
1221 // sret things on win32 aren't void, they return the sret pointer.
1222 QualType ret = FI.getReturnType();
1223 llvm::Type *ty = ConvertType(ret);
1224 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1225 resultType = llvm::PointerType::get(ty, addressSpace);
1226 } else {
1227 resultType = llvm::Type::getVoidTy(getLLVMContext());
1228 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001229 break;
1230
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001231 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001232 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1233 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001234 break;
1235 }
1236
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001237 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001238 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001239 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001240 }
Mike Stump11289f42009-09-09 15:08:12 +00001241
Alexey Samsonov153004f2014-09-29 22:08:00 +00001242 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1243 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1244
1245 // Add type for sret argument.
1246 if (IRFunctionArgs.hasSRetArg()) {
1247 QualType Ret = FI.getReturnType();
1248 llvm::Type *Ty = ConvertType(Ret);
1249 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1250 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1251 llvm::PointerType::get(Ty, AddressSpace);
1252 }
1253
1254 // Add type for inalloca argument.
1255 if (IRFunctionArgs.hasInallocaArg()) {
1256 auto ArgStruct = FI.getArgStruct();
1257 assert(ArgStruct);
1258 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1259 }
1260
John McCallc818bbb2012-12-07 07:03:17 +00001261 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001262 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001263 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1264 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001265 for (; it != ie; ++it, ++ArgNo) {
1266 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001267
Rafael Espindolafad28de2012-10-24 01:59:00 +00001268 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001269 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1270 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1271 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001272
Alexey Samsonov153004f2014-09-29 22:08:00 +00001273 unsigned FirstIRArg, NumIRArgs;
1274 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1275
1276 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001277 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001278 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001279 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001280 break;
1281
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001282 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001283 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001284 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001285 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001286 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001287 break;
1288 }
1289
1290 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001291 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001292 // Fast-isel and the optimizer generally like scalar values better than
1293 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001294 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001295 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001296 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1297 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001298 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001299 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001300 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001301 assert(NumIRArgs == 1);
1302 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001303 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001304 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001305 }
Mike Stump11289f42009-09-09 15:08:12 +00001306
Daniel Dunbard3674e62008-09-11 01:48:57 +00001307 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001308 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1309 getExpandedTypes(it->type, ArgTypesIter);
1310 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001311 break;
1312 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001313 }
1314
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001315 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1316 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001317
1318 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001319}
1320
Chris Lattner2192fe52011-07-18 04:24:23 +00001321llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001322 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001323 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001324
Chris Lattner8806e322011-07-10 00:18:59 +00001325 if (!isFuncTypeConvertible(FPT))
1326 return llvm::StructType::get(getLLVMContext());
1327
1328 const CGFunctionInfo *Info;
1329 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001330 Info =
1331 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001332 else
John McCalla729c622012-02-17 03:33:10 +00001333 Info = &arrangeCXXMethodDeclaration(MD);
1334 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001335}
1336
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001337void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001338 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001339 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001340 unsigned &CallingConv,
1341 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001342 llvm::AttrBuilder FuncAttrs;
1343 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001344
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001345 CallingConv = FI.getEffectiveCallingConvention();
1346
John McCallab26cfa2010-02-05 21:31:56 +00001347 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001348 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001349
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001350 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001351 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001352 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001353 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001354 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001355 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001356 if (TargetDecl->hasAttr<NoReturnAttr>())
1357 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001358 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1359 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001360
1361 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001362 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001363 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001364 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001365 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1366 // These attributes are not inherited by overloads.
1367 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1368 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001369 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001370 }
1371
Eric Christopherbf005ec2011-08-15 22:38:22 +00001372 // 'const' and 'pure' attribute functions are also nounwind.
1373 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001374 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1375 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001376 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001377 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1378 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001379 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001380 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001381 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001382 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1383 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001384 }
1385
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001386 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001387 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001388 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001389 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001390 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001391 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001392 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001393 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001394 if (CodeGenOpts.EnableSegmentedStacks &&
1395 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001396 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001397
Bill Wendling2f81db62013-02-22 20:53:29 +00001398 if (AttrOnCallSite) {
1399 // Attributes that should go on the call site only.
1400 if (!CodeGenOpts.SimplifyLibCalls)
1401 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001402 } else {
1403 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001404 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001405 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001406 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001407 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001408 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001409 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001410 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001411 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001412 }
1413
Bill Wendlingdabafea2013-03-13 22:24:33 +00001414 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001415 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001416 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001417 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001418 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001419 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001420 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001421 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001422 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001423 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001424 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001425 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001426
Bill Wendlingd8f49502013-08-01 21:41:02 +00001427 if (!CodeGenOpts.StackRealignment)
1428 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001429 }
1430
Alexey Samsonov153004f2014-09-29 22:08:00 +00001431 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001432
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001433 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001434 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001435 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001436 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001437 if (RetTy->hasSignedIntegerRepresentation())
1438 RetAttrs.addAttribute(llvm::Attribute::SExt);
1439 else if (RetTy->hasUnsignedIntegerRepresentation())
1440 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001441 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001442 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001443 if (RetAI.getInReg())
1444 RetAttrs.addAttribute(llvm::Attribute::InReg);
1445 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001446 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001447 break;
1448
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001449 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001450 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001451 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001452 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1453 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001454 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001455 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001456
Daniel Dunbard3674e62008-09-11 01:48:57 +00001457 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001458 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001459 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001460
Hal Finkela2347ba2014-07-18 15:52:10 +00001461 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1462 QualType PTy = RefTy->getPointeeType();
1463 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1464 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1465 .getQuantity());
1466 else if (getContext().getTargetAddressSpace(PTy) == 0)
1467 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1468 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001469
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001470 // Attach return attributes.
1471 if (RetAttrs.hasAttributes()) {
1472 PAL.push_back(llvm::AttributeSet::get(
1473 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1474 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001475
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001476 // Attach attributes to sret.
1477 if (IRFunctionArgs.hasSRetArg()) {
1478 llvm::AttrBuilder SRETAttrs;
1479 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1480 if (RetAI.getInReg())
1481 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1482 PAL.push_back(llvm::AttributeSet::get(
1483 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1484 }
1485
1486 // Attach attributes to inalloca argument.
1487 if (IRFunctionArgs.hasInallocaArg()) {
1488 llvm::AttrBuilder Attrs;
1489 Attrs.addAttribute(llvm::Attribute::InAlloca);
1490 PAL.push_back(llvm::AttributeSet::get(
1491 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1492 }
1493
1494
1495 unsigned ArgNo = 0;
1496 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1497 E = FI.arg_end();
1498 I != E; ++I, ++ArgNo) {
1499 QualType ParamType = I->type;
1500 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001501 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001502
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001503 // Add attribute for padding argument, if necessary.
1504 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001505 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001506 PAL.push_back(llvm::AttributeSet::get(
1507 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1508 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001509 }
1510
John McCall39ec71f2010-03-27 00:47:27 +00001511 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1512 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001513 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001514 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001515 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001516 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001517 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001518 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001519 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001520 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001521 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001522 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001523 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001524 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001525
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001526 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001527 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001528 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001529
Anders Carlsson20759ad2009-09-16 15:53:40 +00001530 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001531 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001532
Bill Wendlinga7912f82012-10-10 07:36:56 +00001533 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1534
Daniel Dunbarc2304432009-03-18 19:51:01 +00001535 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001536 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1537 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001538 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001539
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001540 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001541 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001542 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001543
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001544 case ABIArgInfo::InAlloca:
1545 // inalloca disables readnone and readonly.
1546 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1547 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001548 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Hal Finkela2347ba2014-07-18 15:52:10 +00001551 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1552 QualType PTy = RefTy->getPointeeType();
1553 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1554 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1555 .getQuantity());
1556 else if (getContext().getTargetAddressSpace(PTy) == 0)
1557 Attrs.addAttribute(llvm::Attribute::NonNull);
1558 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001559
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001560 if (Attrs.hasAttributes()) {
1561 unsigned FirstIRArg, NumIRArgs;
1562 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1563 for (unsigned i = 0; i < NumIRArgs; i++)
1564 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1565 FirstIRArg + i + 1, Attrs));
1566 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001567 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001568 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001569
Bill Wendlinga7912f82012-10-10 07:36:56 +00001570 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001571 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001572 AttributeSet::get(getLLVMContext(),
1573 llvm::AttributeSet::FunctionIndex,
1574 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001575}
1576
John McCalla738c252011-03-09 04:27:21 +00001577/// An argument came in as a promoted argument; demote it back to its
1578/// declared type.
1579static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1580 const VarDecl *var,
1581 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001582 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001583
1584 // This can happen with promotions that actually don't change the
1585 // underlying type, like the enum promotions.
1586 if (value->getType() == varType) return value;
1587
1588 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1589 && "unexpected promotion type");
1590
1591 if (isa<llvm::IntegerType>(varType))
1592 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1593
1594 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1595}
1596
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001597/// Returns the attribute (either parameter attribute, or function
1598/// attribute), which declares argument ArgNo to be non-null.
1599static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1600 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001601 // FIXME: __attribute__((nonnull)) can also be applied to:
1602 // - references to pointers, where the pointee is known to be
1603 // nonnull (apparently a Clang extension)
1604 // - transparent unions containing pointers
1605 // In the former case, LLVM IR cannot represent the constraint. In
1606 // the latter case, we have no guarantee that the transparent union
1607 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001608 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1609 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001610 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001611 if (PVD) {
1612 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1613 return ParmNNAttr;
1614 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001615 // Check function attributes.
1616 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001617 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001618 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001619 if (NNAttr->isNonNull(ArgNo))
1620 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001621 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001622 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001623}
1624
Daniel Dunbard931a872009-02-02 22:03:45 +00001625void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1626 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001627 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001628 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1629 // Naked functions don't have prologues.
1630 return;
1631
John McCallcaa19452009-07-28 01:00:58 +00001632 // If this is an implicit-return-zero function, go ahead and
1633 // initialize the return value. TODO: it might be nice to have
1634 // a more general mechanism for this that didn't require synthesized
1635 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001636 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001637 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001638 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001639 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001640 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001641 Builder.CreateStore(Zero, ReturnValue);
1642 }
1643 }
1644
Mike Stump18bb9282009-05-16 07:57:57 +00001645 // FIXME: We no longer need the types from FunctionArgList; lift up and
1646 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001647
Alexey Samsonov153004f2014-09-29 22:08:00 +00001648 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001649 // Flattened function arguments.
1650 SmallVector<llvm::Argument *, 16> FnArgs;
1651 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1652 for (auto &Arg : Fn->args()) {
1653 FnArgs.push_back(&Arg);
1654 }
1655 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001656
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001657 // If we're using inalloca, all the memory arguments are GEPs off of the last
1658 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001659 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001660 if (IRFunctionArgs.hasInallocaArg()) {
1661 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001662 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1663 }
1664
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001665 // Name the struct return parameter.
1666 if (IRFunctionArgs.hasSRetArg()) {
1667 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001668 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001669 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001670 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001673 // Track if we received the parameter as a pointer (indirect, byval, or
1674 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1675 // into a local alloca for us.
1676 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001677 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001678 SmallVector<ValueAndIsPtr, 16> ArgVals;
1679 ArgVals.reserve(Args.size());
1680
Reid Kleckner739756c2013-12-04 19:23:12 +00001681 // Create a pointer value for every parameter declaration. This usually
1682 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1683 // any cleanups or do anything that might unwind. We do that separately, so
1684 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001685 assert(FI.arg_size() == Args.size() &&
1686 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001687 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001688 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001689 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001690 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001691 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001692 QualType Ty = info_it->type;
1693 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001694
John McCalla738c252011-03-09 04:27:21 +00001695 bool isPromoted =
1696 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1697
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001698 unsigned FirstIRArg, NumIRArgs;
1699 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001700
Daniel Dunbard3674e62008-09-11 01:48:57 +00001701 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001702 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001703 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001704 llvm::Value *V = Builder.CreateStructGEP(
1705 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1706 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001707 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 }
1709
Daniel Dunbar747865a2009-02-05 09:16:39 +00001710 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001711 assert(NumIRArgs == 1);
1712 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001713
John McCall47fb9502013-03-07 21:37:08 +00001714 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001715 // Aggregates and complex variables are accessed by reference. All we
1716 // need to do is realign the value, if requested
1717 if (ArgI.getIndirectRealign()) {
1718 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1719
1720 // Copy from the incoming argument pointer to the temporary with the
1721 // appropriate alignment.
1722 //
1723 // FIXME: We should have a common utility for generating an aggregate
1724 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001725 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001726 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001727 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1728 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1729 Builder.CreateMemCpy(Dst,
1730 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001731 llvm::ConstantInt::get(IntPtrTy,
1732 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001733 ArgI.getIndirectAlign(),
1734 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001735 V = AlignedTemp;
1736 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001737 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001738 } else {
1739 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001740 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001741 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1742 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001743
1744 if (isPromoted)
1745 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001746 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001747 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001748 break;
1749 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001750
1751 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001752 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001753
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001754 // If we have the trivial case, handle it with no muss and fuss.
1755 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001756 ArgI.getCoerceToType() == ConvertType(Ty) &&
1757 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001758 assert(NumIRArgs == 1);
1759 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001760 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001761
Hal Finkel48d53e22014-07-19 01:41:07 +00001762 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001763 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1764 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001765 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1766 AI->getArgNo() + 1,
1767 llvm::Attribute::NonNull));
1768
Hal Finkel48d53e22014-07-19 01:41:07 +00001769 QualType OTy = PVD->getOriginalType();
1770 if (const auto *ArrTy =
1771 getContext().getAsConstantArrayType(OTy)) {
1772 // A C99 array parameter declaration with the static keyword also
1773 // indicates dereferenceability, and if the size is constant we can
1774 // use the dereferenceable attribute (which requires the size in
1775 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001776 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001777 QualType ETy = ArrTy->getElementType();
1778 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1779 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1780 ArrSize) {
1781 llvm::AttrBuilder Attrs;
1782 Attrs.addDereferenceableAttr(
1783 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1784 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1785 AI->getArgNo() + 1, Attrs));
1786 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1787 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1788 AI->getArgNo() + 1,
1789 llvm::Attribute::NonNull));
1790 }
1791 }
1792 } else if (const auto *ArrTy =
1793 getContext().getAsVariableArrayType(OTy)) {
1794 // For C99 VLAs with the static keyword, we don't know the size so
1795 // we can't use the dereferenceable attribute, but in addrspace(0)
1796 // we know that it must be nonnull.
1797 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1798 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1799 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1800 AI->getArgNo() + 1,
1801 llvm::Attribute::NonNull));
1802 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001803
1804 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1805 if (!AVAttr)
1806 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1807 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1808 if (AVAttr) {
1809 llvm::Value *AlignmentValue =
1810 EmitScalarExpr(AVAttr->getAlignment());
1811 llvm::ConstantInt *AlignmentCI =
1812 cast<llvm::ConstantInt>(AlignmentValue);
1813 unsigned Alignment =
1814 std::min((unsigned) AlignmentCI->getZExtValue(),
1815 +llvm::Value::MaximumAlignment);
1816
1817 llvm::AttrBuilder Attrs;
1818 Attrs.addAlignmentAttr(Alignment);
1819 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1820 AI->getArgNo() + 1, Attrs));
1821 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001822 }
1823
Bill Wendling507c3512012-10-16 05:23:44 +00001824 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001825 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1826 AI->getArgNo() + 1,
1827 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001828
Chris Lattner7369c142011-07-20 06:29:00 +00001829 // Ensure the argument is the correct type.
1830 if (V->getType() != ArgI.getCoerceToType())
1831 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1832
John McCalla738c252011-03-09 04:27:21 +00001833 if (isPromoted)
1834 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001835
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001836 if (const CXXMethodDecl *MD =
1837 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001838 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001839 V = CGM.getCXXABI().
1840 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001841 }
1842
Rafael Espindola8778c282012-11-29 16:09:03 +00001843 // Because of merging of function types from multiple decls it is
1844 // possible for the type of an argument to not match the corresponding
1845 // type in the function type. Since we are codegening the callee
1846 // in here, add a cast to the argument type.
1847 llvm::Type *LTy = ConvertType(Arg->getType());
1848 if (V->getType() != LTy)
1849 V = Builder.CreateBitCast(V, LTy);
1850
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001851 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001852 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001855 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001856
Chris Lattnerff941a62010-07-28 18:24:28 +00001857 // The alignment we need to use is the max of the requested alignment for
1858 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001859 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001860 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001861 AlignmentToUse = std::max(AlignmentToUse,
1862 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001863
Chris Lattnerff941a62010-07-28 18:24:28 +00001864 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001865 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001866 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001867
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001868 // If the value is offset in memory, apply the offset now.
1869 if (unsigned Offs = ArgI.getDirectOffset()) {
1870 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1871 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001872 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001873 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1874 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001875
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001876 // Fast-isel and the optimizer generally like scalar values better than
1877 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001878 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001879 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1880 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001881 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001882 llvm::Type *DstTy =
1883 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001884 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001885
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001886 if (SrcSize <= DstSize) {
1887 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1888
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001889 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001890 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001891 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001892 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1893 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001894 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001895 }
1896 } else {
1897 llvm::AllocaInst *TempAlloca =
1898 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1899 TempAlloca->setAlignment(AlignmentToUse);
1900 llvm::Value *TempV = TempAlloca;
1901
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001902 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001903 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001904 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001905 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1906 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001907 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001908 }
1909
1910 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001911 }
1912 } else {
1913 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001914 assert(NumIRArgs == 1);
1915 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001916 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001917 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001918 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001919
1920
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001921 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001922 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001923 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001924 if (isPromoted)
1925 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001926 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1927 } else {
1928 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001929 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001930 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001931 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001932
1933 case ABIArgInfo::Expand: {
1934 // If this structure was expanded into multiple arguments then
1935 // we need to create a temporary and reconstruct it from the
1936 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001937 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001938 CharUnits Align = getContext().getDeclAlign(Arg);
1939 Alloca->setAlignment(Align.getQuantity());
1940 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001941 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001942
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001943 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1944 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1945 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1946 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1947 auto AI = FnArgs[FirstIRArg + i];
1948 AI->setName(Arg->getName() + "." + Twine(i));
1949 }
1950 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001951 }
1952
1953 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001954 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001955 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001956 if (!hasScalarEvaluationKind(Ty)) {
1957 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1958 } else {
1959 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1960 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1961 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001962 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001963 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001964 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001965
Reid Kleckner739756c2013-12-04 19:23:12 +00001966 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1967 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001968 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1969 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001970 } else {
1971 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001972 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1973 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001974 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001975}
1976
John McCallffa2c1a2012-01-29 07:46:59 +00001977static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1978 while (insn->use_empty()) {
1979 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1980 if (!bitcast) return;
1981
1982 // This is "safe" because we would have used a ConstantExpr otherwise.
1983 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1984 bitcast->eraseFromParent();
1985 }
1986}
1987
John McCall31168b02011-06-15 23:02:42 +00001988/// Try to emit a fused autorelease of a return result.
1989static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1990 llvm::Value *result) {
1991 // We must be immediately followed the cast.
1992 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001993 if (BB->empty()) return nullptr;
1994 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001995
Chris Lattner2192fe52011-07-18 04:24:23 +00001996 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001997
1998 // result is in a BasicBlock and is therefore an Instruction.
1999 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2000
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002001 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002002
2003 // Look for:
2004 // %generator = bitcast %type1* %generator2 to %type2*
2005 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2006 // We would have emitted this as a constant if the operand weren't
2007 // an Instruction.
2008 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2009
2010 // Require the generator to be immediately followed by the cast.
2011 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002012 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002013
2014 insnsToKill.push_back(bitcast);
2015 }
2016
2017 // Look for:
2018 // %generator = call i8* @objc_retain(i8* %originalResult)
2019 // or
2020 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2021 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002022 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002023
2024 bool doRetainAutorelease;
2025
2026 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2027 doRetainAutorelease = true;
2028 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2029 .objc_retainAutoreleasedReturnValue) {
2030 doRetainAutorelease = false;
2031
John McCallcfa4e9b2012-09-07 23:30:50 +00002032 // If we emitted an assembly marker for this call (and the
2033 // ARCEntrypoints field should have been set if so), go looking
2034 // for that call. If we can't find it, we can't do this
2035 // optimization. But it should always be the immediately previous
2036 // instruction, unless we needed bitcasts around the call.
2037 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2038 llvm::Instruction *prev = call->getPrevNode();
2039 assert(prev);
2040 if (isa<llvm::BitCastInst>(prev)) {
2041 prev = prev->getPrevNode();
2042 assert(prev);
2043 }
2044 assert(isa<llvm::CallInst>(prev));
2045 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2046 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2047 insnsToKill.push_back(prev);
2048 }
John McCall31168b02011-06-15 23:02:42 +00002049 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002050 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002051 }
2052
2053 result = call->getArgOperand(0);
2054 insnsToKill.push_back(call);
2055
2056 // Keep killing bitcasts, for sanity. Note that we no longer care
2057 // about precise ordering as long as there's exactly one use.
2058 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2059 if (!bitcast->hasOneUse()) break;
2060 insnsToKill.push_back(bitcast);
2061 result = bitcast->getOperand(0);
2062 }
2063
2064 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002065 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002066 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2067 (*i)->eraseFromParent();
2068
2069 // Do the fused retain/autorelease if we were asked to.
2070 if (doRetainAutorelease)
2071 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2072
2073 // Cast back to the result type.
2074 return CGF.Builder.CreateBitCast(result, resultType);
2075}
2076
John McCallffa2c1a2012-01-29 07:46:59 +00002077/// If this is a +1 of the value of an immutable 'self', remove it.
2078static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2079 llvm::Value *result) {
2080 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002081 const ObjCMethodDecl *method =
2082 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002083 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002084 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002085 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002086
2087 // Look for a retain call.
2088 llvm::CallInst *retainCall =
2089 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2090 if (!retainCall ||
2091 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002092 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002093
2094 // Look for an ordinary load of 'self'.
2095 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2096 llvm::LoadInst *load =
2097 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2098 if (!load || load->isAtomic() || load->isVolatile() ||
2099 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002100 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002101
2102 // Okay! Burn it all down. This relies for correctness on the
2103 // assumption that the retain is emitted as part of the return and
2104 // that thereafter everything is used "linearly".
2105 llvm::Type *resultType = result->getType();
2106 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2107 assert(retainCall->use_empty());
2108 retainCall->eraseFromParent();
2109 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2110
2111 return CGF.Builder.CreateBitCast(load, resultType);
2112}
2113
John McCall31168b02011-06-15 23:02:42 +00002114/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002115///
2116/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002117static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2118 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002119 // If we're returning 'self', kill the initial retain. This is a
2120 // heuristic attempt to "encourage correctness" in the really unfortunate
2121 // case where we have a return of self during a dealloc and we desperately
2122 // need to avoid the possible autorelease.
2123 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2124 return self;
2125
John McCall31168b02011-06-15 23:02:42 +00002126 // At -O0, try to emit a fused retain/autorelease.
2127 if (CGF.shouldUseFusedARCCalls())
2128 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2129 return fused;
2130
2131 return CGF.EmitARCAutoreleaseReturnValue(result);
2132}
2133
John McCall6e1c0122012-01-29 02:35:02 +00002134/// Heuristically search for a dominating store to the return-value slot.
2135static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2136 // If there are multiple uses of the return-value slot, just check
2137 // for something immediately preceding the IP. Sometimes this can
2138 // happen with how we generate implicit-returns; it can also happen
2139 // with noreturn cleanups.
2140 if (!CGF.ReturnValue->hasOneUse()) {
2141 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002142 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002143 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002144 if (!store) return nullptr;
2145 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002146 assert(!store->isAtomic() && !store->isVolatile()); // see below
2147 return store;
2148 }
2149
2150 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002151 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002152 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002153
2154 // These aren't actually possible for non-coerced returns, and we
2155 // only care about non-coerced returns on this code path.
2156 assert(!store->isAtomic() && !store->isVolatile());
2157
2158 // Now do a first-and-dirty dominance check: just walk up the
2159 // single-predecessors chain from the current insertion point.
2160 llvm::BasicBlock *StoreBB = store->getParent();
2161 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2162 while (IP != StoreBB) {
2163 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002164 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002165 }
2166
2167 // Okay, the store's basic block dominates the insertion point; we
2168 // can do our thing.
2169 return store;
2170}
2171
Adrian Prantl3be10542013-05-02 17:30:20 +00002172void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002173 bool EmitRetDbgLoc,
2174 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002175 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2176 // Naked functions don't have epilogues.
2177 Builder.CreateUnreachable();
2178 return;
2179 }
2180
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002181 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002182 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002183 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002184 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002185 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002186
Dan Gohman481e40c2010-07-20 20:13:52 +00002187 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002188 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002189 QualType RetTy = FI.getReturnType();
2190 const ABIArgInfo &RetAI = FI.getReturnInfo();
2191
2192 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002193 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002194 // Aggregrates get evaluated directly into the destination. Sometimes we
2195 // need to return the sret value in a register, though.
2196 assert(hasAggregateEvaluationKind(RetTy));
2197 if (RetAI.getInAllocaSRet()) {
2198 llvm::Function::arg_iterator EI = CurFn->arg_end();
2199 --EI;
2200 llvm::Value *ArgStruct = EI;
2201 llvm::Value *SRet =
2202 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2203 RV = Builder.CreateLoad(SRet, "sret");
2204 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002205 break;
2206
Daniel Dunbar03816342010-08-21 02:24:36 +00002207 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002208 auto AI = CurFn->arg_begin();
2209 if (RetAI.isSRetAfterThis())
2210 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002211 switch (getEvaluationKind(RetTy)) {
2212 case TEK_Complex: {
2213 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002214 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2215 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002216 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002217 /*isInit*/ true);
2218 break;
2219 }
2220 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002221 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002222 break;
2223 case TEK_Scalar:
2224 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002225 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002226 /*isInit*/ true);
2227 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002228 }
2229 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002230 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002231
2232 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002233 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002234 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2235 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002236 // The internal return value temp always will have pointer-to-return-type
2237 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002238
John McCall6e1c0122012-01-29 02:35:02 +00002239 // If there is a dominating store to ReturnValue, we can elide
2240 // the load, zap the store, and usually zap the alloca.
2241 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002242 // Reuse the debug location from the store unless there is
2243 // cleanup code to be emitted between the store and return
2244 // instruction.
2245 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002246 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002247 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002248 RV = SI->getValueOperand();
2249 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002250
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002251 // If that was the only use of the return value, nuke it as well now.
2252 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2253 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002254 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002255 }
John McCall6e1c0122012-01-29 02:35:02 +00002256
2257 // Otherwise, we have to do a simple load.
2258 } else {
2259 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002260 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002261 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002262 llvm::Value *V = ReturnValue;
2263 // If the value is offset in memory, apply the offset now.
2264 if (unsigned Offs = RetAI.getDirectOffset()) {
2265 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2266 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002267 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002268 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2269 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002270
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002271 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002272 }
John McCall31168b02011-06-15 23:02:42 +00002273
2274 // In ARC, end functions that return a retainable type with a call
2275 // to objc_autoreleaseReturnValue.
2276 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002277 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002278 !FI.isReturnsRetained() &&
2279 RetTy->isObjCRetainableType());
2280 RV = emitAutoreleaseOfResult(*this, RV);
2281 }
2282
Chris Lattner726b3d02010-06-26 23:13:19 +00002283 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002284
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002285 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002286 break;
2287
2288 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002289 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002290 }
2291
Alexey Samsonovde443c52014-08-13 00:26:40 +00002292 llvm::Instruction *Ret;
2293 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002294 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002295 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2296 SanitizerScope SanScope(this);
2297 llvm::Value *Cond = Builder.CreateICmpNE(
2298 RV, llvm::Constant::getNullValue(RV->getType()));
2299 llvm::Constant *StaticData[] = {
2300 EmitCheckSourceLocation(EndLoc),
2301 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2302 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002303 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2304 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002305 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002306 }
2307 Ret = Builder.CreateRet(RV);
2308 } else {
2309 Ret = Builder.CreateRetVoid();
2310 }
2311
Devang Patel65497582010-07-21 18:08:50 +00002312 if (!RetDbgLoc.isUnknown())
2313 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002314}
2315
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002316static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2317 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2318 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2319}
2320
2321static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2322 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2323 // placeholders.
2324 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2325 llvm::Value *Placeholder =
2326 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2327 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2328 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2329 Ty.getQualifiers(),
2330 AggValueSlot::IsNotDestructed,
2331 AggValueSlot::DoesNotNeedGCBarriers,
2332 AggValueSlot::IsNotAliased);
2333}
2334
John McCall32ea9692011-03-11 20:59:21 +00002335void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002336 const VarDecl *param,
2337 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002338 // StartFunction converted the ABI-lowered parameter(s) into a
2339 // local alloca. We need to turn that into an r-value suitable
2340 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002341 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002342
John McCall32ea9692011-03-11 20:59:21 +00002343 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002344
John McCall23f66262010-05-26 22:34:26 +00002345 // For the most part, we just need to load the alloca, except:
2346 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002347 // 2) references to non-scalars are pointers directly to the aggregate.
2348 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002349 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002350 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002351 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002352
2353 // Locals which are references to scalars are represented
2354 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002355 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002356 }
2357
Reid Klecknerab2090d2014-07-26 01:34:32 +00002358 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2359 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002360
Nick Lewycky2d84e842013-10-02 02:29:49 +00002361 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002362}
2363
John McCall31168b02011-06-15 23:02:42 +00002364static bool isProvablyNull(llvm::Value *addr) {
2365 return isa<llvm::ConstantPointerNull>(addr);
2366}
2367
2368static bool isProvablyNonNull(llvm::Value *addr) {
2369 return isa<llvm::AllocaInst>(addr);
2370}
2371
2372/// Emit the actual writing-back of a writeback.
2373static void emitWriteback(CodeGenFunction &CGF,
2374 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002375 const LValue &srcLV = writeback.Source;
2376 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002377 assert(!isProvablyNull(srcAddr) &&
2378 "shouldn't have writeback for provably null argument");
2379
Craig Topper8a13c412014-05-21 05:09:00 +00002380 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002381
2382 // If the argument wasn't provably non-null, we need to null check
2383 // before doing the store.
2384 bool provablyNonNull = isProvablyNonNull(srcAddr);
2385 if (!provablyNonNull) {
2386 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2387 contBB = CGF.createBasicBlock("icr.done");
2388
2389 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2390 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2391 CGF.EmitBlock(writebackBB);
2392 }
2393
2394 // Load the value to writeback.
2395 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2396
2397 // Cast it back, in case we're writing an id to a Foo* or something.
2398 value = CGF.Builder.CreateBitCast(value,
2399 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2400 "icr.writeback-cast");
2401
2402 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002403
2404 // If we have a "to use" value, it's something we need to emit a use
2405 // of. This has to be carefully threaded in: if it's done after the
2406 // release it's potentially undefined behavior (and the optimizer
2407 // will ignore it), and if it happens before the retain then the
2408 // optimizer could move the release there.
2409 if (writeback.ToUse) {
2410 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2411
2412 // Retain the new value. No need to block-copy here: the block's
2413 // being passed up the stack.
2414 value = CGF.EmitARCRetainNonBlock(value);
2415
2416 // Emit the intrinsic use here.
2417 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2418
2419 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002420 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002421
2422 // Put the new value in place (primitively).
2423 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2424
2425 // Release the old value.
2426 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2427
2428 // Otherwise, we can just do a normal lvalue store.
2429 } else {
2430 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2431 }
John McCall31168b02011-06-15 23:02:42 +00002432
2433 // Jump to the continuation block.
2434 if (!provablyNonNull)
2435 CGF.EmitBlock(contBB);
2436}
2437
2438static void emitWritebacks(CodeGenFunction &CGF,
2439 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002440 for (const auto &I : args.writebacks())
2441 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002442}
2443
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002444static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2445 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002446 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002447 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2448 CallArgs.getCleanupsToDeactivate();
2449 // Iterate in reverse to increase the likelihood of popping the cleanup.
2450 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2451 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2452 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2453 I->IsActiveIP->eraseFromParent();
2454 }
2455}
2456
John McCalleff18842013-03-23 02:35:54 +00002457static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2458 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2459 if (uop->getOpcode() == UO_AddrOf)
2460 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002461 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002462}
2463
John McCall31168b02011-06-15 23:02:42 +00002464/// Emit an argument that's being passed call-by-writeback. That is,
2465/// we are passing the address of
2466static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2467 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002468 LValue srcLV;
2469
2470 // Make an optimistic effort to emit the address as an l-value.
2471 // This can fail if the the argument expression is more complicated.
2472 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2473 srcLV = CGF.EmitLValue(lvExpr);
2474
2475 // Otherwise, just emit it as a scalar.
2476 } else {
2477 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2478
2479 QualType srcAddrType =
2480 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2481 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2482 }
2483 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002484
2485 // The dest and src types don't necessarily match in LLVM terms
2486 // because of the crazy ObjC compatibility rules.
2487
Chris Lattner2192fe52011-07-18 04:24:23 +00002488 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002489 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2490
2491 // If the address is a constant null, just pass the appropriate null.
2492 if (isProvablyNull(srcAddr)) {
2493 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2494 CRE->getType());
2495 return;
2496 }
2497
John McCall31168b02011-06-15 23:02:42 +00002498 // Create the temporary.
2499 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2500 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002501 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2502 // and that cleanup will be conditional if we can't prove that the l-value
2503 // isn't null, so we need to register a dominating point so that the cleanups
2504 // system will make valid IR.
2505 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2506
John McCall31168b02011-06-15 23:02:42 +00002507 // Zero-initialize it if we're not doing a copy-initialization.
2508 bool shouldCopy = CRE->shouldCopy();
2509 if (!shouldCopy) {
2510 llvm::Value *null =
2511 llvm::ConstantPointerNull::get(
2512 cast<llvm::PointerType>(destType->getElementType()));
2513 CGF.Builder.CreateStore(null, temp);
2514 }
Craig Topper8a13c412014-05-21 05:09:00 +00002515
2516 llvm::BasicBlock *contBB = nullptr;
2517 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002518
2519 // If the address is *not* known to be non-null, we need to switch.
2520 llvm::Value *finalArgument;
2521
2522 bool provablyNonNull = isProvablyNonNull(srcAddr);
2523 if (provablyNonNull) {
2524 finalArgument = temp;
2525 } else {
2526 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2527
2528 finalArgument = CGF.Builder.CreateSelect(isNull,
2529 llvm::ConstantPointerNull::get(destType),
2530 temp, "icr.argument");
2531
2532 // If we need to copy, then the load has to be conditional, which
2533 // means we need control flow.
2534 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002535 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002536 contBB = CGF.createBasicBlock("icr.cont");
2537 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2538 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2539 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002540 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002541 }
2542 }
2543
Craig Topper8a13c412014-05-21 05:09:00 +00002544 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002545
John McCall31168b02011-06-15 23:02:42 +00002546 // Perform a copy if necessary.
2547 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002548 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002549 assert(srcRV.isScalar());
2550
2551 llvm::Value *src = srcRV.getScalarVal();
2552 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2553 "icr.cast");
2554
2555 // Use an ordinary store, not a store-to-lvalue.
2556 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002557
2558 // If optimization is enabled, and the value was held in a
2559 // __strong variable, we need to tell the optimizer that this
2560 // value has to stay alive until we're doing the store back.
2561 // This is because the temporary is effectively unretained,
2562 // and so otherwise we can violate the high-level semantics.
2563 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2564 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2565 valueToUse = src;
2566 }
John McCall31168b02011-06-15 23:02:42 +00002567 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002568
John McCall31168b02011-06-15 23:02:42 +00002569 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002570 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002571 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002572 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002573
2574 // Make a phi for the value to intrinsically use.
2575 if (valueToUse) {
2576 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2577 "icr.to-use");
2578 phiToUse->addIncoming(valueToUse, copyBB);
2579 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2580 originBB);
2581 valueToUse = phiToUse;
2582 }
2583
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002584 condEval.end(CGF);
2585 }
John McCall31168b02011-06-15 23:02:42 +00002586
John McCalleff18842013-03-23 02:35:54 +00002587 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002588 args.add(RValue::get(finalArgument), CRE->getType());
2589}
2590
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002591void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2592 assert(!StackBase && !StackCleanup.isValid());
2593
2594 // Save the stack.
2595 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2596 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2597
2598 // Control gets really tied up in landing pads, so we have to spill the
2599 // stacksave to an alloca to avoid violating SSA form.
2600 // TODO: This is dead if we never emit the cleanup. We should create the
2601 // alloca and store lazily on the first cleanup emission.
2602 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2603 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2604 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2605 StackCleanup = CGF.EHStack.getInnermostEHScope();
2606 assert(StackCleanup.isValid());
2607}
2608
2609void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2610 if (StackBase) {
2611 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2612 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2613 // We could load StackBase from StackBaseMem, but in the non-exceptional
2614 // case we can skip it.
2615 CGF.Builder.CreateCall(F, StackBase);
2616 }
2617}
2618
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002619static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2620 QualType ArgType, SourceLocation ArgLoc,
2621 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002622 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002623 return;
2624 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2625 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2626 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2627 if (!NNAttr)
2628 return;
2629 CodeGenFunction::SanitizerScope SanScope(&CGF);
2630 assert(RV.isScalar());
2631 llvm::Value *V = RV.getScalarVal();
2632 llvm::Value *Cond =
2633 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2634 llvm::Constant *StaticData[] = {
2635 CGF.EmitCheckSourceLocation(ArgLoc),
2636 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2637 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2638 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002639 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2640 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002641}
2642
Reid Kleckner739756c2013-12-04 19:23:12 +00002643void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2644 ArrayRef<QualType> ArgTypes,
2645 CallExpr::const_arg_iterator ArgBeg,
2646 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002647 const FunctionDecl *CalleeDecl,
2648 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002649 bool ForceColumnInfo) {
2650 CGDebugInfo *DI = getDebugInfo();
2651 SourceLocation CallLoc;
2652 if (DI) CallLoc = DI->getLocation();
2653
2654 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2655 // because arguments are destroyed left to right in the callee.
2656 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002657 // Insert a stack save if we're going to need any inalloca args.
2658 bool HasInAllocaArgs = false;
2659 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2660 I != E && !HasInAllocaArgs; ++I)
2661 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2662 if (HasInAllocaArgs) {
2663 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2664 Args.allocateArgumentMemory(*this);
2665 }
2666
2667 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002668 size_t CallArgsStart = Args.size();
2669 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2670 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2671 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002672 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2673 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002674 // Restore the debug location.
2675 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2676 }
2677
2678 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2679 // IR function.
2680 std::reverse(Args.begin() + CallArgsStart, Args.end());
2681 return;
2682 }
2683
2684 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2685 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2686 assert(Arg != ArgEnd);
2687 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002688 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2689 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002690 // Restore the debug location.
2691 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2692 }
2693}
2694
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002695namespace {
2696
2697struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2698 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2699 : Addr(Addr), Ty(Ty) {}
2700
2701 llvm::Value *Addr;
2702 QualType Ty;
2703
Craig Topper4f12f102014-03-12 06:41:41 +00002704 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002705 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2706 assert(!Dtor->isTrivial());
2707 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2708 /*Delegating=*/false, Addr);
2709 }
2710};
2711
2712}
2713
John McCall32ea9692011-03-11 20:59:21 +00002714void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2715 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002716 if (const ObjCIndirectCopyRestoreExpr *CRE
2717 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002718 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002719 assert(getContext().hasSameType(E->getType(), type));
2720 return emitWritebackArg(*this, args, CRE);
2721 }
2722
John McCall0a76c0c2011-08-26 18:42:59 +00002723 assert(type->isReferenceType() == E->isGLValue() &&
2724 "reference binding to unmaterialized r-value!");
2725
John McCall17054bd62011-08-26 21:08:13 +00002726 if (E->isGLValue()) {
2727 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002728 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002731 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2732
2733 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2734 // However, we still have to push an EH-only cleanup in case we unwind before
2735 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002736 if (HasAggregateEvalKind &&
2737 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2738 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002739 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002740 AggValueSlot Slot;
2741 if (args.isUsingInAlloca())
2742 Slot = createPlaceholderSlot(*this, type);
2743 else
2744 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002745
2746 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2747 bool DestroyedInCallee =
2748 RD && RD->hasNonTrivialDestructor() &&
2749 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2750 if (DestroyedInCallee)
2751 Slot.setExternallyDestructed();
2752
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002753 EmitAggExpr(E, Slot);
2754 RValue RV = Slot.asRValue();
2755 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002756
Reid Klecknere39ee212014-05-03 00:33:28 +00002757 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002758 // Create a no-op GEP between the placeholder and the cleanup so we can
2759 // RAUW it successfully. It also serves as a marker of the first
2760 // instruction where the cleanup is active.
2761 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002762 // This unreachable is a temporary marker which will be removed later.
2763 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2764 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002765 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002766 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002767 }
2768
2769 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002770 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2771 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2772 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002773 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2774 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2775 } else {
2776 // We can't represent a misaligned lvalue in the CallArgList, so copy
2777 // to an aligned temporary now.
2778 llvm::Value *tmp = CreateMemTemp(type);
2779 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2780 L.getAlignment());
2781 args.add(RValue::getAggregate(tmp), type);
2782 }
Eli Friedmandf968192011-05-26 00:10:27 +00002783 return;
2784 }
2785
John McCall32ea9692011-03-11 20:59:21 +00002786 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002787}
2788
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002789QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2790 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2791 // implicitly widens null pointer constants that are arguments to varargs
2792 // functions to pointer-sized ints.
2793 if (!getTarget().getTriple().isOSWindows())
2794 return Arg->getType();
2795
2796 if (Arg->getType()->isIntegerType() &&
2797 getContext().getTypeSize(Arg->getType()) <
2798 getContext().getTargetInfo().getPointerWidth(0) &&
2799 Arg->isNullPointerConstant(getContext(),
2800 Expr::NPC_ValueDependentIsNotNull)) {
2801 return getContext().getIntPtrType();
2802 }
2803
2804 return Arg->getType();
2805}
2806
Dan Gohman515a60d2012-02-16 00:57:37 +00002807// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2808// optimizer it can aggressively ignore unwind edges.
2809void
2810CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2811 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2812 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2813 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2814 CGM.getNoObjCARCExceptionsMetadata());
2815}
2816
John McCall882987f2013-02-28 19:01:20 +00002817/// Emits a call to the given no-arguments nounwind runtime function.
2818llvm::CallInst *
2819CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2820 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002821 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002822}
2823
2824/// Emits a call to the given nounwind runtime function.
2825llvm::CallInst *
2826CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2827 ArrayRef<llvm::Value*> args,
2828 const llvm::Twine &name) {
2829 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2830 call->setDoesNotThrow();
2831 return call;
2832}
2833
2834/// Emits a simple call (never an invoke) to the given no-arguments
2835/// runtime function.
2836llvm::CallInst *
2837CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2838 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002839 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002840}
2841
2842/// Emits a simple call (never an invoke) to the given runtime
2843/// function.
2844llvm::CallInst *
2845CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2846 ArrayRef<llvm::Value*> args,
2847 const llvm::Twine &name) {
2848 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2849 call->setCallingConv(getRuntimeCC());
2850 return call;
2851}
2852
2853/// Emits a call or invoke to the given noreturn runtime function.
2854void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2855 ArrayRef<llvm::Value*> args) {
2856 if (getInvokeDest()) {
2857 llvm::InvokeInst *invoke =
2858 Builder.CreateInvoke(callee,
2859 getUnreachableBlock(),
2860 getInvokeDest(),
2861 args);
2862 invoke->setDoesNotReturn();
2863 invoke->setCallingConv(getRuntimeCC());
2864 } else {
2865 llvm::CallInst *call = Builder.CreateCall(callee, args);
2866 call->setDoesNotReturn();
2867 call->setCallingConv(getRuntimeCC());
2868 Builder.CreateUnreachable();
2869 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002870 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002871}
2872
2873/// Emits a call or invoke instruction to the given nullary runtime
2874/// function.
2875llvm::CallSite
2876CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2877 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002878 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002879}
2880
2881/// Emits a call or invoke instruction to the given runtime function.
2882llvm::CallSite
2883CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2884 ArrayRef<llvm::Value*> args,
2885 const Twine &name) {
2886 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2887 callSite.setCallingConv(getRuntimeCC());
2888 return callSite;
2889}
2890
2891llvm::CallSite
2892CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2893 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002894 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002895}
2896
John McCallbd309292010-07-06 01:34:17 +00002897/// Emits a call or invoke instruction to the given function, depending
2898/// on the current state of the EH stack.
2899llvm::CallSite
2900CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002901 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002902 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002903 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002904
Dan Gohman515a60d2012-02-16 00:57:37 +00002905 llvm::Instruction *Inst;
2906 if (!InvokeDest)
2907 Inst = Builder.CreateCall(Callee, Args, Name);
2908 else {
2909 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2910 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2911 EmitBlock(ContBB);
2912 }
2913
2914 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2915 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002916 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002917 AddObjCARCExceptionMetadata(Inst);
2918
2919 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002920}
2921
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002922/// \brief Store a non-aggregate value to an address to initialize it. For
2923/// initialization, a non-atomic store will be used.
2924static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2925 LValue Dst) {
2926 if (Src.isScalar())
2927 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2928 else
2929 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2930}
2931
2932void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2933 llvm::Value *New) {
2934 DeferredReplacements.push_back(std::make_pair(Old, New));
2935}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002936
Daniel Dunbard931a872009-02-02 22:03:45 +00002937RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002938 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002939 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002940 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002941 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002942 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002943 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002944
2945 // Handle struct-return functions by passing a pointer to the
2946 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002947 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002948 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002949
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002950 llvm::FunctionType *IRFuncTy =
2951 cast<llvm::FunctionType>(
2952 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002953
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002954 // If we're using inalloca, insert the allocation after the stack save.
2955 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002956 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002957 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002958 llvm::Instruction *IP = CallArgs.getStackBase();
2959 llvm::AllocaInst *AI;
2960 if (IP) {
2961 IP = IP->getNextNode();
2962 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2963 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002964 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002965 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002966 AI->setUsedWithInAlloca(true);
2967 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2968 ArgMemory = AI;
2969 }
2970
Alexey Samsonov153004f2014-09-29 22:08:00 +00002971 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002972 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2973
Chris Lattner4ca97c32009-06-13 00:26:38 +00002974 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002975 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002976 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002977 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002978 SRetPtr = ReturnValue.getValue();
2979 if (!SRetPtr)
2980 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002981 if (IRFunctionArgs.hasSRetArg()) {
2982 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002983 } else {
2984 llvm::Value *Addr =
2985 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2986 Builder.CreateStore(SRetPtr, Addr);
2987 }
Anders Carlsson17490832009-12-24 20:40:36 +00002988 }
Mike Stump11289f42009-09-09 15:08:12 +00002989
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002990 assert(CallInfo.arg_size() == CallArgs.size() &&
2991 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002992 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002993 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002994 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002995 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002996 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002997 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002998
John McCall47fb9502013-03-07 21:37:08 +00002999 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003000
3001 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003002 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3003 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3004 llvm::UndefValue::get(ArgInfo.getPaddingType());
3005
3006 unsigned FirstIRArg, NumIRArgs;
3007 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003008
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003009 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003010 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003011 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003012 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3013 if (RV.isAggregate()) {
3014 // Replace the placeholder with the appropriate argument slot GEP.
3015 llvm::Instruction *Placeholder =
3016 cast<llvm::Instruction>(RV.getAggregateAddr());
3017 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3018 Builder.SetInsertPoint(Placeholder);
3019 llvm::Value *Addr = Builder.CreateStructGEP(
3020 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3021 Builder.restoreIP(IP);
3022 deferPlaceholderReplacement(Placeholder, Addr);
3023 } else {
3024 // Store the RValue into the argument struct.
3025 llvm::Value *Addr =
3026 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003027 unsigned AS = Addr->getType()->getPointerAddressSpace();
3028 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3029 // There are some cases where a trivial bitcast is not avoidable. The
3030 // definition of a type later in a translation unit may change it's type
3031 // from {}* to (%struct.foo*)*.
3032 if (Addr->getType() != MemType)
3033 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003034 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3035 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3036 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003037 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003038 }
3039
Daniel Dunbar03816342010-08-21 02:24:36 +00003040 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003041 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003042 if (RV.isScalar() || RV.isComplex()) {
3043 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003044 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3045 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3046 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003047 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003048
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003049 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003050 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003051 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003052 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003053 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003054 // 1. If the argument is not byval, and we are required to copy the
3055 // source. (This case doesn't occur on any common architecture.)
3056 // 2. If the argument is byval, RV is not sufficiently aligned, and
3057 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003058 // 3. If the argument is byval, but RV is located in an address space
3059 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003060 llvm::Value *Addr = RV.getAggregateAddr();
3061 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003062 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003063 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003064 const unsigned ArgAddrSpace =
3065 (FirstIRArg < IRFuncTy->getNumParams()
3066 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3067 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003068 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003069 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00003070 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3071 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003072 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003073 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3074 if (Align > AI->getAlignment())
3075 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003076 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003077 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003078 } else {
3079 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003080 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003081 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003082 }
3083 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003084 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003085
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003086 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003087 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003088 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003089
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003090 case ABIArgInfo::Extend:
3091 case ABIArgInfo::Direct: {
3092 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003093 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3094 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003095 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003096 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003097 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003098 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003099 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003100 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003101
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003102 // We might have to widen integers, but we should never truncate.
3103 if (ArgInfo.getCoerceToType() != V->getType() &&
3104 V->getType()->isIntegerTy())
3105 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3106
Chris Lattner3ce86682011-07-12 04:53:39 +00003107 // If the argument doesn't match, perform a bitcast to coerce it. This
3108 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003109 if (FirstIRArg < IRFuncTy->getNumParams() &&
3110 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3111 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3112 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003113 break;
3114 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003115
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003116 // FIXME: Avoid the conversion through memory if possible.
3117 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003118 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003119 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003120 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003121 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003122 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003123 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003124
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003125 // If the value is offset in memory, apply the offset now.
3126 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3127 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3128 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003129 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003130 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3131
3132 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003133
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003134 // Fast-isel and the optimizer generally like scalar values better than
3135 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003136 llvm::StructType *STy =
3137 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003138 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003139 llvm::Type *SrcTy =
3140 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3141 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3142 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3143
3144 // If the source type is smaller than the destination type of the
3145 // coerce-to logic, copy the source value into a temp alloca the size
3146 // of the destination type to allow loading all of it. The bits past
3147 // the source value are left undef.
3148 if (SrcSize < DstSize) {
3149 llvm::AllocaInst *TempAlloca
3150 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3151 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3152 SrcPtr = TempAlloca;
3153 } else {
3154 SrcPtr = Builder.CreateBitCast(SrcPtr,
3155 llvm::PointerType::getUnqual(STy));
3156 }
3157
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003158 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003159 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3160 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003161 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3162 // We don't know what we're loading from.
3163 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003164 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003165 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003166 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003167 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003168 assert(NumIRArgs == 1);
3169 IRCallArgs[FirstIRArg] =
3170 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003171 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003172
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003173 break;
3174 }
3175
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003176 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003177 unsigned IRArgPos = FirstIRArg;
3178 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3179 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003180 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003181 }
3182 }
Mike Stump11289f42009-09-09 15:08:12 +00003183
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003184 if (ArgMemory) {
3185 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003186 if (CallInfo.isVariadic()) {
3187 // When passing non-POD arguments by value to variadic functions, we will
3188 // end up with a variadic prototype and an inalloca call site. In such
3189 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3190 // the callee.
3191 unsigned CalleeAS =
3192 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3193 Callee = Builder.CreateBitCast(
3194 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3195 } else {
3196 llvm::Type *LastParamTy =
3197 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3198 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003199#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003200 // Assert that these structs have equivalent element types.
3201 llvm::StructType *FullTy = CallInfo.getArgStruct();
3202 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3203 cast<llvm::PointerType>(LastParamTy)->getElementType());
3204 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3205 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3206 DE = DeclaredTy->element_end(),
3207 FI = FullTy->element_begin();
3208 DI != DE; ++DI, ++FI)
3209 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003210#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003211 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3212 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003213 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003214 assert(IRFunctionArgs.hasInallocaArg());
3215 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003216 }
3217
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003218 if (!CallArgs.getCleanupsToDeactivate().empty())
3219 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3220
Chris Lattner4ca97c32009-06-13 00:26:38 +00003221 // If the callee is a bitcast of a function to a varargs pointer to function
3222 // type, check to see if we can remove the bitcast. This handles some cases
3223 // with unprototyped functions.
3224 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3225 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003226 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3227 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003228 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003229 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003230
Chris Lattner4ca97c32009-06-13 00:26:38 +00003231 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3232 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003233 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003234 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003235 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003236 bool ArgsMatch = true;
3237 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3238 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3239 ArgsMatch = false;
3240 break;
3241 }
Mike Stump11289f42009-09-09 15:08:12 +00003242
Chris Lattner4ca97c32009-06-13 00:26:38 +00003243 // Strip the cast if we can get away with it. This is a nice cleanup,
3244 // but also allows us to inline the function at -O0 if it is marked
3245 // always_inline.
3246 if (ArgsMatch)
3247 Callee = CalleeF;
3248 }
3249 }
Mike Stump11289f42009-09-09 15:08:12 +00003250
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003251 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3252 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3253 // Inalloca argument can have different type.
3254 if (IRFunctionArgs.hasInallocaArg() &&
3255 i == IRFunctionArgs.getInallocaArgNo())
3256 continue;
3257 if (i < IRFuncTy->getNumParams())
3258 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3259 }
3260
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003261 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003262 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003263 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3264 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003265 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003266 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003267
Craig Topper8a13c412014-05-21 05:09:00 +00003268 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003269 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3270 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003271 InvokeDest = getInvokeDest();
3272
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003273 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003274 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003275 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003276 } else {
3277 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003278 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003279 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003280 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003281 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003282 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003283
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003284 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3285 !CS.hasFnAttr(llvm::Attribute::NoInline))
3286 Attrs =
3287 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3288 llvm::Attribute::AlwaysInline);
3289
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003290 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003291 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003292
Dan Gohman515a60d2012-02-16 00:57:37 +00003293 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3294 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003295 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003296 AddObjCARCExceptionMetadata(CS.getInstruction());
3297
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003298 // If the call doesn't return, finish the basic block and clear the
3299 // insertion point; this allows the rest of IRgen to discard
3300 // unreachable code.
3301 if (CS.doesNotReturn()) {
3302 Builder.CreateUnreachable();
3303 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003304
Mike Stump18bb9282009-05-16 07:57:57 +00003305 // FIXME: For now, emit a dummy basic block because expr emitters in
3306 // generally are not ready to handle emitting expressions at unreachable
3307 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003308 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003309
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003310 // Return a reasonable RValue.
3311 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003312 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003313
3314 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003315 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003316 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003317
John McCall31168b02011-06-15 23:02:42 +00003318 // Emit any writebacks immediately. Arguably this should happen
3319 // after any return-value munging.
3320 if (CallArgs.hasWritebacks())
3321 emitWritebacks(*this, CallArgs);
3322
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003323 // The stack cleanup for inalloca arguments has to run out of the normal
3324 // lexical order, so deactivate it and run it manually here.
3325 CallArgs.freeArgumentMemory(*this);
3326
Hal Finkelee90a222014-09-26 05:04:30 +00003327 RValue Ret = [&] {
3328 switch (RetAI.getKind()) {
3329 case ABIArgInfo::InAlloca:
3330 case ABIArgInfo::Indirect:
3331 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003332
Hal Finkelee90a222014-09-26 05:04:30 +00003333 case ABIArgInfo::Ignore:
3334 // If we are ignoring an argument that had a result, make sure to
3335 // construct the appropriate return value for our caller.
3336 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003337
Hal Finkelee90a222014-09-26 05:04:30 +00003338 case ABIArgInfo::Extend:
3339 case ABIArgInfo::Direct: {
3340 llvm::Type *RetIRTy = ConvertType(RetTy);
3341 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3342 switch (getEvaluationKind(RetTy)) {
3343 case TEK_Complex: {
3344 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3345 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3346 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003347 }
Hal Finkelee90a222014-09-26 05:04:30 +00003348 case TEK_Aggregate: {
3349 llvm::Value *DestPtr = ReturnValue.getValue();
3350 bool DestIsVolatile = ReturnValue.isVolatile();
3351
3352 if (!DestPtr) {
3353 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3354 DestIsVolatile = false;
3355 }
3356 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3357 return RValue::getAggregate(DestPtr);
3358 }
3359 case TEK_Scalar: {
3360 // If the argument doesn't match, perform a bitcast to coerce it. This
3361 // can happen due to trivial type mismatches.
3362 llvm::Value *V = CI;
3363 if (V->getType() != RetIRTy)
3364 V = Builder.CreateBitCast(V, RetIRTy);
3365 return RValue::get(V);
3366 }
3367 }
3368 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003369 }
Hal Finkelee90a222014-09-26 05:04:30 +00003370
3371 llvm::Value *DestPtr = ReturnValue.getValue();
3372 bool DestIsVolatile = ReturnValue.isVolatile();
3373
3374 if (!DestPtr) {
3375 DestPtr = CreateMemTemp(RetTy, "coerce");
3376 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003377 }
Hal Finkelee90a222014-09-26 05:04:30 +00003378
3379 // If the value is offset in memory, apply the offset now.
3380 llvm::Value *StorePtr = DestPtr;
3381 if (unsigned Offs = RetAI.getDirectOffset()) {
3382 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3383 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3384 StorePtr = Builder.CreateBitCast(StorePtr,
3385 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003386 }
Hal Finkelee90a222014-09-26 05:04:30 +00003387 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3388
3389 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003390 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003391
Hal Finkelee90a222014-09-26 05:04:30 +00003392 case ABIArgInfo::Expand:
3393 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003394 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003395
Hal Finkelee90a222014-09-26 05:04:30 +00003396 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3397 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003398
Hal Finkelee90a222014-09-26 05:04:30 +00003399 if (Ret.isScalar() && TargetDecl) {
3400 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3401 llvm::Value *OffsetValue = nullptr;
3402 if (const auto *Offset = AA->getOffset())
3403 OffsetValue = EmitScalarExpr(Offset);
3404
3405 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3406 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3407 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3408 OffsetValue);
3409 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003410 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003411
Hal Finkelee90a222014-09-26 05:04:30 +00003412 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003413}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003414
3415/* VarArg handling */
3416
3417llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3418 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3419}