blob: 7e6fef9edff5d3db0e119ef6cf07788d6c58306c [file] [log] [blame]
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar0dbe2272008-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 Lattnerce933992010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCallde5d3c72012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Lacey8b549992013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070029#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070032#include "llvm/IR/Intrinsics.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCall04a67a62010-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 Gregorf813a2c2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davise8519c32013-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 Korobeynikov414d8962011-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 Benyei38980082012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Stephen Hines176edba2014-12-01 14:53:08 -080050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
53 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Stephen Hines0e2c34f2015-03-23 12:09:02 -070054 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
55 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCall04a67a62010-02-05 21:31:56 +000056 }
57}
58
John McCall0b0ef0a2010-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 McCallead608a2010-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 Dunbar45c25ba2008-09-10 04:01:49 +000065}
66
John McCall0b0ef0a2010-02-24 07:14:12 +000067/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000068static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
69 return MD->getType()->getCanonicalTypeUnqualified()
70 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-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 McCallead608a2010-02-26 00:48:12 +000077static CanQualType GetReturnType(QualType RetTy) {
78 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000079}
80
John McCall0f3d0972012-07-07 06:41:13 +000081/// Arrange the argument and result information for a value of the given
82/// unprototyped freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +000083const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +000084CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCallde5d3c72012-02-17 03:33:10 +000085 // When translating an unprototyped function type, always use a
86 // variadic type.
Stephen Hines651f13c2014-04-23 16:59:28 -070087 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -070088 /*instanceMethod=*/false,
89 /*chainCall=*/false, None,
90 FTNP->getExtInfo(), RequiredArgs(0));
John McCall0b0ef0a2010-02-24 07:14:12 +000091}
92
John McCall0f3d0972012-07-07 06:41:13 +000093/// Arrange the LLVM function layout for a value of the given function
Stephen Hines176edba2014-12-01 14:53:08 -080094/// type, on top of any implicit parameters already stored.
95static const CGFunctionInfo &
Stephen Hines0e2c34f2015-03-23 12:09:02 -070096arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Stephen Hines176edba2014-12-01 14:53:08 -080097 SmallVectorImpl<CanQualType> &prefix,
98 CanQual<FunctionProtoType> FTP) {
John McCall0f3d0972012-07-07 06:41:13 +000099 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000100 // FIXME: Kill copy.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700101 prefix.append(FTP->param_type_begin(), FTP->param_type_end());
Stephen Hines651f13c2014-04-23 16:59:28 -0700102 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700103 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
104 /*chainCall=*/false, prefix,
Stephen Hines176edba2014-12-01 14:53:08 -0800105 FTP->getExtInfo(), required);
John McCall0b0ef0a2010-02-24 07:14:12 +0000106}
107
John McCallde5d3c72012-02-17 03:33:10 +0000108/// Arrange the argument and result information for a value of the
John McCall0f3d0972012-07-07 06:41:13 +0000109/// given freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +0000110const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000111CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCallde5d3c72012-02-17 03:33:10 +0000112 SmallVector<CanQualType, 16> argTypes;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700113 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
114 FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000115}
116
Stephen Hines651f13c2014-04-23 16:59:28 -0700117static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000118 // Set the appropriate calling convention for the Function.
119 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000120 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000121
122 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000123 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000124
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000125 if (D->hasAttr<ThisCallAttr>())
126 return CC_X86ThisCall;
127
Stephen Hines176edba2014-12-01 14:53:08 -0800128 if (D->hasAttr<VectorCallAttr>())
129 return CC_X86VectorCall;
130
Dawn Perchik52fc3142010-09-03 01:29:35 +0000131 if (D->hasAttr<PascalAttr>())
132 return CC_X86Pascal;
133
Anton Korobeynikov414d8962011-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 Benyei38980082012-12-25 08:53:55 +0000137 if (D->hasAttr<IntelOclBiccAttr>())
138 return CC_IntelOclBicc;
139
Stephen Hines651f13c2014-04-23 16:59:28 -0700140 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 McCall04a67a62010-02-05 21:31:56 +0000146 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000147}
148
John McCallde5d3c72012-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 Iskhodzhanov8f189a92013-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 McCallde5d3c72012-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 McCall0b0ef0a2010-02-24 07:14:12 +0000159
Anders Carlsson375c31c2009-10-03 19:43:08 +0000160 // Add the 'this' pointer.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000161 if (RD)
162 argTypes.push_back(GetThisType(Context, RD));
163 else
164 argTypes.push_back(Context.VoidPtrTy);
John McCall0b0ef0a2010-02-24 07:14:12 +0000165
Stephen Hines176edba2014-12-01 14:53:08 -0800166 return ::arrangeLLVMFunctionInfo(
167 *this, true, argTypes,
168 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000169}
170
John McCallde5d3c72012-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 Kramere5753592013-09-09 14:48:42 +0000177 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCallfc400282010-09-03 01:26:39 +0000178 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
179
John McCallde5d3c72012-02-17 03:33:10 +0000180 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
John McCallde5d3c72012-02-17 03:33:10 +0000182 if (MD->isInstance()) {
183 // The abstract case is perfectly fine.
Mark Lacey25296602013-10-02 20:35:23 +0000184 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000185 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCallde5d3c72012-02-17 03:33:10 +0000186 }
187
John McCall0f3d0972012-07-07 06:41:13 +0000188 return arrangeFreeFunctionType(prototype);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000189}
190
John McCallde5d3c72012-02-17 03:33:10 +0000191const CGFunctionInfo &
Stephen Hines176edba2014-12-01 14:53:08 -0800192CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
193 StructorType Type) {
194
John McCallde5d3c72012-02-17 03:33:10 +0000195 SmallVector<CanQualType, 16> argTypes;
Stephen Hines176edba2014-12-01 14:53:08 -0800196 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000197
Stephen Hines176edba2014-12-01 14:53:08 -0800198 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 Carlssonf6c56e22009-11-25 03:15:49 +0000205
Stephen Hines176edba2014-12-01 14:53:08 -0800206 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall4c40d982010-08-31 07:33:07 +0000207
208 // Add the formal parameters.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700209 argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
Stephen Hines651f13c2014-04-23 16:59:28 -0700210
Stephen Hines176edba2014-12-01 14:53:08 -0800211 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Stephen Hines651f13c2014-04-23 16:59:28 -0700212
213 RequiredArgs required =
Stephen Hines176edba2014-12-01 14:53:08 -0800214 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
John McCall4c40d982010-08-31 07:33:07 +0000215
John McCall0f3d0972012-07-07 06:41:13 +0000216 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Stephen Hines176edba2014-12-01 14:53:08 -0800217 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
218 ? argTypes.front()
219 : TheCXXABI.hasMostDerivedReturn(GD)
220 ? CGM.getContext().VoidPtrTy
221 : Context.VoidTy;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700222 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
223 /*chainCall=*/false, argTypes, extInfo,
224 required);
Stephen Hines651f13c2014-04-23 16:59:28 -0700225}
226
227/// 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;
Stephen Hines176edba2014-12-01 14:53:08 -0800235 for (const auto &Arg : args)
236 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Stephen Hines651f13c2014-04-23 16:59:28 -0700237
238 CanQual<FunctionProtoType> FPT = GetFormalType(D);
239 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
240 GlobalDecl GD(D, CtorKind);
Stephen Hines176edba2014-12-01 14:53:08 -0800241 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
242 ? ArgTypes.front()
243 : TheCXXABI.hasMostDerivedReturn(GD)
244 ? CGM.getContext().VoidPtrTy
245 : Context.VoidTy;
Stephen Hines651f13c2014-04-23 16:59:28 -0700246
247 FunctionType::ExtInfo Info = FPT->getExtInfo();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700248 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
249 /*chainCall=*/false, ArgTypes, Info,
250 Required);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000251}
252
John McCallde5d3c72012-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 Lattner3eb67ca2009-05-12 20:27:19 +0000257 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000258 if (MD->isInstance())
John McCallde5d3c72012-02-17 03:33:10 +0000259 return arrangeCXXMethodDeclaration(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
John McCallead608a2010-02-26 00:48:12 +0000261 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCallde5d3c72012-02-17 03:33:10 +0000262
John McCallead608a2010-02-26 00:48:12 +0000263 assert(isa<FunctionType>(FTy));
John McCallde5d3c72012-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>();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700269 return arrangeLLVMFunctionInfo(
270 noProto->getReturnType(), /*instanceMethod=*/false,
271 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000272 }
273
John McCallead608a2010-02-26 00:48:12 +0000274 assert(isa<FunctionProtoType>(FTy));
John McCall0f3d0972012-07-07 06:41:13 +0000275 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000276}
277
John McCallde5d3c72012-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 Dunbar541b63b2009-02-02 23:23:47 +0000299 // FIXME: Kill copy?
Stephen Hines651f13c2014-04-23 16:59:28 -0700300 for (const auto *I : MD->params()) {
301 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall0b0ef0a2010-02-24 07:14:12 +0000302 }
John McCallf85e1932011-06-15 23:02:42 +0000303
304 FunctionType::ExtInfo einfo;
Stephen Hines651f13c2014-04-23 16:59:28 -0700305 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
306 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCallf85e1932011-06-15 23:02:42 +0000307
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000309 MD->hasAttr<NSReturnsRetainedAttr>())
310 einfo = einfo.withProducesResult(true);
311
John McCallde5d3c72012-02-17 03:33:10 +0000312 RequiredArgs required =
313 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
314
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700315 return arrangeLLVMFunctionInfo(
316 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
317 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000318}
319
John McCallde5d3c72012-02-17 03:33:10 +0000320const CGFunctionInfo &
321CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000322 // FIXME: Do we need to handle ObjCMethodDecl?
323 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000324
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000325 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Stephen Hines176edba2014-12-01 14:53:08 -0800326 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000327
328 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Stephen Hines176edba2014-12-01 14:53:08 -0800329 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000330
John McCallde5d3c72012-02-17 03:33:10 +0000331 return arrangeFunctionDeclaration(FD);
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000332}
333
Stephen Hines176edba2014-12-01 14:53:08 -0800334/// 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()) };
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700344 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
345 /*chainCall=*/false, ArgTys,
Stephen Hines176edba2014-12-01 14:53:08 -0800346 FTP->getExtInfo(), RequiredArgs(1));
347}
348
John McCalle56bb362012-12-07 07:03:17 +0000349/// Arrange a call as unto a free function, except possibly with an
350/// additional number of formal parameters considered required.
351static const CGFunctionInfo &
352arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000353 CodeGenModule &CGM,
John McCalle56bb362012-12-07 07:03:17 +0000354 const CallArgList &args,
355 const FunctionType *fnType,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700356 unsigned numExtraRequiredArgs,
357 bool chainCall) {
John McCalle56bb362012-12-07 07:03:17 +0000358 assert(args.size() >= numExtraRequiredArgs);
359
360 // In most cases, there are no optional arguments.
361 RequiredArgs required = RequiredArgs::All;
362
363 // If we have a variadic prototype, the required arguments are the
364 // extra prefix plus the arguments in the prototype.
365 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
366 if (proto->isVariadic())
Stephen Hines651f13c2014-04-23 16:59:28 -0700367 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCalle56bb362012-12-07 07:03:17 +0000368
369 // If we don't have a prototype at all, but we're supposed to
370 // explicitly use the variadic convention for unprototyped calls,
371 // treat all of the arguments as required but preserve the nominal
372 // possibility of variadics.
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000373 } else if (CGM.getTargetCodeGenInfo()
374 .isNoProtoCallVariadic(args,
375 cast<FunctionNoProtoType>(fnType))) {
John McCalle56bb362012-12-07 07:03:17 +0000376 required = RequiredArgs(args.size());
377 }
378
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700379 // FIXME: Kill copy.
380 SmallVector<CanQualType, 16> argTypes;
381 for (const auto &arg : args)
382 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
383 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
384 /*instanceMethod=*/false, chainCall,
385 argTypes, fnType->getExtInfo(), required);
John McCalle56bb362012-12-07 07:03:17 +0000386}
387
John McCallde5d3c72012-02-17 03:33:10 +0000388/// Figure out the rules for calling a function with the given formal
389/// type using the given arguments. The arguments are necessary
390/// because the function might be unprototyped, in which case it's
391/// target-dependent in crazy ways.
392const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000393CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700394 const FunctionType *fnType,
395 bool chainCall) {
396 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
397 chainCall ? 1 : 0, chainCall);
John McCalle56bb362012-12-07 07:03:17 +0000398}
John McCallde5d3c72012-02-17 03:33:10 +0000399
John McCalle56bb362012-12-07 07:03:17 +0000400/// A block function call is essentially a free-function call with an
401/// extra implicit argument.
402const CGFunctionInfo &
403CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
404 const FunctionType *fnType) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700405 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
406 /*chainCall=*/false);
John McCallde5d3c72012-02-17 03:33:10 +0000407}
408
409const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000410CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
411 const CallArgList &args,
412 FunctionType::ExtInfo info,
413 RequiredArgs required) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000414 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000415 SmallVector<CanQualType, 16> argTypes;
Stephen Hines176edba2014-12-01 14:53:08 -0800416 for (const auto &Arg : args)
417 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700418 return arrangeLLVMFunctionInfo(
419 GetReturnType(resultType), /*instanceMethod=*/false,
420 /*chainCall=*/false, argTypes, info, required);
John McCall0f3d0972012-07-07 06:41:13 +0000421}
422
423/// Arrange a call to a C++ method, passing the given arguments.
424const CGFunctionInfo &
425CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
426 const FunctionProtoType *FPT,
427 RequiredArgs required) {
428 // FIXME: Kill copy.
429 SmallVector<CanQualType, 16> argTypes;
Stephen Hines176edba2014-12-01 14:53:08 -0800430 for (const auto &Arg : args)
431 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall0f3d0972012-07-07 06:41:13 +0000432
433 FunctionType::ExtInfo info = FPT->getExtInfo();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700434 return arrangeLLVMFunctionInfo(
435 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
436 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000437}
438
Stephen Hines651f13c2014-04-23 16:59:28 -0700439const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
440 QualType resultType, const FunctionArgList &args,
441 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000442 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000443 SmallVector<CanQualType, 16> argTypes;
Stephen Hines176edba2014-12-01 14:53:08 -0800444 for (auto Arg : args)
445 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCallde5d3c72012-02-17 03:33:10 +0000446
447 RequiredArgs required =
448 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700449 return arrangeLLVMFunctionInfo(
450 GetReturnType(resultType), /*instanceMethod=*/false,
451 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000452}
453
John McCallde5d3c72012-02-17 03:33:10 +0000454const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700455 return arrangeLLVMFunctionInfo(
456 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
457 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalld26bc762011-03-09 04:27:21 +0000458}
459
John McCallde5d3c72012-02-17 03:33:10 +0000460/// Arrange the argument and result information for an abstract value
461/// of a given function type. This is the method which all of the
462/// above functions ultimately defer to.
463const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000464CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700465 bool instanceMethod,
466 bool chainCall,
John McCall0f3d0972012-07-07 06:41:13 +0000467 ArrayRef<CanQualType> argTypes,
468 FunctionType::ExtInfo info,
469 RequiredArgs required) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700470 assert(std::all_of(argTypes.begin(), argTypes.end(),
471 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCallead608a2010-02-26 00:48:12 +0000472
John McCallde5d3c72012-02-17 03:33:10 +0000473 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000474
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000475 // Lookup or create unique function info.
476 llvm::FoldingSetNodeID ID;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700477 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
478 resultType, argTypes);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000479
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700480 void *insertPos = nullptr;
John McCallde5d3c72012-02-17 03:33:10 +0000481 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000482 if (FI)
483 return *FI;
484
John McCallde5d3c72012-02-17 03:33:10 +0000485 // Construct the function info. We co-allocate the ArgInfos.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700486 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
487 resultType, argTypes, required);
John McCallde5d3c72012-02-17 03:33:10 +0000488 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000489
Stephen Hines176edba2014-12-01 14:53:08 -0800490 bool inserted = FunctionsBeingProcessed.insert(FI).second;
491 (void)inserted;
John McCallde5d3c72012-02-17 03:33:10 +0000492 assert(inserted && "Recursively being processed?");
Chris Lattner71305cc2011-07-15 05:16:14 +0000493
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000494 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000495 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000496
Chris Lattner800588f2010-07-29 06:26:06 +0000497 // Loop over all of the computed argument and return value info. If any of
498 // them are direct or extend without a specified coerce type, specify the
499 // default now.
John McCallde5d3c72012-02-17 03:33:10 +0000500 ABIArgInfo &retInfo = FI->getReturnInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700501 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCallde5d3c72012-02-17 03:33:10 +0000502 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000503
Stephen Hines651f13c2014-04-23 16:59:28 -0700504 for (auto &I : FI->arguments())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700505 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Stephen Hines651f13c2014-04-23 16:59:28 -0700506 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000507
John McCallde5d3c72012-02-17 03:33:10 +0000508 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
509 assert(erased && "Not in set?");
Chris Lattnerd26c0712011-07-15 06:41:05 +0000510
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000511 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000512}
513
John McCallde5d3c72012-02-17 03:33:10 +0000514CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700515 bool instanceMethod,
516 bool chainCall,
John McCallde5d3c72012-02-17 03:33:10 +0000517 const FunctionType::ExtInfo &info,
518 CanQualType resultType,
519 ArrayRef<CanQualType> argTypes,
520 RequiredArgs required) {
521 void *buffer = operator new(sizeof(CGFunctionInfo) +
522 sizeof(ArgInfo) * (argTypes.size() + 1));
523 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
524 FI->CallingConvention = llvmCC;
525 FI->EffectiveCallingConvention = llvmCC;
526 FI->ASTCallingConvention = info.getCC();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700527 FI->InstanceMethod = instanceMethod;
528 FI->ChainCall = chainCall;
John McCallde5d3c72012-02-17 03:33:10 +0000529 FI->NoReturn = info.getNoReturn();
530 FI->ReturnsRetained = info.getProducesResult();
531 FI->Required = required;
532 FI->HasRegParm = info.getHasRegParm();
533 FI->RegParm = info.getRegParm();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700534 FI->ArgStruct = nullptr;
John McCallde5d3c72012-02-17 03:33:10 +0000535 FI->NumArgs = argTypes.size();
536 FI->getArgsBuffer()[0].type = resultType;
537 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
538 FI->getArgsBuffer()[i + 1].type = argTypes[i];
539 return FI;
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000540}
541
542/***/
543
Stephen Hines176edba2014-12-01 14:53:08 -0800544namespace {
545// ABIArgInfo::Expand implementation.
546
547// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
548struct TypeExpansion {
549 enum TypeExpansionKind {
550 // Elements of constant arrays are expanded recursively.
551 TEK_ConstantArray,
552 // Record fields are expanded recursively (but if record is a union, only
553 // the field with the largest size is expanded).
554 TEK_Record,
555 // For complex types, real and imaginary parts are expanded recursively.
556 TEK_Complex,
557 // All other types are not expandable.
558 TEK_None
559 };
560
561 const TypeExpansionKind Kind;
562
563 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
564 virtual ~TypeExpansion() {}
565};
566
567struct ConstantArrayExpansion : TypeExpansion {
568 QualType EltTy;
569 uint64_t NumElts;
570
571 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
572 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
573 static bool classof(const TypeExpansion *TE) {
574 return TE->Kind == TEK_ConstantArray;
575 }
576};
577
578struct RecordExpansion : TypeExpansion {
579 SmallVector<const CXXBaseSpecifier *, 1> Bases;
580
581 SmallVector<const FieldDecl *, 1> Fields;
582
583 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
584 SmallVector<const FieldDecl *, 1> &&Fields)
585 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
586 static bool classof(const TypeExpansion *TE) {
587 return TE->Kind == TEK_Record;
588 }
589};
590
591struct ComplexExpansion : TypeExpansion {
592 QualType EltTy;
593
594 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
595 static bool classof(const TypeExpansion *TE) {
596 return TE->Kind == TEK_Complex;
597 }
598};
599
600struct NoExpansion : TypeExpansion {
601 NoExpansion() : TypeExpansion(TEK_None) {}
602 static bool classof(const TypeExpansion *TE) {
603 return TE->Kind == TEK_None;
604 }
605};
606} // namespace
607
608static std::unique_ptr<TypeExpansion>
609getTypeExpansion(QualType Ty, const ASTContext &Context) {
610 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
611 return llvm::make_unique<ConstantArrayExpansion>(
612 AT->getElementType(), AT->getSize().getZExtValue());
613 }
614 if (const RecordType *RT = Ty->getAs<RecordType>()) {
615 SmallVector<const CXXBaseSpecifier *, 1> Bases;
616 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilson194f06a2011-08-03 05:58:22 +0000617 const RecordDecl *RD = RT->getDecl();
618 assert(!RD->hasFlexibleArrayMember() &&
619 "Cannot expand structure with flexible array.");
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000620 if (RD->isUnion()) {
621 // Unions can be here only in degenerative cases - all the fields are same
622 // after flattening. Thus we have to use the "largest" field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700623 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000624 CharUnits UnionSize = CharUnits::Zero();
625
Stephen Hines651f13c2014-04-23 16:59:28 -0700626 for (const auto *FD : RD->fields()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800627 // Skip zero length bitfields.
628 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
629 continue;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000630 assert(!FD->isBitField() &&
631 "Cannot expand structure with bit-field members.");
Stephen Hines176edba2014-12-01 14:53:08 -0800632 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000633 if (UnionSize < FieldSize) {
634 UnionSize = FieldSize;
635 LargestFD = FD;
636 }
637 }
638 if (LargestFD)
Stephen Hines176edba2014-12-01 14:53:08 -0800639 Fields.push_back(LargestFD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000640 } else {
Stephen Hines176edba2014-12-01 14:53:08 -0800641 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
642 assert(!CXXRD->isDynamicClass() &&
643 "cannot expand vtable pointers in dynamic classes");
644 for (const CXXBaseSpecifier &BS : CXXRD->bases())
645 Bases.push_back(&BS);
646 }
647
648 for (const auto *FD : RD->fields()) {
649 // Skip zero length bitfields.
650 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
651 continue;
652 assert(!FD->isBitField() &&
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000653 "Cannot expand structure with bit-field members.");
Stephen Hines176edba2014-12-01 14:53:08 -0800654 Fields.push_back(FD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000655 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000656 }
Stephen Hines176edba2014-12-01 14:53:08 -0800657 return llvm::make_unique<RecordExpansion>(std::move(Bases),
658 std::move(Fields));
659 }
660 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
661 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
662 }
663 return llvm::make_unique<NoExpansion>();
Daniel Dunbar56273772008-09-17 00:51:38 +0000664}
665
Stephen Hines176edba2014-12-01 14:53:08 -0800666static int getExpansionSize(QualType Ty, const ASTContext &Context) {
667 auto Exp = getTypeExpansion(Ty, Context);
668 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
669 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
670 }
671 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
672 int Res = 0;
673 for (auto BS : RExp->Bases)
674 Res += getExpansionSize(BS->getType(), Context);
675 for (auto FD : RExp->Fields)
676 Res += getExpansionSize(FD->getType(), Context);
677 return Res;
678 }
679 if (isa<ComplexExpansion>(Exp.get()))
680 return 2;
681 assert(isa<NoExpansion>(Exp.get()));
682 return 1;
683}
684
685void
686CodeGenTypes::getExpandedTypes(QualType Ty,
687 SmallVectorImpl<llvm::Type *>::iterator &TI) {
688 auto Exp = getTypeExpansion(Ty, Context);
689 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
690 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
691 getExpandedTypes(CAExp->EltTy, TI);
692 }
693 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
694 for (auto BS : RExp->Bases)
695 getExpandedTypes(BS->getType(), TI);
696 for (auto FD : RExp->Fields)
697 getExpandedTypes(FD->getType(), TI);
698 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
699 llvm::Type *EltTy = ConvertType(CExp->EltTy);
700 *TI++ = EltTy;
701 *TI++ = EltTy;
702 } else {
703 assert(isa<NoExpansion>(Exp.get()));
704 *TI++ = ConvertType(Ty);
705 }
706}
707
708void CodeGenFunction::ExpandTypeFromArgs(
709 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000710 assert(LV.isSimple() &&
711 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000712
Stephen Hines176edba2014-12-01 14:53:08 -0800713 auto Exp = getTypeExpansion(Ty, getContext());
714 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
715 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
716 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
717 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
718 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000719 }
Stephen Hines176edba2014-12-01 14:53:08 -0800720 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
721 llvm::Value *This = LV.getAddress();
722 for (const CXXBaseSpecifier *BS : RExp->Bases) {
723 // Perform a single step derived-to-base conversion.
724 llvm::Value *Base =
725 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
726 /*NullCheckValue=*/false, SourceLocation());
727 LValue SubLV = MakeAddrLValue(Base, BS->getType());
Bob Wilson194f06a2011-08-03 05:58:22 +0000728
Stephen Hines176edba2014-12-01 14:53:08 -0800729 // Recurse onto bases.
730 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
Bob Wilson194f06a2011-08-03 05:58:22 +0000731 }
Stephen Hines176edba2014-12-01 14:53:08 -0800732 for (auto FD : RExp->Fields) {
733 // FIXME: What are the right qualifiers here?
734 LValue SubLV = EmitLValueForField(LV, FD);
735 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
736 }
737 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman377ecc72012-04-16 03:54:45 +0000738 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Stephen Hines176edba2014-12-01 14:53:08 -0800739 EmitStoreThroughLValue(RValue::get(*AI++),
740 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman377ecc72012-04-16 03:54:45 +0000741 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Stephen Hines176edba2014-12-01 14:53:08 -0800742 EmitStoreThroughLValue(RValue::get(*AI++),
743 MakeAddrLValue(ImagAddr, CExp->EltTy));
Bob Wilson194f06a2011-08-03 05:58:22 +0000744 } else {
Stephen Hines176edba2014-12-01 14:53:08 -0800745 assert(isa<NoExpansion>(Exp.get()));
746 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar56273772008-09-17 00:51:38 +0000747 }
Stephen Hines176edba2014-12-01 14:53:08 -0800748}
Daniel Dunbar56273772008-09-17 00:51:38 +0000749
Stephen Hines176edba2014-12-01 14:53:08 -0800750void CodeGenFunction::ExpandTypeToArgs(
751 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
752 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
753 auto Exp = getTypeExpansion(Ty, getContext());
754 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
755 llvm::Value *Addr = RV.getAggregateAddr();
756 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
757 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
758 RValue EltRV =
759 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
760 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
761 }
762 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
763 llvm::Value *This = RV.getAggregateAddr();
764 for (const CXXBaseSpecifier *BS : RExp->Bases) {
765 // Perform a single step derived-to-base conversion.
766 llvm::Value *Base =
767 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
768 /*NullCheckValue=*/false, SourceLocation());
769 RValue BaseRV = RValue::getAggregate(Base);
770
771 // Recurse onto bases.
772 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
773 IRCallArgPos);
774 }
775
776 LValue LV = MakeAddrLValue(This, Ty);
777 for (auto FD : RExp->Fields) {
778 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
779 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
780 IRCallArgPos);
781 }
782 } else if (isa<ComplexExpansion>(Exp.get())) {
783 ComplexPairTy CV = RV.getComplexVal();
784 IRCallArgs[IRCallArgPos++] = CV.first;
785 IRCallArgs[IRCallArgPos++] = CV.second;
786 } else {
787 assert(isa<NoExpansion>(Exp.get()));
788 assert(RV.isScalar() &&
789 "Unexpected non-scalar rvalue during struct expansion.");
790
791 // Insert a bitcast as needed.
792 llvm::Value *V = RV.getScalarVal();
793 if (IRCallArgPos < IRFuncTy->getNumParams() &&
794 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
795 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
796
797 IRCallArgs[IRCallArgPos++] = V;
798 }
Daniel Dunbar56273772008-09-17 00:51:38 +0000799}
800
Chris Lattnere7bb7772010-06-27 06:04:18 +0000801/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000802/// accessing some number of bytes out of it, try to gep into the struct to get
803/// at its inner goodness. Dive as deep as possible without entering an element
804/// with an in-memory size smaller than DstSize.
805static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000806EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000807 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000808 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000809 // We can't dive into a zero-element struct.
810 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000811
Chris Lattner2acc6e32011-07-18 04:24:23 +0000812 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000813
Chris Lattner08dd2a02010-06-27 05:56:15 +0000814 // If the first elt is at least as large as what we're looking for, or if the
Stephen Hines176edba2014-12-01 14:53:08 -0800815 // first element is the same size as the whole struct, we can enter it. The
816 // comparison must be made on the store size and not the alloca size. Using
817 // the alloca size may overstate the size of the load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000818 uint64_t FirstEltSize =
Stephen Hines176edba2014-12-01 14:53:08 -0800819 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000820 if (FirstEltSize < DstSize &&
Stephen Hines176edba2014-12-01 14:53:08 -0800821 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner08dd2a02010-06-27 05:56:15 +0000822 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000823
Chris Lattner08dd2a02010-06-27 05:56:15 +0000824 // GEP into the first element.
825 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000826
Chris Lattner08dd2a02010-06-27 05:56:15 +0000827 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000828 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000829 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000830 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000831 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000832
833 return SrcPtr;
834}
835
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000836/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
837/// are either integers or pointers. This does a truncation of the value if it
838/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000839///
840/// This behaves as if the value were coerced through memory, so on big-endian
841/// targets the high bits are preserved in a truncation, while little-endian
842/// targets preserve the low bits.
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000843static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000844 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000845 CodeGenFunction &CGF) {
846 if (Val->getType() == Ty)
847 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000848
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000849 if (isa<llvm::PointerType>(Val->getType())) {
850 // If this is Pointer->Pointer avoid conversion to and from int.
851 if (isa<llvm::PointerType>(Ty))
852 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000853
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000854 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000855 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000856 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000857
Chris Lattner2acc6e32011-07-18 04:24:23 +0000858 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000859 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000860 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000861
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000862 if (Val->getType() != DestIntTy) {
863 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
864 if (DL.isBigEndian()) {
865 // Preserve the high bits on big-endian targets.
866 // That is what memory coercion does.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700867 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
868 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
869
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000870 if (SrcSize > DstSize) {
871 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
872 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
873 } else {
874 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
875 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
876 }
877 } else {
878 // Little-endian targets preserve the low bits. No shifts required.
879 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
880 }
881 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000882
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000883 if (isa<llvm::PointerType>(Ty))
884 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
885 return Val;
886}
887
Chris Lattner08dd2a02010-06-27 05:56:15 +0000888
889
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000890/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
891/// a pointer to an object of type \arg Ty.
892///
893/// This safely handles the case when the src type is smaller than the
894/// destination type; in this situation the values of bits which not
895/// present in the src are undefined.
896static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000897 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000898 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000899 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000900 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000901
Chris Lattner6ae00692010-06-28 22:51:39 +0000902 // If SrcTy and Ty are the same, just do a load.
903 if (SrcTy == Ty)
904 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000905
Micah Villmow25a6a842012-10-08 16:25:52 +0000906 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000907
Chris Lattner2acc6e32011-07-18 04:24:23 +0000908 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000909 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000910 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
911 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000912
Micah Villmow25a6a842012-10-08 16:25:52 +0000913 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000914
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000915 // If the source and destination are integer or pointer types, just do an
916 // extension or truncation to the desired type.
917 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
918 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
919 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
920 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
921 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000922
Daniel Dunbarb225be42009-02-03 05:59:18 +0000923 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000924 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000925 // Generally SrcSize is never greater than DstSize, since this means we are
926 // losing bits. However, this can happen in cases where the structure has
927 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000928 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000929 // FIXME: Assert that we aren't truncating non-padding bits when have access
930 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000931 llvm::Value *Casted =
932 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000933 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
934 // FIXME: Use better alignment / avoid requiring aligned load.
935 Load->setAlignment(1);
936 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000937 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000938
Chris Lattner35b21b82010-06-27 01:06:27 +0000939 // Otherwise do coercion through memory. This is stupid, but
940 // simple.
941 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Renf51c61c2012-11-28 22:08:52 +0000942 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
943 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
944 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +0000945 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000946 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
947 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
948 1, false);
Chris Lattner35b21b82010-06-27 01:06:27 +0000949 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000950}
951
Eli Friedmanbadea572011-05-17 21:08:01 +0000952// Function to store a first-class aggregate into memory. We prefer to
953// store the elements rather than the aggregate to be more friendly to
954// fast-isel.
955// FIXME: Do we need to recurse here?
956static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
957 llvm::Value *DestPtr, bool DestIsVolatile,
958 bool LowAlignment) {
959 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000960 if (llvm::StructType *STy =
Eli Friedmanbadea572011-05-17 21:08:01 +0000961 dyn_cast<llvm::StructType>(Val->getType())) {
962 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
963 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
964 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
965 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
966 DestIsVolatile);
967 if (LowAlignment)
968 SI->setAlignment(1);
969 }
970 } else {
Bill Wendling08212632012-03-16 21:45:12 +0000971 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
972 if (LowAlignment)
973 SI->setAlignment(1);
Eli Friedmanbadea572011-05-17 21:08:01 +0000974 }
975}
976
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000977/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
978/// where the source and destination may have different types.
979///
980/// This safely handles the case when the src type is larger than the
981/// destination type; the upper bits of the src will be lost.
982static void CreateCoercedStore(llvm::Value *Src,
983 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000984 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000985 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000986 llvm::Type *SrcTy = Src->getType();
987 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000988 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000989 if (SrcTy == DstTy) {
990 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
991 return;
992 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000993
Micah Villmow25a6a842012-10-08 16:25:52 +0000994 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000995
Chris Lattner2acc6e32011-07-18 04:24:23 +0000996 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000997 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
998 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
999 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001000
Chris Lattner6d11cdb2010-06-27 06:26:04 +00001001 // If the source and destination are integer or pointer types, just do an
1002 // extension or truncation to the desired type.
1003 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1004 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1005 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1006 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1007 return;
1008 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001009
Micah Villmow25a6a842012-10-08 16:25:52 +00001010 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001011
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001012 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +00001013 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001014 llvm::Value *Casted =
1015 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +00001016 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +00001017 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001018 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001019 // Otherwise do coercion through memory. This is stupid, but
1020 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +00001021
1022 // Generally SrcSize is never greater than DstSize, since this means we are
1023 // losing bits. However, this can happen in cases where the structure has
1024 // additional padding, for example due to a user specified alignment.
1025 //
1026 // FIXME: Assert that we aren't truncating non-padding bits when have access
1027 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001028 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1029 CGF.Builder.CreateStore(Src, Tmp);
Manman Renf51c61c2012-11-28 22:08:52 +00001030 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1031 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1032 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +00001033 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +00001034 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1035 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1036 1, false);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001037 }
1038}
1039
Stephen Hines176edba2014-12-01 14:53:08 -08001040namespace {
1041
1042/// Encapsulates information about the way function arguments from
1043/// CGFunctionInfo should be passed to actual LLVM IR function.
1044class ClangToLLVMArgMapping {
1045 static const unsigned InvalidIndex = ~0U;
1046 unsigned InallocaArgNo;
1047 unsigned SRetArgNo;
1048 unsigned TotalIRArgs;
1049
1050 /// Arguments of LLVM IR function corresponding to single Clang argument.
1051 struct IRArgs {
1052 unsigned PaddingArgIndex;
1053 // Argument is expanded to IR arguments at positions
1054 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1055 unsigned FirstArgIndex;
1056 unsigned NumberOfArgs;
1057
1058 IRArgs()
1059 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1060 NumberOfArgs(0) {}
1061 };
1062
1063 SmallVector<IRArgs, 8> ArgInfo;
1064
1065public:
1066 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1067 bool OnlyRequiredArgs = false)
1068 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1069 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1070 construct(Context, FI, OnlyRequiredArgs);
1071 }
1072
1073 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1074 unsigned getInallocaArgNo() const {
1075 assert(hasInallocaArg());
1076 return InallocaArgNo;
1077 }
1078
1079 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1080 unsigned getSRetArgNo() const {
1081 assert(hasSRetArg());
1082 return SRetArgNo;
1083 }
1084
1085 unsigned totalIRArgs() const { return TotalIRArgs; }
1086
1087 bool hasPaddingArg(unsigned ArgNo) const {
1088 assert(ArgNo < ArgInfo.size());
1089 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1090 }
1091 unsigned getPaddingArgNo(unsigned ArgNo) const {
1092 assert(hasPaddingArg(ArgNo));
1093 return ArgInfo[ArgNo].PaddingArgIndex;
1094 }
1095
1096 /// Returns index of first IR argument corresponding to ArgNo, and their
1097 /// quantity.
1098 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1099 assert(ArgNo < ArgInfo.size());
1100 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1101 ArgInfo[ArgNo].NumberOfArgs);
1102 }
1103
1104private:
1105 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1106 bool OnlyRequiredArgs);
1107};
1108
1109void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1110 const CGFunctionInfo &FI,
1111 bool OnlyRequiredArgs) {
1112 unsigned IRArgNo = 0;
1113 bool SwapThisWithSRet = false;
1114 const ABIArgInfo &RetAI = FI.getReturnInfo();
1115
1116 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1117 SwapThisWithSRet = RetAI.isSRetAfterThis();
1118 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1119 }
1120
1121 unsigned ArgNo = 0;
1122 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1123 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1124 ++I, ++ArgNo) {
1125 assert(I != FI.arg_end());
1126 QualType ArgType = I->type;
1127 const ABIArgInfo &AI = I->info;
1128 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1129 auto &IRArgs = ArgInfo[ArgNo];
1130
1131 if (AI.getPaddingType())
1132 IRArgs.PaddingArgIndex = IRArgNo++;
1133
1134 switch (AI.getKind()) {
1135 case ABIArgInfo::Extend:
1136 case ABIArgInfo::Direct: {
1137 // FIXME: handle sseregparm someday...
1138 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1139 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1140 IRArgs.NumberOfArgs = STy->getNumElements();
1141 } else {
1142 IRArgs.NumberOfArgs = 1;
1143 }
1144 break;
1145 }
1146 case ABIArgInfo::Indirect:
1147 IRArgs.NumberOfArgs = 1;
1148 break;
1149 case ABIArgInfo::Ignore:
1150 case ABIArgInfo::InAlloca:
1151 // ignore and inalloca doesn't have matching LLVM parameters.
1152 IRArgs.NumberOfArgs = 0;
1153 break;
1154 case ABIArgInfo::Expand: {
1155 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1156 break;
1157 }
1158 }
1159
1160 if (IRArgs.NumberOfArgs > 0) {
1161 IRArgs.FirstArgIndex = IRArgNo;
1162 IRArgNo += IRArgs.NumberOfArgs;
1163 }
1164
1165 // Skip over the sret parameter when it comes second. We already handled it
1166 // above.
1167 if (IRArgNo == 1 && SwapThisWithSRet)
1168 IRArgNo++;
1169 }
1170 assert(ArgNo == ArgInfo.size());
1171
1172 if (FI.usesInAlloca())
1173 InallocaArgNo = IRArgNo++;
1174
1175 TotalIRArgs = IRArgNo;
1176}
1177} // namespace
1178
Daniel Dunbar56273772008-09-17 00:51:38 +00001179/***/
1180
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001181bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001182 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001183}
1184
Stephen Hines651f13c2014-04-23 16:59:28 -07001185bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1186 return ReturnTypeUsesSRet(FI) &&
1187 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1188}
1189
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001190bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1191 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1192 switch (BT->getKind()) {
1193 default:
1194 return false;
1195 case BuiltinType::Float:
John McCall64aa4b32013-04-16 22:48:15 +00001196 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001197 case BuiltinType::Double:
John McCall64aa4b32013-04-16 22:48:15 +00001198 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001199 case BuiltinType::LongDouble:
John McCall64aa4b32013-04-16 22:48:15 +00001200 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001201 }
1202 }
1203
1204 return false;
1205}
1206
Anders Carlssoneea64802011-10-31 16:27:11 +00001207bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1208 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1209 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1210 if (BT->getKind() == BuiltinType::LongDouble)
John McCall64aa4b32013-04-16 22:48:15 +00001211 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlssoneea64802011-10-31 16:27:11 +00001212 }
1213 }
1214
1215 return false;
1216}
1217
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001218llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallde5d3c72012-02-17 03:33:10 +00001219 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1220 return GetFunctionType(FI);
John McCallc0bf4622010-02-23 00:48:20 +00001221}
1222
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001223llvm::FunctionType *
John McCallde5d3c72012-02-17 03:33:10 +00001224CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001225
Stephen Hines176edba2014-12-01 14:53:08 -08001226 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1227 (void)Inserted;
1228 assert(Inserted && "Recursively being processed?");
1229
1230 llvm::Type *resultType = nullptr;
John McCall42e06112011-05-15 02:19:42 +00001231 const ABIArgInfo &retAI = FI.getReturnInfo();
1232 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001233 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +00001234 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001235
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001236 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001237 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +00001238 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001239 break;
1240
Stephen Hines651f13c2014-04-23 16:59:28 -07001241 case ABIArgInfo::InAlloca:
1242 if (retAI.getInAllocaSRet()) {
1243 // sret things on win32 aren't void, they return the sret pointer.
1244 QualType ret = FI.getReturnType();
1245 llvm::Type *ty = ConvertType(ret);
1246 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1247 resultType = llvm::PointerType::get(ty, addressSpace);
1248 } else {
1249 resultType = llvm::Type::getVoidTy(getLLVMContext());
1250 }
1251 break;
1252
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001253 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +00001254 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1255 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001256 break;
1257 }
1258
Daniel Dunbar11434922009-01-26 21:26:08 +00001259 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +00001260 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +00001261 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Stephen Hines176edba2014-12-01 14:53:08 -08001264 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1265 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1266
1267 // Add type for sret argument.
1268 if (IRFunctionArgs.hasSRetArg()) {
1269 QualType Ret = FI.getReturnType();
1270 llvm::Type *Ty = ConvertType(Ret);
1271 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1272 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1273 llvm::PointerType::get(Ty, AddressSpace);
John McCalle56bb362012-12-07 07:03:17 +00001274 }
Stephen Hines176edba2014-12-01 14:53:08 -08001275
1276 // Add type for inalloca argument.
1277 if (IRFunctionArgs.hasInallocaArg()) {
1278 auto ArgStruct = FI.getArgStruct();
1279 assert(ArgStruct);
1280 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1281 }
1282
1283 // Add in all of the required arguments.
1284 unsigned ArgNo = 0;
1285 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1286 ie = it + FI.getNumRequiredArgs();
1287 for (; it != ie; ++it, ++ArgNo) {
1288 const ABIArgInfo &ArgInfo = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001290 // Insert a padding type to ensure proper alignment.
Stephen Hines176edba2014-12-01 14:53:08 -08001291 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1292 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1293 ArgInfo.getPaddingType();
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001294
Stephen Hines176edba2014-12-01 14:53:08 -08001295 unsigned FirstIRArg, NumIRArgs;
1296 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1297
1298 switch (ArgInfo.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +00001299 case ABIArgInfo::Ignore:
Stephen Hines651f13c2014-04-23 16:59:28 -07001300 case ABIArgInfo::InAlloca:
Stephen Hines176edba2014-12-01 14:53:08 -08001301 assert(NumIRArgs == 0);
Daniel Dunbar11434922009-01-26 21:26:08 +00001302 break;
1303
Chris Lattner800588f2010-07-29 06:26:06 +00001304 case ABIArgInfo::Indirect: {
Stephen Hines176edba2014-12-01 14:53:08 -08001305 assert(NumIRArgs == 1);
Chris Lattner800588f2010-07-29 06:26:06 +00001306 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001307 llvm::Type *LTy = ConvertTypeForMem(it->type);
Stephen Hines176edba2014-12-01 14:53:08 -08001308 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattner800588f2010-07-29 06:26:06 +00001309 break;
1310 }
1311
1312 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +00001313 case ABIArgInfo::Direct: {
Stephen Hines176edba2014-12-01 14:53:08 -08001314 // Fast-isel and the optimizer generally like scalar values better than
1315 // FCAs, so we flatten them if this is safe to do for this argument.
1316 llvm::Type *argType = ArgInfo.getCoerceToType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001317 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Stephen Hines176edba2014-12-01 14:53:08 -08001318 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1319 assert(NumIRArgs == st->getNumElements());
John McCall42e06112011-05-15 02:19:42 +00001320 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Stephen Hines176edba2014-12-01 14:53:08 -08001321 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattnerce700162010-06-28 23:44:11 +00001322 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08001323 assert(NumIRArgs == 1);
1324 ArgTypes[FirstIRArg] = argType;
Chris Lattnerce700162010-06-28 23:44:11 +00001325 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001326 break;
Chris Lattner1ed72672010-07-29 06:44:09 +00001327 }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001329 case ABIArgInfo::Expand:
Stephen Hines176edba2014-12-01 14:53:08 -08001330 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1331 getExpandedTypes(it->type, ArgTypesIter);
1332 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001333 break;
1334 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001335 }
1336
Chris Lattner71305cc2011-07-15 05:16:14 +00001337 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1338 assert(Erased && "Not in set?");
Stephen Hines176edba2014-12-01 14:53:08 -08001339
1340 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar3913f182008-09-09 23:48:28 +00001341}
1342
Chris Lattner2acc6e32011-07-18 04:24:23 +00001343llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +00001344 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +00001345 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001346
Chris Lattnerf742eb02011-07-10 00:18:59 +00001347 if (!isFuncTypeConvertible(FPT))
1348 return llvm::StructType::get(getLLVMContext());
1349
1350 const CGFunctionInfo *Info;
1351 if (isa<CXXDestructorDecl>(MD))
Stephen Hines176edba2014-12-01 14:53:08 -08001352 Info =
1353 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattnerf742eb02011-07-10 00:18:59 +00001354 else
John McCallde5d3c72012-02-17 03:33:10 +00001355 Info = &arrangeCXXMethodDeclaration(MD);
1356 return GetFunctionType(*Info);
Anders Carlssonecf282b2009-11-24 05:08:52 +00001357}
1358
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001359void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +00001360 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001361 AttributeListType &PAL,
Bill Wendling94236e72013-02-22 00:13:35 +00001362 unsigned &CallingConv,
1363 bool AttrOnCallSite) {
Bill Wendling0d583392012-10-15 20:36:26 +00001364 llvm::AttrBuilder FuncAttrs;
1365 llvm::AttrBuilder RetAttrs;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001366 bool HasOptnone = false;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001367
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001368 CallingConv = FI.getEffectiveCallingConvention();
1369
John McCall04a67a62010-02-05 21:31:56 +00001370 if (FI.isNoReturn())
Bill Wendling72390b32012-12-20 19:27:06 +00001371 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall04a67a62010-02-05 21:31:56 +00001372
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001373 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001374 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +00001375 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001376 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001377 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001378 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith7586a6e2013-01-30 05:45:05 +00001379 if (TargetDecl->hasAttr<NoReturnAttr>())
1380 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Stephen Hines651f13c2014-04-23 16:59:28 -07001381 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1382 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smith7586a6e2013-01-30 05:45:05 +00001383
1384 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCall9c0c1f32010-07-08 06:48:12 +00001385 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001386 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling72390b32012-12-20 19:27:06 +00001387 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith3c5cd152013-03-05 08:30:04 +00001388 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1389 // These attributes are not inherited by overloads.
1390 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1391 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smith7586a6e2013-01-30 05:45:05 +00001392 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall9c0c1f32010-07-08 06:48:12 +00001393 }
1394
Eric Christopher041087c2011-08-15 22:38:22 +00001395 // 'const' and 'pure' attribute functions are also nounwind.
1396 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001397 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1398 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001399 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001400 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1401 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001402 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001403 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001404 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Stephen Hines176edba2014-12-01 14:53:08 -08001405 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1406 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001407
1408 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001409 }
1410
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001411 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1412 if (!HasOptnone) {
1413 if (CodeGenOpts.OptimizeSize)
1414 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1415 if (CodeGenOpts.OptimizeSize == 2)
1416 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1417 }
1418
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001419 if (CodeGenOpts.DisableRedZone)
Bill Wendling72390b32012-12-20 19:27:06 +00001420 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001421 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling72390b32012-12-20 19:27:06 +00001422 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001423 if (CodeGenOpts.EnableSegmentedStacks &&
1424 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1425 FuncAttrs.addAttribute("split-stack");
Devang Patel24095da2009-06-04 23:32:02 +00001426
Bill Wendling93e4bff2013-02-22 20:53:29 +00001427 if (AttrOnCallSite) {
1428 // Attributes that should go on the call site only.
1429 if (!CodeGenOpts.SimplifyLibCalls)
1430 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001431 } else {
1432 // Attributes that should go on the function, but not the call site.
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001433 if (!CodeGenOpts.DisableFPElim) {
Bill Wendling4159f052013-03-13 22:24:33 +00001434 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001435 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendling4159f052013-03-13 22:24:33 +00001436 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001437 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001438 } else {
Bill Wendling4159f052013-03-13 22:24:33 +00001439 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001440 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001441 }
1442
Bill Wendling4159f052013-03-13 22:24:33 +00001443 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001444 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendling4159f052013-03-13 22:24:33 +00001445 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001446 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001447 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001448 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001449 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001450 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001451 FuncAttrs.addAttribute("use-soft-float",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001452 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendling45ccf282013-07-22 20:15:41 +00001453 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling8d230b42013-07-12 22:26:07 +00001454 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlingcab4a092013-07-25 00:32:41 +00001455
Bill Wendling1cf9ab82013-08-01 21:41:02 +00001456 if (!CodeGenOpts.StackRealignment)
1457 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +00001458 }
1459
Stephen Hines176edba2014-12-01 14:53:08 -08001460 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
1461
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001462 QualType RetTy = FI.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001463 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001464 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001465 case ABIArgInfo::Extend:
Jakob Stoklund Olesen5baefa82013-05-29 03:57:23 +00001466 if (RetTy->hasSignedIntegerRepresentation())
1467 RetAttrs.addAttribute(llvm::Attribute::SExt);
1468 else if (RetTy->hasUnsignedIntegerRepresentation())
1469 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001470 // FALL THROUGH
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001471 case ABIArgInfo::Direct:
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001472 if (RetAI.getInReg())
1473 RetAttrs.addAttribute(llvm::Attribute::InReg);
1474 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001475 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001476 break;
1477
Stephen Hines176edba2014-12-01 14:53:08 -08001478 case ABIArgInfo::InAlloca:
Rafael Espindolab48280b2012-07-31 02:44:24 +00001479 case ABIArgInfo::Indirect: {
Stephen Hines176edba2014-12-01 14:53:08 -08001480 // inalloca and sret disable readnone and readonly
Bill Wendling72390b32012-12-20 19:27:06 +00001481 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1482 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001483 break;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001484 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001485
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001486 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001487 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001488 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001489
Stephen Hines176edba2014-12-01 14:53:08 -08001490 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1491 QualType PTy = RefTy->getPointeeType();
1492 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1493 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1494 .getQuantity());
1495 else if (getContext().getTargetAddressSpace(PTy) == 0)
1496 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1497 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001498
Stephen Hines176edba2014-12-01 14:53:08 -08001499 // Attach return attributes.
1500 if (RetAttrs.hasAttributes()) {
1501 PAL.push_back(llvm::AttributeSet::get(
1502 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1503 }
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001504
Stephen Hines176edba2014-12-01 14:53:08 -08001505 // Attach attributes to sret.
1506 if (IRFunctionArgs.hasSRetArg()) {
1507 llvm::AttrBuilder SRETAttrs;
1508 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1509 if (RetAI.getInReg())
1510 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1511 PAL.push_back(llvm::AttributeSet::get(
1512 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1513 }
1514
1515 // Attach attributes to inalloca argument.
1516 if (IRFunctionArgs.hasInallocaArg()) {
1517 llvm::AttrBuilder Attrs;
1518 Attrs.addAttribute(llvm::Attribute::InAlloca);
1519 PAL.push_back(llvm::AttributeSet::get(
1520 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1521 }
1522
Stephen Hines176edba2014-12-01 14:53:08 -08001523 unsigned ArgNo = 0;
1524 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1525 E = FI.arg_end();
1526 I != E; ++I, ++ArgNo) {
1527 QualType ParamType = I->type;
1528 const ABIArgInfo &AI = I->info;
Bill Wendling0d583392012-10-15 20:36:26 +00001529 llvm::AttrBuilder Attrs;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001530
Stephen Hines176edba2014-12-01 14:53:08 -08001531 // Add attribute for padding argument, if necessary.
1532 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001533 if (AI.getPaddingInReg())
Stephen Hines176edba2014-12-01 14:53:08 -08001534 PAL.push_back(llvm::AttributeSet::get(
1535 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1536 llvm::Attribute::InReg));
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001537 }
1538
John McCalld8e10d22010-03-27 00:47:27 +00001539 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1540 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +00001541 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001542 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +00001543 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +00001544 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001545 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001546 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001547 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattner800588f2010-07-29 06:26:06 +00001548 // FALL THROUGH
Stephen Hines176edba2014-12-01 14:53:08 -08001549 case ABIArgInfo::Direct:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001550 if (ArgNo == 0 && FI.isChainCall())
1551 Attrs.addAttribute(llvm::Attribute::Nest);
1552 else if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001553 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattner800588f2010-07-29 06:26:06 +00001554 break;
Stephen Hines176edba2014-12-01 14:53:08 -08001555
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001556 case ABIArgInfo::Indirect:
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001557 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001558 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001559
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001560 if (AI.getIndirectByVal())
Bill Wendling72390b32012-12-20 19:27:06 +00001561 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001562
Bill Wendling603571a2012-10-10 07:36:56 +00001563 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1564
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001565 // byval disables readnone and readonly.
Bill Wendling72390b32012-12-20 19:27:06 +00001566 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1567 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001568 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001569
Daniel Dunbar11434922009-01-26 21:26:08 +00001570 case ABIArgInfo::Ignore:
Stephen Hines176edba2014-12-01 14:53:08 -08001571 case ABIArgInfo::Expand:
Mike Stump1eb44332009-09-09 15:08:12 +00001572 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001573
Stephen Hines651f13c2014-04-23 16:59:28 -07001574 case ABIArgInfo::InAlloca:
1575 // inalloca disables readnone and readonly.
1576 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1577 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar56273772008-09-17 00:51:38 +00001578 continue;
1579 }
Stephen Hines176edba2014-12-01 14:53:08 -08001580
1581 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1582 QualType PTy = RefTy->getPointeeType();
1583 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1584 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1585 .getQuantity());
1586 else if (getContext().getTargetAddressSpace(PTy) == 0)
1587 Attrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Stephen Hines176edba2014-12-01 14:53:08 -08001590 if (Attrs.hasAttributes()) {
1591 unsigned FirstIRArg, NumIRArgs;
1592 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1593 for (unsigned i = 0; i < NumIRArgs; i++)
1594 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1595 FirstIRArg + i + 1, Attrs));
1596 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001597 }
Stephen Hines176edba2014-12-01 14:53:08 -08001598 assert(ArgNo == FI.arg_size());
Stephen Hines651f13c2014-04-23 16:59:28 -07001599
Bill Wendling603571a2012-10-10 07:36:56 +00001600 if (FuncAttrs.hasAttributes())
Bill Wendling75d37b42012-10-15 07:31:59 +00001601 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001602 AttributeSet::get(getLLVMContext(),
1603 llvm::AttributeSet::FunctionIndex,
1604 FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001605}
1606
John McCalld26bc762011-03-09 04:27:21 +00001607/// An argument came in as a promoted argument; demote it back to its
1608/// declared type.
1609static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1610 const VarDecl *var,
1611 llvm::Value *value) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001612 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-03-09 04:27:21 +00001613
1614 // This can happen with promotions that actually don't change the
1615 // underlying type, like the enum promotions.
1616 if (value->getType() == varType) return value;
1617
1618 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1619 && "unexpected promotion type");
1620
1621 if (isa<llvm::IntegerType>(varType))
1622 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1623
1624 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1625}
1626
Stephen Hines176edba2014-12-01 14:53:08 -08001627/// Returns the attribute (either parameter attribute, or function
1628/// attribute), which declares argument ArgNo to be non-null.
1629static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1630 QualType ArgType, unsigned ArgNo) {
1631 // FIXME: __attribute__((nonnull)) can also be applied to:
1632 // - references to pointers, where the pointee is known to be
1633 // nonnull (apparently a Clang extension)
1634 // - transparent unions containing pointers
1635 // In the former case, LLVM IR cannot represent the constraint. In
1636 // the latter case, we have no guarantee that the transparent union
1637 // is in fact passed as a pointer.
1638 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1639 return nullptr;
1640 // First, check attribute on parameter itself.
1641 if (PVD) {
1642 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1643 return ParmNNAttr;
1644 }
1645 // Check function attributes.
1646 if (!FD)
1647 return nullptr;
1648 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
1649 if (NNAttr->isNonNull(ArgNo))
1650 return NNAttr;
1651 }
1652 return nullptr;
1653}
1654
Daniel Dunbar88b53962009-02-02 22:03:45 +00001655void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1656 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001657 const FunctionArgList &Args) {
Stephen Hines176edba2014-12-01 14:53:08 -08001658 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1659 // Naked functions don't have prologues.
1660 return;
1661
John McCall0cfeb632009-07-28 01:00:58 +00001662 // If this is an implicit-return-zero function, go ahead and
1663 // initialize the return value. TODO: it might be nice to have
1664 // a more general mechanism for this that didn't require synthesized
1665 // return statements.
John McCallf5ebf9b2013-05-03 07:33:41 +00001666 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +00001667 if (FD->hasImplicitReturnZero()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001668 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001669 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001670 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +00001671 Builder.CreateStore(Zero, ReturnValue);
1672 }
1673 }
1674
Mike Stumpf5408fe2009-05-16 07:57:57 +00001675 // FIXME: We no longer need the types from FunctionArgList; lift up and
1676 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001677
Stephen Hines176edba2014-12-01 14:53:08 -08001678 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
1679 // Flattened function arguments.
1680 SmallVector<llvm::Argument *, 16> FnArgs;
1681 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1682 for (auto &Arg : Fn->args()) {
1683 FnArgs.push_back(&Arg);
1684 }
1685 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Stephen Hines651f13c2014-04-23 16:59:28 -07001687 // If we're using inalloca, all the memory arguments are GEPs off of the last
1688 // parameter, which is a pointer to the complete memory area.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001689 llvm::Value *ArgStruct = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08001690 if (IRFunctionArgs.hasInallocaArg()) {
1691 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Stephen Hines651f13c2014-04-23 16:59:28 -07001692 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1693 }
1694
Stephen Hines176edba2014-12-01 14:53:08 -08001695 // Name the struct return parameter.
1696 if (IRFunctionArgs.hasSRetArg()) {
1697 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001698 AI->setName("agg.result");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001699 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendling89530e42013-01-23 06:15:10 +00001700 llvm::Attribute::NoAlias));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Stephen Hines651f13c2014-04-23 16:59:28 -07001703 // Track if we received the parameter as a pointer (indirect, byval, or
1704 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1705 // into a local alloca for us.
1706 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
1707 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
1708 SmallVector<ValueAndIsPtr, 16> ArgVals;
1709 ArgVals.reserve(Args.size());
1710
1711 // Create a pointer value for every parameter declaration. This usually
1712 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1713 // any cleanups or do anything that might unwind. We do that separately, so
1714 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001715 assert(FI.arg_size() == Args.size() &&
1716 "Mismatch between function signature & arguments.");
Stephen Hines176edba2014-12-01 14:53:08 -08001717 unsigned ArgNo = 0;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001718 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Stephen Hines176edba2014-12-01 14:53:08 -08001719 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel093ac462011-03-03 20:13:15 +00001720 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +00001721 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001722 QualType Ty = info_it->type;
1723 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001724
John McCalld26bc762011-03-09 04:27:21 +00001725 bool isPromoted =
1726 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1727
Stephen Hines176edba2014-12-01 14:53:08 -08001728 unsigned FirstIRArg, NumIRArgs;
1729 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001730
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001731 switch (ArgI.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001732 case ABIArgInfo::InAlloca: {
Stephen Hines176edba2014-12-01 14:53:08 -08001733 assert(NumIRArgs == 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07001734 llvm::Value *V = Builder.CreateStructGEP(
1735 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1736 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Stephen Hines176edba2014-12-01 14:53:08 -08001737 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07001738 }
1739
Daniel Dunbar1f745982009-02-05 09:16:39 +00001740 case ABIArgInfo::Indirect: {
Stephen Hines176edba2014-12-01 14:53:08 -08001741 assert(NumIRArgs == 1);
1742 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001743
John McCall9d232c82013-03-07 21:37:08 +00001744 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001745 // Aggregates and complex variables are accessed by reference. All we
1746 // need to do is realign the value, if requested
1747 if (ArgI.getIndirectRealign()) {
1748 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1749
1750 // Copy from the incoming argument pointer to the temporary with the
1751 // appropriate alignment.
1752 //
1753 // FIXME: We should have a common utility for generating an aggregate
1754 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001755 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +00001756 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +00001757 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1758 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1759 Builder.CreateMemCpy(Dst,
1760 Src,
Ken Dyckfe710082011-01-19 01:58:38 +00001761 llvm::ConstantInt::get(IntPtrTy,
1762 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +00001763 ArgI.getIndirectAlign(),
1764 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001765 V = AlignedTemp;
1766 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001767 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar1f745982009-02-05 09:16:39 +00001768 } else {
1769 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +00001770 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001771 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1772 Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001773
1774 if (isPromoted)
1775 V = emitArgumentDemotion(*this, Arg, V);
Stephen Hines651f13c2014-04-23 16:59:28 -07001776 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar1f745982009-02-05 09:16:39 +00001777 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001778 break;
1779 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001780
1781 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001782 case ABIArgInfo::Direct: {
Akira Hatanaka4ba3fd42012-01-09 19:08:06 +00001783
Chris Lattner800588f2010-07-29 06:26:06 +00001784 // If we have the trivial case, handle it with no muss and fuss.
1785 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001786 ArgI.getCoerceToType() == ConvertType(Ty) &&
1787 ArgI.getDirectOffset() == 0) {
Stephen Hines176edba2014-12-01 14:53:08 -08001788 assert(NumIRArgs == 1);
1789 auto AI = FnArgs[FirstIRArg];
Chris Lattner800588f2010-07-29 06:26:06 +00001790 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001791
Stephen Hines176edba2014-12-01 14:53:08 -08001792 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
1793 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1794 PVD->getFunctionScopeIndex()))
1795 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1796 AI->getArgNo() + 1,
1797 llvm::Attribute::NonNull));
1798
1799 QualType OTy = PVD->getOriginalType();
1800 if (const auto *ArrTy =
1801 getContext().getAsConstantArrayType(OTy)) {
1802 // A C99 array parameter declaration with the static keyword also
1803 // indicates dereferenceability, and if the size is constant we can
1804 // use the dereferenceable attribute (which requires the size in
1805 // bytes).
1806 if (ArrTy->getSizeModifier() == ArrayType::Static) {
1807 QualType ETy = ArrTy->getElementType();
1808 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1809 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1810 ArrSize) {
1811 llvm::AttrBuilder Attrs;
1812 Attrs.addDereferenceableAttr(
1813 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1814 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1815 AI->getArgNo() + 1, Attrs));
1816 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1817 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1818 AI->getArgNo() + 1,
1819 llvm::Attribute::NonNull));
1820 }
1821 }
1822 } else if (const auto *ArrTy =
1823 getContext().getAsVariableArrayType(OTy)) {
1824 // For C99 VLAs with the static keyword, we don't know the size so
1825 // we can't use the dereferenceable attribute, but in addrspace(0)
1826 // we know that it must be nonnull.
1827 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1828 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1829 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1830 AI->getArgNo() + 1,
1831 llvm::Attribute::NonNull));
1832 }
1833
1834 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1835 if (!AVAttr)
1836 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1837 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1838 if (AVAttr) {
1839 llvm::Value *AlignmentValue =
1840 EmitScalarExpr(AVAttr->getAlignment());
1841 llvm::ConstantInt *AlignmentCI =
1842 cast<llvm::ConstantInt>(AlignmentValue);
1843 unsigned Alignment =
1844 std::min((unsigned) AlignmentCI->getZExtValue(),
1845 +llvm::Value::MaximumAlignment);
1846
1847 llvm::AttrBuilder Attrs;
1848 Attrs.addAlignmentAttr(Alignment);
1849 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1850 AI->getArgNo() + 1, Attrs));
1851 }
1852 }
1853
Bill Wendlinga6375562012-10-16 05:23:44 +00001854 if (Arg->getType().isRestrictQualified())
Bill Wendling89530e42013-01-23 06:15:10 +00001855 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1856 AI->getArgNo() + 1,
1857 llvm::Attribute::NoAlias));
John McCalld8e10d22010-03-27 00:47:27 +00001858
Chris Lattnerb13eab92011-07-20 06:29:00 +00001859 // Ensure the argument is the correct type.
1860 if (V->getType() != ArgI.getCoerceToType())
1861 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1862
John McCalld26bc762011-03-09 04:27:21 +00001863 if (isPromoted)
1864 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001865
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001866 if (const CXXMethodDecl *MD =
1867 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001868 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001869 V = CGM.getCXXABI().
1870 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001871 }
1872
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001873 // Because of merging of function types from multiple decls it is
1874 // possible for the type of an argument to not match the corresponding
1875 // type in the function type. Since we are codegening the callee
1876 // in here, add a cast to the argument type.
1877 llvm::Type *LTy = ConvertType(Arg->getType());
1878 if (V->getType() != LTy)
1879 V = Builder.CreateBitCast(V, LTy);
1880
Stephen Hines651f13c2014-04-23 16:59:28 -07001881 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattner800588f2010-07-29 06:26:06 +00001882 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001883 }
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001885 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001886
Chris Lattnerdeabde22010-07-28 18:24:28 +00001887 // The alignment we need to use is the max of the requested alignment for
1888 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001889 unsigned AlignmentToUse =
Micah Villmow25a6a842012-10-08 16:25:52 +00001890 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001891 AlignmentToUse = std::max(AlignmentToUse,
1892 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001893
Chris Lattnerdeabde22010-07-28 18:24:28 +00001894 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001895 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001896 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001897
Chris Lattner117e3f42010-07-30 04:02:24 +00001898 // If the value is offset in memory, apply the offset now.
1899 if (unsigned Offs = ArgI.getDirectOffset()) {
1900 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1901 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001902 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001903 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1904 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001905
Stephen Hines176edba2014-12-01 14:53:08 -08001906 // Fast-isel and the optimizer generally like scalar values better than
1907 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001908 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Stephen Hines176edba2014-12-01 14:53:08 -08001909 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1910 STy->getNumElements() > 1) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001911 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001912 llvm::Type *DstTy =
1913 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001914 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001915
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001916 if (SrcSize <= DstSize) {
1917 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1918
Stephen Hines176edba2014-12-01 14:53:08 -08001919 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001920 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Stephen Hines176edba2014-12-01 14:53:08 -08001921 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001922 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1923 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Stephen Hines176edba2014-12-01 14:53:08 -08001924 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001925 }
1926 } else {
1927 llvm::AllocaInst *TempAlloca =
1928 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1929 TempAlloca->setAlignment(AlignmentToUse);
1930 llvm::Value *TempV = TempAlloca;
1931
Stephen Hines176edba2014-12-01 14:53:08 -08001932 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001933 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Stephen Hines176edba2014-12-01 14:53:08 -08001934 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001935 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1936 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Stephen Hines176edba2014-12-01 14:53:08 -08001937 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001938 }
1939
1940 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner309c59f2010-06-29 00:06:42 +00001941 }
1942 } else {
1943 // Simple case, just do a coerced store of the argument into the alloca.
Stephen Hines176edba2014-12-01 14:53:08 -08001944 assert(NumIRArgs == 1);
1945 auto AI = FnArgs[FirstIRArg];
Chris Lattner225e2862010-06-29 00:14:52 +00001946 AI->setName(Arg->getName() + ".coerce");
Stephen Hines176edba2014-12-01 14:53:08 -08001947 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001948 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001949
1950
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001951 // Match to what EmitParmDecl is expecting for this type.
John McCall9d232c82013-03-07 21:37:08 +00001952 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001953 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001954 if (isPromoted)
1955 V = emitArgumentDemotion(*this, Arg, V);
Stephen Hines651f13c2014-04-23 16:59:28 -07001956 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1957 } else {
1958 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001959 }
Stephen Hines176edba2014-12-01 14:53:08 -08001960 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001961 }
Chris Lattner800588f2010-07-29 06:26:06 +00001962
1963 case ABIArgInfo::Expand: {
1964 // If this structure was expanded into multiple arguments then
1965 // we need to create a temporary and reconstruct it from the
1966 // arguments.
Eli Friedman1bb94a42011-11-03 21:39:02 +00001967 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedman6da2c712011-12-03 04:14:32 +00001968 CharUnits Align = getContext().getDeclAlign(Arg);
1969 Alloca->setAlignment(Align.getQuantity());
1970 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Stephen Hines651f13c2014-04-23 16:59:28 -07001971 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattner800588f2010-07-29 06:26:06 +00001972
Stephen Hines176edba2014-12-01 14:53:08 -08001973 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1974 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1975 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1976 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1977 auto AI = FnArgs[FirstIRArg + i];
1978 AI->setName(Arg->getName() + "." + Twine(i));
1979 }
1980 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001981 }
1982
1983 case ABIArgInfo::Ignore:
Stephen Hines176edba2014-12-01 14:53:08 -08001984 assert(NumIRArgs == 0);
Chris Lattner800588f2010-07-29 06:26:06 +00001985 // Initialize the local variable appropriately.
Stephen Hines651f13c2014-04-23 16:59:28 -07001986 if (!hasScalarEvaluationKind(Ty)) {
1987 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1988 } else {
1989 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1990 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1991 }
Stephen Hines176edba2014-12-01 14:53:08 -08001992 break;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001993 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001994 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001995
Stephen Hines651f13c2014-04-23 16:59:28 -07001996 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1997 for (int I = Args.size() - 1; I >= 0; --I)
1998 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1999 I + 1);
2000 } else {
2001 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2002 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2003 I + 1);
2004 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002005}
2006
John McCall77fe6cd2012-01-29 07:46:59 +00002007static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2008 while (insn->use_empty()) {
2009 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2010 if (!bitcast) return;
2011
2012 // This is "safe" because we would have used a ConstantExpr otherwise.
2013 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2014 bitcast->eraseFromParent();
2015 }
2016}
2017
John McCallf85e1932011-06-15 23:02:42 +00002018/// Try to emit a fused autorelease of a return result.
2019static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2020 llvm::Value *result) {
2021 // We must be immediately followed the cast.
2022 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002023 if (BB->empty()) return nullptr;
2024 if (&BB->back() != result) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002025
Chris Lattner2acc6e32011-07-18 04:24:23 +00002026 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00002027
2028 // result is in a BasicBlock and is therefore an Instruction.
2029 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2030
Chris Lattner5f9e2722011-07-23 10:55:15 +00002031 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00002032
2033 // Look for:
2034 // %generator = bitcast %type1* %generator2 to %type2*
2035 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2036 // We would have emitted this as a constant if the operand weren't
2037 // an Instruction.
2038 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2039
2040 // Require the generator to be immediately followed by the cast.
2041 if (generator->getNextNode() != bitcast)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002042 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002043
2044 insnsToKill.push_back(bitcast);
2045 }
2046
2047 // Look for:
2048 // %generator = call i8* @objc_retain(i8* %originalResult)
2049 // or
2050 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2051 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002052 if (!call) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002053
2054 bool doRetainAutorelease;
2055
2056 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2057 doRetainAutorelease = true;
2058 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2059 .objc_retainAutoreleasedReturnValue) {
2060 doRetainAutorelease = false;
2061
John McCallf9fdcc02012-09-07 23:30:50 +00002062 // If we emitted an assembly marker for this call (and the
2063 // ARCEntrypoints field should have been set if so), go looking
2064 // for that call. If we can't find it, we can't do this
2065 // optimization. But it should always be the immediately previous
2066 // instruction, unless we needed bitcasts around the call.
2067 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2068 llvm::Instruction *prev = call->getPrevNode();
2069 assert(prev);
2070 if (isa<llvm::BitCastInst>(prev)) {
2071 prev = prev->getPrevNode();
2072 assert(prev);
2073 }
2074 assert(isa<llvm::CallInst>(prev));
2075 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2076 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2077 insnsToKill.push_back(prev);
2078 }
John McCallf85e1932011-06-15 23:02:42 +00002079 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002080 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002081 }
2082
2083 result = call->getArgOperand(0);
2084 insnsToKill.push_back(call);
2085
2086 // Keep killing bitcasts, for sanity. Note that we no longer care
2087 // about precise ordering as long as there's exactly one use.
2088 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2089 if (!bitcast->hasOneUse()) break;
2090 insnsToKill.push_back(bitcast);
2091 result = bitcast->getOperand(0);
2092 }
2093
2094 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002095 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00002096 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2097 (*i)->eraseFromParent();
2098
2099 // Do the fused retain/autorelease if we were asked to.
2100 if (doRetainAutorelease)
2101 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2102
2103 // Cast back to the result type.
2104 return CGF.Builder.CreateBitCast(result, resultType);
2105}
2106
John McCall77fe6cd2012-01-29 07:46:59 +00002107/// If this is a +1 of the value of an immutable 'self', remove it.
2108static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2109 llvm::Value *result) {
2110 // This is only applicable to a method with an immutable 'self'.
John McCallbd9b65a2012-07-31 00:33:55 +00002111 const ObjCMethodDecl *method =
2112 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002113 if (!method) return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00002114 const VarDecl *self = method->getSelfDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002115 if (!self->getType().isConstQualified()) return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00002116
2117 // Look for a retain call.
2118 llvm::CallInst *retainCall =
2119 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2120 if (!retainCall ||
2121 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002122 return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00002123
2124 // Look for an ordinary load of 'self'.
2125 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2126 llvm::LoadInst *load =
2127 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2128 if (!load || load->isAtomic() || load->isVolatile() ||
2129 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002130 return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00002131
2132 // Okay! Burn it all down. This relies for correctness on the
2133 // assumption that the retain is emitted as part of the return and
2134 // that thereafter everything is used "linearly".
2135 llvm::Type *resultType = result->getType();
2136 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2137 assert(retainCall->use_empty());
2138 retainCall->eraseFromParent();
2139 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2140
2141 return CGF.Builder.CreateBitCast(load, resultType);
2142}
2143
John McCallf85e1932011-06-15 23:02:42 +00002144/// Emit an ARC autorelease of the result of a function.
John McCall77fe6cd2012-01-29 07:46:59 +00002145///
2146/// \return the value to actually return from the function
John McCallf85e1932011-06-15 23:02:42 +00002147static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2148 llvm::Value *result) {
John McCall77fe6cd2012-01-29 07:46:59 +00002149 // If we're returning 'self', kill the initial retain. This is a
2150 // heuristic attempt to "encourage correctness" in the really unfortunate
2151 // case where we have a return of self during a dealloc and we desperately
2152 // need to avoid the possible autorelease.
2153 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2154 return self;
2155
John McCallf85e1932011-06-15 23:02:42 +00002156 // At -O0, try to emit a fused retain/autorelease.
2157 if (CGF.shouldUseFusedARCCalls())
2158 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2159 return fused;
2160
2161 return CGF.EmitARCAutoreleaseReturnValue(result);
2162}
2163
John McCallf48f7962012-01-29 02:35:02 +00002164/// Heuristically search for a dominating store to the return-value slot.
2165static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2166 // If there are multiple uses of the return-value slot, just check
2167 // for something immediately preceding the IP. Sometimes this can
2168 // happen with how we generate implicit-returns; it can also happen
2169 // with noreturn cleanups.
2170 if (!CGF.ReturnValue->hasOneUse()) {
2171 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002172 if (IP->empty()) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00002173 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002174 if (!store) return nullptr;
2175 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00002176 assert(!store->isAtomic() && !store->isVolatile()); // see below
2177 return store;
2178 }
2179
2180 llvm::StoreInst *store =
Stephen Hines651f13c2014-04-23 16:59:28 -07002181 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002182 if (!store) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00002183
2184 // These aren't actually possible for non-coerced returns, and we
2185 // only care about non-coerced returns on this code path.
2186 assert(!store->isAtomic() && !store->isVolatile());
2187
2188 // Now do a first-and-dirty dominance check: just walk up the
2189 // single-predecessors chain from the current insertion point.
2190 llvm::BasicBlock *StoreBB = store->getParent();
2191 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2192 while (IP != StoreBB) {
2193 if (!(IP = IP->getSinglePredecessor()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002194 return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00002195 }
2196
2197 // Okay, the store's basic block dominates the insertion point; we
2198 // can do our thing.
2199 return store;
2200}
2201
Adrian Prantlfa6b0792013-05-02 17:30:20 +00002202void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002203 bool EmitRetDbgLoc,
2204 SourceLocation EndLoc) {
Stephen Hines176edba2014-12-01 14:53:08 -08002205 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2206 // Naked functions don't have epilogues.
2207 Builder.CreateUnreachable();
2208 return;
2209 }
2210
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002211 // Functions with no result always return void.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002212 if (!ReturnValue) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002213 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002214 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002215 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00002216
Dan Gohman4751a532010-07-20 20:13:52 +00002217 llvm::DebugLoc RetDbgLoc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002218 llvm::Value *RV = nullptr;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002219 QualType RetTy = FI.getReturnType();
2220 const ABIArgInfo &RetAI = FI.getReturnInfo();
2221
2222 switch (RetAI.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002223 case ABIArgInfo::InAlloca:
2224 // Aggregrates get evaluated directly into the destination. Sometimes we
2225 // need to return the sret value in a register, though.
2226 assert(hasAggregateEvaluationKind(RetTy));
2227 if (RetAI.getInAllocaSRet()) {
2228 llvm::Function::arg_iterator EI = CurFn->arg_end();
2229 --EI;
2230 llvm::Value *ArgStruct = EI;
2231 llvm::Value *SRet =
2232 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2233 RV = Builder.CreateLoad(SRet, "sret");
2234 }
2235 break;
2236
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002237 case ABIArgInfo::Indirect: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002238 auto AI = CurFn->arg_begin();
2239 if (RetAI.isSRetAfterThis())
2240 ++AI;
John McCall9d232c82013-03-07 21:37:08 +00002241 switch (getEvaluationKind(RetTy)) {
2242 case TEK_Complex: {
2243 ComplexPairTy RT =
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002244 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2245 EndLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002246 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall9d232c82013-03-07 21:37:08 +00002247 /*isInit*/ true);
2248 break;
2249 }
2250 case TEK_Aggregate:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002251 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall9d232c82013-03-07 21:37:08 +00002252 break;
2253 case TEK_Scalar:
2254 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002255 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall9d232c82013-03-07 21:37:08 +00002256 /*isInit*/ true);
2257 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002258 }
2259 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002260 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002261
2262 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00002263 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00002264 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2265 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00002266 // The internal return value temp always will have pointer-to-return-type
2267 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002268
John McCallf48f7962012-01-29 02:35:02 +00002269 // If there is a dominating store to ReturnValue, we can elide
2270 // the load, zap the store, and usually zap the alloca.
2271 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl7c731f52013-05-30 18:12:23 +00002272 // Reuse the debug location from the store unless there is
2273 // cleanup code to be emitted between the store and return
2274 // instruction.
2275 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantlfa6b0792013-05-02 17:30:20 +00002276 RetDbgLoc = SI->getDebugLoc();
Chris Lattner800588f2010-07-29 06:26:06 +00002277 // Get the stored value and nuke the now-dead store.
Chris Lattner800588f2010-07-29 06:26:06 +00002278 RV = SI->getValueOperand();
2279 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002280
Chris Lattner800588f2010-07-29 06:26:06 +00002281 // If that was the only use of the return value, nuke it as well now.
2282 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2283 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002284 ReturnValue = nullptr;
Chris Lattner800588f2010-07-29 06:26:06 +00002285 }
John McCallf48f7962012-01-29 02:35:02 +00002286
2287 // Otherwise, we have to do a simple load.
2288 } else {
2289 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner35b21b82010-06-27 01:06:27 +00002290 }
Chris Lattner800588f2010-07-29 06:26:06 +00002291 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00002292 llvm::Value *V = ReturnValue;
2293 // If the value is offset in memory, apply the offset now.
2294 if (unsigned Offs = RetAI.getDirectOffset()) {
2295 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2296 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002297 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00002298 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2299 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002300
Chris Lattner117e3f42010-07-30 04:02:24 +00002301 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00002302 }
John McCallf85e1932011-06-15 23:02:42 +00002303
2304 // In ARC, end functions that return a retainable type with a call
2305 // to objc_autoreleaseReturnValue.
2306 if (AutoreleaseResult) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002307 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002308 !FI.isReturnsRetained() &&
2309 RetTy->isObjCRetainableType());
2310 RV = emitAutoreleaseOfResult(*this, RV);
2311 }
2312
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002313 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002314
Chris Lattner800588f2010-07-29 06:26:06 +00002315 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002316 break;
2317
2318 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00002319 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00002320 }
2321
Stephen Hines176edba2014-12-01 14:53:08 -08002322 llvm::Instruction *Ret;
2323 if (RV) {
2324 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2325 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2326 SanitizerScope SanScope(this);
2327 llvm::Value *Cond = Builder.CreateICmpNE(
2328 RV, llvm::Constant::getNullValue(RV->getType()));
2329 llvm::Constant *StaticData[] = {
2330 EmitCheckSourceLocation(EndLoc),
2331 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2332 };
2333 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2334 "nonnull_return", StaticData, None);
2335 }
2336 }
2337 Ret = Builder.CreateRet(RV);
2338 } else {
2339 Ret = Builder.CreateRetVoid();
2340 }
2341
Devang Pateld3f265d2010-07-21 18:08:50 +00002342 if (!RetDbgLoc.isUnknown())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002343 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002344}
2345
Stephen Hines651f13c2014-04-23 16:59:28 -07002346static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2347 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2348 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2349}
2350
2351static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2352 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2353 // placeholders.
2354 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2355 llvm::Value *Placeholder =
2356 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2357 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2358 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2359 Ty.getQualifiers(),
2360 AggValueSlot::IsNotDestructed,
2361 AggValueSlot::DoesNotNeedGCBarriers,
2362 AggValueSlot::IsNotAliased);
2363}
2364
John McCall413ebdb2011-03-11 20:59:21 +00002365void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002366 const VarDecl *param,
2367 SourceLocation loc) {
John McCall27360712010-05-26 22:34:26 +00002368 // StartFunction converted the ABI-lowered parameter(s) into a
2369 // local alloca. We need to turn that into an r-value suitable
2370 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00002371 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00002372
John McCall413ebdb2011-03-11 20:59:21 +00002373 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002374
John McCall27360712010-05-26 22:34:26 +00002375 // For the most part, we just need to load the alloca, except:
2376 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall9d232c82013-03-07 21:37:08 +00002377 // 2) references to non-scalars are pointers directly to the aggregate.
2378 // I don't know why references to scalars are different here.
John McCall413ebdb2011-03-11 20:59:21 +00002379 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall9d232c82013-03-07 21:37:08 +00002380 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall413ebdb2011-03-11 20:59:21 +00002381 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00002382
2383 // Locals which are references to scalars are represented
2384 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00002385 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00002386 }
2387
Stephen Hines176edba2014-12-01 14:53:08 -08002388 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2389 "cannot emit delegate call arguments for inalloca arguments!");
Stephen Hines651f13c2014-04-23 16:59:28 -07002390
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002391 args.add(convertTempToRValue(local, type, loc), type);
John McCall27360712010-05-26 22:34:26 +00002392}
2393
John McCallf85e1932011-06-15 23:02:42 +00002394static bool isProvablyNull(llvm::Value *addr) {
2395 return isa<llvm::ConstantPointerNull>(addr);
2396}
2397
2398static bool isProvablyNonNull(llvm::Value *addr) {
2399 return isa<llvm::AllocaInst>(addr);
2400}
2401
2402/// Emit the actual writing-back of a writeback.
2403static void emitWriteback(CodeGenFunction &CGF,
2404 const CallArgList::Writeback &writeback) {
John McCallb6a60792013-03-23 02:35:54 +00002405 const LValue &srcLV = writeback.Source;
2406 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00002407 assert(!isProvablyNull(srcAddr) &&
2408 "shouldn't have writeback for provably null argument");
2409
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002410 llvm::BasicBlock *contBB = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002411
2412 // If the argument wasn't provably non-null, we need to null check
2413 // before doing the store.
2414 bool provablyNonNull = isProvablyNonNull(srcAddr);
2415 if (!provablyNonNull) {
2416 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2417 contBB = CGF.createBasicBlock("icr.done");
2418
2419 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2420 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2421 CGF.EmitBlock(writebackBB);
2422 }
2423
2424 // Load the value to writeback.
2425 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2426
2427 // Cast it back, in case we're writing an id to a Foo* or something.
2428 value = CGF.Builder.CreateBitCast(value,
2429 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2430 "icr.writeback-cast");
2431
2432 // Perform the writeback.
John McCallb6a60792013-03-23 02:35:54 +00002433
2434 // If we have a "to use" value, it's something we need to emit a use
2435 // of. This has to be carefully threaded in: if it's done after the
2436 // release it's potentially undefined behavior (and the optimizer
2437 // will ignore it), and if it happens before the retain then the
2438 // optimizer could move the release there.
2439 if (writeback.ToUse) {
2440 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2441
2442 // Retain the new value. No need to block-copy here: the block's
2443 // being passed up the stack.
2444 value = CGF.EmitARCRetainNonBlock(value);
2445
2446 // Emit the intrinsic use here.
2447 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2448
2449 // Load the old value (primitively).
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002450 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCallb6a60792013-03-23 02:35:54 +00002451
2452 // Put the new value in place (primitively).
2453 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2454
2455 // Release the old value.
2456 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2457
2458 // Otherwise, we can just do a normal lvalue store.
2459 } else {
2460 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2461 }
John McCallf85e1932011-06-15 23:02:42 +00002462
2463 // Jump to the continuation block.
2464 if (!provablyNonNull)
2465 CGF.EmitBlock(contBB);
2466}
2467
2468static void emitWritebacks(CodeGenFunction &CGF,
2469 const CallArgList &args) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002470 for (const auto &I : args.writebacks())
2471 emitWriteback(CGF, I);
John McCallf85e1932011-06-15 23:02:42 +00002472}
2473
Reid Kleckner9b601952013-06-21 12:45:15 +00002474static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2475 const CallArgList &CallArgs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002476 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner9b601952013-06-21 12:45:15 +00002477 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2478 CallArgs.getCleanupsToDeactivate();
2479 // Iterate in reverse to increase the likelihood of popping the cleanup.
2480 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2481 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2482 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2483 I->IsActiveIP->eraseFromParent();
2484 }
2485}
2486
John McCallb6a60792013-03-23 02:35:54 +00002487static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2488 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2489 if (uop->getOpcode() == UO_AddrOf)
2490 return uop->getSubExpr();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002491 return nullptr;
John McCallb6a60792013-03-23 02:35:54 +00002492}
2493
John McCallf85e1932011-06-15 23:02:42 +00002494/// Emit an argument that's being passed call-by-writeback. That is,
2495/// we are passing the address of
2496static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2497 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCallb6a60792013-03-23 02:35:54 +00002498 LValue srcLV;
2499
2500 // Make an optimistic effort to emit the address as an l-value.
2501 // This can fail if the the argument expression is more complicated.
2502 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2503 srcLV = CGF.EmitLValue(lvExpr);
2504
2505 // Otherwise, just emit it as a scalar.
2506 } else {
2507 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2508
2509 QualType srcAddrType =
2510 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2511 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2512 }
2513 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00002514
2515 // The dest and src types don't necessarily match in LLVM terms
2516 // because of the crazy ObjC compatibility rules.
2517
Chris Lattner2acc6e32011-07-18 04:24:23 +00002518 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00002519 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2520
2521 // If the address is a constant null, just pass the appropriate null.
2522 if (isProvablyNull(srcAddr)) {
2523 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2524 CRE->getType());
2525 return;
2526 }
2527
John McCallf85e1932011-06-15 23:02:42 +00002528 // Create the temporary.
2529 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2530 "icr.temp");
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002531 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2532 // and that cleanup will be conditional if we can't prove that the l-value
2533 // isn't null, so we need to register a dominating point so that the cleanups
2534 // system will make valid IR.
2535 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2536
John McCallf85e1932011-06-15 23:02:42 +00002537 // Zero-initialize it if we're not doing a copy-initialization.
2538 bool shouldCopy = CRE->shouldCopy();
2539 if (!shouldCopy) {
2540 llvm::Value *null =
2541 llvm::ConstantPointerNull::get(
2542 cast<llvm::PointerType>(destType->getElementType()));
2543 CGF.Builder.CreateStore(null, temp);
2544 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002545
2546 llvm::BasicBlock *contBB = nullptr;
2547 llvm::BasicBlock *originBB = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002548
2549 // If the address is *not* known to be non-null, we need to switch.
2550 llvm::Value *finalArgument;
2551
2552 bool provablyNonNull = isProvablyNonNull(srcAddr);
2553 if (provablyNonNull) {
2554 finalArgument = temp;
2555 } else {
2556 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2557
2558 finalArgument = CGF.Builder.CreateSelect(isNull,
2559 llvm::ConstantPointerNull::get(destType),
2560 temp, "icr.argument");
2561
2562 // If we need to copy, then the load has to be conditional, which
2563 // means we need control flow.
2564 if (shouldCopy) {
John McCallb6a60792013-03-23 02:35:54 +00002565 originBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00002566 contBB = CGF.createBasicBlock("icr.cont");
2567 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2568 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2569 CGF.EmitBlock(copyBB);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002570 condEval.begin(CGF);
John McCallf85e1932011-06-15 23:02:42 +00002571 }
2572 }
2573
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002574 llvm::Value *valueToUse = nullptr;
John McCallb6a60792013-03-23 02:35:54 +00002575
John McCallf85e1932011-06-15 23:02:42 +00002576 // Perform a copy if necessary.
2577 if (shouldCopy) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002578 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002579 assert(srcRV.isScalar());
2580
2581 llvm::Value *src = srcRV.getScalarVal();
2582 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2583 "icr.cast");
2584
2585 // Use an ordinary store, not a store-to-lvalue.
2586 CGF.Builder.CreateStore(src, temp);
John McCallb6a60792013-03-23 02:35:54 +00002587
2588 // If optimization is enabled, and the value was held in a
2589 // __strong variable, we need to tell the optimizer that this
2590 // value has to stay alive until we're doing the store back.
2591 // This is because the temporary is effectively unretained,
2592 // and so otherwise we can violate the high-level semantics.
2593 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2594 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2595 valueToUse = src;
2596 }
John McCallf85e1932011-06-15 23:02:42 +00002597 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002598
John McCallf85e1932011-06-15 23:02:42 +00002599 // Finish the control flow if we needed it.
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002600 if (shouldCopy && !provablyNonNull) {
John McCallb6a60792013-03-23 02:35:54 +00002601 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00002602 CGF.EmitBlock(contBB);
John McCallb6a60792013-03-23 02:35:54 +00002603
2604 // Make a phi for the value to intrinsically use.
2605 if (valueToUse) {
2606 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2607 "icr.to-use");
2608 phiToUse->addIncoming(valueToUse, copyBB);
2609 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2610 originBB);
2611 valueToUse = phiToUse;
2612 }
2613
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002614 condEval.end(CGF);
2615 }
John McCallf85e1932011-06-15 23:02:42 +00002616
John McCallb6a60792013-03-23 02:35:54 +00002617 args.addWriteback(srcLV, temp, valueToUse);
John McCallf85e1932011-06-15 23:02:42 +00002618 args.add(RValue::get(finalArgument), CRE->getType());
2619}
2620
Stephen Hines651f13c2014-04-23 16:59:28 -07002621void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2622 assert(!StackBase && !StackCleanup.isValid());
2623
2624 // Save the stack.
2625 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2626 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2627
2628 // Control gets really tied up in landing pads, so we have to spill the
2629 // stacksave to an alloca to avoid violating SSA form.
2630 // TODO: This is dead if we never emit the cleanup. We should create the
2631 // alloca and store lazily on the first cleanup emission.
2632 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2633 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2634 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2635 StackCleanup = CGF.EHStack.getInnermostEHScope();
2636 assert(StackCleanup.isValid());
2637}
2638
2639void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2640 if (StackBase) {
2641 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2642 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2643 // We could load StackBase from StackBaseMem, but in the non-exceptional
2644 // case we can skip it.
2645 CGF.Builder.CreateCall(F, StackBase);
2646 }
2647}
2648
Stephen Hines176edba2014-12-01 14:53:08 -08002649static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2650 QualType ArgType, SourceLocation ArgLoc,
2651 const FunctionDecl *FD, unsigned ParmNum) {
2652 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
2653 return;
2654 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2655 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2656 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2657 if (!NNAttr)
2658 return;
2659 CodeGenFunction::SanitizerScope SanScope(&CGF);
2660 assert(RV.isScalar());
2661 llvm::Value *V = RV.getScalarVal();
2662 llvm::Value *Cond =
2663 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2664 llvm::Constant *StaticData[] = {
2665 CGF.EmitCheckSourceLocation(ArgLoc),
2666 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2667 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2668 };
2669 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2670 "nonnull_arg", StaticData, None);
2671}
2672
Stephen Hines651f13c2014-04-23 16:59:28 -07002673void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2674 ArrayRef<QualType> ArgTypes,
2675 CallExpr::const_arg_iterator ArgBeg,
2676 CallExpr::const_arg_iterator ArgEnd,
Stephen Hines176edba2014-12-01 14:53:08 -08002677 const FunctionDecl *CalleeDecl,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002678 unsigned ParamsToSkip) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002679 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2680 // because arguments are destroyed left to right in the callee.
2681 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2682 // Insert a stack save if we're going to need any inalloca args.
2683 bool HasInAllocaArgs = false;
2684 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2685 I != E && !HasInAllocaArgs; ++I)
2686 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2687 if (HasInAllocaArgs) {
2688 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2689 Args.allocateArgumentMemory(*this);
2690 }
2691
2692 // Evaluate each argument.
2693 size_t CallArgsStart = Args.size();
2694 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2695 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2696 EmitCallArg(Args, *Arg, ArgTypes[I]);
Stephen Hines176edba2014-12-01 14:53:08 -08002697 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2698 CalleeDecl, ParamsToSkip + I);
Stephen Hines651f13c2014-04-23 16:59:28 -07002699 }
2700
2701 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2702 // IR function.
2703 std::reverse(Args.begin() + CallArgsStart, Args.end());
2704 return;
2705 }
2706
2707 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2708 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2709 assert(Arg != ArgEnd);
2710 EmitCallArg(Args, *Arg, ArgTypes[I]);
Stephen Hines176edba2014-12-01 14:53:08 -08002711 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2712 CalleeDecl, ParamsToSkip + I);
Stephen Hines651f13c2014-04-23 16:59:28 -07002713 }
2714}
2715
2716namespace {
2717
2718struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2719 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2720 : Addr(Addr), Ty(Ty) {}
2721
2722 llvm::Value *Addr;
2723 QualType Ty;
2724
2725 void Emit(CodeGenFunction &CGF, Flags flags) override {
2726 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2727 assert(!Dtor->isTrivial());
2728 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2729 /*Delegating=*/false, Addr);
2730 }
2731};
2732
2733}
2734
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002735struct DisableDebugLocationUpdates {
2736 CodeGenFunction &CGF;
2737 bool disabledDebugInfo;
2738 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2739 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2740 CGF.disableDebugInfo();
2741 }
2742 ~DisableDebugLocationUpdates() {
2743 if (disabledDebugInfo)
2744 CGF.enableDebugInfo();
2745 }
2746};
2747
John McCall413ebdb2011-03-11 20:59:21 +00002748void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2749 QualType type) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002750 DisableDebugLocationUpdates Dis(*this, E);
John McCallf85e1932011-06-15 23:02:42 +00002751 if (const ObjCIndirectCopyRestoreExpr *CRE
2752 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002753 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00002754 assert(getContext().hasSameType(E->getType(), type));
2755 return emitWritebackArg(*this, args, CRE);
2756 }
2757
John McCall8affed52011-08-26 18:42:59 +00002758 assert(type->isReferenceType() == E->isGLValue() &&
2759 "reference binding to unmaterialized r-value!");
2760
John McCallcec52f02011-08-26 21:08:13 +00002761 if (E->isGLValue()) {
2762 assert(E->getObjectKind() == OK_Ordinary);
Richard Smithd4ec5622013-06-12 23:38:09 +00002763 return args.add(EmitReferenceBindingToExpr(E), type);
John McCallcec52f02011-08-26 21:08:13 +00002764 }
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Reid Kleckner9b601952013-06-21 12:45:15 +00002766 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2767
2768 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2769 // However, we still have to push an EH-only cleanup in case we unwind before
2770 // we make it to the call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002771 if (HasAggregateEvalKind &&
2772 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2773 // If we're using inalloca, use the argument memory. Otherwise, use a
2774 // temporary.
2775 AggValueSlot Slot;
2776 if (args.isUsingInAlloca())
2777 Slot = createPlaceholderSlot(*this, type);
2778 else
2779 Slot = CreateAggTemp(type, "agg.tmp");
2780
2781 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2782 bool DestroyedInCallee =
2783 RD && RD->hasNonTrivialDestructor() &&
2784 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2785 if (DestroyedInCallee)
2786 Slot.setExternallyDestructed();
2787
Stephen Hines651f13c2014-04-23 16:59:28 -07002788 EmitAggExpr(E, Slot);
2789 RValue RV = Slot.asRValue();
2790 args.add(RV, type);
Reid Kleckner9b601952013-06-21 12:45:15 +00002791
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002792 if (DestroyedInCallee) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002793 // Create a no-op GEP between the placeholder and the cleanup so we can
2794 // RAUW it successfully. It also serves as a marker of the first
2795 // instruction where the cleanup is active.
2796 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner9b601952013-06-21 12:45:15 +00002797 // This unreachable is a temporary marker which will be removed later.
2798 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2799 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner9b601952013-06-21 12:45:15 +00002800 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002801 return;
Reid Kleckner9b601952013-06-21 12:45:15 +00002802 }
2803
2804 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00002805 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2806 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2807 assert(L.isSimple());
Eli Friedmand39083d2013-06-11 01:08:22 +00002808 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2809 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2810 } else {
2811 // We can't represent a misaligned lvalue in the CallArgList, so copy
2812 // to an aligned temporary now.
2813 llvm::Value *tmp = CreateMemTemp(type);
2814 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2815 L.getAlignment());
2816 args.add(RValue::getAggregate(tmp), type);
2817 }
Eli Friedman55d48482011-05-26 00:10:27 +00002818 return;
2819 }
2820
John McCall413ebdb2011-03-11 20:59:21 +00002821 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00002822}
2823
Stephen Hines176edba2014-12-01 14:53:08 -08002824QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2825 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2826 // implicitly widens null pointer constants that are arguments to varargs
2827 // functions to pointer-sized ints.
2828 if (!getTarget().getTriple().isOSWindows())
2829 return Arg->getType();
2830
2831 if (Arg->getType()->isIntegerType() &&
2832 getContext().getTypeSize(Arg->getType()) <
2833 getContext().getTargetInfo().getPointerWidth(0) &&
2834 Arg->isNullPointerConstant(getContext(),
2835 Expr::NPC_ValueDependentIsNotNull)) {
2836 return getContext().getIntPtrType();
2837 }
2838
2839 return Arg->getType();
2840}
2841
Dan Gohmanb49bd272012-02-16 00:57:37 +00002842// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2843// optimizer it can aggressively ignore unwind edges.
2844void
2845CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2846 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2847 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2848 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2849 CGM.getNoObjCARCExceptionsMetadata());
2850}
2851
John McCallbd7370a2013-02-28 19:01:20 +00002852/// Emits a call to the given no-arguments nounwind runtime function.
2853llvm::CallInst *
2854CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2855 const llvm::Twine &name) {
Stephen Hines176edba2014-12-01 14:53:08 -08002856 return EmitNounwindRuntimeCall(callee, None, name);
John McCallbd7370a2013-02-28 19:01:20 +00002857}
2858
2859/// Emits a call to the given nounwind runtime function.
2860llvm::CallInst *
2861CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2862 ArrayRef<llvm::Value*> args,
2863 const llvm::Twine &name) {
2864 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2865 call->setDoesNotThrow();
2866 return call;
2867}
2868
2869/// Emits a simple call (never an invoke) to the given no-arguments
2870/// runtime function.
2871llvm::CallInst *
2872CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2873 const llvm::Twine &name) {
Stephen Hines176edba2014-12-01 14:53:08 -08002874 return EmitRuntimeCall(callee, None, name);
John McCallbd7370a2013-02-28 19:01:20 +00002875}
2876
2877/// Emits a simple call (never an invoke) to the given runtime
2878/// function.
2879llvm::CallInst *
2880CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2881 ArrayRef<llvm::Value*> args,
2882 const llvm::Twine &name) {
2883 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2884 call->setCallingConv(getRuntimeCC());
2885 return call;
2886}
2887
2888/// Emits a call or invoke to the given noreturn runtime function.
2889void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2890 ArrayRef<llvm::Value*> args) {
2891 if (getInvokeDest()) {
2892 llvm::InvokeInst *invoke =
2893 Builder.CreateInvoke(callee,
2894 getUnreachableBlock(),
2895 getInvokeDest(),
2896 args);
2897 invoke->setDoesNotReturn();
2898 invoke->setCallingConv(getRuntimeCC());
2899 } else {
2900 llvm::CallInst *call = Builder.CreateCall(callee, args);
2901 call->setDoesNotReturn();
2902 call->setCallingConv(getRuntimeCC());
2903 Builder.CreateUnreachable();
2904 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002905 PGO.setCurrentRegionUnreachable();
John McCallbd7370a2013-02-28 19:01:20 +00002906}
2907
2908/// Emits a call or invoke instruction to the given nullary runtime
2909/// function.
2910llvm::CallSite
2911CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2912 const Twine &name) {
Stephen Hines176edba2014-12-01 14:53:08 -08002913 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCallbd7370a2013-02-28 19:01:20 +00002914}
2915
2916/// Emits a call or invoke instruction to the given runtime function.
2917llvm::CallSite
2918CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2919 ArrayRef<llvm::Value*> args,
2920 const Twine &name) {
2921 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2922 callSite.setCallingConv(getRuntimeCC());
2923 return callSite;
2924}
2925
2926llvm::CallSite
2927CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2928 const Twine &Name) {
Stephen Hines176edba2014-12-01 14:53:08 -08002929 return EmitCallOrInvoke(Callee, None, Name);
John McCallbd7370a2013-02-28 19:01:20 +00002930}
2931
John McCallf1549f62010-07-06 01:34:17 +00002932/// Emits a call or invoke instruction to the given function, depending
2933/// on the current state of the EH stack.
2934llvm::CallSite
2935CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002936 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002937 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00002938 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallf1549f62010-07-06 01:34:17 +00002939
Dan Gohmanb49bd272012-02-16 00:57:37 +00002940 llvm::Instruction *Inst;
2941 if (!InvokeDest)
2942 Inst = Builder.CreateCall(Callee, Args, Name);
2943 else {
2944 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2945 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2946 EmitBlock(ContBB);
2947 }
2948
2949 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2950 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002951 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002952 AddObjCARCExceptionMetadata(Inst);
2953
2954 return Inst;
John McCallf1549f62010-07-06 01:34:17 +00002955}
2956
Stephen Hines651f13c2014-04-23 16:59:28 -07002957/// \brief Store a non-aggregate value to an address to initialize it. For
2958/// initialization, a non-atomic store will be used.
2959static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2960 LValue Dst) {
2961 if (Src.isScalar())
2962 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2963 else
2964 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2965}
2966
2967void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2968 llvm::Value *New) {
2969 DeferredReplacements.push_back(std::make_pair(Old, New));
2970}
Chris Lattner811bf362011-07-12 06:29:11 +00002971
Daniel Dunbar88b53962009-02-02 22:03:45 +00002972RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002973 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00002974 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002975 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00002976 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00002977 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002978 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002979
2980 // Handle struct-return functions by passing a pointer to the
2981 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002982 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002983 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002984
Chris Lattner70855442011-07-12 04:46:18 +00002985 llvm::FunctionType *IRFuncTy =
2986 cast<llvm::FunctionType>(
2987 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Stephen Hines651f13c2014-04-23 16:59:28 -07002989 // If we're using inalloca, insert the allocation after the stack save.
2990 // FIXME: Do this earlier rather than hacking it in here!
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002991 llvm::Value *ArgMemory = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002992 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002993 llvm::Instruction *IP = CallArgs.getStackBase();
2994 llvm::AllocaInst *AI;
2995 if (IP) {
2996 IP = IP->getNextNode();
2997 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2998 } else {
2999 AI = CreateTempAlloca(ArgStruct, "argmem");
3000 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003001 AI->setUsedWithInAlloca(true);
3002 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3003 ArgMemory = AI;
3004 }
3005
Stephen Hines176edba2014-12-01 14:53:08 -08003006 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
3007 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3008
Chris Lattner5db7ae52009-06-13 00:26:38 +00003009 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00003010 // alloca to hold the result, unless one is given to us.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003011 llvm::Value *SRetPtr = nullptr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003012 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003013 SRetPtr = ReturnValue.getValue();
3014 if (!SRetPtr)
3015 SRetPtr = CreateMemTemp(RetTy);
Stephen Hines176edba2014-12-01 14:53:08 -08003016 if (IRFunctionArgs.hasSRetArg()) {
3017 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003018 } else {
3019 llvm::Value *Addr =
3020 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3021 Builder.CreateStore(SRetPtr, Addr);
3022 }
Anders Carlssond2490a92009-12-24 20:40:36 +00003023 }
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00003025 assert(CallInfo.arg_size() == CallArgs.size() &&
3026 "Mismatch between function signature & arguments.");
Stephen Hines176edba2014-12-01 14:53:08 -08003027 unsigned ArgNo = 0;
Daniel Dunbarb225be42009-02-03 05:59:18 +00003028 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00003029 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Stephen Hines176edba2014-12-01 14:53:08 -08003030 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb225be42009-02-03 05:59:18 +00003031 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00003032 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00003033
John McCall9d232c82013-03-07 21:37:08 +00003034 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00003035
3036 // Insert a padding argument to ensure proper alignment.
Stephen Hines176edba2014-12-01 14:53:08 -08003037 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3038 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3039 llvm::UndefValue::get(ArgInfo.getPaddingType());
3040
3041 unsigned FirstIRArg, NumIRArgs;
3042 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00003043
Daniel Dunbar56273772008-09-17 00:51:38 +00003044 switch (ArgInfo.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003045 case ABIArgInfo::InAlloca: {
Stephen Hines176edba2014-12-01 14:53:08 -08003046 assert(NumIRArgs == 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07003047 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3048 if (RV.isAggregate()) {
3049 // Replace the placeholder with the appropriate argument slot GEP.
3050 llvm::Instruction *Placeholder =
3051 cast<llvm::Instruction>(RV.getAggregateAddr());
3052 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3053 Builder.SetInsertPoint(Placeholder);
3054 llvm::Value *Addr = Builder.CreateStructGEP(
3055 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3056 Builder.restoreIP(IP);
3057 deferPlaceholderReplacement(Placeholder, Addr);
3058 } else {
3059 // Store the RValue into the argument struct.
3060 llvm::Value *Addr =
3061 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
3062 unsigned AS = Addr->getType()->getPointerAddressSpace();
3063 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3064 // There are some cases where a trivial bitcast is not avoidable. The
3065 // definition of a type later in a translation unit may change it's type
3066 // from {}* to (%struct.foo*)*.
3067 if (Addr->getType() != MemType)
3068 Addr = Builder.CreateBitCast(Addr, MemType);
3069 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3070 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3071 }
Stephen Hines176edba2014-12-01 14:53:08 -08003072 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003073 }
3074
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00003075 case ABIArgInfo::Indirect: {
Stephen Hines176edba2014-12-01 14:53:08 -08003076 assert(NumIRArgs == 1);
Daniel Dunbar1f745982009-02-05 09:16:39 +00003077 if (RV.isScalar() || RV.isComplex()) {
3078 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00003079 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3080 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3081 AI->setAlignment(ArgInfo.getIndirectAlign());
Stephen Hines176edba2014-12-01 14:53:08 -08003082 IRCallArgs[FirstIRArg] = AI;
John McCall9d232c82013-03-07 21:37:08 +00003083
Stephen Hines176edba2014-12-01 14:53:08 -08003084 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Stephen Hines651f13c2014-04-23 16:59:28 -07003085 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar1f745982009-02-05 09:16:39 +00003086 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00003087 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyeid436c992013-03-10 12:59:00 +00003088 // however, we need one in three cases:
Eli Friedmanea5e4da2011-06-14 01:37:52 +00003089 // 1. If the argument is not byval, and we are required to copy the
3090 // source. (This case doesn't occur on any common architecture.)
3091 // 2. If the argument is byval, RV is not sufficiently aligned, and
3092 // we cannot force it to be sufficiently aligned.
Guy Benyeid436c992013-03-10 12:59:00 +00003093 // 3. If the argument is byval, but RV is located in an address space
3094 // different than that of the argument (0).
Eli Friedman97cb5a42011-06-15 22:09:18 +00003095 llvm::Value *Addr = RV.getAggregateAddr();
3096 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmow25a6a842012-10-08 16:25:52 +00003097 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyeid436c992013-03-10 12:59:00 +00003098 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Stephen Hines176edba2014-12-01 14:53:08 -08003099 const unsigned ArgAddrSpace =
3100 (FirstIRArg < IRFuncTy->getNumParams()
3101 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3102 : 0);
Eli Friedman97cb5a42011-06-15 22:09:18 +00003103 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall9d232c82013-03-07 21:37:08 +00003104 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyeid436c992013-03-10 12:59:00 +00003105 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3106 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00003107 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00003108 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3109 if (Align > AI->getAlignment())
3110 AI->setAlignment(Align);
Stephen Hines176edba2014-12-01 14:53:08 -08003111 IRCallArgs[FirstIRArg] = AI;
Chad Rosier649b4a12012-03-29 17:37:10 +00003112 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmanea5e4da2011-06-14 01:37:52 +00003113 } else {
3114 // Skip the extra memcpy call.
Stephen Hines176edba2014-12-01 14:53:08 -08003115 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmanea5e4da2011-06-14 01:37:52 +00003116 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00003117 }
3118 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00003119 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00003120
Daniel Dunbar11434922009-01-26 21:26:08 +00003121 case ABIArgInfo::Ignore:
Stephen Hines176edba2014-12-01 14:53:08 -08003122 assert(NumIRArgs == 0);
Daniel Dunbar11434922009-01-26 21:26:08 +00003123 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003124
Chris Lattner800588f2010-07-29 06:26:06 +00003125 case ABIArgInfo::Extend:
3126 case ABIArgInfo::Direct: {
3127 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00003128 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3129 ArgInfo.getDirectOffset() == 0) {
Stephen Hines176edba2014-12-01 14:53:08 -08003130 assert(NumIRArgs == 1);
Chris Lattner70855442011-07-12 04:46:18 +00003131 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00003132 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00003133 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00003134 else
Chris Lattner70855442011-07-12 04:46:18 +00003135 V = Builder.CreateLoad(RV.getAggregateAddr());
Stephen Hines176edba2014-12-01 14:53:08 -08003136
3137 // We might have to widen integers, but we should never truncate.
3138 if (ArgInfo.getCoerceToType() != V->getType() &&
3139 V->getType()->isIntegerTy())
3140 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3141
Chris Lattner21ca1fd2011-07-12 04:53:39 +00003142 // If the argument doesn't match, perform a bitcast to coerce it. This
3143 // can happen due to trivial type mismatches.
Stephen Hines176edba2014-12-01 14:53:08 -08003144 if (FirstIRArg < IRFuncTy->getNumParams() &&
3145 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3146 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3147 IRCallArgs[FirstIRArg] = V;
Chris Lattner800588f2010-07-29 06:26:06 +00003148 break;
3149 }
Daniel Dunbar11434922009-01-26 21:26:08 +00003150
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00003151 // FIXME: Avoid the conversion through memory if possible.
3152 llvm::Value *SrcPtr;
John McCall9d232c82013-03-07 21:37:08 +00003153 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00003154 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall9d232c82013-03-07 21:37:08 +00003155 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Stephen Hines651f13c2014-04-23 16:59:28 -07003156 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump1eb44332009-09-09 15:08:12 +00003157 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00003158 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003159
Chris Lattner117e3f42010-07-30 04:02:24 +00003160 // If the value is offset in memory, apply the offset now.
3161 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3162 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3163 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003164 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00003165 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3166
3167 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003168
Stephen Hines176edba2014-12-01 14:53:08 -08003169 // Fast-isel and the optimizer generally like scalar values better than
3170 // FCAs, so we flatten them if this is safe to do for this argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003171 llvm::StructType *STy =
3172 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Stephen Hines176edba2014-12-01 14:53:08 -08003173 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carruthf82232c2012-10-10 11:29:08 +00003174 llvm::Type *SrcTy =
3175 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3176 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3177 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3178
3179 // If the source type is smaller than the destination type of the
3180 // coerce-to logic, copy the source value into a temp alloca the size
3181 // of the destination type to allow loading all of it. The bits past
3182 // the source value are left undef.
3183 if (SrcSize < DstSize) {
3184 llvm::AllocaInst *TempAlloca
3185 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3186 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3187 SrcPtr = TempAlloca;
3188 } else {
3189 SrcPtr = Builder.CreateBitCast(SrcPtr,
3190 llvm::PointerType::getUnqual(STy));
3191 }
3192
Stephen Hines176edba2014-12-01 14:53:08 -08003193 assert(NumIRArgs == STy->getNumElements());
Chris Lattner92826882010-07-05 20:41:41 +00003194 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3195 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00003196 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3197 // We don't know what we're loading from.
3198 LI->setAlignment(1);
Stephen Hines176edba2014-12-01 14:53:08 -08003199 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner309c59f2010-06-29 00:06:42 +00003200 }
Chris Lattnerce700162010-06-28 23:44:11 +00003201 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00003202 // In the simple case, just pass the coerced loaded value.
Stephen Hines176edba2014-12-01 14:53:08 -08003203 assert(NumIRArgs == 1);
3204 IRCallArgs[FirstIRArg] =
3205 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattnerce700162010-06-28 23:44:11 +00003206 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003207
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00003208 break;
3209 }
3210
Daniel Dunbar56273772008-09-17 00:51:38 +00003211 case ABIArgInfo::Expand:
Stephen Hines176edba2014-12-01 14:53:08 -08003212 unsigned IRArgPos = FirstIRArg;
3213 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3214 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar56273772008-09-17 00:51:38 +00003215 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00003216 }
3217 }
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Stephen Hines651f13c2014-04-23 16:59:28 -07003219 if (ArgMemory) {
3220 llvm::Value *Arg = ArgMemory;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003221 if (CallInfo.isVariadic()) {
3222 // When passing non-POD arguments by value to variadic functions, we will
3223 // end up with a variadic prototype and an inalloca call site. In such
3224 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3225 // the callee.
3226 unsigned CalleeAS =
3227 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3228 Callee = Builder.CreateBitCast(
3229 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3230 } else {
3231 llvm::Type *LastParamTy =
3232 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3233 if (Arg->getType() != LastParamTy) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003234#ifndef NDEBUG
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003235 // Assert that these structs have equivalent element types.
3236 llvm::StructType *FullTy = CallInfo.getArgStruct();
3237 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3238 cast<llvm::PointerType>(LastParamTy)->getElementType());
3239 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3240 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3241 DE = DeclaredTy->element_end(),
3242 FI = FullTy->element_begin();
3243 DI != DE; ++DI, ++FI)
3244 assert(*DI == *FI);
Stephen Hines651f13c2014-04-23 16:59:28 -07003245#endif
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003246 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3247 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003248 }
Stephen Hines176edba2014-12-01 14:53:08 -08003249 assert(IRFunctionArgs.hasInallocaArg());
3250 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Stephen Hines651f13c2014-04-23 16:59:28 -07003251 }
3252
Reid Kleckner9b601952013-06-21 12:45:15 +00003253 if (!CallArgs.getCleanupsToDeactivate().empty())
3254 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3255
Chris Lattner5db7ae52009-06-13 00:26:38 +00003256 // If the callee is a bitcast of a function to a varargs pointer to function
3257 // type, check to see if we can remove the bitcast. This handles some cases
3258 // with unprototyped functions.
3259 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3260 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00003261 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3262 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00003263 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00003264 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Chris Lattner5db7ae52009-06-13 00:26:38 +00003266 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3267 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00003268 ActualFT->getNumParams() == CurFT->getNumParams() &&
Stephen Hines176edba2014-12-01 14:53:08 -08003269 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00003270 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00003271 bool ArgsMatch = true;
3272 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3273 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3274 ArgsMatch = false;
3275 break;
3276 }
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Chris Lattner5db7ae52009-06-13 00:26:38 +00003278 // Strip the cast if we can get away with it. This is a nice cleanup,
3279 // but also allows us to inline the function at -O0 if it is marked
3280 // always_inline.
3281 if (ArgsMatch)
3282 Callee = CalleeF;
3283 }
3284 }
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Stephen Hines176edba2014-12-01 14:53:08 -08003286 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3287 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3288 // Inalloca argument can have different type.
3289 if (IRFunctionArgs.hasInallocaArg() &&
3290 i == IRFunctionArgs.getInallocaArgNo())
3291 continue;
3292 if (i < IRFuncTy->getNumParams())
3293 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3294 }
3295
Daniel Dunbarca6408c2009-09-12 00:59:20 +00003296 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00003297 CodeGen::AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +00003298 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3299 CallingConv, true);
Bill Wendling785b7782012-12-07 23:17:26 +00003300 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendling94236e72013-02-22 00:13:35 +00003301 AttributeList);
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003303 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling01ad9542012-12-30 10:32:17 +00003304 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003305 llvm::Attribute::NoUnwind) ||
3306 currentFunctionUsesSEHTry())
John McCallf1549f62010-07-06 01:34:17 +00003307 InvokeDest = getInvokeDest();
3308
Daniel Dunbard14151d2009-03-02 04:32:35 +00003309 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00003310 if (!InvokeDest) {
Stephen Hines176edba2014-12-01 14:53:08 -08003311 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00003312 } else {
3313 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Stephen Hines176edba2014-12-01 14:53:08 -08003314 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00003315 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00003316 }
Chris Lattnerce933992010-06-29 16:40:28 +00003317 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00003318 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00003319
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003320 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3321 !CS.hasFnAttr(llvm::Attribute::NoInline))
3322 Attrs =
3323 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3324 llvm::Attribute::AlwaysInline);
3325
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003326 // Disable inlining inside SEH __try blocks.
3327 if (isSEHTryScope())
3328 Attrs =
3329 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3330 llvm::Attribute::NoInline);
3331
Daniel Dunbard14151d2009-03-02 04:32:35 +00003332 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00003333 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00003334
Dan Gohmanb49bd272012-02-16 00:57:37 +00003335 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3336 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00003337 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00003338 AddObjCARCExceptionMetadata(CS.getInstruction());
3339
Daniel Dunbard14151d2009-03-02 04:32:35 +00003340 // If the call doesn't return, finish the basic block and clear the
3341 // insertion point; this allows the rest of IRgen to discard
3342 // unreachable code.
3343 if (CS.doesNotReturn()) {
3344 Builder.CreateUnreachable();
3345 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00003346
Mike Stumpf5408fe2009-05-16 07:57:57 +00003347 // FIXME: For now, emit a dummy basic block because expr emitters in
3348 // generally are not ready to handle emitting expressions at unreachable
3349 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00003350 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Daniel Dunbard14151d2009-03-02 04:32:35 +00003352 // Return a reasonable RValue.
3353 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003354 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00003355
3356 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00003357 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00003358 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00003359
John McCallf85e1932011-06-15 23:02:42 +00003360 // Emit any writebacks immediately. Arguably this should happen
3361 // after any return-value munging.
3362 if (CallArgs.hasWritebacks())
3363 emitWritebacks(*this, CallArgs);
3364
Stephen Hines651f13c2014-04-23 16:59:28 -07003365 // The stack cleanup for inalloca arguments has to run out of the normal
3366 // lexical order, so deactivate it and run it manually here.
3367 CallArgs.freeArgumentMemory(*this);
3368
Stephen Hines176edba2014-12-01 14:53:08 -08003369 RValue Ret = [&] {
3370 switch (RetAI.getKind()) {
3371 case ABIArgInfo::InAlloca:
3372 case ABIArgInfo::Indirect:
3373 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00003374
Stephen Hines176edba2014-12-01 14:53:08 -08003375 case ABIArgInfo::Ignore:
3376 // If we are ignoring an argument that had a result, make sure to
3377 // construct the appropriate return value for our caller.
3378 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003379
Stephen Hines176edba2014-12-01 14:53:08 -08003380 case ABIArgInfo::Extend:
3381 case ABIArgInfo::Direct: {
3382 llvm::Type *RetIRTy = ConvertType(RetTy);
3383 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3384 switch (getEvaluationKind(RetTy)) {
3385 case TEK_Complex: {
3386 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3387 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3388 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattner800588f2010-07-29 06:26:06 +00003389 }
Stephen Hines176edba2014-12-01 14:53:08 -08003390 case TEK_Aggregate: {
3391 llvm::Value *DestPtr = ReturnValue.getValue();
3392 bool DestIsVolatile = ReturnValue.isVolatile();
3393
3394 if (!DestPtr) {
3395 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3396 DestIsVolatile = false;
3397 }
3398 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3399 return RValue::getAggregate(DestPtr);
3400 }
3401 case TEK_Scalar: {
3402 // If the argument doesn't match, perform a bitcast to coerce it. This
3403 // can happen due to trivial type mismatches.
3404 llvm::Value *V = CI;
3405 if (V->getType() != RetIRTy)
3406 V = Builder.CreateBitCast(V, RetIRTy);
3407 return RValue::get(V);
3408 }
3409 }
3410 llvm_unreachable("bad evaluation kind");
Chris Lattner800588f2010-07-29 06:26:06 +00003411 }
Stephen Hines176edba2014-12-01 14:53:08 -08003412
3413 llvm::Value *DestPtr = ReturnValue.getValue();
3414 bool DestIsVolatile = ReturnValue.isVolatile();
3415
3416 if (!DestPtr) {
3417 DestPtr = CreateMemTemp(RetTy, "coerce");
3418 DestIsVolatile = false;
John McCall9d232c82013-03-07 21:37:08 +00003419 }
Stephen Hines176edba2014-12-01 14:53:08 -08003420
3421 // If the value is offset in memory, apply the offset now.
3422 llvm::Value *StorePtr = DestPtr;
3423 if (unsigned Offs = RetAI.getDirectOffset()) {
3424 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3425 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3426 StorePtr = Builder.CreateBitCast(StorePtr,
3427 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall9d232c82013-03-07 21:37:08 +00003428 }
Stephen Hines176edba2014-12-01 14:53:08 -08003429 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3430
3431 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattner800588f2010-07-29 06:26:06 +00003432 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003433
Stephen Hines176edba2014-12-01 14:53:08 -08003434 case ABIArgInfo::Expand:
3435 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlssond2490a92009-12-24 20:40:36 +00003436 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003437
Stephen Hines176edba2014-12-01 14:53:08 -08003438 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3439 } ();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003440
Stephen Hines176edba2014-12-01 14:53:08 -08003441 if (Ret.isScalar() && TargetDecl) {
3442 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3443 llvm::Value *OffsetValue = nullptr;
3444 if (const auto *Offset = AA->getOffset())
3445 OffsetValue = EmitScalarExpr(Offset);
3446
3447 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3448 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3449 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3450 OffsetValue);
3451 }
Daniel Dunbar639ffe42008-09-10 07:04:09 +00003452 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00003453
Stephen Hines176edba2014-12-01 14:53:08 -08003454 return Ret;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00003455}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00003456
3457/* VarArg handling */
3458
3459llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3460 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3461}