blob: 3cb72bd1512a096a75524e10ba4604a2b812d9fc [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000053 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000054 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
55 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000056 }
57}
58
John McCall8ee376f2010-02-24 07:14:12 +000059/// Derives the 'this' type for codegen purposes, i.e. ignoring method
60/// qualification.
61/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000062static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
63 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
64 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000065}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000068static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
69 return MD->getType()->getCanonicalTypeUnqualified()
70 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000071}
72
73/// Returns the "extra-canonicalized" return type, which discards
74/// qualifiers on the return type. Codegen doesn't care about them,
75/// and it makes ABI code a little easier to be able to assume that
76/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000077static CanQualType GetReturnType(QualType RetTy) {
78 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
John McCall8dda7b22012-07-07 06:41:13 +000081/// Arrange the argument and result information for a value of the given
82/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000083const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000084CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000085 // When translating an unprototyped function type, always use a
86 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000087 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000088 /*instanceMethod=*/false,
89 /*chainCall=*/false, None,
90 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000091}
92
John McCall8dda7b22012-07-07 06:41:13 +000093/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000094/// type, on top of any implicit parameters already stored.
95static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +000096arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000097 SmallVectorImpl<CanQualType> &prefix,
98 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000099 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000100 // FIXME: Kill copy.
Benjamin Kramerf9890422015-02-17 16:48:30 +0000101 prefix.append(FTP->param_type_begin(), FTP->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +0000102 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000103 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
104 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000105 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000106}
107
John McCalla729c622012-02-17 03:33:10 +0000108/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000109/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000110const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000111CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000112 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000113 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
114 FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000115}
116
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000117static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000118 // Set the appropriate calling convention for the Function.
119 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000120 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000121
122 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000123 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000124
Douglas Gregora941dca2010-05-18 16:57:00 +0000125 if (D->hasAttr<ThisCallAttr>())
126 return CC_X86ThisCall;
127
Reid Klecknerd7857f02014-10-24 17:42:17 +0000128 if (D->hasAttr<VectorCallAttr>())
129 return CC_X86VectorCall;
130
Dawn Perchik335e16b2010-09-03 01:29:35 +0000131 if (D->hasAttr<PascalAttr>())
132 return CC_X86Pascal;
133
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000134 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
135 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
136
Guy Benyeif0a014b2012-12-25 08:53:55 +0000137 if (D->hasAttr<IntelOclBiccAttr>())
138 return CC_IntelOclBicc;
139
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000140 if (D->hasAttr<MSABIAttr>())
141 return IsWindows ? CC_C : CC_X86_64Win64;
142
143 if (D->hasAttr<SysVABIAttr>())
144 return IsWindows ? CC_X86_64SysV : CC_C;
145
John McCallab26cfa2010-02-05 21:31:56 +0000146 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000147}
148
John McCalla729c622012-02-17 03:33:10 +0000149/// Arrange the argument and result information for a call to an
150/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000151/// (Zero value of RD means we don't have any meaningful "this" argument type,
152/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000153/// The member function must be an ordinary function, i.e. not a
154/// constructor or destructor.
155const CGFunctionInfo &
156CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
157 const FunctionProtoType *FTP) {
158 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000159
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000160 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000161 if (RD)
162 argTypes.push_back(GetThisType(Context, RD));
163 else
164 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000165
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000166 return ::arrangeLLVMFunctionInfo(
167 *this, true, argTypes,
168 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000169}
170
John McCalla729c622012-02-17 03:33:10 +0000171/// Arrange the argument and result information for a declaration or
172/// definition of the given C++ non-static member function. The
173/// member function must be an ordinary function, i.e. not a
174/// constructor or destructor.
175const CGFunctionInfo &
176CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000177 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000178 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
179
John McCalla729c622012-02-17 03:33:10 +0000180 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000181
John McCalla729c622012-02-17 03:33:10 +0000182 if (MD->isInstance()) {
183 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000184 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000185 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000186 }
187
John McCall8dda7b22012-07-07 06:41:13 +0000188 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000189}
190
John McCalla729c622012-02-17 03:33:10 +0000191const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000192CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
193 StructorType Type) {
194
John McCalla729c622012-02-17 03:33:10 +0000195 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000196 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000197
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000198 GlobalDecl GD;
199 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
200 GD = GlobalDecl(CD, toCXXCtorType(Type));
201 } else {
202 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
203 GD = GlobalDecl(DD, toCXXDtorType(Type));
204 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000205
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000206 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000207
208 // Add the formal parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +0000209 argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
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;
Peter Collingbournef7706832014-12-12 23:41:25 +0000222 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
223 /*chainCall=*/false, argTypes, extInfo,
224 required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000225}
226
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000227/// Arrange a call to a C++ method, passing the given arguments.
228const CGFunctionInfo &
229CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
230 const CXXConstructorDecl *D,
231 CXXCtorType CtorKind,
232 unsigned ExtraArgs) {
233 // FIXME: Kill copy.
234 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000235 for (const auto &Arg : args)
236 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000237
238 CanQual<FunctionProtoType> FPT = GetFormalType(D);
239 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
240 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000241 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
242 ? ArgTypes.front()
243 : TheCXXABI.hasMostDerivedReturn(GD)
244 ? CGM.getContext().VoidPtrTy
245 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000246
247 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000248 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
249 /*chainCall=*/false, ArgTypes, Info,
250 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000251}
252
John McCalla729c622012-02-17 03:33:10 +0000253/// Arrange the argument and result information for the declaration or
254/// definition of the given function.
255const CGFunctionInfo &
256CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000257 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000258 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000259 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000260
John McCall2da83a32010-02-26 00:48:12 +0000261 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000262
John McCall2da83a32010-02-26 00:48:12 +0000263 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000264
265 // When declaring a function without a prototype, always use a
266 // non-variadic type.
267 if (isa<FunctionNoProtoType>(FTy)) {
268 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000269 return arrangeLLVMFunctionInfo(
270 noProto->getReturnType(), /*instanceMethod=*/false,
271 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000272 }
273
John McCall2da83a32010-02-26 00:48:12 +0000274 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000275 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000276}
277
John McCalla729c622012-02-17 03:33:10 +0000278/// Arrange the argument and result information for the declaration or
279/// definition of an Objective-C method.
280const CGFunctionInfo &
281CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
282 // It happens that this is the same as a call with no optional
283 // arguments, except also using the formal 'self' type.
284 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
285}
286
287/// Arrange the argument and result information for the function type
288/// through which to perform a send to the given Objective-C method,
289/// using the given receiver type. The receiver type is not always
290/// the 'self' type of the method or even an Objective-C pointer type.
291/// This is *not* the right method for actually performing such a
292/// message send, due to the possibility of optional arguments.
293const CGFunctionInfo &
294CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
295 QualType receiverType) {
296 SmallVector<CanQualType, 16> argTys;
297 argTys.push_back(Context.getCanonicalParamType(receiverType));
298 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000299 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000300 for (const auto *I : MD->params()) {
301 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000302 }
John McCall31168b02011-06-15 23:02:42 +0000303
304 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000305 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
306 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000307
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000309 MD->hasAttr<NSReturnsRetainedAttr>())
310 einfo = einfo.withProducesResult(true);
311
John McCalla729c622012-02-17 03:33:10 +0000312 RequiredArgs required =
313 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
314
Peter Collingbournef7706832014-12-12 23:41:25 +0000315 return arrangeLLVMFunctionInfo(
316 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
317 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000318}
319
John McCalla729c622012-02-17 03:33:10 +0000320const CGFunctionInfo &
321CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000322 // FIXME: Do we need to handle ObjCMethodDecl?
323 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000324
Anders Carlsson6710c532010-02-06 02:44:09 +0000325 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000326 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000327
328 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000329 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000330
John McCalla729c622012-02-17 03:33:10 +0000331 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000332}
333
Reid Klecknerc3473512014-08-29 21:43:29 +0000334/// Arrange a thunk that takes 'this' as the first parameter followed by
335/// varargs. Return a void pointer, regardless of the actual return type.
336/// The body of the thunk will end in a musttail call to a function of the
337/// correct type, and the caller will bitcast the function to the correct
338/// prototype.
339const CGFunctionInfo &
340CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
341 assert(MD->isVirtual() && "only virtual memptrs have thunks");
342 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
343 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000344 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
345 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000346 FTP->getExtInfo(), RequiredArgs(1));
347}
348
David Majnemerdfa6d202015-03-11 18:36:39 +0000349const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000350CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
351 CXXCtorType CT) {
352 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
353
David Majnemerdfa6d202015-03-11 18:36:39 +0000354 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
355 SmallVector<CanQualType, 2> ArgTys;
356 const CXXRecordDecl *RD = CD->getParent();
357 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000358 if (CT == Ctor_CopyingClosure)
359 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000360 if (RD->getNumVBases() > 0)
361 ArgTys.push_back(Context.IntTy);
362 CallingConv CC = Context.getDefaultCallingConvention(
363 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
364 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
365 /*chainCall=*/false, ArgTys,
366 FunctionType::ExtInfo(CC), RequiredArgs::All);
367}
368
John McCallc818bbb2012-12-07 07:03:17 +0000369/// Arrange a call as unto a free function, except possibly with an
370/// additional number of formal parameters considered required.
371static const CGFunctionInfo &
372arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000373 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000374 const CallArgList &args,
375 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000376 unsigned numExtraRequiredArgs,
377 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000378 assert(args.size() >= numExtraRequiredArgs);
379
380 // In most cases, there are no optional arguments.
381 RequiredArgs required = RequiredArgs::All;
382
383 // If we have a variadic prototype, the required arguments are the
384 // extra prefix plus the arguments in the prototype.
385 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
386 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000387 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000388
389 // If we don't have a prototype at all, but we're supposed to
390 // explicitly use the variadic convention for unprototyped calls,
391 // treat all of the arguments as required but preserve the nominal
392 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000393 } else if (CGM.getTargetCodeGenInfo()
394 .isNoProtoCallVariadic(args,
395 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000396 required = RequiredArgs(args.size());
397 }
398
Peter Collingbournef7706832014-12-12 23:41:25 +0000399 // FIXME: Kill copy.
400 SmallVector<CanQualType, 16> argTypes;
401 for (const auto &arg : args)
402 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
403 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
404 /*instanceMethod=*/false, chainCall,
405 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000406}
407
John McCalla729c622012-02-17 03:33:10 +0000408/// Figure out the rules for calling a function with the given formal
409/// type using the given arguments. The arguments are necessary
410/// because the function might be unprototyped, in which case it's
411/// target-dependent in crazy ways.
412const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000413CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000414 const FunctionType *fnType,
415 bool chainCall) {
416 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
417 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000418}
John McCalla729c622012-02-17 03:33:10 +0000419
John McCallc818bbb2012-12-07 07:03:17 +0000420/// A block function call is essentially a free-function call with an
421/// extra implicit argument.
422const CGFunctionInfo &
423CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
424 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000425 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
426 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000427}
428
429const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000430CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
431 const CallArgList &args,
432 FunctionType::ExtInfo info,
433 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000434 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000435 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000436 for (const auto &Arg : args)
437 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000438 return arrangeLLVMFunctionInfo(
439 GetReturnType(resultType), /*instanceMethod=*/false,
440 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000441}
442
443/// Arrange a call to a C++ method, passing the given arguments.
444const CGFunctionInfo &
445CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
446 const FunctionProtoType *FPT,
447 RequiredArgs required) {
448 // FIXME: Kill copy.
449 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000450 for (const auto &Arg : args)
451 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000452
453 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000454 return arrangeLLVMFunctionInfo(
455 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
456 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000457}
458
Reid Kleckner4982b822014-01-31 22:54:50 +0000459const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
460 QualType resultType, const FunctionArgList &args,
461 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000462 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000463 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000464 for (auto Arg : args)
465 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000466
467 RequiredArgs required =
468 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000469 return arrangeLLVMFunctionInfo(
470 GetReturnType(resultType), /*instanceMethod=*/false,
471 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000472}
473
John McCalla729c622012-02-17 03:33:10 +0000474const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000475 return arrangeLLVMFunctionInfo(
476 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
477 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000478}
479
John McCalla729c622012-02-17 03:33:10 +0000480/// Arrange the argument and result information for an abstract value
481/// of a given function type. This is the method which all of the
482/// above functions ultimately defer to.
483const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000484CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000485 bool instanceMethod,
486 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000487 ArrayRef<CanQualType> argTypes,
488 FunctionType::ExtInfo info,
489 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000490 assert(std::all_of(argTypes.begin(), argTypes.end(),
491 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000492
John McCalla729c622012-02-17 03:33:10 +0000493 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000494
Daniel Dunbare0be8292009-02-03 00:07:12 +0000495 // Lookup or create unique function info.
496 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000497 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
498 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000499
Craig Topper8a13c412014-05-21 05:09:00 +0000500 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000501 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000502 if (FI)
503 return *FI;
504
John McCalla729c622012-02-17 03:33:10 +0000505 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000506 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
507 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000508 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000509
David Blaikie82e95a32014-11-19 07:49:47 +0000510 bool inserted = FunctionsBeingProcessed.insert(FI).second;
511 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000512 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000513
Daniel Dunbar313321e2009-02-03 05:31:23 +0000514 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000515 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000516
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000517 // Loop over all of the computed argument and return value info. If any of
518 // them are direct or extend without a specified coerce type, specify the
519 // default now.
John McCalla729c622012-02-17 03:33:10 +0000520 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000521 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000522 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000523
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000524 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000525 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000526 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000527
John McCalla729c622012-02-17 03:33:10 +0000528 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
529 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000530
Daniel Dunbare0be8292009-02-03 00:07:12 +0000531 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000532}
533
John McCalla729c622012-02-17 03:33:10 +0000534CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000535 bool instanceMethod,
536 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000537 const FunctionType::ExtInfo &info,
538 CanQualType resultType,
539 ArrayRef<CanQualType> argTypes,
540 RequiredArgs required) {
541 void *buffer = operator new(sizeof(CGFunctionInfo) +
542 sizeof(ArgInfo) * (argTypes.size() + 1));
543 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
544 FI->CallingConvention = llvmCC;
545 FI->EffectiveCallingConvention = llvmCC;
546 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000547 FI->InstanceMethod = instanceMethod;
548 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000549 FI->NoReturn = info.getNoReturn();
550 FI->ReturnsRetained = info.getProducesResult();
551 FI->Required = required;
552 FI->HasRegParm = info.getHasRegParm();
553 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000554 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000555 FI->NumArgs = argTypes.size();
556 FI->getArgsBuffer()[0].type = resultType;
557 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
558 FI->getArgsBuffer()[i + 1].type = argTypes[i];
559 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000560}
561
562/***/
563
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000564namespace {
565// ABIArgInfo::Expand implementation.
566
567// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
568struct TypeExpansion {
569 enum TypeExpansionKind {
570 // Elements of constant arrays are expanded recursively.
571 TEK_ConstantArray,
572 // Record fields are expanded recursively (but if record is a union, only
573 // the field with the largest size is expanded).
574 TEK_Record,
575 // For complex types, real and imaginary parts are expanded recursively.
576 TEK_Complex,
577 // All other types are not expandable.
578 TEK_None
579 };
580
581 const TypeExpansionKind Kind;
582
583 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
584 virtual ~TypeExpansion() {}
585};
586
587struct ConstantArrayExpansion : TypeExpansion {
588 QualType EltTy;
589 uint64_t NumElts;
590
591 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
592 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
593 static bool classof(const TypeExpansion *TE) {
594 return TE->Kind == TEK_ConstantArray;
595 }
596};
597
598struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000599 SmallVector<const CXXBaseSpecifier *, 1> Bases;
600
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000601 SmallVector<const FieldDecl *, 1> Fields;
602
Reid Klecknere9f6a712014-10-31 17:10:41 +0000603 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
604 SmallVector<const FieldDecl *, 1> &&Fields)
605 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000606 static bool classof(const TypeExpansion *TE) {
607 return TE->Kind == TEK_Record;
608 }
609};
610
611struct ComplexExpansion : TypeExpansion {
612 QualType EltTy;
613
614 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
615 static bool classof(const TypeExpansion *TE) {
616 return TE->Kind == TEK_Complex;
617 }
618};
619
620struct NoExpansion : TypeExpansion {
621 NoExpansion() : TypeExpansion(TEK_None) {}
622 static bool classof(const TypeExpansion *TE) {
623 return TE->Kind == TEK_None;
624 }
625};
626} // namespace
627
628static std::unique_ptr<TypeExpansion>
629getTypeExpansion(QualType Ty, const ASTContext &Context) {
630 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
631 return llvm::make_unique<ConstantArrayExpansion>(
632 AT->getElementType(), AT->getSize().getZExtValue());
633 }
634 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000635 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000636 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000637 const RecordDecl *RD = RT->getDecl();
638 assert(!RD->hasFlexibleArrayMember() &&
639 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000640 if (RD->isUnion()) {
641 // Unions can be here only in degenerative cases - all the fields are same
642 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000643 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000644 CharUnits UnionSize = CharUnits::Zero();
645
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000646 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000647 // Skip zero length bitfields.
648 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
649 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000650 assert(!FD->isBitField() &&
651 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000652 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000653 if (UnionSize < FieldSize) {
654 UnionSize = FieldSize;
655 LargestFD = FD;
656 }
657 }
658 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000659 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000660 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000661 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
662 assert(!CXXRD->isDynamicClass() &&
663 "cannot expand vtable pointers in dynamic classes");
664 for (const CXXBaseSpecifier &BS : CXXRD->bases())
665 Bases.push_back(&BS);
666 }
667
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000668 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000669 // Skip zero length bitfields.
670 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
671 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000672 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000673 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000674 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000675 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000676 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000677 return llvm::make_unique<RecordExpansion>(std::move(Bases),
678 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000679 }
680 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
681 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
682 }
683 return llvm::make_unique<NoExpansion>();
684}
685
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000686static int getExpansionSize(QualType Ty, const ASTContext &Context) {
687 auto Exp = getTypeExpansion(Ty, Context);
688 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
689 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
690 }
691 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
692 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000693 for (auto BS : RExp->Bases)
694 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000695 for (auto FD : RExp->Fields)
696 Res += getExpansionSize(FD->getType(), Context);
697 return Res;
698 }
699 if (isa<ComplexExpansion>(Exp.get()))
700 return 2;
701 assert(isa<NoExpansion>(Exp.get()));
702 return 1;
703}
704
Alexey Samsonov153004f2014-09-29 22:08:00 +0000705void
706CodeGenTypes::getExpandedTypes(QualType Ty,
707 SmallVectorImpl<llvm::Type *>::iterator &TI) {
708 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000709 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
710 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000711 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000712 }
713 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000714 for (auto BS : RExp->Bases)
715 getExpandedTypes(BS->getType(), TI);
716 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000717 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000718 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
719 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000720 *TI++ = EltTy;
721 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000722 } else {
723 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000724 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000725 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000726}
727
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000728void CodeGenFunction::ExpandTypeFromArgs(
729 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000730 assert(LV.isSimple() &&
731 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000732
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000733 auto Exp = getTypeExpansion(Ty, getContext());
734 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
735 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
736 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
737 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
738 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000739 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000740 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000741 llvm::Value *This = LV.getAddress();
742 for (const CXXBaseSpecifier *BS : RExp->Bases) {
743 // Perform a single step derived-to-base conversion.
744 llvm::Value *Base =
745 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
746 /*NullCheckValue=*/false, SourceLocation());
747 LValue SubLV = MakeAddrLValue(Base, BS->getType());
748
749 // Recurse onto bases.
750 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
751 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000752 for (auto FD : RExp->Fields) {
753 // FIXME: What are the right qualifiers here?
754 LValue SubLV = EmitLValueForField(LV, FD);
755 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000756 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000757 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000758 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000759 EmitStoreThroughLValue(RValue::get(*AI++),
760 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000761 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000762 EmitStoreThroughLValue(RValue::get(*AI++),
763 MakeAddrLValue(ImagAddr, CExp->EltTy));
764 } else {
765 assert(isa<NoExpansion>(Exp.get()));
766 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000767 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000768}
769
770void CodeGenFunction::ExpandTypeToArgs(
771 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
772 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
773 auto Exp = getTypeExpansion(Ty, getContext());
774 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
775 llvm::Value *Addr = RV.getAggregateAddr();
776 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
777 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
778 RValue EltRV =
779 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
780 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
781 }
782 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000783 llvm::Value *This = RV.getAggregateAddr();
784 for (const CXXBaseSpecifier *BS : RExp->Bases) {
785 // Perform a single step derived-to-base conversion.
786 llvm::Value *Base =
787 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
788 /*NullCheckValue=*/false, SourceLocation());
789 RValue BaseRV = RValue::getAggregate(Base);
790
791 // Recurse onto bases.
792 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
793 IRCallArgPos);
794 }
795
796 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000797 for (auto FD : RExp->Fields) {
798 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
799 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
800 IRCallArgPos);
801 }
802 } else if (isa<ComplexExpansion>(Exp.get())) {
803 ComplexPairTy CV = RV.getComplexVal();
804 IRCallArgs[IRCallArgPos++] = CV.first;
805 IRCallArgs[IRCallArgPos++] = CV.second;
806 } else {
807 assert(isa<NoExpansion>(Exp.get()));
808 assert(RV.isScalar() &&
809 "Unexpected non-scalar rvalue during struct expansion.");
810
811 // Insert a bitcast as needed.
812 llvm::Value *V = RV.getScalarVal();
813 if (IRCallArgPos < IRFuncTy->getNumParams() &&
814 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
815 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
816
817 IRCallArgs[IRCallArgPos++] = V;
818 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000819}
820
Chris Lattner895c52b2010-06-27 06:04:18 +0000821/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000822/// accessing some number of bytes out of it, try to gep into the struct to get
823/// at its inner goodness. Dive as deep as possible without entering an element
824/// with an in-memory size smaller than DstSize.
825static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000826EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000827 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000828 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000829 // We can't dive into a zero-element struct.
830 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000831
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000833
Chris Lattner1cd66982010-06-27 05:56:15 +0000834 // 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 +0000835 // first element is the same size as the whole struct, we can enter it. The
836 // comparison must be made on the store size and not the alloca size. Using
837 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000838 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000839 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000840 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000841 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000842 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000843
Chris Lattner1cd66982010-06-27 05:56:15 +0000844 // GEP into the first element.
845 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000846
Chris Lattner1cd66982010-06-27 05:56:15 +0000847 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000848 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000849 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000850 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000851 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000852
853 return SrcPtr;
854}
855
Chris Lattner055097f2010-06-27 06:26:04 +0000856/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
857/// are either integers or pointers. This does a truncation of the value if it
858/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000859///
860/// This behaves as if the value were coerced through memory, so on big-endian
861/// targets the high bits are preserved in a truncation, while little-endian
862/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000863static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000864 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000865 CodeGenFunction &CGF) {
866 if (Val->getType() == Ty)
867 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000868
Chris Lattner055097f2010-06-27 06:26:04 +0000869 if (isa<llvm::PointerType>(Val->getType())) {
870 // If this is Pointer->Pointer avoid conversion to and from int.
871 if (isa<llvm::PointerType>(Ty))
872 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000873
Chris Lattner055097f2010-06-27 06:26:04 +0000874 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000875 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000876 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000877
Chris Lattner2192fe52011-07-18 04:24:23 +0000878 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000879 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000880 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000881
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000882 if (Val->getType() != DestIntTy) {
883 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
884 if (DL.isBigEndian()) {
885 // Preserve the high bits on big-endian targets.
886 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000887 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
888 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
889
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000890 if (SrcSize > DstSize) {
891 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
892 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
893 } else {
894 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
895 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
896 }
897 } else {
898 // Little-endian targets preserve the low bits. No shifts required.
899 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
900 }
901 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000902
Chris Lattner055097f2010-06-27 06:26:04 +0000903 if (isa<llvm::PointerType>(Ty))
904 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
905 return Val;
906}
907
Chris Lattner1cd66982010-06-27 05:56:15 +0000908
909
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000910/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
911/// a pointer to an object of type \arg Ty.
912///
913/// This safely handles the case when the src type is smaller than the
914/// destination type; in this situation the values of bits which not
915/// present in the src are undefined.
916static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000917 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000918 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000919 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000920 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000921
Chris Lattnerd200eda2010-06-28 22:51:39 +0000922 // If SrcTy and Ty are the same, just do a load.
923 if (SrcTy == Ty)
924 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000925
Micah Villmowdd31ca12012-10-08 16:25:52 +0000926 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000927
Chris Lattner2192fe52011-07-18 04:24:23 +0000928 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000929 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000930 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
931 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000932
Micah Villmowdd31ca12012-10-08 16:25:52 +0000933 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000934
Chris Lattner055097f2010-06-27 06:26:04 +0000935 // If the source and destination are integer or pointer types, just do an
936 // extension or truncation to the desired type.
937 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
938 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
939 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
940 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
941 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000942
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000943 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000944 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000945 // Generally SrcSize is never greater than DstSize, since this means we are
946 // losing bits. However, this can happen in cases where the structure has
947 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000948 //
Mike Stump18bb9282009-05-16 07:57:57 +0000949 // FIXME: Assert that we aren't truncating non-padding bits when have access
950 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000951 llvm::Value *Casted =
952 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000953 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
954 // FIXME: Use better alignment / avoid requiring aligned load.
955 Load->setAlignment(1);
956 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000957 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000958
Chris Lattner3fcc7902010-06-27 01:06:27 +0000959 // Otherwise do coercion through memory. This is stupid, but
960 // simple.
961 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000962 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
963 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
964 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000965 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000966 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
967 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
968 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000969 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000970}
971
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000972// Function to store a first-class aggregate into memory. We prefer to
973// store the elements rather than the aggregate to be more friendly to
974// fast-isel.
975// FIXME: Do we need to recurse here?
976static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
977 llvm::Value *DestPtr, bool DestIsVolatile,
978 bool LowAlignment) {
979 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000980 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000981 dyn_cast<llvm::StructType>(Val->getType())) {
982 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
983 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
984 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
985 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
986 DestIsVolatile);
987 if (LowAlignment)
988 SI->setAlignment(1);
989 }
990 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000991 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
992 if (LowAlignment)
993 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000994 }
995}
996
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000997/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
998/// where the source and destination may have different types.
999///
1000/// This safely handles the case when the src type is larger than the
1001/// destination type; the upper bits of the src will be lost.
1002static void CreateCoercedStore(llvm::Value *Src,
1003 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +00001004 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001005 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001006 llvm::Type *SrcTy = Src->getType();
1007 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001008 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001009 if (SrcTy == DstTy) {
1010 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1011 return;
1012 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001013
Micah Villmowdd31ca12012-10-08 16:25:52 +00001014 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001015
Chris Lattner2192fe52011-07-18 04:24:23 +00001016 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +00001017 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1018 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1019 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001020
Chris Lattner055097f2010-06-27 06:26:04 +00001021 // If the source and destination are integer or pointer types, just do an
1022 // extension or truncation to the desired type.
1023 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1024 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1025 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1026 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1027 return;
1028 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001029
Micah Villmowdd31ca12012-10-08 16:25:52 +00001030 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001031
Daniel Dunbar313321e2009-02-03 05:31:23 +00001032 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001033 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001034 llvm::Value *Casted =
1035 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +00001036 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001037 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001038 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001039 // Otherwise do coercion through memory. This is stupid, but
1040 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001041
1042 // Generally SrcSize is never greater than DstSize, since this means we are
1043 // losing bits. However, this can happen in cases where the structure has
1044 // additional padding, for example due to a user specified alignment.
1045 //
1046 // FIXME: Assert that we aren't truncating non-padding bits when have access
1047 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001048 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1049 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001050 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1051 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1052 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001053 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001054 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1055 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1056 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001057 }
1058}
1059
Alexey Samsonov153004f2014-09-29 22:08:00 +00001060namespace {
1061
1062/// Encapsulates information about the way function arguments from
1063/// CGFunctionInfo should be passed to actual LLVM IR function.
1064class ClangToLLVMArgMapping {
1065 static const unsigned InvalidIndex = ~0U;
1066 unsigned InallocaArgNo;
1067 unsigned SRetArgNo;
1068 unsigned TotalIRArgs;
1069
1070 /// Arguments of LLVM IR function corresponding to single Clang argument.
1071 struct IRArgs {
1072 unsigned PaddingArgIndex;
1073 // Argument is expanded to IR arguments at positions
1074 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1075 unsigned FirstArgIndex;
1076 unsigned NumberOfArgs;
1077
1078 IRArgs()
1079 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1080 NumberOfArgs(0) {}
1081 };
1082
1083 SmallVector<IRArgs, 8> ArgInfo;
1084
1085public:
1086 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1087 bool OnlyRequiredArgs = false)
1088 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1089 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1090 construct(Context, FI, OnlyRequiredArgs);
1091 }
1092
1093 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1094 unsigned getInallocaArgNo() const {
1095 assert(hasInallocaArg());
1096 return InallocaArgNo;
1097 }
1098
1099 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1100 unsigned getSRetArgNo() const {
1101 assert(hasSRetArg());
1102 return SRetArgNo;
1103 }
1104
1105 unsigned totalIRArgs() const { return TotalIRArgs; }
1106
1107 bool hasPaddingArg(unsigned ArgNo) const {
1108 assert(ArgNo < ArgInfo.size());
1109 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1110 }
1111 unsigned getPaddingArgNo(unsigned ArgNo) const {
1112 assert(hasPaddingArg(ArgNo));
1113 return ArgInfo[ArgNo].PaddingArgIndex;
1114 }
1115
1116 /// Returns index of first IR argument corresponding to ArgNo, and their
1117 /// quantity.
1118 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1119 assert(ArgNo < ArgInfo.size());
1120 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1121 ArgInfo[ArgNo].NumberOfArgs);
1122 }
1123
1124private:
1125 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1126 bool OnlyRequiredArgs);
1127};
1128
1129void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1130 const CGFunctionInfo &FI,
1131 bool OnlyRequiredArgs) {
1132 unsigned IRArgNo = 0;
1133 bool SwapThisWithSRet = false;
1134 const ABIArgInfo &RetAI = FI.getReturnInfo();
1135
1136 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1137 SwapThisWithSRet = RetAI.isSRetAfterThis();
1138 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1139 }
1140
1141 unsigned ArgNo = 0;
1142 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1143 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1144 ++I, ++ArgNo) {
1145 assert(I != FI.arg_end());
1146 QualType ArgType = I->type;
1147 const ABIArgInfo &AI = I->info;
1148 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1149 auto &IRArgs = ArgInfo[ArgNo];
1150
1151 if (AI.getPaddingType())
1152 IRArgs.PaddingArgIndex = IRArgNo++;
1153
1154 switch (AI.getKind()) {
1155 case ABIArgInfo::Extend:
1156 case ABIArgInfo::Direct: {
1157 // FIXME: handle sseregparm someday...
1158 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1159 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1160 IRArgs.NumberOfArgs = STy->getNumElements();
1161 } else {
1162 IRArgs.NumberOfArgs = 1;
1163 }
1164 break;
1165 }
1166 case ABIArgInfo::Indirect:
1167 IRArgs.NumberOfArgs = 1;
1168 break;
1169 case ABIArgInfo::Ignore:
1170 case ABIArgInfo::InAlloca:
1171 // ignore and inalloca doesn't have matching LLVM parameters.
1172 IRArgs.NumberOfArgs = 0;
1173 break;
1174 case ABIArgInfo::Expand: {
1175 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1176 break;
1177 }
1178 }
1179
1180 if (IRArgs.NumberOfArgs > 0) {
1181 IRArgs.FirstArgIndex = IRArgNo;
1182 IRArgNo += IRArgs.NumberOfArgs;
1183 }
1184
1185 // Skip over the sret parameter when it comes second. We already handled it
1186 // above.
1187 if (IRArgNo == 1 && SwapThisWithSRet)
1188 IRArgNo++;
1189 }
1190 assert(ArgNo == ArgInfo.size());
1191
1192 if (FI.usesInAlloca())
1193 InallocaArgNo = IRArgNo++;
1194
1195 TotalIRArgs = IRArgNo;
1196}
1197} // namespace
1198
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001199/***/
1200
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001201bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001202 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001203}
1204
Tim Northovere77cc392014-03-29 13:28:05 +00001205bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1206 return ReturnTypeUsesSRet(FI) &&
1207 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1208}
1209
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001210bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1211 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1212 switch (BT->getKind()) {
1213 default:
1214 return false;
1215 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001216 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001217 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001218 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001219 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001220 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001221 }
1222 }
1223
1224 return false;
1225}
1226
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001227bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1228 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1229 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1230 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001231 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001232 }
1233 }
1234
1235 return false;
1236}
1237
Chris Lattnera5f58b02011-07-09 17:41:47 +00001238llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001239 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1240 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001241}
1242
Chris Lattnera5f58b02011-07-09 17:41:47 +00001243llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001244CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001245
David Blaikie82e95a32014-11-19 07:49:47 +00001246 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1247 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001248 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001249
Alexey Samsonov153004f2014-09-29 22:08:00 +00001250 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001251 const ABIArgInfo &retAI = FI.getReturnInfo();
1252 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001253 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001254 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001255
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001256 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001257 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001258 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001259 break;
1260
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001261 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001262 if (retAI.getInAllocaSRet()) {
1263 // sret things on win32 aren't void, they return the sret pointer.
1264 QualType ret = FI.getReturnType();
1265 llvm::Type *ty = ConvertType(ret);
1266 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1267 resultType = llvm::PointerType::get(ty, addressSpace);
1268 } else {
1269 resultType = llvm::Type::getVoidTy(getLLVMContext());
1270 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001271 break;
1272
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001273 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001274 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1275 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001276 break;
1277 }
1278
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001279 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001280 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001281 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001282 }
Mike Stump11289f42009-09-09 15:08:12 +00001283
Alexey Samsonov153004f2014-09-29 22:08:00 +00001284 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1285 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1286
1287 // Add type for sret argument.
1288 if (IRFunctionArgs.hasSRetArg()) {
1289 QualType Ret = FI.getReturnType();
1290 llvm::Type *Ty = ConvertType(Ret);
1291 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1292 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1293 llvm::PointerType::get(Ty, AddressSpace);
1294 }
1295
1296 // Add type for inalloca argument.
1297 if (IRFunctionArgs.hasInallocaArg()) {
1298 auto ArgStruct = FI.getArgStruct();
1299 assert(ArgStruct);
1300 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1301 }
1302
John McCallc818bbb2012-12-07 07:03:17 +00001303 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001304 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001305 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1306 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001307 for (; it != ie; ++it, ++ArgNo) {
1308 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Rafael Espindolafad28de2012-10-24 01:59:00 +00001310 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001311 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1312 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1313 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001314
Alexey Samsonov153004f2014-09-29 22:08:00 +00001315 unsigned FirstIRArg, NumIRArgs;
1316 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1317
1318 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001319 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001320 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001321 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001322 break;
1323
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001324 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001325 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001326 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001327 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001328 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001329 break;
1330 }
1331
1332 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001333 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001334 // Fast-isel and the optimizer generally like scalar values better than
1335 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001336 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001337 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001338 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1339 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001340 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001341 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001342 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001343 assert(NumIRArgs == 1);
1344 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001345 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001346 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Daniel Dunbard3674e62008-09-11 01:48:57 +00001349 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001350 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1351 getExpandedTypes(it->type, ArgTypesIter);
1352 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001353 break;
1354 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001355 }
1356
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001357 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1358 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001359
1360 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001361}
1362
Chris Lattner2192fe52011-07-18 04:24:23 +00001363llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001364 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001365 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001366
Chris Lattner8806e322011-07-10 00:18:59 +00001367 if (!isFuncTypeConvertible(FPT))
1368 return llvm::StructType::get(getLLVMContext());
1369
1370 const CGFunctionInfo *Info;
1371 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001372 Info =
1373 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001374 else
John McCalla729c622012-02-17 03:33:10 +00001375 Info = &arrangeCXXMethodDeclaration(MD);
1376 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001377}
1378
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001379void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001380 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001381 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001382 unsigned &CallingConv,
1383 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001384 llvm::AttrBuilder FuncAttrs;
1385 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001386 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001387
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001388 CallingConv = FI.getEffectiveCallingConvention();
1389
John McCallab26cfa2010-02-05 21:31:56 +00001390 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001391 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001392
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001393 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001394 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001395 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001396 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001397 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001398 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001399 if (TargetDecl->hasAttr<NoReturnAttr>())
1400 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001401 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1402 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001403
1404 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001405 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001406 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001407 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001408 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1409 // These attributes are not inherited by overloads.
1410 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1411 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001412 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001413 }
1414
Eric Christopherbf005ec2011-08-15 22:38:22 +00001415 // 'const' and 'pure' attribute functions are also nounwind.
1416 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001417 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1418 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001419 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001420 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1421 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001422 }
David Majnemer631a90b2015-02-04 07:23:21 +00001423 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001424 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001425 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1426 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001427
1428 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001429 }
1430
Paul Robinson08556952014-12-11 20:14:04 +00001431 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1432 if (!HasOptnone) {
1433 if (CodeGenOpts.OptimizeSize)
1434 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1435 if (CodeGenOpts.OptimizeSize == 2)
1436 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1437 }
1438
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001439 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001440 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001441 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001442 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001443 if (CodeGenOpts.EnableSegmentedStacks &&
1444 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001445 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001446
Bill Wendling2f81db62013-02-22 20:53:29 +00001447 if (AttrOnCallSite) {
1448 // Attributes that should go on the call site only.
1449 if (!CodeGenOpts.SimplifyLibCalls)
1450 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001451 } else {
1452 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001453 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001454 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001455 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001456 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001457 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001458 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001459 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001460 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001461 }
1462
Bill Wendlingdabafea2013-03-13 22:24:33 +00001463 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001464 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001465 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001466 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001467 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001468 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001469 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001470 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001471 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001472 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001473 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001474 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001475
Bill Wendlingd8f49502013-08-01 21:41:02 +00001476 if (!CodeGenOpts.StackRealignment)
1477 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001478 }
1479
Alexey Samsonov153004f2014-09-29 22:08:00 +00001480 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001481
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001482 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001483 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001484 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001485 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001486 if (RetTy->hasSignedIntegerRepresentation())
1487 RetAttrs.addAttribute(llvm::Attribute::SExt);
1488 else if (RetTy->hasUnsignedIntegerRepresentation())
1489 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001490 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001491 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001492 if (RetAI.getInReg())
1493 RetAttrs.addAttribute(llvm::Attribute::InReg);
1494 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001495 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001496 break;
1497
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001498 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001499 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001500 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001501 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1502 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001503 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001504 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001505
Daniel Dunbard3674e62008-09-11 01:48:57 +00001506 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001507 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001508 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001509
Hal Finkela2347ba2014-07-18 15:52:10 +00001510 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1511 QualType PTy = RefTy->getPointeeType();
1512 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1513 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1514 .getQuantity());
1515 else if (getContext().getTargetAddressSpace(PTy) == 0)
1516 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1517 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001518
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001519 // Attach return attributes.
1520 if (RetAttrs.hasAttributes()) {
1521 PAL.push_back(llvm::AttributeSet::get(
1522 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1523 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001524
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001525 // Attach attributes to sret.
1526 if (IRFunctionArgs.hasSRetArg()) {
1527 llvm::AttrBuilder SRETAttrs;
1528 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1529 if (RetAI.getInReg())
1530 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1531 PAL.push_back(llvm::AttributeSet::get(
1532 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1533 }
1534
1535 // Attach attributes to inalloca argument.
1536 if (IRFunctionArgs.hasInallocaArg()) {
1537 llvm::AttrBuilder Attrs;
1538 Attrs.addAttribute(llvm::Attribute::InAlloca);
1539 PAL.push_back(llvm::AttributeSet::get(
1540 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1541 }
1542
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001543 unsigned ArgNo = 0;
1544 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1545 E = FI.arg_end();
1546 I != E; ++I, ++ArgNo) {
1547 QualType ParamType = I->type;
1548 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001549 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001550
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001551 // Add attribute for padding argument, if necessary.
1552 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001553 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001554 PAL.push_back(llvm::AttributeSet::get(
1555 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1556 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001557 }
1558
John McCall39ec71f2010-03-27 00:47:27 +00001559 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1560 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001561 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001562 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001563 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001564 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001565 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001566 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001567 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001568 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001569 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001570 if (ArgNo == 0 && FI.isChainCall())
1571 Attrs.addAttribute(llvm::Attribute::Nest);
1572 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001573 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001574 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001575
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001576 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001577 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001578 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001579
Anders Carlsson20759ad2009-09-16 15:53:40 +00001580 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001581 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001582
Bill Wendlinga7912f82012-10-10 07:36:56 +00001583 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1584
Daniel Dunbarc2304432009-03-18 19:51:01 +00001585 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001586 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1587 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001588 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001589
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001590 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001591 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001592 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001593
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001594 case ABIArgInfo::InAlloca:
1595 // inalloca disables readnone and readonly.
1596 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1597 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001598 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Hal Finkela2347ba2014-07-18 15:52:10 +00001601 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1602 QualType PTy = RefTy->getPointeeType();
1603 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1604 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1605 .getQuantity());
1606 else if (getContext().getTargetAddressSpace(PTy) == 0)
1607 Attrs.addAttribute(llvm::Attribute::NonNull);
1608 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001609
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001610 if (Attrs.hasAttributes()) {
1611 unsigned FirstIRArg, NumIRArgs;
1612 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1613 for (unsigned i = 0; i < NumIRArgs; i++)
1614 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1615 FirstIRArg + i + 1, Attrs));
1616 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001617 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001618 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001619
Bill Wendlinga7912f82012-10-10 07:36:56 +00001620 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001621 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001622 AttributeSet::get(getLLVMContext(),
1623 llvm::AttributeSet::FunctionIndex,
1624 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001625}
1626
John McCalla738c252011-03-09 04:27:21 +00001627/// An argument came in as a promoted argument; demote it back to its
1628/// declared type.
1629static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1630 const VarDecl *var,
1631 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001632 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001633
1634 // This can happen with promotions that actually don't change the
1635 // underlying type, like the enum promotions.
1636 if (value->getType() == varType) return value;
1637
1638 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1639 && "unexpected promotion type");
1640
1641 if (isa<llvm::IntegerType>(varType))
1642 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1643
1644 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1645}
1646
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001647/// Returns the attribute (either parameter attribute, or function
1648/// attribute), which declares argument ArgNo to be non-null.
1649static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1650 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001651 // FIXME: __attribute__((nonnull)) can also be applied to:
1652 // - references to pointers, where the pointee is known to be
1653 // nonnull (apparently a Clang extension)
1654 // - transparent unions containing pointers
1655 // In the former case, LLVM IR cannot represent the constraint. In
1656 // the latter case, we have no guarantee that the transparent union
1657 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001658 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1659 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001660 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001661 if (PVD) {
1662 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1663 return ParmNNAttr;
1664 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001665 // Check function attributes.
1666 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001667 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001668 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001669 if (NNAttr->isNonNull(ArgNo))
1670 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001671 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001672 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001673}
1674
Daniel Dunbard931a872009-02-02 22:03:45 +00001675void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1676 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001677 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001678 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1679 // Naked functions don't have prologues.
1680 return;
1681
John McCallcaa19452009-07-28 01:00:58 +00001682 // If this is an implicit-return-zero function, go ahead and
1683 // initialize the return value. TODO: it might be nice to have
1684 // a more general mechanism for this that didn't require synthesized
1685 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001686 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001687 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001688 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001689 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001690 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001691 Builder.CreateStore(Zero, ReturnValue);
1692 }
1693 }
1694
Mike Stump18bb9282009-05-16 07:57:57 +00001695 // FIXME: We no longer need the types from FunctionArgList; lift up and
1696 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001697
Alexey Samsonov153004f2014-09-29 22:08:00 +00001698 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001699 // Flattened function arguments.
1700 SmallVector<llvm::Argument *, 16> FnArgs;
1701 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1702 for (auto &Arg : Fn->args()) {
1703 FnArgs.push_back(&Arg);
1704 }
1705 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001706
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001707 // If we're using inalloca, all the memory arguments are GEPs off of the last
1708 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001709 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001710 if (IRFunctionArgs.hasInallocaArg()) {
1711 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001712 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1713 }
1714
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001715 // Name the struct return parameter.
1716 if (IRFunctionArgs.hasSRetArg()) {
1717 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001718 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001719 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001720 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001721 }
Mike Stump11289f42009-09-09 15:08:12 +00001722
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001723 // Track if we received the parameter as a pointer (indirect, byval, or
1724 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1725 // into a local alloca for us.
1726 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001727 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001728 SmallVector<ValueAndIsPtr, 16> ArgVals;
1729 ArgVals.reserve(Args.size());
1730
Reid Kleckner739756c2013-12-04 19:23:12 +00001731 // Create a pointer value for every parameter declaration. This usually
1732 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1733 // any cleanups or do anything that might unwind. We do that separately, so
1734 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001735 assert(FI.arg_size() == Args.size() &&
1736 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001737 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001738 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001739 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001740 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001741 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001742 QualType Ty = info_it->type;
1743 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001744
John McCalla738c252011-03-09 04:27:21 +00001745 bool isPromoted =
1746 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1747
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001748 unsigned FirstIRArg, NumIRArgs;
1749 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001750
Daniel Dunbard3674e62008-09-11 01:48:57 +00001751 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001752 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001753 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001754 llvm::Value *V = Builder.CreateStructGEP(
1755 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1756 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001757 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001758 }
1759
Daniel Dunbar747865a2009-02-05 09:16:39 +00001760 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001761 assert(NumIRArgs == 1);
1762 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001763
John McCall47fb9502013-03-07 21:37:08 +00001764 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001765 // Aggregates and complex variables are accessed by reference. All we
1766 // need to do is realign the value, if requested
1767 if (ArgI.getIndirectRealign()) {
1768 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1769
1770 // Copy from the incoming argument pointer to the temporary with the
1771 // appropriate alignment.
1772 //
1773 // FIXME: We should have a common utility for generating an aggregate
1774 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001775 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001776 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001777 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1778 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1779 Builder.CreateMemCpy(Dst,
1780 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001781 llvm::ConstantInt::get(IntPtrTy,
1782 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001783 ArgI.getIndirectAlign(),
1784 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001785 V = AlignedTemp;
1786 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001787 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001788 } else {
1789 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001790 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001791 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1792 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001793
1794 if (isPromoted)
1795 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001796 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001797 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001798 break;
1799 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001800
1801 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001802 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001803
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001804 // If we have the trivial case, handle it with no muss and fuss.
1805 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001806 ArgI.getCoerceToType() == ConvertType(Ty) &&
1807 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001808 assert(NumIRArgs == 1);
1809 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001810 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001811
Hal Finkel48d53e22014-07-19 01:41:07 +00001812 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001813 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1814 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001815 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1816 AI->getArgNo() + 1,
1817 llvm::Attribute::NonNull));
1818
Hal Finkel48d53e22014-07-19 01:41:07 +00001819 QualType OTy = PVD->getOriginalType();
1820 if (const auto *ArrTy =
1821 getContext().getAsConstantArrayType(OTy)) {
1822 // A C99 array parameter declaration with the static keyword also
1823 // indicates dereferenceability, and if the size is constant we can
1824 // use the dereferenceable attribute (which requires the size in
1825 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001826 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001827 QualType ETy = ArrTy->getElementType();
1828 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1829 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1830 ArrSize) {
1831 llvm::AttrBuilder Attrs;
1832 Attrs.addDereferenceableAttr(
1833 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1834 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1835 AI->getArgNo() + 1, Attrs));
1836 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1837 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1838 AI->getArgNo() + 1,
1839 llvm::Attribute::NonNull));
1840 }
1841 }
1842 } else if (const auto *ArrTy =
1843 getContext().getAsVariableArrayType(OTy)) {
1844 // For C99 VLAs with the static keyword, we don't know the size so
1845 // we can't use the dereferenceable attribute, but in addrspace(0)
1846 // we know that it must be nonnull.
1847 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1848 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1849 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1850 AI->getArgNo() + 1,
1851 llvm::Attribute::NonNull));
1852 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001853
1854 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1855 if (!AVAttr)
1856 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1857 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1858 if (AVAttr) {
1859 llvm::Value *AlignmentValue =
1860 EmitScalarExpr(AVAttr->getAlignment());
1861 llvm::ConstantInt *AlignmentCI =
1862 cast<llvm::ConstantInt>(AlignmentValue);
1863 unsigned Alignment =
1864 std::min((unsigned) AlignmentCI->getZExtValue(),
1865 +llvm::Value::MaximumAlignment);
1866
1867 llvm::AttrBuilder Attrs;
1868 Attrs.addAlignmentAttr(Alignment);
1869 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1870 AI->getArgNo() + 1, Attrs));
1871 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001872 }
1873
Bill Wendling507c3512012-10-16 05:23:44 +00001874 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001875 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1876 AI->getArgNo() + 1,
1877 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001878
Chris Lattner7369c142011-07-20 06:29:00 +00001879 // Ensure the argument is the correct type.
1880 if (V->getType() != ArgI.getCoerceToType())
1881 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1882
John McCalla738c252011-03-09 04:27:21 +00001883 if (isPromoted)
1884 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001885
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001886 if (const CXXMethodDecl *MD =
1887 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001888 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001889 V = CGM.getCXXABI().
1890 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001891 }
1892
Rafael Espindola8778c282012-11-29 16:09:03 +00001893 // Because of merging of function types from multiple decls it is
1894 // possible for the type of an argument to not match the corresponding
1895 // type in the function type. Since we are codegening the callee
1896 // in here, add a cast to the argument type.
1897 llvm::Type *LTy = ConvertType(Arg->getType());
1898 if (V->getType() != LTy)
1899 V = Builder.CreateBitCast(V, LTy);
1900
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001901 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001902 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001905 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001906
Chris Lattnerff941a62010-07-28 18:24:28 +00001907 // The alignment we need to use is the max of the requested alignment for
1908 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001909 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001910 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001911 AlignmentToUse = std::max(AlignmentToUse,
1912 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001913
Chris Lattnerff941a62010-07-28 18:24:28 +00001914 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001915 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001916 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001917
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001918 // If the value is offset in memory, apply the offset now.
1919 if (unsigned Offs = ArgI.getDirectOffset()) {
1920 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1921 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001922 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001923 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1924 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001925
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001926 // Fast-isel and the optimizer generally like scalar values better than
1927 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001928 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001929 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1930 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001931 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001932 llvm::Type *DstTy =
1933 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001934 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001935
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001936 if (SrcSize <= DstSize) {
1937 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1938
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001939 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001940 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001941 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001942 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1943 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001944 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001945 }
1946 } else {
1947 llvm::AllocaInst *TempAlloca =
1948 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1949 TempAlloca->setAlignment(AlignmentToUse);
1950 llvm::Value *TempV = TempAlloca;
1951
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001952 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001953 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001954 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001955 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1956 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001957 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001958 }
1959
1960 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001961 }
1962 } else {
1963 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001964 assert(NumIRArgs == 1);
1965 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001966 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001967 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001968 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001969
1970
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001971 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001972 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001973 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001974 if (isPromoted)
1975 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001976 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1977 } else {
1978 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001979 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001980 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001981 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001982
1983 case ABIArgInfo::Expand: {
1984 // If this structure was expanded into multiple arguments then
1985 // we need to create a temporary and reconstruct it from the
1986 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001987 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001988 CharUnits Align = getContext().getDeclAlign(Arg);
1989 Alloca->setAlignment(Align.getQuantity());
1990 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001991 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001992
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001993 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1994 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1995 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1996 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1997 auto AI = FnArgs[FirstIRArg + i];
1998 AI->setName(Arg->getName() + "." + Twine(i));
1999 }
2000 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002001 }
2002
2003 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002004 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002005 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002006 if (!hasScalarEvaluationKind(Ty)) {
2007 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
2008 } else {
2009 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2010 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
2011 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002012 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002013 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002014 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002015
Reid Kleckner739756c2013-12-04 19:23:12 +00002016 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2017 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002018 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2019 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002020 } else {
2021 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002022 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2023 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002024 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002025}
2026
John McCallffa2c1a2012-01-29 07:46:59 +00002027static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2028 while (insn->use_empty()) {
2029 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2030 if (!bitcast) return;
2031
2032 // This is "safe" because we would have used a ConstantExpr otherwise.
2033 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2034 bitcast->eraseFromParent();
2035 }
2036}
2037
John McCall31168b02011-06-15 23:02:42 +00002038/// Try to emit a fused autorelease of a return result.
2039static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2040 llvm::Value *result) {
2041 // We must be immediately followed the cast.
2042 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002043 if (BB->empty()) return nullptr;
2044 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002045
Chris Lattner2192fe52011-07-18 04:24:23 +00002046 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002047
2048 // result is in a BasicBlock and is therefore an Instruction.
2049 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2050
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002051 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002052
2053 // Look for:
2054 // %generator = bitcast %type1* %generator2 to %type2*
2055 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2056 // We would have emitted this as a constant if the operand weren't
2057 // an Instruction.
2058 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2059
2060 // Require the generator to be immediately followed by the cast.
2061 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002062 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002063
2064 insnsToKill.push_back(bitcast);
2065 }
2066
2067 // Look for:
2068 // %generator = call i8* @objc_retain(i8* %originalResult)
2069 // or
2070 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2071 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002072 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002073
2074 bool doRetainAutorelease;
2075
2076 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2077 doRetainAutorelease = true;
2078 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2079 .objc_retainAutoreleasedReturnValue) {
2080 doRetainAutorelease = false;
2081
John McCallcfa4e9b2012-09-07 23:30:50 +00002082 // If we emitted an assembly marker for this call (and the
2083 // ARCEntrypoints field should have been set if so), go looking
2084 // for that call. If we can't find it, we can't do this
2085 // optimization. But it should always be the immediately previous
2086 // instruction, unless we needed bitcasts around the call.
2087 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2088 llvm::Instruction *prev = call->getPrevNode();
2089 assert(prev);
2090 if (isa<llvm::BitCastInst>(prev)) {
2091 prev = prev->getPrevNode();
2092 assert(prev);
2093 }
2094 assert(isa<llvm::CallInst>(prev));
2095 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2096 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2097 insnsToKill.push_back(prev);
2098 }
John McCall31168b02011-06-15 23:02:42 +00002099 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002100 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002101 }
2102
2103 result = call->getArgOperand(0);
2104 insnsToKill.push_back(call);
2105
2106 // Keep killing bitcasts, for sanity. Note that we no longer care
2107 // about precise ordering as long as there's exactly one use.
2108 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2109 if (!bitcast->hasOneUse()) break;
2110 insnsToKill.push_back(bitcast);
2111 result = bitcast->getOperand(0);
2112 }
2113
2114 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002115 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002116 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2117 (*i)->eraseFromParent();
2118
2119 // Do the fused retain/autorelease if we were asked to.
2120 if (doRetainAutorelease)
2121 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2122
2123 // Cast back to the result type.
2124 return CGF.Builder.CreateBitCast(result, resultType);
2125}
2126
John McCallffa2c1a2012-01-29 07:46:59 +00002127/// If this is a +1 of the value of an immutable 'self', remove it.
2128static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2129 llvm::Value *result) {
2130 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002131 const ObjCMethodDecl *method =
2132 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002133 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002134 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002135 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002136
2137 // Look for a retain call.
2138 llvm::CallInst *retainCall =
2139 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2140 if (!retainCall ||
2141 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002142 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002143
2144 // Look for an ordinary load of 'self'.
2145 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2146 llvm::LoadInst *load =
2147 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2148 if (!load || load->isAtomic() || load->isVolatile() ||
2149 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002150 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002151
2152 // Okay! Burn it all down. This relies for correctness on the
2153 // assumption that the retain is emitted as part of the return and
2154 // that thereafter everything is used "linearly".
2155 llvm::Type *resultType = result->getType();
2156 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2157 assert(retainCall->use_empty());
2158 retainCall->eraseFromParent();
2159 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2160
2161 return CGF.Builder.CreateBitCast(load, resultType);
2162}
2163
John McCall31168b02011-06-15 23:02:42 +00002164/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002165///
2166/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002167static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2168 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002169 // If we're returning 'self', kill the initial retain. This is a
2170 // heuristic attempt to "encourage correctness" in the really unfortunate
2171 // case where we have a return of self during a dealloc and we desperately
2172 // need to avoid the possible autorelease.
2173 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2174 return self;
2175
John McCall31168b02011-06-15 23:02:42 +00002176 // At -O0, try to emit a fused retain/autorelease.
2177 if (CGF.shouldUseFusedARCCalls())
2178 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2179 return fused;
2180
2181 return CGF.EmitARCAutoreleaseReturnValue(result);
2182}
2183
John McCall6e1c0122012-01-29 02:35:02 +00002184/// Heuristically search for a dominating store to the return-value slot.
2185static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2186 // If there are multiple uses of the return-value slot, just check
2187 // for something immediately preceding the IP. Sometimes this can
2188 // happen with how we generate implicit-returns; it can also happen
2189 // with noreturn cleanups.
2190 if (!CGF.ReturnValue->hasOneUse()) {
2191 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002192 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002193 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002194 if (!store) return nullptr;
2195 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002196 assert(!store->isAtomic() && !store->isVolatile()); // see below
2197 return store;
2198 }
2199
2200 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002201 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002202 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002203
2204 // These aren't actually possible for non-coerced returns, and we
2205 // only care about non-coerced returns on this code path.
2206 assert(!store->isAtomic() && !store->isVolatile());
2207
2208 // Now do a first-and-dirty dominance check: just walk up the
2209 // single-predecessors chain from the current insertion point.
2210 llvm::BasicBlock *StoreBB = store->getParent();
2211 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2212 while (IP != StoreBB) {
2213 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002214 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002215 }
2216
2217 // Okay, the store's basic block dominates the insertion point; we
2218 // can do our thing.
2219 return store;
2220}
2221
Adrian Prantl3be10542013-05-02 17:30:20 +00002222void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002223 bool EmitRetDbgLoc,
2224 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002225 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2226 // Naked functions don't have epilogues.
2227 Builder.CreateUnreachable();
2228 return;
2229 }
2230
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002231 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002232 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002233 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002234 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002235 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002236
Dan Gohman481e40c2010-07-20 20:13:52 +00002237 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002238 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002239 QualType RetTy = FI.getReturnType();
2240 const ABIArgInfo &RetAI = FI.getReturnInfo();
2241
2242 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002243 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002244 // Aggregrates get evaluated directly into the destination. Sometimes we
2245 // need to return the sret value in a register, though.
2246 assert(hasAggregateEvaluationKind(RetTy));
2247 if (RetAI.getInAllocaSRet()) {
2248 llvm::Function::arg_iterator EI = CurFn->arg_end();
2249 --EI;
2250 llvm::Value *ArgStruct = EI;
2251 llvm::Value *SRet =
2252 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2253 RV = Builder.CreateLoad(SRet, "sret");
2254 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002255 break;
2256
Daniel Dunbar03816342010-08-21 02:24:36 +00002257 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002258 auto AI = CurFn->arg_begin();
2259 if (RetAI.isSRetAfterThis())
2260 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002261 switch (getEvaluationKind(RetTy)) {
2262 case TEK_Complex: {
2263 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002264 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2265 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002266 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002267 /*isInit*/ true);
2268 break;
2269 }
2270 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002271 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002272 break;
2273 case TEK_Scalar:
2274 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002275 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002276 /*isInit*/ true);
2277 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002278 }
2279 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002280 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002281
2282 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002283 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002284 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2285 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002286 // The internal return value temp always will have pointer-to-return-type
2287 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002288
John McCall6e1c0122012-01-29 02:35:02 +00002289 // If there is a dominating store to ReturnValue, we can elide
2290 // the load, zap the store, and usually zap the alloca.
2291 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002292 // Reuse the debug location from the store unless there is
2293 // cleanup code to be emitted between the store and return
2294 // instruction.
2295 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002296 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002297 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002298 RV = SI->getValueOperand();
2299 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002300
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002301 // If that was the only use of the return value, nuke it as well now.
2302 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2303 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002304 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002305 }
John McCall6e1c0122012-01-29 02:35:02 +00002306
2307 // Otherwise, we have to do a simple load.
2308 } else {
2309 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002310 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002311 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002312 llvm::Value *V = ReturnValue;
2313 // If the value is offset in memory, apply the offset now.
2314 if (unsigned Offs = RetAI.getDirectOffset()) {
2315 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2316 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002317 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002318 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2319 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002320
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002321 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002322 }
John McCall31168b02011-06-15 23:02:42 +00002323
2324 // In ARC, end functions that return a retainable type with a call
2325 // to objc_autoreleaseReturnValue.
2326 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002327 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002328 !FI.isReturnsRetained() &&
2329 RetTy->isObjCRetainableType());
2330 RV = emitAutoreleaseOfResult(*this, RV);
2331 }
2332
Chris Lattner726b3d02010-06-26 23:13:19 +00002333 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002334
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002335 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002336 break;
2337
2338 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002339 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002340 }
2341
Alexey Samsonovde443c52014-08-13 00:26:40 +00002342 llvm::Instruction *Ret;
2343 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002344 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002345 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2346 SanitizerScope SanScope(this);
2347 llvm::Value *Cond = Builder.CreateICmpNE(
2348 RV, llvm::Constant::getNullValue(RV->getType()));
2349 llvm::Constant *StaticData[] = {
2350 EmitCheckSourceLocation(EndLoc),
2351 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2352 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002353 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2354 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002355 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002356 }
2357 Ret = Builder.CreateRet(RV);
2358 } else {
2359 Ret = Builder.CreateRetVoid();
2360 }
2361
Devang Patel65497582010-07-21 18:08:50 +00002362 if (!RetDbgLoc.isUnknown())
Benjamin Kramer03278662015-02-07 13:15:54 +00002363 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002364}
2365
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002366static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2367 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2368 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2369}
2370
2371static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2372 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2373 // placeholders.
2374 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2375 llvm::Value *Placeholder =
2376 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2377 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2378 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2379 Ty.getQualifiers(),
2380 AggValueSlot::IsNotDestructed,
2381 AggValueSlot::DoesNotNeedGCBarriers,
2382 AggValueSlot::IsNotAliased);
2383}
2384
John McCall32ea9692011-03-11 20:59:21 +00002385void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002386 const VarDecl *param,
2387 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002388 // StartFunction converted the ABI-lowered parameter(s) into a
2389 // local alloca. We need to turn that into an r-value suitable
2390 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002391 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002392
John McCall32ea9692011-03-11 20:59:21 +00002393 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002394
John McCall23f66262010-05-26 22:34:26 +00002395 // For the most part, we just need to load the alloca, except:
2396 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002397 // 2) references to non-scalars are pointers directly to the aggregate.
2398 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002399 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002400 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002401 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002402
2403 // Locals which are references to scalars are represented
2404 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002405 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002406 }
2407
Reid Klecknerab2090d2014-07-26 01:34:32 +00002408 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2409 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002410
Nick Lewycky2d84e842013-10-02 02:29:49 +00002411 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002412}
2413
John McCall31168b02011-06-15 23:02:42 +00002414static bool isProvablyNull(llvm::Value *addr) {
2415 return isa<llvm::ConstantPointerNull>(addr);
2416}
2417
2418static bool isProvablyNonNull(llvm::Value *addr) {
2419 return isa<llvm::AllocaInst>(addr);
2420}
2421
2422/// Emit the actual writing-back of a writeback.
2423static void emitWriteback(CodeGenFunction &CGF,
2424 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002425 const LValue &srcLV = writeback.Source;
2426 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002427 assert(!isProvablyNull(srcAddr) &&
2428 "shouldn't have writeback for provably null argument");
2429
Craig Topper8a13c412014-05-21 05:09:00 +00002430 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002431
2432 // If the argument wasn't provably non-null, we need to null check
2433 // before doing the store.
2434 bool provablyNonNull = isProvablyNonNull(srcAddr);
2435 if (!provablyNonNull) {
2436 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2437 contBB = CGF.createBasicBlock("icr.done");
2438
2439 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2440 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2441 CGF.EmitBlock(writebackBB);
2442 }
2443
2444 // Load the value to writeback.
2445 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2446
2447 // Cast it back, in case we're writing an id to a Foo* or something.
2448 value = CGF.Builder.CreateBitCast(value,
2449 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2450 "icr.writeback-cast");
2451
2452 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002453
2454 // If we have a "to use" value, it's something we need to emit a use
2455 // of. This has to be carefully threaded in: if it's done after the
2456 // release it's potentially undefined behavior (and the optimizer
2457 // will ignore it), and if it happens before the retain then the
2458 // optimizer could move the release there.
2459 if (writeback.ToUse) {
2460 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2461
2462 // Retain the new value. No need to block-copy here: the block's
2463 // being passed up the stack.
2464 value = CGF.EmitARCRetainNonBlock(value);
2465
2466 // Emit the intrinsic use here.
2467 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2468
2469 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002470 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002471
2472 // Put the new value in place (primitively).
2473 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2474
2475 // Release the old value.
2476 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2477
2478 // Otherwise, we can just do a normal lvalue store.
2479 } else {
2480 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2481 }
John McCall31168b02011-06-15 23:02:42 +00002482
2483 // Jump to the continuation block.
2484 if (!provablyNonNull)
2485 CGF.EmitBlock(contBB);
2486}
2487
2488static void emitWritebacks(CodeGenFunction &CGF,
2489 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002490 for (const auto &I : args.writebacks())
2491 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002492}
2493
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002494static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2495 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002496 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002497 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2498 CallArgs.getCleanupsToDeactivate();
2499 // Iterate in reverse to increase the likelihood of popping the cleanup.
2500 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2501 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2502 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2503 I->IsActiveIP->eraseFromParent();
2504 }
2505}
2506
John McCalleff18842013-03-23 02:35:54 +00002507static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2508 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2509 if (uop->getOpcode() == UO_AddrOf)
2510 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002511 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002512}
2513
John McCall31168b02011-06-15 23:02:42 +00002514/// Emit an argument that's being passed call-by-writeback. That is,
2515/// we are passing the address of
2516static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2517 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002518 LValue srcLV;
2519
2520 // Make an optimistic effort to emit the address as an l-value.
2521 // This can fail if the the argument expression is more complicated.
2522 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2523 srcLV = CGF.EmitLValue(lvExpr);
2524
2525 // Otherwise, just emit it as a scalar.
2526 } else {
2527 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2528
2529 QualType srcAddrType =
2530 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2531 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2532 }
2533 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002534
2535 // The dest and src types don't necessarily match in LLVM terms
2536 // because of the crazy ObjC compatibility rules.
2537
Chris Lattner2192fe52011-07-18 04:24:23 +00002538 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002539 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2540
2541 // If the address is a constant null, just pass the appropriate null.
2542 if (isProvablyNull(srcAddr)) {
2543 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2544 CRE->getType());
2545 return;
2546 }
2547
John McCall31168b02011-06-15 23:02:42 +00002548 // Create the temporary.
2549 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2550 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002551 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2552 // and that cleanup will be conditional if we can't prove that the l-value
2553 // isn't null, so we need to register a dominating point so that the cleanups
2554 // system will make valid IR.
2555 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2556
John McCall31168b02011-06-15 23:02:42 +00002557 // Zero-initialize it if we're not doing a copy-initialization.
2558 bool shouldCopy = CRE->shouldCopy();
2559 if (!shouldCopy) {
2560 llvm::Value *null =
2561 llvm::ConstantPointerNull::get(
2562 cast<llvm::PointerType>(destType->getElementType()));
2563 CGF.Builder.CreateStore(null, temp);
2564 }
Craig Topper8a13c412014-05-21 05:09:00 +00002565
2566 llvm::BasicBlock *contBB = nullptr;
2567 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002568
2569 // If the address is *not* known to be non-null, we need to switch.
2570 llvm::Value *finalArgument;
2571
2572 bool provablyNonNull = isProvablyNonNull(srcAddr);
2573 if (provablyNonNull) {
2574 finalArgument = temp;
2575 } else {
2576 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2577
2578 finalArgument = CGF.Builder.CreateSelect(isNull,
2579 llvm::ConstantPointerNull::get(destType),
2580 temp, "icr.argument");
2581
2582 // If we need to copy, then the load has to be conditional, which
2583 // means we need control flow.
2584 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002585 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002586 contBB = CGF.createBasicBlock("icr.cont");
2587 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2588 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2589 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002590 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002591 }
2592 }
2593
Craig Topper8a13c412014-05-21 05:09:00 +00002594 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002595
John McCall31168b02011-06-15 23:02:42 +00002596 // Perform a copy if necessary.
2597 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002598 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002599 assert(srcRV.isScalar());
2600
2601 llvm::Value *src = srcRV.getScalarVal();
2602 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2603 "icr.cast");
2604
2605 // Use an ordinary store, not a store-to-lvalue.
2606 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002607
2608 // If optimization is enabled, and the value was held in a
2609 // __strong variable, we need to tell the optimizer that this
2610 // value has to stay alive until we're doing the store back.
2611 // This is because the temporary is effectively unretained,
2612 // and so otherwise we can violate the high-level semantics.
2613 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2614 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2615 valueToUse = src;
2616 }
John McCall31168b02011-06-15 23:02:42 +00002617 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002618
John McCall31168b02011-06-15 23:02:42 +00002619 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002620 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002621 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002622 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002623
2624 // Make a phi for the value to intrinsically use.
2625 if (valueToUse) {
2626 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2627 "icr.to-use");
2628 phiToUse->addIncoming(valueToUse, copyBB);
2629 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2630 originBB);
2631 valueToUse = phiToUse;
2632 }
2633
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002634 condEval.end(CGF);
2635 }
John McCall31168b02011-06-15 23:02:42 +00002636
John McCalleff18842013-03-23 02:35:54 +00002637 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002638 args.add(RValue::get(finalArgument), CRE->getType());
2639}
2640
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002641void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2642 assert(!StackBase && !StackCleanup.isValid());
2643
2644 // Save the stack.
2645 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2646 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2647
2648 // Control gets really tied up in landing pads, so we have to spill the
2649 // stacksave to an alloca to avoid violating SSA form.
2650 // TODO: This is dead if we never emit the cleanup. We should create the
2651 // alloca and store lazily on the first cleanup emission.
2652 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2653 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2654 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2655 StackCleanup = CGF.EHStack.getInnermostEHScope();
2656 assert(StackCleanup.isValid());
2657}
2658
2659void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2660 if (StackBase) {
2661 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2662 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2663 // We could load StackBase from StackBaseMem, but in the non-exceptional
2664 // case we can skip it.
2665 CGF.Builder.CreateCall(F, StackBase);
2666 }
2667}
2668
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002669static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2670 QualType ArgType, SourceLocation ArgLoc,
2671 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002672 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002673 return;
2674 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2675 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2676 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2677 if (!NNAttr)
2678 return;
2679 CodeGenFunction::SanitizerScope SanScope(&CGF);
2680 assert(RV.isScalar());
2681 llvm::Value *V = RV.getScalarVal();
2682 llvm::Value *Cond =
2683 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2684 llvm::Constant *StaticData[] = {
2685 CGF.EmitCheckSourceLocation(ArgLoc),
2686 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2687 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2688 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002689 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2690 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002691}
2692
Reid Kleckner739756c2013-12-04 19:23:12 +00002693void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2694 ArrayRef<QualType> ArgTypes,
2695 CallExpr::const_arg_iterator ArgBeg,
2696 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002697 const FunctionDecl *CalleeDecl,
David Blaikie835afb22015-01-21 23:08:17 +00002698 unsigned ParamsToSkip) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002699 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2700 // because arguments are destroyed left to right in the callee.
2701 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002702 // Insert a stack save if we're going to need any inalloca args.
2703 bool HasInAllocaArgs = false;
2704 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2705 I != E && !HasInAllocaArgs; ++I)
2706 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2707 if (HasInAllocaArgs) {
2708 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2709 Args.allocateArgumentMemory(*this);
2710 }
2711
2712 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002713 size_t CallArgsStart = Args.size();
2714 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2715 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2716 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002717 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2718 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002719 }
2720
2721 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2722 // IR function.
2723 std::reverse(Args.begin() + CallArgsStart, Args.end());
2724 return;
2725 }
2726
2727 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2728 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2729 assert(Arg != ArgEnd);
2730 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002731 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2732 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002733 }
2734}
2735
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002736namespace {
2737
2738struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2739 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2740 : Addr(Addr), Ty(Ty) {}
2741
2742 llvm::Value *Addr;
2743 QualType Ty;
2744
Craig Topper4f12f102014-03-12 06:41:41 +00002745 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002746 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2747 assert(!Dtor->isTrivial());
2748 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2749 /*Delegating=*/false, Addr);
2750 }
2751};
2752
2753}
2754
David Blaikie38b25912015-02-09 19:13:51 +00002755struct DisableDebugLocationUpdates {
2756 CodeGenFunction &CGF;
2757 bool disabledDebugInfo;
2758 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2759 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2760 CGF.disableDebugInfo();
2761 }
2762 ~DisableDebugLocationUpdates() {
2763 if (disabledDebugInfo)
2764 CGF.enableDebugInfo();
2765 }
2766};
2767
John McCall32ea9692011-03-11 20:59:21 +00002768void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2769 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002770 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002771 if (const ObjCIndirectCopyRestoreExpr *CRE
2772 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002773 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002774 assert(getContext().hasSameType(E->getType(), type));
2775 return emitWritebackArg(*this, args, CRE);
2776 }
2777
John McCall0a76c0c2011-08-26 18:42:59 +00002778 assert(type->isReferenceType() == E->isGLValue() &&
2779 "reference binding to unmaterialized r-value!");
2780
John McCall17054bd62011-08-26 21:08:13 +00002781 if (E->isGLValue()) {
2782 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002783 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002786 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2787
2788 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2789 // However, we still have to push an EH-only cleanup in case we unwind before
2790 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002791 if (HasAggregateEvalKind &&
2792 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2793 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002794 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002795 AggValueSlot Slot;
2796 if (args.isUsingInAlloca())
2797 Slot = createPlaceholderSlot(*this, type);
2798 else
2799 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002800
2801 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2802 bool DestroyedInCallee =
2803 RD && RD->hasNonTrivialDestructor() &&
2804 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2805 if (DestroyedInCallee)
2806 Slot.setExternallyDestructed();
2807
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002808 EmitAggExpr(E, Slot);
2809 RValue RV = Slot.asRValue();
2810 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002811
Reid Klecknere39ee212014-05-03 00:33:28 +00002812 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002813 // Create a no-op GEP between the placeholder and the cleanup so we can
2814 // RAUW it successfully. It also serves as a marker of the first
2815 // instruction where the cleanup is active.
2816 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002817 // This unreachable is a temporary marker which will be removed later.
2818 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2819 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002820 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002821 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002822 }
2823
2824 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002825 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2826 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2827 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002828 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2829 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2830 } else {
2831 // We can't represent a misaligned lvalue in the CallArgList, so copy
2832 // to an aligned temporary now.
2833 llvm::Value *tmp = CreateMemTemp(type);
2834 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2835 L.getAlignment());
2836 args.add(RValue::getAggregate(tmp), type);
2837 }
Eli Friedmandf968192011-05-26 00:10:27 +00002838 return;
2839 }
2840
John McCall32ea9692011-03-11 20:59:21 +00002841 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002842}
2843
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002844QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2845 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2846 // implicitly widens null pointer constants that are arguments to varargs
2847 // functions to pointer-sized ints.
2848 if (!getTarget().getTriple().isOSWindows())
2849 return Arg->getType();
2850
2851 if (Arg->getType()->isIntegerType() &&
2852 getContext().getTypeSize(Arg->getType()) <
2853 getContext().getTargetInfo().getPointerWidth(0) &&
2854 Arg->isNullPointerConstant(getContext(),
2855 Expr::NPC_ValueDependentIsNotNull)) {
2856 return getContext().getIntPtrType();
2857 }
2858
2859 return Arg->getType();
2860}
2861
Dan Gohman515a60d2012-02-16 00:57:37 +00002862// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2863// optimizer it can aggressively ignore unwind edges.
2864void
2865CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2866 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2867 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2868 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2869 CGM.getNoObjCARCExceptionsMetadata());
2870}
2871
John McCall882987f2013-02-28 19:01:20 +00002872/// Emits a call to the given no-arguments nounwind runtime function.
2873llvm::CallInst *
2874CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2875 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002876 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002877}
2878
2879/// Emits a call to the given nounwind runtime function.
2880llvm::CallInst *
2881CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2882 ArrayRef<llvm::Value*> args,
2883 const llvm::Twine &name) {
2884 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2885 call->setDoesNotThrow();
2886 return call;
2887}
2888
2889/// Emits a simple call (never an invoke) to the given no-arguments
2890/// runtime function.
2891llvm::CallInst *
2892CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2893 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002894 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002895}
2896
2897/// Emits a simple call (never an invoke) to the given runtime
2898/// function.
2899llvm::CallInst *
2900CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2901 ArrayRef<llvm::Value*> args,
2902 const llvm::Twine &name) {
2903 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2904 call->setCallingConv(getRuntimeCC());
2905 return call;
2906}
2907
2908/// Emits a call or invoke to the given noreturn runtime function.
2909void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2910 ArrayRef<llvm::Value*> args) {
2911 if (getInvokeDest()) {
2912 llvm::InvokeInst *invoke =
2913 Builder.CreateInvoke(callee,
2914 getUnreachableBlock(),
2915 getInvokeDest(),
2916 args);
2917 invoke->setDoesNotReturn();
2918 invoke->setCallingConv(getRuntimeCC());
2919 } else {
2920 llvm::CallInst *call = Builder.CreateCall(callee, args);
2921 call->setDoesNotReturn();
2922 call->setCallingConv(getRuntimeCC());
2923 Builder.CreateUnreachable();
2924 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002925 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002926}
2927
2928/// Emits a call or invoke instruction to the given nullary runtime
2929/// function.
2930llvm::CallSite
2931CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2932 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002933 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002934}
2935
2936/// Emits a call or invoke instruction to the given runtime function.
2937llvm::CallSite
2938CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2939 ArrayRef<llvm::Value*> args,
2940 const Twine &name) {
2941 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2942 callSite.setCallingConv(getRuntimeCC());
2943 return callSite;
2944}
2945
2946llvm::CallSite
2947CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2948 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002949 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002950}
2951
John McCallbd309292010-07-06 01:34:17 +00002952/// Emits a call or invoke instruction to the given function, depending
2953/// on the current state of the EH stack.
2954llvm::CallSite
2955CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002956 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002957 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002958 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002959
Dan Gohman515a60d2012-02-16 00:57:37 +00002960 llvm::Instruction *Inst;
2961 if (!InvokeDest)
2962 Inst = Builder.CreateCall(Callee, Args, Name);
2963 else {
2964 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2965 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2966 EmitBlock(ContBB);
2967 }
2968
2969 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2970 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002971 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002972 AddObjCARCExceptionMetadata(Inst);
2973
2974 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002975}
2976
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002977/// \brief Store a non-aggregate value to an address to initialize it. For
2978/// initialization, a non-atomic store will be used.
2979static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2980 LValue Dst) {
2981 if (Src.isScalar())
2982 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2983 else
2984 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2985}
2986
2987void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2988 llvm::Value *New) {
2989 DeferredReplacements.push_back(std::make_pair(Old, New));
2990}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002991
Daniel Dunbard931a872009-02-02 22:03:45 +00002992RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002993 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002994 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002995 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002996 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002997 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002998 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002999
3000 // Handle struct-return functions by passing a pointer to the
3001 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003002 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003003 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003004
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003005 llvm::FunctionType *IRFuncTy =
3006 cast<llvm::FunctionType>(
3007 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003008
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003009 // If we're using inalloca, insert the allocation after the stack save.
3010 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00003011 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003012 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00003013 llvm::Instruction *IP = CallArgs.getStackBase();
3014 llvm::AllocaInst *AI;
3015 if (IP) {
3016 IP = IP->getNextNode();
3017 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3018 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003019 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003020 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003021 AI->setUsedWithInAlloca(true);
3022 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3023 ArgMemory = AI;
3024 }
3025
Alexey Samsonov153004f2014-09-29 22:08:00 +00003026 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003027 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3028
Chris Lattner4ca97c32009-06-13 00:26:38 +00003029 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003030 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00003031 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003032 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003033 SRetPtr = ReturnValue.getValue();
3034 if (!SRetPtr)
3035 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003036 if (IRFunctionArgs.hasSRetArg()) {
3037 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003038 } else {
3039 llvm::Value *Addr =
3040 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3041 Builder.CreateStore(SRetPtr, Addr);
3042 }
Anders Carlsson17490832009-12-24 20:40:36 +00003043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003045 assert(CallInfo.arg_size() == CallArgs.size() &&
3046 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003047 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003048 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003049 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003050 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003051 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003052 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003053
John McCall47fb9502013-03-07 21:37:08 +00003054 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003055
3056 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003057 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3058 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3059 llvm::UndefValue::get(ArgInfo.getPaddingType());
3060
3061 unsigned FirstIRArg, NumIRArgs;
3062 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003063
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003064 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003065 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003066 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003067 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3068 if (RV.isAggregate()) {
3069 // Replace the placeholder with the appropriate argument slot GEP.
3070 llvm::Instruction *Placeholder =
3071 cast<llvm::Instruction>(RV.getAggregateAddr());
3072 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3073 Builder.SetInsertPoint(Placeholder);
3074 llvm::Value *Addr = Builder.CreateStructGEP(
3075 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3076 Builder.restoreIP(IP);
3077 deferPlaceholderReplacement(Placeholder, Addr);
3078 } else {
3079 // Store the RValue into the argument struct.
3080 llvm::Value *Addr =
3081 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003082 unsigned AS = Addr->getType()->getPointerAddressSpace();
3083 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3084 // There are some cases where a trivial bitcast is not avoidable. The
3085 // definition of a type later in a translation unit may change it's type
3086 // from {}* to (%struct.foo*)*.
3087 if (Addr->getType() != MemType)
3088 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003089 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3090 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3091 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003092 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003093 }
3094
Daniel Dunbar03816342010-08-21 02:24:36 +00003095 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003096 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003097 if (RV.isScalar() || RV.isComplex()) {
3098 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003099 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3100 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3101 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003102 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003103
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003104 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003105 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003106 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003107 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003108 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003109 // 1. If the argument is not byval, and we are required to copy the
3110 // source. (This case doesn't occur on any common architecture.)
3111 // 2. If the argument is byval, RV is not sufficiently aligned, and
3112 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003113 // 3. If the argument is byval, but RV is located in an address space
3114 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003115 llvm::Value *Addr = RV.getAggregateAddr();
3116 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003117 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003118 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003119 const unsigned ArgAddrSpace =
3120 (FirstIRArg < IRFuncTy->getNumParams()
3121 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3122 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003123 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003124 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Mehdi Aminib3d52092015-03-10 02:36:43 +00003125 llvm::getOrEnforceKnownAlignment(Addr, Align, *TD) < Align) ||
3126 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003127 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003128 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3129 if (Align > AI->getAlignment())
3130 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003131 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003132 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003133 } else {
3134 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003135 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003136 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003137 }
3138 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003139 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003140
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003141 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003142 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003143 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003144
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003145 case ABIArgInfo::Extend:
3146 case ABIArgInfo::Direct: {
3147 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003148 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3149 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003150 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003151 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003152 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003153 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003154 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003155 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003156
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003157 // We might have to widen integers, but we should never truncate.
3158 if (ArgInfo.getCoerceToType() != V->getType() &&
3159 V->getType()->isIntegerTy())
3160 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3161
Chris Lattner3ce86682011-07-12 04:53:39 +00003162 // If the argument doesn't match, perform a bitcast to coerce it. This
3163 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003164 if (FirstIRArg < IRFuncTy->getNumParams() &&
3165 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3166 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3167 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003168 break;
3169 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003170
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003171 // FIXME: Avoid the conversion through memory if possible.
3172 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003173 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003174 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003175 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003176 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003177 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003178 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003179
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003180 // If the value is offset in memory, apply the offset now.
3181 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3182 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3183 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003184 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003185 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3186
3187 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003188
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003189 // Fast-isel and the optimizer generally like scalar values better than
3190 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003191 llvm::StructType *STy =
3192 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003193 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003194 llvm::Type *SrcTy =
3195 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3196 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3197 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3198
3199 // If the source type is smaller than the destination type of the
3200 // coerce-to logic, copy the source value into a temp alloca the size
3201 // of the destination type to allow loading all of it. The bits past
3202 // the source value are left undef.
3203 if (SrcSize < DstSize) {
3204 llvm::AllocaInst *TempAlloca
3205 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3206 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3207 SrcPtr = TempAlloca;
3208 } else {
3209 SrcPtr = Builder.CreateBitCast(SrcPtr,
3210 llvm::PointerType::getUnqual(STy));
3211 }
3212
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003213 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3215 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003216 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3217 // We don't know what we're loading from.
3218 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003219 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003220 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003221 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003222 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003223 assert(NumIRArgs == 1);
3224 IRCallArgs[FirstIRArg] =
3225 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003226 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003227
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003228 break;
3229 }
3230
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003231 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003232 unsigned IRArgPos = FirstIRArg;
3233 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3234 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003235 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003236 }
3237 }
Mike Stump11289f42009-09-09 15:08:12 +00003238
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003239 if (ArgMemory) {
3240 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003241 if (CallInfo.isVariadic()) {
3242 // When passing non-POD arguments by value to variadic functions, we will
3243 // end up with a variadic prototype and an inalloca call site. In such
3244 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3245 // the callee.
3246 unsigned CalleeAS =
3247 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3248 Callee = Builder.CreateBitCast(
3249 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3250 } else {
3251 llvm::Type *LastParamTy =
3252 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3253 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003254#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003255 // Assert that these structs have equivalent element types.
3256 llvm::StructType *FullTy = CallInfo.getArgStruct();
3257 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3258 cast<llvm::PointerType>(LastParamTy)->getElementType());
3259 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3260 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3261 DE = DeclaredTy->element_end(),
3262 FI = FullTy->element_begin();
3263 DI != DE; ++DI, ++FI)
3264 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003265#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003266 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3267 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003268 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003269 assert(IRFunctionArgs.hasInallocaArg());
3270 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003271 }
3272
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003273 if (!CallArgs.getCleanupsToDeactivate().empty())
3274 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3275
Chris Lattner4ca97c32009-06-13 00:26:38 +00003276 // If the callee is a bitcast of a function to a varargs pointer to function
3277 // type, check to see if we can remove the bitcast. This handles some cases
3278 // with unprototyped functions.
3279 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3280 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003281 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3282 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003283 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003284 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003285
Chris Lattner4ca97c32009-06-13 00:26:38 +00003286 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3287 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003288 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003289 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003290 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003291 bool ArgsMatch = true;
3292 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3293 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3294 ArgsMatch = false;
3295 break;
3296 }
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattner4ca97c32009-06-13 00:26:38 +00003298 // Strip the cast if we can get away with it. This is a nice cleanup,
3299 // but also allows us to inline the function at -O0 if it is marked
3300 // always_inline.
3301 if (ArgsMatch)
3302 Callee = CalleeF;
3303 }
3304 }
Mike Stump11289f42009-09-09 15:08:12 +00003305
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003306 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3307 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3308 // Inalloca argument can have different type.
3309 if (IRFunctionArgs.hasInallocaArg() &&
3310 i == IRFunctionArgs.getInallocaArgNo())
3311 continue;
3312 if (i < IRFuncTy->getNumParams())
3313 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3314 }
3315
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003316 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003317 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003318 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3319 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003320 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003321 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003322
Craig Topper8a13c412014-05-21 05:09:00 +00003323 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003324 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00003325 llvm::Attribute::NoUnwind) ||
3326 currentFunctionUsesSEHTry())
John McCallbd309292010-07-06 01:34:17 +00003327 InvokeDest = getInvokeDest();
3328
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003329 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003330 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003331 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003332 } else {
3333 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003334 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003335 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003336 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003337 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003338 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003339
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003340 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3341 !CS.hasFnAttr(llvm::Attribute::NoInline))
3342 Attrs =
3343 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3344 llvm::Attribute::AlwaysInline);
3345
Reid Klecknera5930002015-02-11 21:40:48 +00003346 // Disable inlining inside SEH __try blocks.
Reid Kleckner11c033e2015-02-12 23:40:45 +00003347 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003348 Attrs =
3349 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3350 llvm::Attribute::NoInline);
3351
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003352 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003353 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003354
Dan Gohman515a60d2012-02-16 00:57:37 +00003355 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3356 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003357 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003358 AddObjCARCExceptionMetadata(CS.getInstruction());
3359
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003360 // If the call doesn't return, finish the basic block and clear the
3361 // insertion point; this allows the rest of IRgen to discard
3362 // unreachable code.
3363 if (CS.doesNotReturn()) {
3364 Builder.CreateUnreachable();
3365 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003366
Mike Stump18bb9282009-05-16 07:57:57 +00003367 // FIXME: For now, emit a dummy basic block because expr emitters in
3368 // generally are not ready to handle emitting expressions at unreachable
3369 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003370 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003371
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003372 // Return a reasonable RValue.
3373 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003374 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003375
3376 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003377 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003378 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003379
John McCall31168b02011-06-15 23:02:42 +00003380 // Emit any writebacks immediately. Arguably this should happen
3381 // after any return-value munging.
3382 if (CallArgs.hasWritebacks())
3383 emitWritebacks(*this, CallArgs);
3384
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003385 // The stack cleanup for inalloca arguments has to run out of the normal
3386 // lexical order, so deactivate it and run it manually here.
3387 CallArgs.freeArgumentMemory(*this);
3388
Hal Finkelee90a222014-09-26 05:04:30 +00003389 RValue Ret = [&] {
3390 switch (RetAI.getKind()) {
3391 case ABIArgInfo::InAlloca:
3392 case ABIArgInfo::Indirect:
3393 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003394
Hal Finkelee90a222014-09-26 05:04:30 +00003395 case ABIArgInfo::Ignore:
3396 // If we are ignoring an argument that had a result, make sure to
3397 // construct the appropriate return value for our caller.
3398 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003399
Hal Finkelee90a222014-09-26 05:04:30 +00003400 case ABIArgInfo::Extend:
3401 case ABIArgInfo::Direct: {
3402 llvm::Type *RetIRTy = ConvertType(RetTy);
3403 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3404 switch (getEvaluationKind(RetTy)) {
3405 case TEK_Complex: {
3406 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3407 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3408 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003409 }
Hal Finkelee90a222014-09-26 05:04:30 +00003410 case TEK_Aggregate: {
3411 llvm::Value *DestPtr = ReturnValue.getValue();
3412 bool DestIsVolatile = ReturnValue.isVolatile();
3413
3414 if (!DestPtr) {
3415 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3416 DestIsVolatile = false;
3417 }
3418 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3419 return RValue::getAggregate(DestPtr);
3420 }
3421 case TEK_Scalar: {
3422 // If the argument doesn't match, perform a bitcast to coerce it. This
3423 // can happen due to trivial type mismatches.
3424 llvm::Value *V = CI;
3425 if (V->getType() != RetIRTy)
3426 V = Builder.CreateBitCast(V, RetIRTy);
3427 return RValue::get(V);
3428 }
3429 }
3430 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003431 }
Hal Finkelee90a222014-09-26 05:04:30 +00003432
3433 llvm::Value *DestPtr = ReturnValue.getValue();
3434 bool DestIsVolatile = ReturnValue.isVolatile();
3435
3436 if (!DestPtr) {
3437 DestPtr = CreateMemTemp(RetTy, "coerce");
3438 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003439 }
Hal Finkelee90a222014-09-26 05:04:30 +00003440
3441 // If the value is offset in memory, apply the offset now.
3442 llvm::Value *StorePtr = DestPtr;
3443 if (unsigned Offs = RetAI.getDirectOffset()) {
3444 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3445 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3446 StorePtr = Builder.CreateBitCast(StorePtr,
3447 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003448 }
Hal Finkelee90a222014-09-26 05:04:30 +00003449 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3450
3451 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003452 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003453
Hal Finkelee90a222014-09-26 05:04:30 +00003454 case ABIArgInfo::Expand:
3455 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003456 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003457
Hal Finkelee90a222014-09-26 05:04:30 +00003458 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3459 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003460
Hal Finkelee90a222014-09-26 05:04:30 +00003461 if (Ret.isScalar() && TargetDecl) {
3462 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3463 llvm::Value *OffsetValue = nullptr;
3464 if (const auto *Offset = AA->getOffset())
3465 OffsetValue = EmitScalarExpr(Offset);
3466
3467 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3468 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3469 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3470 OffsetValue);
3471 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003472 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003473
Hal Finkelee90a222014-09-26 05:04:30 +00003474 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003475}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003476
3477/* VarArg handling */
3478
3479llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3480 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3481}