blob: 678496421184072a4ff443d3a086ba72488f9678 [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 &
350CodeGenTypes::arrangeMSCopyCtorClosure(const CXXConstructorDecl *CD) {
351 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
352 SmallVector<CanQualType, 2> ArgTys;
353 const CXXRecordDecl *RD = CD->getParent();
354 ArgTys.push_back(GetThisType(Context, RD));
355 ArgTys.push_back(*FTP->param_type_begin());
356 if (RD->getNumVBases() > 0)
357 ArgTys.push_back(Context.IntTy);
358 CallingConv CC = Context.getDefaultCallingConvention(
359 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
360 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
361 /*chainCall=*/false, ArgTys,
362 FunctionType::ExtInfo(CC), RequiredArgs::All);
363}
364
John McCallc818bbb2012-12-07 07:03:17 +0000365/// Arrange a call as unto a free function, except possibly with an
366/// additional number of formal parameters considered required.
367static const CGFunctionInfo &
368arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000369 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000370 const CallArgList &args,
371 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000372 unsigned numExtraRequiredArgs,
373 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000374 assert(args.size() >= numExtraRequiredArgs);
375
376 // In most cases, there are no optional arguments.
377 RequiredArgs required = RequiredArgs::All;
378
379 // If we have a variadic prototype, the required arguments are the
380 // extra prefix plus the arguments in the prototype.
381 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
382 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000383 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000384
385 // If we don't have a prototype at all, but we're supposed to
386 // explicitly use the variadic convention for unprototyped calls,
387 // treat all of the arguments as required but preserve the nominal
388 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000389 } else if (CGM.getTargetCodeGenInfo()
390 .isNoProtoCallVariadic(args,
391 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000392 required = RequiredArgs(args.size());
393 }
394
Peter Collingbournef7706832014-12-12 23:41:25 +0000395 // FIXME: Kill copy.
396 SmallVector<CanQualType, 16> argTypes;
397 for (const auto &arg : args)
398 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
399 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
400 /*instanceMethod=*/false, chainCall,
401 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000402}
403
John McCalla729c622012-02-17 03:33:10 +0000404/// Figure out the rules for calling a function with the given formal
405/// type using the given arguments. The arguments are necessary
406/// because the function might be unprototyped, in which case it's
407/// target-dependent in crazy ways.
408const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000409CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000410 const FunctionType *fnType,
411 bool chainCall) {
412 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
413 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000414}
John McCalla729c622012-02-17 03:33:10 +0000415
John McCallc818bbb2012-12-07 07:03:17 +0000416/// A block function call is essentially a free-function call with an
417/// extra implicit argument.
418const CGFunctionInfo &
419CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
420 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000421 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
422 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000423}
424
425const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000426CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
427 const CallArgList &args,
428 FunctionType::ExtInfo info,
429 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000430 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000431 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000432 for (const auto &Arg : args)
433 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000434 return arrangeLLVMFunctionInfo(
435 GetReturnType(resultType), /*instanceMethod=*/false,
436 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000437}
438
439/// Arrange a call to a C++ method, passing the given arguments.
440const CGFunctionInfo &
441CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
442 const FunctionProtoType *FPT,
443 RequiredArgs required) {
444 // FIXME: Kill copy.
445 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000446 for (const auto &Arg : args)
447 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000448
449 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000450 return arrangeLLVMFunctionInfo(
451 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
452 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000453}
454
Reid Kleckner4982b822014-01-31 22:54:50 +0000455const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
456 QualType resultType, const FunctionArgList &args,
457 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000458 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000459 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000460 for (auto Arg : args)
461 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000462
463 RequiredArgs required =
464 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000465 return arrangeLLVMFunctionInfo(
466 GetReturnType(resultType), /*instanceMethod=*/false,
467 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000468}
469
John McCalla729c622012-02-17 03:33:10 +0000470const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000471 return arrangeLLVMFunctionInfo(
472 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
473 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000474}
475
John McCalla729c622012-02-17 03:33:10 +0000476/// Arrange the argument and result information for an abstract value
477/// of a given function type. This is the method which all of the
478/// above functions ultimately defer to.
479const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000480CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000481 bool instanceMethod,
482 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000483 ArrayRef<CanQualType> argTypes,
484 FunctionType::ExtInfo info,
485 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000486 assert(std::all_of(argTypes.begin(), argTypes.end(),
487 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000488
John McCalla729c622012-02-17 03:33:10 +0000489 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000490
Daniel Dunbare0be8292009-02-03 00:07:12 +0000491 // Lookup or create unique function info.
492 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000493 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
494 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000495
Craig Topper8a13c412014-05-21 05:09:00 +0000496 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000497 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000498 if (FI)
499 return *FI;
500
John McCalla729c622012-02-17 03:33:10 +0000501 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000502 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
503 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000504 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000505
David Blaikie82e95a32014-11-19 07:49:47 +0000506 bool inserted = FunctionsBeingProcessed.insert(FI).second;
507 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000508 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000509
Daniel Dunbar313321e2009-02-03 05:31:23 +0000510 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000511 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000512
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000513 // Loop over all of the computed argument and return value info. If any of
514 // them are direct or extend without a specified coerce type, specify the
515 // default now.
John McCalla729c622012-02-17 03:33:10 +0000516 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000517 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000518 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000519
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000520 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000521 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000522 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000523
John McCalla729c622012-02-17 03:33:10 +0000524 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
525 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000526
Daniel Dunbare0be8292009-02-03 00:07:12 +0000527 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000528}
529
John McCalla729c622012-02-17 03:33:10 +0000530CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000531 bool instanceMethod,
532 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000533 const FunctionType::ExtInfo &info,
534 CanQualType resultType,
535 ArrayRef<CanQualType> argTypes,
536 RequiredArgs required) {
537 void *buffer = operator new(sizeof(CGFunctionInfo) +
538 sizeof(ArgInfo) * (argTypes.size() + 1));
539 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
540 FI->CallingConvention = llvmCC;
541 FI->EffectiveCallingConvention = llvmCC;
542 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000543 FI->InstanceMethod = instanceMethod;
544 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000545 FI->NoReturn = info.getNoReturn();
546 FI->ReturnsRetained = info.getProducesResult();
547 FI->Required = required;
548 FI->HasRegParm = info.getHasRegParm();
549 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000550 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000551 FI->NumArgs = argTypes.size();
552 FI->getArgsBuffer()[0].type = resultType;
553 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
554 FI->getArgsBuffer()[i + 1].type = argTypes[i];
555 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000556}
557
558/***/
559
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000560namespace {
561// ABIArgInfo::Expand implementation.
562
563// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
564struct TypeExpansion {
565 enum TypeExpansionKind {
566 // Elements of constant arrays are expanded recursively.
567 TEK_ConstantArray,
568 // Record fields are expanded recursively (but if record is a union, only
569 // the field with the largest size is expanded).
570 TEK_Record,
571 // For complex types, real and imaginary parts are expanded recursively.
572 TEK_Complex,
573 // All other types are not expandable.
574 TEK_None
575 };
576
577 const TypeExpansionKind Kind;
578
579 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
580 virtual ~TypeExpansion() {}
581};
582
583struct ConstantArrayExpansion : TypeExpansion {
584 QualType EltTy;
585 uint64_t NumElts;
586
587 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
588 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
589 static bool classof(const TypeExpansion *TE) {
590 return TE->Kind == TEK_ConstantArray;
591 }
592};
593
594struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000595 SmallVector<const CXXBaseSpecifier *, 1> Bases;
596
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000597 SmallVector<const FieldDecl *, 1> Fields;
598
Reid Klecknere9f6a712014-10-31 17:10:41 +0000599 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
600 SmallVector<const FieldDecl *, 1> &&Fields)
601 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000602 static bool classof(const TypeExpansion *TE) {
603 return TE->Kind == TEK_Record;
604 }
605};
606
607struct ComplexExpansion : TypeExpansion {
608 QualType EltTy;
609
610 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
611 static bool classof(const TypeExpansion *TE) {
612 return TE->Kind == TEK_Complex;
613 }
614};
615
616struct NoExpansion : TypeExpansion {
617 NoExpansion() : TypeExpansion(TEK_None) {}
618 static bool classof(const TypeExpansion *TE) {
619 return TE->Kind == TEK_None;
620 }
621};
622} // namespace
623
624static std::unique_ptr<TypeExpansion>
625getTypeExpansion(QualType Ty, const ASTContext &Context) {
626 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
627 return llvm::make_unique<ConstantArrayExpansion>(
628 AT->getElementType(), AT->getSize().getZExtValue());
629 }
630 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000631 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000632 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000633 const RecordDecl *RD = RT->getDecl();
634 assert(!RD->hasFlexibleArrayMember() &&
635 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000636 if (RD->isUnion()) {
637 // Unions can be here only in degenerative cases - all the fields are same
638 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000639 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000640 CharUnits UnionSize = CharUnits::Zero();
641
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000642 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000643 // Skip zero length bitfields.
644 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
645 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000646 assert(!FD->isBitField() &&
647 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000648 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000649 if (UnionSize < FieldSize) {
650 UnionSize = FieldSize;
651 LargestFD = FD;
652 }
653 }
654 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000655 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000656 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000657 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
658 assert(!CXXRD->isDynamicClass() &&
659 "cannot expand vtable pointers in dynamic classes");
660 for (const CXXBaseSpecifier &BS : CXXRD->bases())
661 Bases.push_back(&BS);
662 }
663
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000664 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000665 // Skip zero length bitfields.
666 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
667 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000668 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000669 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000670 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000671 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000672 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000673 return llvm::make_unique<RecordExpansion>(std::move(Bases),
674 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000675 }
676 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
677 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
678 }
679 return llvm::make_unique<NoExpansion>();
680}
681
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000682static int getExpansionSize(QualType Ty, const ASTContext &Context) {
683 auto Exp = getTypeExpansion(Ty, Context);
684 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
685 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
686 }
687 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
688 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000689 for (auto BS : RExp->Bases)
690 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000691 for (auto FD : RExp->Fields)
692 Res += getExpansionSize(FD->getType(), Context);
693 return Res;
694 }
695 if (isa<ComplexExpansion>(Exp.get()))
696 return 2;
697 assert(isa<NoExpansion>(Exp.get()));
698 return 1;
699}
700
Alexey Samsonov153004f2014-09-29 22:08:00 +0000701void
702CodeGenTypes::getExpandedTypes(QualType Ty,
703 SmallVectorImpl<llvm::Type *>::iterator &TI) {
704 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000705 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
706 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000707 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000708 }
709 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000710 for (auto BS : RExp->Bases)
711 getExpandedTypes(BS->getType(), TI);
712 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000713 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000714 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
715 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000716 *TI++ = EltTy;
717 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000718 } else {
719 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000720 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000721 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000722}
723
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000724void CodeGenFunction::ExpandTypeFromArgs(
725 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000726 assert(LV.isSimple() &&
727 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000728
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000729 auto Exp = getTypeExpansion(Ty, getContext());
730 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
731 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
732 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
733 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
734 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000735 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000736 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000737 llvm::Value *This = LV.getAddress();
738 for (const CXXBaseSpecifier *BS : RExp->Bases) {
739 // Perform a single step derived-to-base conversion.
740 llvm::Value *Base =
741 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
742 /*NullCheckValue=*/false, SourceLocation());
743 LValue SubLV = MakeAddrLValue(Base, BS->getType());
744
745 // Recurse onto bases.
746 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
747 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000748 for (auto FD : RExp->Fields) {
749 // FIXME: What are the right qualifiers here?
750 LValue SubLV = EmitLValueForField(LV, FD);
751 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000752 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000753 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000754 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000755 EmitStoreThroughLValue(RValue::get(*AI++),
756 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000757 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000758 EmitStoreThroughLValue(RValue::get(*AI++),
759 MakeAddrLValue(ImagAddr, CExp->EltTy));
760 } else {
761 assert(isa<NoExpansion>(Exp.get()));
762 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000763 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000764}
765
766void CodeGenFunction::ExpandTypeToArgs(
767 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
768 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
769 auto Exp = getTypeExpansion(Ty, getContext());
770 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
771 llvm::Value *Addr = RV.getAggregateAddr();
772 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
773 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
774 RValue EltRV =
775 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
776 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
777 }
778 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000779 llvm::Value *This = RV.getAggregateAddr();
780 for (const CXXBaseSpecifier *BS : RExp->Bases) {
781 // Perform a single step derived-to-base conversion.
782 llvm::Value *Base =
783 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
784 /*NullCheckValue=*/false, SourceLocation());
785 RValue BaseRV = RValue::getAggregate(Base);
786
787 // Recurse onto bases.
788 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
789 IRCallArgPos);
790 }
791
792 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000793 for (auto FD : RExp->Fields) {
794 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
795 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
796 IRCallArgPos);
797 }
798 } else if (isa<ComplexExpansion>(Exp.get())) {
799 ComplexPairTy CV = RV.getComplexVal();
800 IRCallArgs[IRCallArgPos++] = CV.first;
801 IRCallArgs[IRCallArgPos++] = CV.second;
802 } else {
803 assert(isa<NoExpansion>(Exp.get()));
804 assert(RV.isScalar() &&
805 "Unexpected non-scalar rvalue during struct expansion.");
806
807 // Insert a bitcast as needed.
808 llvm::Value *V = RV.getScalarVal();
809 if (IRCallArgPos < IRFuncTy->getNumParams() &&
810 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
811 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
812
813 IRCallArgs[IRCallArgPos++] = V;
814 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000815}
816
Chris Lattner895c52b2010-06-27 06:04:18 +0000817/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000818/// accessing some number of bytes out of it, try to gep into the struct to get
819/// at its inner goodness. Dive as deep as possible without entering an element
820/// with an in-memory size smaller than DstSize.
821static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000822EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000823 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000824 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000825 // We can't dive into a zero-element struct.
826 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000827
Chris Lattner2192fe52011-07-18 04:24:23 +0000828 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000829
Chris Lattner1cd66982010-06-27 05:56:15 +0000830 // 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 +0000831 // first element is the same size as the whole struct, we can enter it. The
832 // comparison must be made on the store size and not the alloca size. Using
833 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000834 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000835 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000836 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000837 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000838 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000839
Chris Lattner1cd66982010-06-27 05:56:15 +0000840 // GEP into the first element.
841 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000842
Chris Lattner1cd66982010-06-27 05:56:15 +0000843 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000844 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000845 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000846 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000847 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000848
849 return SrcPtr;
850}
851
Chris Lattner055097f2010-06-27 06:26:04 +0000852/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
853/// are either integers or pointers. This does a truncation of the value if it
854/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000855///
856/// This behaves as if the value were coerced through memory, so on big-endian
857/// targets the high bits are preserved in a truncation, while little-endian
858/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000859static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000860 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000861 CodeGenFunction &CGF) {
862 if (Val->getType() == Ty)
863 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000864
Chris Lattner055097f2010-06-27 06:26:04 +0000865 if (isa<llvm::PointerType>(Val->getType())) {
866 // If this is Pointer->Pointer avoid conversion to and from int.
867 if (isa<llvm::PointerType>(Ty))
868 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000869
Chris Lattner055097f2010-06-27 06:26:04 +0000870 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000871 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000872 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000873
Chris Lattner2192fe52011-07-18 04:24:23 +0000874 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000875 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000876 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000877
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000878 if (Val->getType() != DestIntTy) {
879 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
880 if (DL.isBigEndian()) {
881 // Preserve the high bits on big-endian targets.
882 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000883 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
884 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
885
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000886 if (SrcSize > DstSize) {
887 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
888 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
889 } else {
890 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
891 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
892 }
893 } else {
894 // Little-endian targets preserve the low bits. No shifts required.
895 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
896 }
897 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000898
Chris Lattner055097f2010-06-27 06:26:04 +0000899 if (isa<llvm::PointerType>(Ty))
900 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
901 return Val;
902}
903
Chris Lattner1cd66982010-06-27 05:56:15 +0000904
905
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000906/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
907/// a pointer to an object of type \arg Ty.
908///
909/// This safely handles the case when the src type is smaller than the
910/// destination type; in this situation the values of bits which not
911/// present in the src are undefined.
912static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000913 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000914 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000915 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000916 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000917
Chris Lattnerd200eda2010-06-28 22:51:39 +0000918 // If SrcTy and Ty are the same, just do a load.
919 if (SrcTy == Ty)
920 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000921
Micah Villmowdd31ca12012-10-08 16:25:52 +0000922 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000923
Chris Lattner2192fe52011-07-18 04:24:23 +0000924 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000925 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000926 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
927 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000928
Micah Villmowdd31ca12012-10-08 16:25:52 +0000929 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000930
Chris Lattner055097f2010-06-27 06:26:04 +0000931 // If the source and destination are integer or pointer types, just do an
932 // extension or truncation to the desired type.
933 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
934 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
935 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
936 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
937 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000938
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000939 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000940 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000941 // Generally SrcSize is never greater than DstSize, since this means we are
942 // losing bits. However, this can happen in cases where the structure has
943 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000944 //
Mike Stump18bb9282009-05-16 07:57:57 +0000945 // FIXME: Assert that we aren't truncating non-padding bits when have access
946 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000947 llvm::Value *Casted =
948 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000949 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
950 // FIXME: Use better alignment / avoid requiring aligned load.
951 Load->setAlignment(1);
952 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000953 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000954
Chris Lattner3fcc7902010-06-27 01:06:27 +0000955 // Otherwise do coercion through memory. This is stupid, but
956 // simple.
957 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000958 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
959 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
960 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000961 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000962 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
963 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
964 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000965 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000966}
967
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000968// Function to store a first-class aggregate into memory. We prefer to
969// store the elements rather than the aggregate to be more friendly to
970// fast-isel.
971// FIXME: Do we need to recurse here?
972static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
973 llvm::Value *DestPtr, bool DestIsVolatile,
974 bool LowAlignment) {
975 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000976 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000977 dyn_cast<llvm::StructType>(Val->getType())) {
978 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
979 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
980 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
981 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
982 DestIsVolatile);
983 if (LowAlignment)
984 SI->setAlignment(1);
985 }
986 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000987 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
988 if (LowAlignment)
989 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000990 }
991}
992
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000993/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
994/// where the source and destination may have different types.
995///
996/// This safely handles the case when the src type is larger than the
997/// destination type; the upper bits of the src will be lost.
998static void CreateCoercedStore(llvm::Value *Src,
999 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +00001000 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001001 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001002 llvm::Type *SrcTy = Src->getType();
1003 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001004 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001005 if (SrcTy == DstTy) {
1006 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1007 return;
1008 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001009
Micah Villmowdd31ca12012-10-08 16:25:52 +00001010 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001011
Chris Lattner2192fe52011-07-18 04:24:23 +00001012 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +00001013 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1014 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1015 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001016
Chris Lattner055097f2010-06-27 06:26:04 +00001017 // If the source and destination are integer or pointer types, just do an
1018 // extension or truncation to the desired type.
1019 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1020 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1021 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1022 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1023 return;
1024 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001025
Micah Villmowdd31ca12012-10-08 16:25:52 +00001026 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001027
Daniel Dunbar313321e2009-02-03 05:31:23 +00001028 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001029 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001030 llvm::Value *Casted =
1031 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +00001032 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001033 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001034 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001035 // Otherwise do coercion through memory. This is stupid, but
1036 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001037
1038 // Generally SrcSize is never greater than DstSize, since this means we are
1039 // losing bits. However, this can happen in cases where the structure has
1040 // additional padding, for example due to a user specified alignment.
1041 //
1042 // FIXME: Assert that we aren't truncating non-padding bits when have access
1043 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001044 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1045 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001046 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1047 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1048 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001049 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001050 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1051 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1052 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001053 }
1054}
1055
Alexey Samsonov153004f2014-09-29 22:08:00 +00001056namespace {
1057
1058/// Encapsulates information about the way function arguments from
1059/// CGFunctionInfo should be passed to actual LLVM IR function.
1060class ClangToLLVMArgMapping {
1061 static const unsigned InvalidIndex = ~0U;
1062 unsigned InallocaArgNo;
1063 unsigned SRetArgNo;
1064 unsigned TotalIRArgs;
1065
1066 /// Arguments of LLVM IR function corresponding to single Clang argument.
1067 struct IRArgs {
1068 unsigned PaddingArgIndex;
1069 // Argument is expanded to IR arguments at positions
1070 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1071 unsigned FirstArgIndex;
1072 unsigned NumberOfArgs;
1073
1074 IRArgs()
1075 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1076 NumberOfArgs(0) {}
1077 };
1078
1079 SmallVector<IRArgs, 8> ArgInfo;
1080
1081public:
1082 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1083 bool OnlyRequiredArgs = false)
1084 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1085 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1086 construct(Context, FI, OnlyRequiredArgs);
1087 }
1088
1089 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1090 unsigned getInallocaArgNo() const {
1091 assert(hasInallocaArg());
1092 return InallocaArgNo;
1093 }
1094
1095 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1096 unsigned getSRetArgNo() const {
1097 assert(hasSRetArg());
1098 return SRetArgNo;
1099 }
1100
1101 unsigned totalIRArgs() const { return TotalIRArgs; }
1102
1103 bool hasPaddingArg(unsigned ArgNo) const {
1104 assert(ArgNo < ArgInfo.size());
1105 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1106 }
1107 unsigned getPaddingArgNo(unsigned ArgNo) const {
1108 assert(hasPaddingArg(ArgNo));
1109 return ArgInfo[ArgNo].PaddingArgIndex;
1110 }
1111
1112 /// Returns index of first IR argument corresponding to ArgNo, and their
1113 /// quantity.
1114 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1115 assert(ArgNo < ArgInfo.size());
1116 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1117 ArgInfo[ArgNo].NumberOfArgs);
1118 }
1119
1120private:
1121 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1122 bool OnlyRequiredArgs);
1123};
1124
1125void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1126 const CGFunctionInfo &FI,
1127 bool OnlyRequiredArgs) {
1128 unsigned IRArgNo = 0;
1129 bool SwapThisWithSRet = false;
1130 const ABIArgInfo &RetAI = FI.getReturnInfo();
1131
1132 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1133 SwapThisWithSRet = RetAI.isSRetAfterThis();
1134 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1135 }
1136
1137 unsigned ArgNo = 0;
1138 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1139 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1140 ++I, ++ArgNo) {
1141 assert(I != FI.arg_end());
1142 QualType ArgType = I->type;
1143 const ABIArgInfo &AI = I->info;
1144 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1145 auto &IRArgs = ArgInfo[ArgNo];
1146
1147 if (AI.getPaddingType())
1148 IRArgs.PaddingArgIndex = IRArgNo++;
1149
1150 switch (AI.getKind()) {
1151 case ABIArgInfo::Extend:
1152 case ABIArgInfo::Direct: {
1153 // FIXME: handle sseregparm someday...
1154 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1155 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1156 IRArgs.NumberOfArgs = STy->getNumElements();
1157 } else {
1158 IRArgs.NumberOfArgs = 1;
1159 }
1160 break;
1161 }
1162 case ABIArgInfo::Indirect:
1163 IRArgs.NumberOfArgs = 1;
1164 break;
1165 case ABIArgInfo::Ignore:
1166 case ABIArgInfo::InAlloca:
1167 // ignore and inalloca doesn't have matching LLVM parameters.
1168 IRArgs.NumberOfArgs = 0;
1169 break;
1170 case ABIArgInfo::Expand: {
1171 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1172 break;
1173 }
1174 }
1175
1176 if (IRArgs.NumberOfArgs > 0) {
1177 IRArgs.FirstArgIndex = IRArgNo;
1178 IRArgNo += IRArgs.NumberOfArgs;
1179 }
1180
1181 // Skip over the sret parameter when it comes second. We already handled it
1182 // above.
1183 if (IRArgNo == 1 && SwapThisWithSRet)
1184 IRArgNo++;
1185 }
1186 assert(ArgNo == ArgInfo.size());
1187
1188 if (FI.usesInAlloca())
1189 InallocaArgNo = IRArgNo++;
1190
1191 TotalIRArgs = IRArgNo;
1192}
1193} // namespace
1194
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001195/***/
1196
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001197bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001198 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001199}
1200
Tim Northovere77cc392014-03-29 13:28:05 +00001201bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1202 return ReturnTypeUsesSRet(FI) &&
1203 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1204}
1205
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001206bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1207 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1208 switch (BT->getKind()) {
1209 default:
1210 return false;
1211 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001212 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001213 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001214 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001215 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001216 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001217 }
1218 }
1219
1220 return false;
1221}
1222
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001223bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1224 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1225 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1226 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001227 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001228 }
1229 }
1230
1231 return false;
1232}
1233
Chris Lattnera5f58b02011-07-09 17:41:47 +00001234llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001235 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1236 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001237}
1238
Chris Lattnera5f58b02011-07-09 17:41:47 +00001239llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001240CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001241
David Blaikie82e95a32014-11-19 07:49:47 +00001242 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1243 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001244 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001245
Alexey Samsonov153004f2014-09-29 22:08:00 +00001246 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001247 const ABIArgInfo &retAI = FI.getReturnInfo();
1248 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001249 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001250 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001251
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001252 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001253 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001254 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001255 break;
1256
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001257 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001258 if (retAI.getInAllocaSRet()) {
1259 // sret things on win32 aren't void, they return the sret pointer.
1260 QualType ret = FI.getReturnType();
1261 llvm::Type *ty = ConvertType(ret);
1262 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1263 resultType = llvm::PointerType::get(ty, addressSpace);
1264 } else {
1265 resultType = llvm::Type::getVoidTy(getLLVMContext());
1266 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001267 break;
1268
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001269 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001270 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1271 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001272 break;
1273 }
1274
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001275 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001276 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001277 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Alexey Samsonov153004f2014-09-29 22:08:00 +00001280 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1281 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1282
1283 // Add type for sret argument.
1284 if (IRFunctionArgs.hasSRetArg()) {
1285 QualType Ret = FI.getReturnType();
1286 llvm::Type *Ty = ConvertType(Ret);
1287 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1288 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1289 llvm::PointerType::get(Ty, AddressSpace);
1290 }
1291
1292 // Add type for inalloca argument.
1293 if (IRFunctionArgs.hasInallocaArg()) {
1294 auto ArgStruct = FI.getArgStruct();
1295 assert(ArgStruct);
1296 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1297 }
1298
John McCallc818bbb2012-12-07 07:03:17 +00001299 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001300 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001301 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1302 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001303 for (; it != ie; ++it, ++ArgNo) {
1304 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001305
Rafael Espindolafad28de2012-10-24 01:59:00 +00001306 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001307 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1308 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1309 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001310
Alexey Samsonov153004f2014-09-29 22:08:00 +00001311 unsigned FirstIRArg, NumIRArgs;
1312 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1313
1314 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001315 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001316 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001317 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001318 break;
1319
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001320 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001321 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001322 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001323 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001324 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001325 break;
1326 }
1327
1328 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001329 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001330 // Fast-isel and the optimizer generally like scalar values better than
1331 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001332 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001333 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001334 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1335 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001336 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001337 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001338 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001339 assert(NumIRArgs == 1);
1340 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001341 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001342 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Daniel Dunbard3674e62008-09-11 01:48:57 +00001345 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001346 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1347 getExpandedTypes(it->type, ArgTypesIter);
1348 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001349 break;
1350 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001351 }
1352
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001353 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1354 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001355
1356 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001357}
1358
Chris Lattner2192fe52011-07-18 04:24:23 +00001359llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001360 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001361 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001362
Chris Lattner8806e322011-07-10 00:18:59 +00001363 if (!isFuncTypeConvertible(FPT))
1364 return llvm::StructType::get(getLLVMContext());
1365
1366 const CGFunctionInfo *Info;
1367 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001368 Info =
1369 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001370 else
John McCalla729c622012-02-17 03:33:10 +00001371 Info = &arrangeCXXMethodDeclaration(MD);
1372 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001373}
1374
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001375void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001376 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001377 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001378 unsigned &CallingConv,
1379 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001380 llvm::AttrBuilder FuncAttrs;
1381 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001382 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001383
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001384 CallingConv = FI.getEffectiveCallingConvention();
1385
John McCallab26cfa2010-02-05 21:31:56 +00001386 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001387 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001388
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001389 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001390 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001391 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001392 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001393 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001394 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001395 if (TargetDecl->hasAttr<NoReturnAttr>())
1396 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001397 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1398 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001399
1400 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001401 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001402 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001403 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001404 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1405 // These attributes are not inherited by overloads.
1406 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1407 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001408 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001409 }
1410
Eric Christopherbf005ec2011-08-15 22:38:22 +00001411 // 'const' and 'pure' attribute functions are also nounwind.
1412 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001413 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1414 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001415 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001416 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1417 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001418 }
David Majnemer631a90b2015-02-04 07:23:21 +00001419 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001420 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001421 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1422 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001423
1424 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001425 }
1426
Paul Robinson08556952014-12-11 20:14:04 +00001427 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1428 if (!HasOptnone) {
1429 if (CodeGenOpts.OptimizeSize)
1430 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1431 if (CodeGenOpts.OptimizeSize == 2)
1432 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1433 }
1434
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001435 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001436 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001437 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001438 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001439 if (CodeGenOpts.EnableSegmentedStacks &&
1440 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001441 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001442
Bill Wendling2f81db62013-02-22 20:53:29 +00001443 if (AttrOnCallSite) {
1444 // Attributes that should go on the call site only.
1445 if (!CodeGenOpts.SimplifyLibCalls)
1446 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001447 } else {
1448 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001449 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001450 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001451 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001452 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001453 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001454 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001455 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001456 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001457 }
1458
Bill Wendlingdabafea2013-03-13 22:24:33 +00001459 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001460 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001461 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001462 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001463 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001464 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001465 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001466 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001467 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001468 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001469 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001470 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001471
Bill Wendlingd8f49502013-08-01 21:41:02 +00001472 if (!CodeGenOpts.StackRealignment)
1473 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001474 }
1475
Alexey Samsonov153004f2014-09-29 22:08:00 +00001476 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001477
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001478 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001479 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001480 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001481 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001482 if (RetTy->hasSignedIntegerRepresentation())
1483 RetAttrs.addAttribute(llvm::Attribute::SExt);
1484 else if (RetTy->hasUnsignedIntegerRepresentation())
1485 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001486 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001487 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001488 if (RetAI.getInReg())
1489 RetAttrs.addAttribute(llvm::Attribute::InReg);
1490 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001491 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001492 break;
1493
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001494 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001495 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001496 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001497 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1498 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001499 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001500 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001501
Daniel Dunbard3674e62008-09-11 01:48:57 +00001502 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001503 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001504 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001505
Hal Finkela2347ba2014-07-18 15:52:10 +00001506 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1507 QualType PTy = RefTy->getPointeeType();
1508 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1509 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1510 .getQuantity());
1511 else if (getContext().getTargetAddressSpace(PTy) == 0)
1512 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1513 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001514
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001515 // Attach return attributes.
1516 if (RetAttrs.hasAttributes()) {
1517 PAL.push_back(llvm::AttributeSet::get(
1518 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1519 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001520
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001521 // Attach attributes to sret.
1522 if (IRFunctionArgs.hasSRetArg()) {
1523 llvm::AttrBuilder SRETAttrs;
1524 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1525 if (RetAI.getInReg())
1526 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1527 PAL.push_back(llvm::AttributeSet::get(
1528 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1529 }
1530
1531 // Attach attributes to inalloca argument.
1532 if (IRFunctionArgs.hasInallocaArg()) {
1533 llvm::AttrBuilder Attrs;
1534 Attrs.addAttribute(llvm::Attribute::InAlloca);
1535 PAL.push_back(llvm::AttributeSet::get(
1536 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1537 }
1538
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001539 unsigned ArgNo = 0;
1540 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1541 E = FI.arg_end();
1542 I != E; ++I, ++ArgNo) {
1543 QualType ParamType = I->type;
1544 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001545 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001546
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001547 // Add attribute for padding argument, if necessary.
1548 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001549 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001550 PAL.push_back(llvm::AttributeSet::get(
1551 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1552 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001553 }
1554
John McCall39ec71f2010-03-27 00:47:27 +00001555 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1556 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001557 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001558 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001559 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001560 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001561 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001562 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001563 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001564 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001565 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001566 if (ArgNo == 0 && FI.isChainCall())
1567 Attrs.addAttribute(llvm::Attribute::Nest);
1568 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001569 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001570 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001571
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001572 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001573 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001574 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001575
Anders Carlsson20759ad2009-09-16 15:53:40 +00001576 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001577 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001578
Bill Wendlinga7912f82012-10-10 07:36:56 +00001579 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1580
Daniel Dunbarc2304432009-03-18 19:51:01 +00001581 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001582 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1583 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001584 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001585
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001586 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001587 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001588 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001589
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001590 case ABIArgInfo::InAlloca:
1591 // inalloca disables readnone and readonly.
1592 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1593 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001594 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001595 }
Mike Stump11289f42009-09-09 15:08:12 +00001596
Hal Finkela2347ba2014-07-18 15:52:10 +00001597 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1598 QualType PTy = RefTy->getPointeeType();
1599 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1600 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1601 .getQuantity());
1602 else if (getContext().getTargetAddressSpace(PTy) == 0)
1603 Attrs.addAttribute(llvm::Attribute::NonNull);
1604 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001605
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001606 if (Attrs.hasAttributes()) {
1607 unsigned FirstIRArg, NumIRArgs;
1608 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1609 for (unsigned i = 0; i < NumIRArgs; i++)
1610 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1611 FirstIRArg + i + 1, Attrs));
1612 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001613 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001614 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001615
Bill Wendlinga7912f82012-10-10 07:36:56 +00001616 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001617 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001618 AttributeSet::get(getLLVMContext(),
1619 llvm::AttributeSet::FunctionIndex,
1620 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001621}
1622
John McCalla738c252011-03-09 04:27:21 +00001623/// An argument came in as a promoted argument; demote it back to its
1624/// declared type.
1625static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1626 const VarDecl *var,
1627 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001628 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001629
1630 // This can happen with promotions that actually don't change the
1631 // underlying type, like the enum promotions.
1632 if (value->getType() == varType) return value;
1633
1634 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1635 && "unexpected promotion type");
1636
1637 if (isa<llvm::IntegerType>(varType))
1638 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1639
1640 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1641}
1642
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001643/// Returns the attribute (either parameter attribute, or function
1644/// attribute), which declares argument ArgNo to be non-null.
1645static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1646 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001647 // FIXME: __attribute__((nonnull)) can also be applied to:
1648 // - references to pointers, where the pointee is known to be
1649 // nonnull (apparently a Clang extension)
1650 // - transparent unions containing pointers
1651 // In the former case, LLVM IR cannot represent the constraint. In
1652 // the latter case, we have no guarantee that the transparent union
1653 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001654 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1655 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001656 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001657 if (PVD) {
1658 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1659 return ParmNNAttr;
1660 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001661 // Check function attributes.
1662 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001663 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001664 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001665 if (NNAttr->isNonNull(ArgNo))
1666 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001667 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001668 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001669}
1670
Daniel Dunbard931a872009-02-02 22:03:45 +00001671void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1672 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001673 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001674 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1675 // Naked functions don't have prologues.
1676 return;
1677
John McCallcaa19452009-07-28 01:00:58 +00001678 // If this is an implicit-return-zero function, go ahead and
1679 // initialize the return value. TODO: it might be nice to have
1680 // a more general mechanism for this that didn't require synthesized
1681 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001682 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001683 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001684 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001685 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001686 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001687 Builder.CreateStore(Zero, ReturnValue);
1688 }
1689 }
1690
Mike Stump18bb9282009-05-16 07:57:57 +00001691 // FIXME: We no longer need the types from FunctionArgList; lift up and
1692 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001693
Alexey Samsonov153004f2014-09-29 22:08:00 +00001694 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001695 // Flattened function arguments.
1696 SmallVector<llvm::Argument *, 16> FnArgs;
1697 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1698 for (auto &Arg : Fn->args()) {
1699 FnArgs.push_back(&Arg);
1700 }
1701 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001702
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001703 // If we're using inalloca, all the memory arguments are GEPs off of the last
1704 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001705 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001706 if (IRFunctionArgs.hasInallocaArg()) {
1707 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1709 }
1710
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001711 // Name the struct return parameter.
1712 if (IRFunctionArgs.hasSRetArg()) {
1713 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001714 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001715 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001716 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001719 // Track if we received the parameter as a pointer (indirect, byval, or
1720 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1721 // into a local alloca for us.
1722 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001723 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001724 SmallVector<ValueAndIsPtr, 16> ArgVals;
1725 ArgVals.reserve(Args.size());
1726
Reid Kleckner739756c2013-12-04 19:23:12 +00001727 // Create a pointer value for every parameter declaration. This usually
1728 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1729 // any cleanups or do anything that might unwind. We do that separately, so
1730 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001731 assert(FI.arg_size() == Args.size() &&
1732 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001733 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001734 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001735 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001736 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001737 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001738 QualType Ty = info_it->type;
1739 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001740
John McCalla738c252011-03-09 04:27:21 +00001741 bool isPromoted =
1742 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1743
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001744 unsigned FirstIRArg, NumIRArgs;
1745 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001746
Daniel Dunbard3674e62008-09-11 01:48:57 +00001747 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001748 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001749 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001750 llvm::Value *V = Builder.CreateStructGEP(
1751 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1752 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001753 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001754 }
1755
Daniel Dunbar747865a2009-02-05 09:16:39 +00001756 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001757 assert(NumIRArgs == 1);
1758 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001759
John McCall47fb9502013-03-07 21:37:08 +00001760 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001761 // Aggregates and complex variables are accessed by reference. All we
1762 // need to do is realign the value, if requested
1763 if (ArgI.getIndirectRealign()) {
1764 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1765
1766 // Copy from the incoming argument pointer to the temporary with the
1767 // appropriate alignment.
1768 //
1769 // FIXME: We should have a common utility for generating an aggregate
1770 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001771 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001772 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001773 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1774 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1775 Builder.CreateMemCpy(Dst,
1776 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001777 llvm::ConstantInt::get(IntPtrTy,
1778 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001779 ArgI.getIndirectAlign(),
1780 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001781 V = AlignedTemp;
1782 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001783 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001784 } else {
1785 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001786 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001787 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1788 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001789
1790 if (isPromoted)
1791 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001792 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001793 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001794 break;
1795 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001796
1797 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001798 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001799
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001800 // If we have the trivial case, handle it with no muss and fuss.
1801 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001802 ArgI.getCoerceToType() == ConvertType(Ty) &&
1803 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001804 assert(NumIRArgs == 1);
1805 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001806 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001807
Hal Finkel48d53e22014-07-19 01:41:07 +00001808 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001809 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1810 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001811 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1812 AI->getArgNo() + 1,
1813 llvm::Attribute::NonNull));
1814
Hal Finkel48d53e22014-07-19 01:41:07 +00001815 QualType OTy = PVD->getOriginalType();
1816 if (const auto *ArrTy =
1817 getContext().getAsConstantArrayType(OTy)) {
1818 // A C99 array parameter declaration with the static keyword also
1819 // indicates dereferenceability, and if the size is constant we can
1820 // use the dereferenceable attribute (which requires the size in
1821 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001822 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001823 QualType ETy = ArrTy->getElementType();
1824 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1825 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1826 ArrSize) {
1827 llvm::AttrBuilder Attrs;
1828 Attrs.addDereferenceableAttr(
1829 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1830 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1831 AI->getArgNo() + 1, Attrs));
1832 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1833 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1834 AI->getArgNo() + 1,
1835 llvm::Attribute::NonNull));
1836 }
1837 }
1838 } else if (const auto *ArrTy =
1839 getContext().getAsVariableArrayType(OTy)) {
1840 // For C99 VLAs with the static keyword, we don't know the size so
1841 // we can't use the dereferenceable attribute, but in addrspace(0)
1842 // we know that it must be nonnull.
1843 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1844 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1845 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1846 AI->getArgNo() + 1,
1847 llvm::Attribute::NonNull));
1848 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001849
1850 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1851 if (!AVAttr)
1852 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1853 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1854 if (AVAttr) {
1855 llvm::Value *AlignmentValue =
1856 EmitScalarExpr(AVAttr->getAlignment());
1857 llvm::ConstantInt *AlignmentCI =
1858 cast<llvm::ConstantInt>(AlignmentValue);
1859 unsigned Alignment =
1860 std::min((unsigned) AlignmentCI->getZExtValue(),
1861 +llvm::Value::MaximumAlignment);
1862
1863 llvm::AttrBuilder Attrs;
1864 Attrs.addAlignmentAttr(Alignment);
1865 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1866 AI->getArgNo() + 1, Attrs));
1867 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001868 }
1869
Bill Wendling507c3512012-10-16 05:23:44 +00001870 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001871 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1872 AI->getArgNo() + 1,
1873 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001874
Chris Lattner7369c142011-07-20 06:29:00 +00001875 // Ensure the argument is the correct type.
1876 if (V->getType() != ArgI.getCoerceToType())
1877 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1878
John McCalla738c252011-03-09 04:27:21 +00001879 if (isPromoted)
1880 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001881
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001882 if (const CXXMethodDecl *MD =
1883 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001884 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001885 V = CGM.getCXXABI().
1886 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001887 }
1888
Rafael Espindola8778c282012-11-29 16:09:03 +00001889 // Because of merging of function types from multiple decls it is
1890 // possible for the type of an argument to not match the corresponding
1891 // type in the function type. Since we are codegening the callee
1892 // in here, add a cast to the argument type.
1893 llvm::Type *LTy = ConvertType(Arg->getType());
1894 if (V->getType() != LTy)
1895 V = Builder.CreateBitCast(V, LTy);
1896
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001897 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001898 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001899 }
Mike Stump11289f42009-09-09 15:08:12 +00001900
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001901 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001902
Chris Lattnerff941a62010-07-28 18:24:28 +00001903 // The alignment we need to use is the max of the requested alignment for
1904 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001905 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001906 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001907 AlignmentToUse = std::max(AlignmentToUse,
1908 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001909
Chris Lattnerff941a62010-07-28 18:24:28 +00001910 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001911 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001912 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001913
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001914 // If the value is offset in memory, apply the offset now.
1915 if (unsigned Offs = ArgI.getDirectOffset()) {
1916 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1917 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001918 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001919 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1920 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001921
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001922 // Fast-isel and the optimizer generally like scalar values better than
1923 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001924 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001925 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1926 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001927 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001928 llvm::Type *DstTy =
1929 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001930 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001931
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001932 if (SrcSize <= DstSize) {
1933 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1934
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001935 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001936 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001937 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001938 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1939 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001940 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001941 }
1942 } else {
1943 llvm::AllocaInst *TempAlloca =
1944 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1945 TempAlloca->setAlignment(AlignmentToUse);
1946 llvm::Value *TempV = TempAlloca;
1947
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001948 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001949 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001950 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001951 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1952 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001953 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001954 }
1955
1956 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001957 }
1958 } else {
1959 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001960 assert(NumIRArgs == 1);
1961 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001962 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001963 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001964 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001965
1966
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001967 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001968 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001969 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001970 if (isPromoted)
1971 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001972 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1973 } else {
1974 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001975 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001976 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001977 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001978
1979 case ABIArgInfo::Expand: {
1980 // If this structure was expanded into multiple arguments then
1981 // we need to create a temporary and reconstruct it from the
1982 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001983 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001984 CharUnits Align = getContext().getDeclAlign(Arg);
1985 Alloca->setAlignment(Align.getQuantity());
1986 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001987 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001988
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001989 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1990 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1991 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1992 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1993 auto AI = FnArgs[FirstIRArg + i];
1994 AI->setName(Arg->getName() + "." + Twine(i));
1995 }
1996 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001997 }
1998
1999 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002000 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002001 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002002 if (!hasScalarEvaluationKind(Ty)) {
2003 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
2004 } else {
2005 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2006 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
2007 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002008 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002009 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002010 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002011
Reid Kleckner739756c2013-12-04 19:23:12 +00002012 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2013 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002014 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2015 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002016 } else {
2017 for (unsigned I = 0, E = Args.size(); I != E; ++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 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002021}
2022
John McCallffa2c1a2012-01-29 07:46:59 +00002023static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2024 while (insn->use_empty()) {
2025 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2026 if (!bitcast) return;
2027
2028 // This is "safe" because we would have used a ConstantExpr otherwise.
2029 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2030 bitcast->eraseFromParent();
2031 }
2032}
2033
John McCall31168b02011-06-15 23:02:42 +00002034/// Try to emit a fused autorelease of a return result.
2035static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2036 llvm::Value *result) {
2037 // We must be immediately followed the cast.
2038 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002039 if (BB->empty()) return nullptr;
2040 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002041
Chris Lattner2192fe52011-07-18 04:24:23 +00002042 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002043
2044 // result is in a BasicBlock and is therefore an Instruction.
2045 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2046
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002047 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002048
2049 // Look for:
2050 // %generator = bitcast %type1* %generator2 to %type2*
2051 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2052 // We would have emitted this as a constant if the operand weren't
2053 // an Instruction.
2054 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2055
2056 // Require the generator to be immediately followed by the cast.
2057 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002058 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002059
2060 insnsToKill.push_back(bitcast);
2061 }
2062
2063 // Look for:
2064 // %generator = call i8* @objc_retain(i8* %originalResult)
2065 // or
2066 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2067 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002068 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002069
2070 bool doRetainAutorelease;
2071
2072 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2073 doRetainAutorelease = true;
2074 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2075 .objc_retainAutoreleasedReturnValue) {
2076 doRetainAutorelease = false;
2077
John McCallcfa4e9b2012-09-07 23:30:50 +00002078 // If we emitted an assembly marker for this call (and the
2079 // ARCEntrypoints field should have been set if so), go looking
2080 // for that call. If we can't find it, we can't do this
2081 // optimization. But it should always be the immediately previous
2082 // instruction, unless we needed bitcasts around the call.
2083 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2084 llvm::Instruction *prev = call->getPrevNode();
2085 assert(prev);
2086 if (isa<llvm::BitCastInst>(prev)) {
2087 prev = prev->getPrevNode();
2088 assert(prev);
2089 }
2090 assert(isa<llvm::CallInst>(prev));
2091 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2092 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2093 insnsToKill.push_back(prev);
2094 }
John McCall31168b02011-06-15 23:02:42 +00002095 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002096 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002097 }
2098
2099 result = call->getArgOperand(0);
2100 insnsToKill.push_back(call);
2101
2102 // Keep killing bitcasts, for sanity. Note that we no longer care
2103 // about precise ordering as long as there's exactly one use.
2104 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2105 if (!bitcast->hasOneUse()) break;
2106 insnsToKill.push_back(bitcast);
2107 result = bitcast->getOperand(0);
2108 }
2109
2110 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002111 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002112 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2113 (*i)->eraseFromParent();
2114
2115 // Do the fused retain/autorelease if we were asked to.
2116 if (doRetainAutorelease)
2117 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2118
2119 // Cast back to the result type.
2120 return CGF.Builder.CreateBitCast(result, resultType);
2121}
2122
John McCallffa2c1a2012-01-29 07:46:59 +00002123/// If this is a +1 of the value of an immutable 'self', remove it.
2124static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2125 llvm::Value *result) {
2126 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002127 const ObjCMethodDecl *method =
2128 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002129 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002130 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002131 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002132
2133 // Look for a retain call.
2134 llvm::CallInst *retainCall =
2135 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2136 if (!retainCall ||
2137 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002138 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002139
2140 // Look for an ordinary load of 'self'.
2141 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2142 llvm::LoadInst *load =
2143 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2144 if (!load || load->isAtomic() || load->isVolatile() ||
2145 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002146 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002147
2148 // Okay! Burn it all down. This relies for correctness on the
2149 // assumption that the retain is emitted as part of the return and
2150 // that thereafter everything is used "linearly".
2151 llvm::Type *resultType = result->getType();
2152 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2153 assert(retainCall->use_empty());
2154 retainCall->eraseFromParent();
2155 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2156
2157 return CGF.Builder.CreateBitCast(load, resultType);
2158}
2159
John McCall31168b02011-06-15 23:02:42 +00002160/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002161///
2162/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002163static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2164 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002165 // If we're returning 'self', kill the initial retain. This is a
2166 // heuristic attempt to "encourage correctness" in the really unfortunate
2167 // case where we have a return of self during a dealloc and we desperately
2168 // need to avoid the possible autorelease.
2169 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2170 return self;
2171
John McCall31168b02011-06-15 23:02:42 +00002172 // At -O0, try to emit a fused retain/autorelease.
2173 if (CGF.shouldUseFusedARCCalls())
2174 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2175 return fused;
2176
2177 return CGF.EmitARCAutoreleaseReturnValue(result);
2178}
2179
John McCall6e1c0122012-01-29 02:35:02 +00002180/// Heuristically search for a dominating store to the return-value slot.
2181static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2182 // If there are multiple uses of the return-value slot, just check
2183 // for something immediately preceding the IP. Sometimes this can
2184 // happen with how we generate implicit-returns; it can also happen
2185 // with noreturn cleanups.
2186 if (!CGF.ReturnValue->hasOneUse()) {
2187 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002188 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002189 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002190 if (!store) return nullptr;
2191 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002192 assert(!store->isAtomic() && !store->isVolatile()); // see below
2193 return store;
2194 }
2195
2196 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002197 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002198 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002199
2200 // These aren't actually possible for non-coerced returns, and we
2201 // only care about non-coerced returns on this code path.
2202 assert(!store->isAtomic() && !store->isVolatile());
2203
2204 // Now do a first-and-dirty dominance check: just walk up the
2205 // single-predecessors chain from the current insertion point.
2206 llvm::BasicBlock *StoreBB = store->getParent();
2207 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2208 while (IP != StoreBB) {
2209 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002210 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002211 }
2212
2213 // Okay, the store's basic block dominates the insertion point; we
2214 // can do our thing.
2215 return store;
2216}
2217
Adrian Prantl3be10542013-05-02 17:30:20 +00002218void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002219 bool EmitRetDbgLoc,
2220 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002221 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2222 // Naked functions don't have epilogues.
2223 Builder.CreateUnreachable();
2224 return;
2225 }
2226
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002227 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002228 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002229 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002230 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002231 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002232
Dan Gohman481e40c2010-07-20 20:13:52 +00002233 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002234 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002235 QualType RetTy = FI.getReturnType();
2236 const ABIArgInfo &RetAI = FI.getReturnInfo();
2237
2238 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002239 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002240 // Aggregrates get evaluated directly into the destination. Sometimes we
2241 // need to return the sret value in a register, though.
2242 assert(hasAggregateEvaluationKind(RetTy));
2243 if (RetAI.getInAllocaSRet()) {
2244 llvm::Function::arg_iterator EI = CurFn->arg_end();
2245 --EI;
2246 llvm::Value *ArgStruct = EI;
2247 llvm::Value *SRet =
2248 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2249 RV = Builder.CreateLoad(SRet, "sret");
2250 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002251 break;
2252
Daniel Dunbar03816342010-08-21 02:24:36 +00002253 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002254 auto AI = CurFn->arg_begin();
2255 if (RetAI.isSRetAfterThis())
2256 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002257 switch (getEvaluationKind(RetTy)) {
2258 case TEK_Complex: {
2259 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002260 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2261 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002262 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002263 /*isInit*/ true);
2264 break;
2265 }
2266 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002267 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002268 break;
2269 case TEK_Scalar:
2270 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002271 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002272 /*isInit*/ true);
2273 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002274 }
2275 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002276 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002277
2278 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002279 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002280 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2281 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002282 // The internal return value temp always will have pointer-to-return-type
2283 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002284
John McCall6e1c0122012-01-29 02:35:02 +00002285 // If there is a dominating store to ReturnValue, we can elide
2286 // the load, zap the store, and usually zap the alloca.
2287 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002288 // Reuse the debug location from the store unless there is
2289 // cleanup code to be emitted between the store and return
2290 // instruction.
2291 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002292 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002293 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002294 RV = SI->getValueOperand();
2295 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002296
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002297 // If that was the only use of the return value, nuke it as well now.
2298 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2299 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002300 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002301 }
John McCall6e1c0122012-01-29 02:35:02 +00002302
2303 // Otherwise, we have to do a simple load.
2304 } else {
2305 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002306 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002307 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002308 llvm::Value *V = ReturnValue;
2309 // If the value is offset in memory, apply the offset now.
2310 if (unsigned Offs = RetAI.getDirectOffset()) {
2311 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2312 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002313 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002314 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2315 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002316
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002317 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002318 }
John McCall31168b02011-06-15 23:02:42 +00002319
2320 // In ARC, end functions that return a retainable type with a call
2321 // to objc_autoreleaseReturnValue.
2322 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002323 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002324 !FI.isReturnsRetained() &&
2325 RetTy->isObjCRetainableType());
2326 RV = emitAutoreleaseOfResult(*this, RV);
2327 }
2328
Chris Lattner726b3d02010-06-26 23:13:19 +00002329 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002330
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002331 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002332 break;
2333
2334 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002335 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002336 }
2337
Alexey Samsonovde443c52014-08-13 00:26:40 +00002338 llvm::Instruction *Ret;
2339 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002340 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002341 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2342 SanitizerScope SanScope(this);
2343 llvm::Value *Cond = Builder.CreateICmpNE(
2344 RV, llvm::Constant::getNullValue(RV->getType()));
2345 llvm::Constant *StaticData[] = {
2346 EmitCheckSourceLocation(EndLoc),
2347 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2348 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002349 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2350 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002351 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002352 }
2353 Ret = Builder.CreateRet(RV);
2354 } else {
2355 Ret = Builder.CreateRetVoid();
2356 }
2357
Devang Patel65497582010-07-21 18:08:50 +00002358 if (!RetDbgLoc.isUnknown())
Benjamin Kramer03278662015-02-07 13:15:54 +00002359 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002360}
2361
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002362static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2363 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2364 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2365}
2366
2367static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2368 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2369 // placeholders.
2370 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2371 llvm::Value *Placeholder =
2372 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2373 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2374 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2375 Ty.getQualifiers(),
2376 AggValueSlot::IsNotDestructed,
2377 AggValueSlot::DoesNotNeedGCBarriers,
2378 AggValueSlot::IsNotAliased);
2379}
2380
John McCall32ea9692011-03-11 20:59:21 +00002381void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002382 const VarDecl *param,
2383 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002384 // StartFunction converted the ABI-lowered parameter(s) into a
2385 // local alloca. We need to turn that into an r-value suitable
2386 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002387 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002388
John McCall32ea9692011-03-11 20:59:21 +00002389 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002390
John McCall23f66262010-05-26 22:34:26 +00002391 // For the most part, we just need to load the alloca, except:
2392 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002393 // 2) references to non-scalars are pointers directly to the aggregate.
2394 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002395 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002396 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002397 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002398
2399 // Locals which are references to scalars are represented
2400 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002401 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002402 }
2403
Reid Klecknerab2090d2014-07-26 01:34:32 +00002404 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2405 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002406
Nick Lewycky2d84e842013-10-02 02:29:49 +00002407 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002408}
2409
John McCall31168b02011-06-15 23:02:42 +00002410static bool isProvablyNull(llvm::Value *addr) {
2411 return isa<llvm::ConstantPointerNull>(addr);
2412}
2413
2414static bool isProvablyNonNull(llvm::Value *addr) {
2415 return isa<llvm::AllocaInst>(addr);
2416}
2417
2418/// Emit the actual writing-back of a writeback.
2419static void emitWriteback(CodeGenFunction &CGF,
2420 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002421 const LValue &srcLV = writeback.Source;
2422 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002423 assert(!isProvablyNull(srcAddr) &&
2424 "shouldn't have writeback for provably null argument");
2425
Craig Topper8a13c412014-05-21 05:09:00 +00002426 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002427
2428 // If the argument wasn't provably non-null, we need to null check
2429 // before doing the store.
2430 bool provablyNonNull = isProvablyNonNull(srcAddr);
2431 if (!provablyNonNull) {
2432 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2433 contBB = CGF.createBasicBlock("icr.done");
2434
2435 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2436 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2437 CGF.EmitBlock(writebackBB);
2438 }
2439
2440 // Load the value to writeback.
2441 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2442
2443 // Cast it back, in case we're writing an id to a Foo* or something.
2444 value = CGF.Builder.CreateBitCast(value,
2445 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2446 "icr.writeback-cast");
2447
2448 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002449
2450 // If we have a "to use" value, it's something we need to emit a use
2451 // of. This has to be carefully threaded in: if it's done after the
2452 // release it's potentially undefined behavior (and the optimizer
2453 // will ignore it), and if it happens before the retain then the
2454 // optimizer could move the release there.
2455 if (writeback.ToUse) {
2456 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2457
2458 // Retain the new value. No need to block-copy here: the block's
2459 // being passed up the stack.
2460 value = CGF.EmitARCRetainNonBlock(value);
2461
2462 // Emit the intrinsic use here.
2463 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2464
2465 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002466 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002467
2468 // Put the new value in place (primitively).
2469 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2470
2471 // Release the old value.
2472 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2473
2474 // Otherwise, we can just do a normal lvalue store.
2475 } else {
2476 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2477 }
John McCall31168b02011-06-15 23:02:42 +00002478
2479 // Jump to the continuation block.
2480 if (!provablyNonNull)
2481 CGF.EmitBlock(contBB);
2482}
2483
2484static void emitWritebacks(CodeGenFunction &CGF,
2485 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002486 for (const auto &I : args.writebacks())
2487 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002488}
2489
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002490static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2491 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002492 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002493 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2494 CallArgs.getCleanupsToDeactivate();
2495 // Iterate in reverse to increase the likelihood of popping the cleanup.
2496 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2497 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2498 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2499 I->IsActiveIP->eraseFromParent();
2500 }
2501}
2502
John McCalleff18842013-03-23 02:35:54 +00002503static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2504 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2505 if (uop->getOpcode() == UO_AddrOf)
2506 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002507 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002508}
2509
John McCall31168b02011-06-15 23:02:42 +00002510/// Emit an argument that's being passed call-by-writeback. That is,
2511/// we are passing the address of
2512static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2513 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002514 LValue srcLV;
2515
2516 // Make an optimistic effort to emit the address as an l-value.
2517 // This can fail if the the argument expression is more complicated.
2518 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2519 srcLV = CGF.EmitLValue(lvExpr);
2520
2521 // Otherwise, just emit it as a scalar.
2522 } else {
2523 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2524
2525 QualType srcAddrType =
2526 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2527 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2528 }
2529 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002530
2531 // The dest and src types don't necessarily match in LLVM terms
2532 // because of the crazy ObjC compatibility rules.
2533
Chris Lattner2192fe52011-07-18 04:24:23 +00002534 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002535 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2536
2537 // If the address is a constant null, just pass the appropriate null.
2538 if (isProvablyNull(srcAddr)) {
2539 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2540 CRE->getType());
2541 return;
2542 }
2543
John McCall31168b02011-06-15 23:02:42 +00002544 // Create the temporary.
2545 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2546 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002547 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2548 // and that cleanup will be conditional if we can't prove that the l-value
2549 // isn't null, so we need to register a dominating point so that the cleanups
2550 // system will make valid IR.
2551 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2552
John McCall31168b02011-06-15 23:02:42 +00002553 // Zero-initialize it if we're not doing a copy-initialization.
2554 bool shouldCopy = CRE->shouldCopy();
2555 if (!shouldCopy) {
2556 llvm::Value *null =
2557 llvm::ConstantPointerNull::get(
2558 cast<llvm::PointerType>(destType->getElementType()));
2559 CGF.Builder.CreateStore(null, temp);
2560 }
Craig Topper8a13c412014-05-21 05:09:00 +00002561
2562 llvm::BasicBlock *contBB = nullptr;
2563 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002564
2565 // If the address is *not* known to be non-null, we need to switch.
2566 llvm::Value *finalArgument;
2567
2568 bool provablyNonNull = isProvablyNonNull(srcAddr);
2569 if (provablyNonNull) {
2570 finalArgument = temp;
2571 } else {
2572 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2573
2574 finalArgument = CGF.Builder.CreateSelect(isNull,
2575 llvm::ConstantPointerNull::get(destType),
2576 temp, "icr.argument");
2577
2578 // If we need to copy, then the load has to be conditional, which
2579 // means we need control flow.
2580 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002581 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002582 contBB = CGF.createBasicBlock("icr.cont");
2583 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2584 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2585 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002586 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002587 }
2588 }
2589
Craig Topper8a13c412014-05-21 05:09:00 +00002590 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002591
John McCall31168b02011-06-15 23:02:42 +00002592 // Perform a copy if necessary.
2593 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002594 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002595 assert(srcRV.isScalar());
2596
2597 llvm::Value *src = srcRV.getScalarVal();
2598 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2599 "icr.cast");
2600
2601 // Use an ordinary store, not a store-to-lvalue.
2602 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002603
2604 // If optimization is enabled, and the value was held in a
2605 // __strong variable, we need to tell the optimizer that this
2606 // value has to stay alive until we're doing the store back.
2607 // This is because the temporary is effectively unretained,
2608 // and so otherwise we can violate the high-level semantics.
2609 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2610 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2611 valueToUse = src;
2612 }
John McCall31168b02011-06-15 23:02:42 +00002613 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002614
John McCall31168b02011-06-15 23:02:42 +00002615 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002616 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002617 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002618 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002619
2620 // Make a phi for the value to intrinsically use.
2621 if (valueToUse) {
2622 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2623 "icr.to-use");
2624 phiToUse->addIncoming(valueToUse, copyBB);
2625 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2626 originBB);
2627 valueToUse = phiToUse;
2628 }
2629
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002630 condEval.end(CGF);
2631 }
John McCall31168b02011-06-15 23:02:42 +00002632
John McCalleff18842013-03-23 02:35:54 +00002633 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002634 args.add(RValue::get(finalArgument), CRE->getType());
2635}
2636
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002637void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2638 assert(!StackBase && !StackCleanup.isValid());
2639
2640 // Save the stack.
2641 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2642 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2643
2644 // Control gets really tied up in landing pads, so we have to spill the
2645 // stacksave to an alloca to avoid violating SSA form.
2646 // TODO: This is dead if we never emit the cleanup. We should create the
2647 // alloca and store lazily on the first cleanup emission.
2648 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2649 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2650 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2651 StackCleanup = CGF.EHStack.getInnermostEHScope();
2652 assert(StackCleanup.isValid());
2653}
2654
2655void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2656 if (StackBase) {
2657 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2658 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2659 // We could load StackBase from StackBaseMem, but in the non-exceptional
2660 // case we can skip it.
2661 CGF.Builder.CreateCall(F, StackBase);
2662 }
2663}
2664
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002665static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2666 QualType ArgType, SourceLocation ArgLoc,
2667 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002668 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002669 return;
2670 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2671 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2672 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2673 if (!NNAttr)
2674 return;
2675 CodeGenFunction::SanitizerScope SanScope(&CGF);
2676 assert(RV.isScalar());
2677 llvm::Value *V = RV.getScalarVal();
2678 llvm::Value *Cond =
2679 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2680 llvm::Constant *StaticData[] = {
2681 CGF.EmitCheckSourceLocation(ArgLoc),
2682 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2683 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2684 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002685 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2686 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002687}
2688
Reid Kleckner739756c2013-12-04 19:23:12 +00002689void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2690 ArrayRef<QualType> ArgTypes,
2691 CallExpr::const_arg_iterator ArgBeg,
2692 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002693 const FunctionDecl *CalleeDecl,
David Blaikie835afb22015-01-21 23:08:17 +00002694 unsigned ParamsToSkip) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002695 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2696 // because arguments are destroyed left to right in the callee.
2697 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002698 // Insert a stack save if we're going to need any inalloca args.
2699 bool HasInAllocaArgs = false;
2700 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2701 I != E && !HasInAllocaArgs; ++I)
2702 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2703 if (HasInAllocaArgs) {
2704 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2705 Args.allocateArgumentMemory(*this);
2706 }
2707
2708 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002709 size_t CallArgsStart = Args.size();
2710 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2711 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2712 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002713 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2714 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002715 }
2716
2717 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2718 // IR function.
2719 std::reverse(Args.begin() + CallArgsStart, Args.end());
2720 return;
2721 }
2722
2723 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2724 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2725 assert(Arg != ArgEnd);
2726 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002727 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2728 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002729 }
2730}
2731
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002732namespace {
2733
2734struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2735 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2736 : Addr(Addr), Ty(Ty) {}
2737
2738 llvm::Value *Addr;
2739 QualType Ty;
2740
Craig Topper4f12f102014-03-12 06:41:41 +00002741 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002742 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2743 assert(!Dtor->isTrivial());
2744 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2745 /*Delegating=*/false, Addr);
2746 }
2747};
2748
2749}
2750
David Blaikie38b25912015-02-09 19:13:51 +00002751struct DisableDebugLocationUpdates {
2752 CodeGenFunction &CGF;
2753 bool disabledDebugInfo;
2754 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2755 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2756 CGF.disableDebugInfo();
2757 }
2758 ~DisableDebugLocationUpdates() {
2759 if (disabledDebugInfo)
2760 CGF.enableDebugInfo();
2761 }
2762};
2763
John McCall32ea9692011-03-11 20:59:21 +00002764void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2765 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002766 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002767 if (const ObjCIndirectCopyRestoreExpr *CRE
2768 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002769 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002770 assert(getContext().hasSameType(E->getType(), type));
2771 return emitWritebackArg(*this, args, CRE);
2772 }
2773
John McCall0a76c0c2011-08-26 18:42:59 +00002774 assert(type->isReferenceType() == E->isGLValue() &&
2775 "reference binding to unmaterialized r-value!");
2776
John McCall17054bd62011-08-26 21:08:13 +00002777 if (E->isGLValue()) {
2778 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002779 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002782 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2783
2784 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2785 // However, we still have to push an EH-only cleanup in case we unwind before
2786 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002787 if (HasAggregateEvalKind &&
2788 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2789 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002790 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002791 AggValueSlot Slot;
2792 if (args.isUsingInAlloca())
2793 Slot = createPlaceholderSlot(*this, type);
2794 else
2795 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002796
2797 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2798 bool DestroyedInCallee =
2799 RD && RD->hasNonTrivialDestructor() &&
2800 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2801 if (DestroyedInCallee)
2802 Slot.setExternallyDestructed();
2803
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002804 EmitAggExpr(E, Slot);
2805 RValue RV = Slot.asRValue();
2806 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002807
Reid Klecknere39ee212014-05-03 00:33:28 +00002808 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002809 // Create a no-op GEP between the placeholder and the cleanup so we can
2810 // RAUW it successfully. It also serves as a marker of the first
2811 // instruction where the cleanup is active.
2812 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002813 // This unreachable is a temporary marker which will be removed later.
2814 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2815 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002816 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002817 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002818 }
2819
2820 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002821 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2822 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2823 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002824 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2825 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2826 } else {
2827 // We can't represent a misaligned lvalue in the CallArgList, so copy
2828 // to an aligned temporary now.
2829 llvm::Value *tmp = CreateMemTemp(type);
2830 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2831 L.getAlignment());
2832 args.add(RValue::getAggregate(tmp), type);
2833 }
Eli Friedmandf968192011-05-26 00:10:27 +00002834 return;
2835 }
2836
John McCall32ea9692011-03-11 20:59:21 +00002837 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002838}
2839
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002840QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2841 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2842 // implicitly widens null pointer constants that are arguments to varargs
2843 // functions to pointer-sized ints.
2844 if (!getTarget().getTriple().isOSWindows())
2845 return Arg->getType();
2846
2847 if (Arg->getType()->isIntegerType() &&
2848 getContext().getTypeSize(Arg->getType()) <
2849 getContext().getTargetInfo().getPointerWidth(0) &&
2850 Arg->isNullPointerConstant(getContext(),
2851 Expr::NPC_ValueDependentIsNotNull)) {
2852 return getContext().getIntPtrType();
2853 }
2854
2855 return Arg->getType();
2856}
2857
Dan Gohman515a60d2012-02-16 00:57:37 +00002858// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2859// optimizer it can aggressively ignore unwind edges.
2860void
2861CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2862 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2863 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2864 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2865 CGM.getNoObjCARCExceptionsMetadata());
2866}
2867
John McCall882987f2013-02-28 19:01:20 +00002868/// Emits a call to the given no-arguments nounwind runtime function.
2869llvm::CallInst *
2870CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2871 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002872 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002873}
2874
2875/// Emits a call to the given nounwind runtime function.
2876llvm::CallInst *
2877CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2878 ArrayRef<llvm::Value*> args,
2879 const llvm::Twine &name) {
2880 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2881 call->setDoesNotThrow();
2882 return call;
2883}
2884
2885/// Emits a simple call (never an invoke) to the given no-arguments
2886/// runtime function.
2887llvm::CallInst *
2888CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2889 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002890 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002891}
2892
2893/// Emits a simple call (never an invoke) to the given runtime
2894/// function.
2895llvm::CallInst *
2896CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2897 ArrayRef<llvm::Value*> args,
2898 const llvm::Twine &name) {
2899 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2900 call->setCallingConv(getRuntimeCC());
2901 return call;
2902}
2903
2904/// Emits a call or invoke to the given noreturn runtime function.
2905void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2906 ArrayRef<llvm::Value*> args) {
2907 if (getInvokeDest()) {
2908 llvm::InvokeInst *invoke =
2909 Builder.CreateInvoke(callee,
2910 getUnreachableBlock(),
2911 getInvokeDest(),
2912 args);
2913 invoke->setDoesNotReturn();
2914 invoke->setCallingConv(getRuntimeCC());
2915 } else {
2916 llvm::CallInst *call = Builder.CreateCall(callee, args);
2917 call->setDoesNotReturn();
2918 call->setCallingConv(getRuntimeCC());
2919 Builder.CreateUnreachable();
2920 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002921 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002922}
2923
2924/// Emits a call or invoke instruction to the given nullary runtime
2925/// function.
2926llvm::CallSite
2927CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2928 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002929 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002930}
2931
2932/// Emits a call or invoke instruction to the given runtime function.
2933llvm::CallSite
2934CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2935 ArrayRef<llvm::Value*> args,
2936 const Twine &name) {
2937 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2938 callSite.setCallingConv(getRuntimeCC());
2939 return callSite;
2940}
2941
2942llvm::CallSite
2943CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2944 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002945 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002946}
2947
John McCallbd309292010-07-06 01:34:17 +00002948/// Emits a call or invoke instruction to the given function, depending
2949/// on the current state of the EH stack.
2950llvm::CallSite
2951CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002952 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002953 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002954 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002955
Dan Gohman515a60d2012-02-16 00:57:37 +00002956 llvm::Instruction *Inst;
2957 if (!InvokeDest)
2958 Inst = Builder.CreateCall(Callee, Args, Name);
2959 else {
2960 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2961 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2962 EmitBlock(ContBB);
2963 }
2964
2965 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2966 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002967 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002968 AddObjCARCExceptionMetadata(Inst);
2969
2970 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002971}
2972
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002973/// \brief Store a non-aggregate value to an address to initialize it. For
2974/// initialization, a non-atomic store will be used.
2975static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2976 LValue Dst) {
2977 if (Src.isScalar())
2978 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2979 else
2980 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2981}
2982
2983void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2984 llvm::Value *New) {
2985 DeferredReplacements.push_back(std::make_pair(Old, New));
2986}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002987
Daniel Dunbard931a872009-02-02 22:03:45 +00002988RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002989 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002990 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002991 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002992 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002993 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002994 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002995
2996 // Handle struct-return functions by passing a pointer to the
2997 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002998 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002999 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003000
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003001 llvm::FunctionType *IRFuncTy =
3002 cast<llvm::FunctionType>(
3003 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003004
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003005 // If we're using inalloca, insert the allocation after the stack save.
3006 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00003007 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003008 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00003009 llvm::Instruction *IP = CallArgs.getStackBase();
3010 llvm::AllocaInst *AI;
3011 if (IP) {
3012 IP = IP->getNextNode();
3013 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3014 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003015 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003016 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003017 AI->setUsedWithInAlloca(true);
3018 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3019 ArgMemory = AI;
3020 }
3021
Alexey Samsonov153004f2014-09-29 22:08:00 +00003022 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003023 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3024
Chris Lattner4ca97c32009-06-13 00:26:38 +00003025 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003026 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00003027 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003028 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003029 SRetPtr = ReturnValue.getValue();
3030 if (!SRetPtr)
3031 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003032 if (IRFunctionArgs.hasSRetArg()) {
3033 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003034 } else {
3035 llvm::Value *Addr =
3036 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3037 Builder.CreateStore(SRetPtr, Addr);
3038 }
Anders Carlsson17490832009-12-24 20:40:36 +00003039 }
Mike Stump11289f42009-09-09 15:08:12 +00003040
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003041 assert(CallInfo.arg_size() == CallArgs.size() &&
3042 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003043 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003044 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003045 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003046 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003047 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003048 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003049
John McCall47fb9502013-03-07 21:37:08 +00003050 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003051
3052 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003053 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3054 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3055 llvm::UndefValue::get(ArgInfo.getPaddingType());
3056
3057 unsigned FirstIRArg, NumIRArgs;
3058 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003059
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003060 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003061 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003062 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003063 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3064 if (RV.isAggregate()) {
3065 // Replace the placeholder with the appropriate argument slot GEP.
3066 llvm::Instruction *Placeholder =
3067 cast<llvm::Instruction>(RV.getAggregateAddr());
3068 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3069 Builder.SetInsertPoint(Placeholder);
3070 llvm::Value *Addr = Builder.CreateStructGEP(
3071 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3072 Builder.restoreIP(IP);
3073 deferPlaceholderReplacement(Placeholder, Addr);
3074 } else {
3075 // Store the RValue into the argument struct.
3076 llvm::Value *Addr =
3077 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003078 unsigned AS = Addr->getType()->getPointerAddressSpace();
3079 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3080 // There are some cases where a trivial bitcast is not avoidable. The
3081 // definition of a type later in a translation unit may change it's type
3082 // from {}* to (%struct.foo*)*.
3083 if (Addr->getType() != MemType)
3084 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003085 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3086 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3087 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003088 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003089 }
3090
Daniel Dunbar03816342010-08-21 02:24:36 +00003091 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003092 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003093 if (RV.isScalar() || RV.isComplex()) {
3094 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003095 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3096 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3097 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003098 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003099
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003100 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003101 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003102 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003103 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003104 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003105 // 1. If the argument is not byval, and we are required to copy the
3106 // source. (This case doesn't occur on any common architecture.)
3107 // 2. If the argument is byval, RV is not sufficiently aligned, and
3108 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003109 // 3. If the argument is byval, but RV is located in an address space
3110 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003111 llvm::Value *Addr = RV.getAggregateAddr();
3112 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003113 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003114 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003115 const unsigned ArgAddrSpace =
3116 (FirstIRArg < IRFuncTy->getNumParams()
3117 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3118 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003119 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003120 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Mehdi Aminib3d52092015-03-10 02:36:43 +00003121 llvm::getOrEnforceKnownAlignment(Addr, Align, *TD) < Align) ||
3122 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003123 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003124 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3125 if (Align > AI->getAlignment())
3126 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003127 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003128 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003129 } else {
3130 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003131 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003132 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003133 }
3134 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003135 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003136
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003137 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003138 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003139 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003140
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003141 case ABIArgInfo::Extend:
3142 case ABIArgInfo::Direct: {
3143 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003144 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3145 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003146 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003147 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003148 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003149 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003150 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003151 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003152
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003153 // We might have to widen integers, but we should never truncate.
3154 if (ArgInfo.getCoerceToType() != V->getType() &&
3155 V->getType()->isIntegerTy())
3156 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3157
Chris Lattner3ce86682011-07-12 04:53:39 +00003158 // If the argument doesn't match, perform a bitcast to coerce it. This
3159 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003160 if (FirstIRArg < IRFuncTy->getNumParams() &&
3161 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3162 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3163 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003164 break;
3165 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003166
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003167 // FIXME: Avoid the conversion through memory if possible.
3168 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003169 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003170 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003171 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003172 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003173 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003174 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003175
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003176 // If the value is offset in memory, apply the offset now.
3177 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3178 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3179 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003180 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003181 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3182
3183 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003184
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003185 // Fast-isel and the optimizer generally like scalar values better than
3186 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003187 llvm::StructType *STy =
3188 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003189 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003190 llvm::Type *SrcTy =
3191 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3192 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3193 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3194
3195 // If the source type is smaller than the destination type of the
3196 // coerce-to logic, copy the source value into a temp alloca the size
3197 // of the destination type to allow loading all of it. The bits past
3198 // the source value are left undef.
3199 if (SrcSize < DstSize) {
3200 llvm::AllocaInst *TempAlloca
3201 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3202 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3203 SrcPtr = TempAlloca;
3204 } else {
3205 SrcPtr = Builder.CreateBitCast(SrcPtr,
3206 llvm::PointerType::getUnqual(STy));
3207 }
3208
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003209 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3211 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003212 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3213 // We don't know what we're loading from.
3214 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003215 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003216 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003217 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003218 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003219 assert(NumIRArgs == 1);
3220 IRCallArgs[FirstIRArg] =
3221 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003222 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003223
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003224 break;
3225 }
3226
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003227 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003228 unsigned IRArgPos = FirstIRArg;
3229 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3230 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003231 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003232 }
3233 }
Mike Stump11289f42009-09-09 15:08:12 +00003234
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003235 if (ArgMemory) {
3236 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003237 if (CallInfo.isVariadic()) {
3238 // When passing non-POD arguments by value to variadic functions, we will
3239 // end up with a variadic prototype and an inalloca call site. In such
3240 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3241 // the callee.
3242 unsigned CalleeAS =
3243 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3244 Callee = Builder.CreateBitCast(
3245 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3246 } else {
3247 llvm::Type *LastParamTy =
3248 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3249 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003250#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003251 // Assert that these structs have equivalent element types.
3252 llvm::StructType *FullTy = CallInfo.getArgStruct();
3253 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3254 cast<llvm::PointerType>(LastParamTy)->getElementType());
3255 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3256 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3257 DE = DeclaredTy->element_end(),
3258 FI = FullTy->element_begin();
3259 DI != DE; ++DI, ++FI)
3260 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003261#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003262 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3263 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003264 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003265 assert(IRFunctionArgs.hasInallocaArg());
3266 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003267 }
3268
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003269 if (!CallArgs.getCleanupsToDeactivate().empty())
3270 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3271
Chris Lattner4ca97c32009-06-13 00:26:38 +00003272 // If the callee is a bitcast of a function to a varargs pointer to function
3273 // type, check to see if we can remove the bitcast. This handles some cases
3274 // with unprototyped functions.
3275 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3276 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003277 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3278 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003279 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003280 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003281
Chris Lattner4ca97c32009-06-13 00:26:38 +00003282 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3283 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003284 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003285 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003286 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003287 bool ArgsMatch = true;
3288 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3289 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3290 ArgsMatch = false;
3291 break;
3292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Chris Lattner4ca97c32009-06-13 00:26:38 +00003294 // Strip the cast if we can get away with it. This is a nice cleanup,
3295 // but also allows us to inline the function at -O0 if it is marked
3296 // always_inline.
3297 if (ArgsMatch)
3298 Callee = CalleeF;
3299 }
3300 }
Mike Stump11289f42009-09-09 15:08:12 +00003301
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003302 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3303 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3304 // Inalloca argument can have different type.
3305 if (IRFunctionArgs.hasInallocaArg() &&
3306 i == IRFunctionArgs.getInallocaArgNo())
3307 continue;
3308 if (i < IRFuncTy->getNumParams())
3309 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3310 }
3311
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003312 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003313 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003314 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3315 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003316 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003317 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003318
Craig Topper8a13c412014-05-21 05:09:00 +00003319 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003320 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00003321 llvm::Attribute::NoUnwind) ||
3322 currentFunctionUsesSEHTry())
John McCallbd309292010-07-06 01:34:17 +00003323 InvokeDest = getInvokeDest();
3324
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003325 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003326 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003327 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003328 } else {
3329 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003330 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003331 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003332 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003333 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003334 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003335
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003336 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3337 !CS.hasFnAttr(llvm::Attribute::NoInline))
3338 Attrs =
3339 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3340 llvm::Attribute::AlwaysInline);
3341
Reid Klecknera5930002015-02-11 21:40:48 +00003342 // Disable inlining inside SEH __try blocks.
Reid Kleckner11c033e2015-02-12 23:40:45 +00003343 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003344 Attrs =
3345 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3346 llvm::Attribute::NoInline);
3347
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003348 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003349 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003350
Dan Gohman515a60d2012-02-16 00:57:37 +00003351 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3352 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003353 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003354 AddObjCARCExceptionMetadata(CS.getInstruction());
3355
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003356 // If the call doesn't return, finish the basic block and clear the
3357 // insertion point; this allows the rest of IRgen to discard
3358 // unreachable code.
3359 if (CS.doesNotReturn()) {
3360 Builder.CreateUnreachable();
3361 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003362
Mike Stump18bb9282009-05-16 07:57:57 +00003363 // FIXME: For now, emit a dummy basic block because expr emitters in
3364 // generally are not ready to handle emitting expressions at unreachable
3365 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003366 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003367
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003368 // Return a reasonable RValue.
3369 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003370 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003371
3372 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003373 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003374 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003375
John McCall31168b02011-06-15 23:02:42 +00003376 // Emit any writebacks immediately. Arguably this should happen
3377 // after any return-value munging.
3378 if (CallArgs.hasWritebacks())
3379 emitWritebacks(*this, CallArgs);
3380
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003381 // The stack cleanup for inalloca arguments has to run out of the normal
3382 // lexical order, so deactivate it and run it manually here.
3383 CallArgs.freeArgumentMemory(*this);
3384
Hal Finkelee90a222014-09-26 05:04:30 +00003385 RValue Ret = [&] {
3386 switch (RetAI.getKind()) {
3387 case ABIArgInfo::InAlloca:
3388 case ABIArgInfo::Indirect:
3389 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003390
Hal Finkelee90a222014-09-26 05:04:30 +00003391 case ABIArgInfo::Ignore:
3392 // If we are ignoring an argument that had a result, make sure to
3393 // construct the appropriate return value for our caller.
3394 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003395
Hal Finkelee90a222014-09-26 05:04:30 +00003396 case ABIArgInfo::Extend:
3397 case ABIArgInfo::Direct: {
3398 llvm::Type *RetIRTy = ConvertType(RetTy);
3399 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3400 switch (getEvaluationKind(RetTy)) {
3401 case TEK_Complex: {
3402 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3403 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3404 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003405 }
Hal Finkelee90a222014-09-26 05:04:30 +00003406 case TEK_Aggregate: {
3407 llvm::Value *DestPtr = ReturnValue.getValue();
3408 bool DestIsVolatile = ReturnValue.isVolatile();
3409
3410 if (!DestPtr) {
3411 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3412 DestIsVolatile = false;
3413 }
3414 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3415 return RValue::getAggregate(DestPtr);
3416 }
3417 case TEK_Scalar: {
3418 // If the argument doesn't match, perform a bitcast to coerce it. This
3419 // can happen due to trivial type mismatches.
3420 llvm::Value *V = CI;
3421 if (V->getType() != RetIRTy)
3422 V = Builder.CreateBitCast(V, RetIRTy);
3423 return RValue::get(V);
3424 }
3425 }
3426 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003427 }
Hal Finkelee90a222014-09-26 05:04:30 +00003428
3429 llvm::Value *DestPtr = ReturnValue.getValue();
3430 bool DestIsVolatile = ReturnValue.isVolatile();
3431
3432 if (!DestPtr) {
3433 DestPtr = CreateMemTemp(RetTy, "coerce");
3434 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003435 }
Hal Finkelee90a222014-09-26 05:04:30 +00003436
3437 // If the value is offset in memory, apply the offset now.
3438 llvm::Value *StorePtr = DestPtr;
3439 if (unsigned Offs = RetAI.getDirectOffset()) {
3440 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3441 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3442 StorePtr = Builder.CreateBitCast(StorePtr,
3443 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003444 }
Hal Finkelee90a222014-09-26 05:04:30 +00003445 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3446
3447 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003448 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003449
Hal Finkelee90a222014-09-26 05:04:30 +00003450 case ABIArgInfo::Expand:
3451 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003452 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003453
Hal Finkelee90a222014-09-26 05:04:30 +00003454 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3455 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003456
Hal Finkelee90a222014-09-26 05:04:30 +00003457 if (Ret.isScalar() && TargetDecl) {
3458 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3459 llvm::Value *OffsetValue = nullptr;
3460 if (const auto *Offset = AA->getOffset())
3461 OffsetValue = EmitScalarExpr(Offset);
3462
3463 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3464 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3465 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3466 OffsetValue);
3467 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003468 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003469
Hal Finkelee90a222014-09-26 05:04:30 +00003470 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003471}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003472
3473/* VarArg handling */
3474
3475llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3476 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3477}