blob: 7fb301c8c3680ee7d3884083d34775ae6e610fc4 [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000029#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000035#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000036#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000037#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000038using namespace clang;
39using namespace CodeGen;
40
41/***/
42
John McCallab26cfa2010-02-05 21:31:56 +000043static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
44 switch (CC) {
45 default: return llvm::CallingConv::C;
46 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
47 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000048 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000049 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
50 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000051 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
52 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000053 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000054 // TODO: Add support for __pascal to LLVM.
55 case CC_X86Pascal: return llvm::CallingConv::C;
56 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000057 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000058 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
59 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000060 }
61}
62
John McCall8ee376f2010-02-24 07:14:12 +000063/// Derives the 'this' type for codegen purposes, i.e. ignoring method
64/// qualification.
65/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000066static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
67 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
68 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000069}
70
John McCall8ee376f2010-02-24 07:14:12 +000071/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
73 return MD->getType()->getCanonicalTypeUnqualified()
74 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000075}
76
77/// Returns the "extra-canonicalized" return type, which discards
78/// qualifiers on the return type. Codegen doesn't care about them,
79/// and it makes ABI code a little easier to be able to assume that
80/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000081static CanQualType GetReturnType(QualType RetTy) {
82 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000083}
84
John McCall8dda7b22012-07-07 06:41:13 +000085/// Arrange the argument and result information for a value of the given
86/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000087const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000088CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000089 // When translating an unprototyped function type, always use a
90 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000091 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000092 /*instanceMethod=*/false,
93 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000094 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000095}
96
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000097/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
98/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
99static void appendParameterTypes(const CodeGenTypes &CGT,
100 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000101 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
102 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000103 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000104 // Fill out paramInfos.
105 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
106 assert(paramInfos.size() <= prefix.size());
107 auto protoParamInfos = FPT->getExtParameterInfos();
108 paramInfos.reserve(prefix.size() + protoParamInfos.size());
109 paramInfos.resize(prefix.size());
110 paramInfos.append(paramInfos.begin(), paramInfos.end());
111 }
112
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000113 // Fast path: unknown target.
114 if (FD == nullptr) {
115 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
116 return;
117 }
118
119 // In the vast majority cases, we'll have precisely FPT->getNumParams()
120 // parameters; the only thing that can change this is the presence of
121 // pass_object_size. So, we preallocate for the common case.
122 prefix.reserve(prefix.size() + FPT->getNumParams());
123
124 assert(FD->getNumParams() == FPT->getNumParams());
125 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
126 prefix.push_back(FPT->getParamType(I));
127 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
128 prefix.push_back(CGT.getContext().getSizeType());
129 }
130}
131
John McCall8dda7b22012-07-07 06:41:13 +0000132/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000133/// type, on top of any implicit parameters already stored.
134static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000135arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000136 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000137 CanQual<FunctionProtoType> FTP,
138 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000139 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
John McCall8dda7b22012-07-07 06:41:13 +0000140 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000141 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000142 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000143 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000144
Peter Collingbournef7706832014-12-12 23:41:25 +0000145 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
146 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000147 FTP->getExtInfo(), paramInfos,
148 required);
John McCall8ee376f2010-02-24 07:14:12 +0000149}
150
John McCalla729c622012-02-17 03:33:10 +0000151/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000152/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000153const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000154CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
155 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000156 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000157 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000158 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000159}
160
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000161static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000162 // Set the appropriate calling convention for the Function.
163 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000164 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000165
166 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000167 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000168
Douglas Gregora941dca2010-05-18 16:57:00 +0000169 if (D->hasAttr<ThisCallAttr>())
170 return CC_X86ThisCall;
171
Reid Klecknerd7857f02014-10-24 17:42:17 +0000172 if (D->hasAttr<VectorCallAttr>())
173 return CC_X86VectorCall;
174
Dawn Perchik335e16b2010-09-03 01:29:35 +0000175 if (D->hasAttr<PascalAttr>())
176 return CC_X86Pascal;
177
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000178 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
179 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
180
Guy Benyeif0a014b2012-12-25 08:53:55 +0000181 if (D->hasAttr<IntelOclBiccAttr>())
182 return CC_IntelOclBicc;
183
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000184 if (D->hasAttr<MSABIAttr>())
185 return IsWindows ? CC_C : CC_X86_64Win64;
186
187 if (D->hasAttr<SysVABIAttr>())
188 return IsWindows ? CC_X86_64SysV : CC_C;
189
John McCallab26cfa2010-02-05 21:31:56 +0000190 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000191}
192
John McCalla729c622012-02-17 03:33:10 +0000193/// Arrange the argument and result information for a call to an
194/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000195/// (Zero value of RD means we don't have any meaningful "this" argument type,
196/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000197/// The member function must be an ordinary function, i.e. not a
198/// constructor or destructor.
199const CGFunctionInfo &
200CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000201 const FunctionProtoType *FTP,
202 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000203 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000204
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000205 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000206 if (RD)
207 argTypes.push_back(GetThisType(Context, RD));
208 else
209 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000210
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000211 return ::arrangeLLVMFunctionInfo(
212 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000213 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000214}
215
John McCalla729c622012-02-17 03:33:10 +0000216/// Arrange the argument and result information for a declaration or
217/// definition of the given C++ non-static member function. The
218/// member function must be an ordinary function, i.e. not a
219/// constructor or destructor.
220const CGFunctionInfo &
221CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000222 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000223 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
224
John McCalla729c622012-02-17 03:33:10 +0000225 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000226
John McCalla729c622012-02-17 03:33:10 +0000227 if (MD->isInstance()) {
228 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000229 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000230 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000231 }
232
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000233 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000234}
235
John McCalla729c622012-02-17 03:33:10 +0000236const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000237CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
238 StructorType Type) {
239
John McCalla729c622012-02-17 03:33:10 +0000240 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000241 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000242 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000243
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000244 GlobalDecl GD;
245 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
246 GD = GlobalDecl(CD, toCXXCtorType(Type));
247 } else {
248 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
249 GD = GlobalDecl(DD, toCXXDtorType(Type));
250 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000251
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000252 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000253
254 // Add the formal parameters.
John McCallc56a8b32016-03-11 04:30:31 +0000255 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000256
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000257 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000258
259 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000260 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000261
John McCall8dda7b22012-07-07 06:41:13 +0000262 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000263 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
264 ? argTypes.front()
265 : TheCXXABI.hasMostDerivedReturn(GD)
266 ? CGM.getContext().VoidPtrTy
267 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000268 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
269 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000270 paramInfos, required);
271}
272
273static SmallVector<CanQualType, 16>
274getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
275 SmallVector<CanQualType, 16> argTypes;
276 for (auto &arg : args)
277 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
278 return argTypes;
279}
280
281static SmallVector<CanQualType, 16>
282getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
283 SmallVector<CanQualType, 16> argTypes;
284 for (auto &arg : args)
285 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
286 return argTypes;
287}
288
289static void addExtParameterInfosForCall(
290 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
291 const FunctionProtoType *proto,
292 unsigned prefixArgs,
293 unsigned totalArgs) {
294 assert(proto->hasExtParameterInfos());
295 assert(paramInfos.size() <= prefixArgs);
296 assert(proto->getNumParams() + prefixArgs <= totalArgs);
297
298 // Add default infos for any prefix args that don't already have infos.
299 paramInfos.resize(prefixArgs);
300
301 // Add infos for the prototype.
302 auto protoInfos = proto->getExtParameterInfos();
303 paramInfos.append(protoInfos.begin(), protoInfos.end());
304
305 // Add default infos for the variadic arguments.
306 paramInfos.resize(totalArgs);
307}
308
309static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
310getExtParameterInfosForCall(const FunctionProtoType *proto,
311 unsigned prefixArgs, unsigned totalArgs) {
312 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
313 if (proto->hasExtParameterInfos()) {
314 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
315 }
316 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000317}
318
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000319/// Arrange a call to a C++ method, passing the given arguments.
320const CGFunctionInfo &
321CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
322 const CXXConstructorDecl *D,
323 CXXCtorType CtorKind,
324 unsigned ExtraArgs) {
325 // FIXME: Kill copy.
326 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000327 for (const auto &Arg : args)
328 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000329
330 CanQual<FunctionProtoType> FPT = GetFormalType(D);
331 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
332 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000333 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
334 ? ArgTypes.front()
335 : TheCXXABI.hasMostDerivedReturn(GD)
336 ? CGM.getContext().VoidPtrTy
337 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000338
339 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000340 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
341 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000342 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
343 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000344 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000345}
346
John McCalla729c622012-02-17 03:33:10 +0000347/// Arrange the argument and result information for the declaration or
348/// definition of the given function.
349const CGFunctionInfo &
350CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000351 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000352 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000353 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000354
John McCall2da83a32010-02-26 00:48:12 +0000355 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000356
John McCall2da83a32010-02-26 00:48:12 +0000357 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000358
359 // When declaring a function without a prototype, always use a
360 // non-variadic type.
361 if (isa<FunctionNoProtoType>(FTy)) {
362 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000363 return arrangeLLVMFunctionInfo(
364 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000365 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000366 }
367
John McCall2da83a32010-02-26 00:48:12 +0000368 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000369 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000370}
371
John McCalla729c622012-02-17 03:33:10 +0000372/// Arrange the argument and result information for the declaration or
373/// definition of an Objective-C method.
374const CGFunctionInfo &
375CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
376 // It happens that this is the same as a call with no optional
377 // arguments, except also using the formal 'self' type.
378 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
379}
380
381/// Arrange the argument and result information for the function type
382/// through which to perform a send to the given Objective-C method,
383/// using the given receiver type. The receiver type is not always
384/// the 'self' type of the method or even an Objective-C pointer type.
385/// This is *not* the right method for actually performing such a
386/// message send, due to the possibility of optional arguments.
387const CGFunctionInfo &
388CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
389 QualType receiverType) {
390 SmallVector<CanQualType, 16> argTys;
391 argTys.push_back(Context.getCanonicalParamType(receiverType));
392 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000393 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000394 for (const auto *I : MD->params()) {
395 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000396 }
John McCall31168b02011-06-15 23:02:42 +0000397
398 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000399 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
400 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000401
David Blaikiebbafb8a2012-03-11 07:00:24 +0000402 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000403 MD->hasAttr<NSReturnsRetainedAttr>())
404 einfo = einfo.withProducesResult(true);
405
John McCalla729c622012-02-17 03:33:10 +0000406 RequiredArgs required =
407 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
408
Peter Collingbournef7706832014-12-12 23:41:25 +0000409 return arrangeLLVMFunctionInfo(
410 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000411 /*chainCall=*/false, argTys, einfo, {}, required);
412}
413
414const CGFunctionInfo &
415CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
416 const CallArgList &args) {
417 auto argTypes = getArgTypesForCall(Context, args);
418 FunctionType::ExtInfo einfo;
419
420 return arrangeLLVMFunctionInfo(
421 GetReturnType(returnType), /*instanceMethod=*/false,
422 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000423}
424
John McCalla729c622012-02-17 03:33:10 +0000425const CGFunctionInfo &
426CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000427 // FIXME: Do we need to handle ObjCMethodDecl?
428 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000429
Anders Carlsson6710c532010-02-06 02:44:09 +0000430 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000431 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000432
433 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000434 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000435
John McCalla729c622012-02-17 03:33:10 +0000436 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000437}
438
Reid Klecknerc3473512014-08-29 21:43:29 +0000439/// Arrange a thunk that takes 'this' as the first parameter followed by
440/// varargs. Return a void pointer, regardless of the actual return type.
441/// The body of the thunk will end in a musttail call to a function of the
442/// correct type, and the caller will bitcast the function to the correct
443/// prototype.
444const CGFunctionInfo &
445CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
446 assert(MD->isVirtual() && "only virtual memptrs have thunks");
447 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
448 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000449 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
450 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000451 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000452}
453
David Majnemerdfa6d202015-03-11 18:36:39 +0000454const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000455CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
456 CXXCtorType CT) {
457 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
458
David Majnemerdfa6d202015-03-11 18:36:39 +0000459 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
460 SmallVector<CanQualType, 2> ArgTys;
461 const CXXRecordDecl *RD = CD->getParent();
462 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000463 if (CT == Ctor_CopyingClosure)
464 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000465 if (RD->getNumVBases() > 0)
466 ArgTys.push_back(Context.IntTy);
467 CallingConv CC = Context.getDefaultCallingConvention(
468 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
469 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
470 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000471 FunctionType::ExtInfo(CC), {},
472 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000473}
474
John McCallc818bbb2012-12-07 07:03:17 +0000475/// Arrange a call as unto a free function, except possibly with an
476/// additional number of formal parameters considered required.
477static const CGFunctionInfo &
478arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000479 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000480 const CallArgList &args,
481 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000482 unsigned numExtraRequiredArgs,
483 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000484 assert(args.size() >= numExtraRequiredArgs);
485
John McCallc56a8b32016-03-11 04:30:31 +0000486 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
487
John McCallc818bbb2012-12-07 07:03:17 +0000488 // In most cases, there are no optional arguments.
489 RequiredArgs required = RequiredArgs::All;
490
491 // If we have a variadic prototype, the required arguments are the
492 // extra prefix plus the arguments in the prototype.
493 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
494 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000495 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000496
John McCallc56a8b32016-03-11 04:30:31 +0000497 if (proto->hasExtParameterInfos())
498 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
499 args.size());
500
John McCallc818bbb2012-12-07 07:03:17 +0000501 // If we don't have a prototype at all, but we're supposed to
502 // explicitly use the variadic convention for unprototyped calls,
503 // treat all of the arguments as required but preserve the nominal
504 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000505 } else if (CGM.getTargetCodeGenInfo()
506 .isNoProtoCallVariadic(args,
507 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000508 required = RequiredArgs(args.size());
509 }
510
Peter Collingbournef7706832014-12-12 23:41:25 +0000511 // FIXME: Kill copy.
512 SmallVector<CanQualType, 16> argTypes;
513 for (const auto &arg : args)
514 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
515 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
516 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000517 argTypes, fnType->getExtInfo(), paramInfos,
518 required);
John McCallc818bbb2012-12-07 07:03:17 +0000519}
520
John McCalla729c622012-02-17 03:33:10 +0000521/// Figure out the rules for calling a function with the given formal
522/// type using the given arguments. The arguments are necessary
523/// because the function might be unprototyped, in which case it's
524/// target-dependent in crazy ways.
525const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000526CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000527 const FunctionType *fnType,
528 bool chainCall) {
529 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
530 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000531}
John McCalla729c622012-02-17 03:33:10 +0000532
John McCallc56a8b32016-03-11 04:30:31 +0000533/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000534/// extra implicit argument.
535const CGFunctionInfo &
536CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
537 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000538 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
539 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000540}
541
542const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000543CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
544 const FunctionArgList &params) {
545 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
546 auto argTypes = getArgTypesForDeclaration(Context, params);
547
548 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
549 /*instanceMethod*/ false, /*chainCall*/ false,
550 argTypes, proto->getExtInfo(), paramInfos,
551 RequiredArgs::forPrototypePlus(proto, 1));
552}
553
554const CGFunctionInfo &
555CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
556 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000557 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000558 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000559 for (const auto &Arg : args)
560 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000561 return arrangeLLVMFunctionInfo(
562 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000563 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
564 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000565}
566
John McCallc56a8b32016-03-11 04:30:31 +0000567const CGFunctionInfo &
568CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
569 const FunctionArgList &args) {
570 auto argTypes = getArgTypesForDeclaration(Context, args);
571
572 return arrangeLLVMFunctionInfo(
573 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
574 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
575}
576
577const CGFunctionInfo &
578CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
579 ArrayRef<CanQualType> argTypes) {
580 return arrangeLLVMFunctionInfo(
581 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
582 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
583}
584
585
John McCall8dda7b22012-07-07 06:41:13 +0000586/// Arrange a call to a C++ method, passing the given arguments.
587const CGFunctionInfo &
588CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000589 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000590 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000591 unsigned numRequiredArgs =
592 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
593 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
594 auto paramInfos =
595 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
596
John McCall8dda7b22012-07-07 06:41:13 +0000597 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000598 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000599
John McCallc56a8b32016-03-11 04:30:31 +0000600 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000601 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000602 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
603 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000604}
605
John McCalla729c622012-02-17 03:33:10 +0000606const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000607 return arrangeLLVMFunctionInfo(
608 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000609 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
610}
611
612const CGFunctionInfo &
613CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
614 const CallArgList &args) {
615 assert(signature.arg_size() <= args.size());
616 if (signature.arg_size() == args.size())
617 return signature;
618
619 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
620 auto sigParamInfos = signature.getExtParameterInfos();
621 if (!sigParamInfos.empty()) {
622 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
623 paramInfos.resize(args.size());
624 }
625
626 auto argTypes = getArgTypesForCall(Context, args);
627
628 assert(signature.getRequiredArgs().allowsOptionalArgs());
629 return arrangeLLVMFunctionInfo(signature.getReturnType(),
630 signature.isInstanceMethod(),
631 signature.isChainCall(),
632 argTypes,
633 signature.getExtInfo(),
634 paramInfos,
635 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000636}
637
John McCalla729c622012-02-17 03:33:10 +0000638/// Arrange the argument and result information for an abstract value
639/// of a given function type. This is the method which all of the
640/// above functions ultimately defer to.
641const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000642CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000643 bool instanceMethod,
644 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000645 ArrayRef<CanQualType> argTypes,
646 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000647 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000648 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000649 assert(std::all_of(argTypes.begin(), argTypes.end(),
650 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000651
Daniel Dunbare0be8292009-02-03 00:07:12 +0000652 // Lookup or create unique function info.
653 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000654 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
655 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000656
Craig Topper8a13c412014-05-21 05:09:00 +0000657 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000658 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000659 if (FI)
660 return *FI;
661
John McCallc56a8b32016-03-11 04:30:31 +0000662 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
663
John McCalla729c622012-02-17 03:33:10 +0000664 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000665 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000666 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000667 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000668
David Blaikie82e95a32014-11-19 07:49:47 +0000669 bool inserted = FunctionsBeingProcessed.insert(FI).second;
670 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000671 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000672
Daniel Dunbar313321e2009-02-03 05:31:23 +0000673 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000674 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000675
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000676 // Loop over all of the computed argument and return value info. If any of
677 // them are direct or extend without a specified coerce type, specify the
678 // default now.
John McCalla729c622012-02-17 03:33:10 +0000679 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000680 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000681 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000682
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000683 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000684 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000685 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000686
John McCalla729c622012-02-17 03:33:10 +0000687 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
688 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000689
Daniel Dunbare0be8292009-02-03 00:07:12 +0000690 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000691}
692
John McCalla729c622012-02-17 03:33:10 +0000693CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000694 bool instanceMethod,
695 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000696 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000697 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000698 CanQualType resultType,
699 ArrayRef<CanQualType> argTypes,
700 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000701 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
702
703 void *buffer =
704 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
705 argTypes.size() + 1, paramInfos.size()));
706
John McCalla729c622012-02-17 03:33:10 +0000707 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
708 FI->CallingConvention = llvmCC;
709 FI->EffectiveCallingConvention = llvmCC;
710 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000711 FI->InstanceMethod = instanceMethod;
712 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000713 FI->NoReturn = info.getNoReturn();
714 FI->ReturnsRetained = info.getProducesResult();
715 FI->Required = required;
716 FI->HasRegParm = info.getHasRegParm();
717 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000718 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000719 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000720 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000721 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000722 FI->getArgsBuffer()[0].type = resultType;
723 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
724 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000725 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
726 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000727 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000728}
729
730/***/
731
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000732namespace {
733// ABIArgInfo::Expand implementation.
734
735// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
736struct TypeExpansion {
737 enum TypeExpansionKind {
738 // Elements of constant arrays are expanded recursively.
739 TEK_ConstantArray,
740 // Record fields are expanded recursively (but if record is a union, only
741 // the field with the largest size is expanded).
742 TEK_Record,
743 // For complex types, real and imaginary parts are expanded recursively.
744 TEK_Complex,
745 // All other types are not expandable.
746 TEK_None
747 };
748
749 const TypeExpansionKind Kind;
750
751 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000752 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000753};
754
755struct ConstantArrayExpansion : TypeExpansion {
756 QualType EltTy;
757 uint64_t NumElts;
758
759 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
760 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
761 static bool classof(const TypeExpansion *TE) {
762 return TE->Kind == TEK_ConstantArray;
763 }
764};
765
766struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000767 SmallVector<const CXXBaseSpecifier *, 1> Bases;
768
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000769 SmallVector<const FieldDecl *, 1> Fields;
770
Reid Klecknere9f6a712014-10-31 17:10:41 +0000771 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
772 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000773 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
774 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000775 static bool classof(const TypeExpansion *TE) {
776 return TE->Kind == TEK_Record;
777 }
778};
779
780struct ComplexExpansion : TypeExpansion {
781 QualType EltTy;
782
783 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
784 static bool classof(const TypeExpansion *TE) {
785 return TE->Kind == TEK_Complex;
786 }
787};
788
789struct NoExpansion : TypeExpansion {
790 NoExpansion() : TypeExpansion(TEK_None) {}
791 static bool classof(const TypeExpansion *TE) {
792 return TE->Kind == TEK_None;
793 }
794};
795} // namespace
796
797static std::unique_ptr<TypeExpansion>
798getTypeExpansion(QualType Ty, const ASTContext &Context) {
799 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
800 return llvm::make_unique<ConstantArrayExpansion>(
801 AT->getElementType(), AT->getSize().getZExtValue());
802 }
803 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000804 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000805 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000806 const RecordDecl *RD = RT->getDecl();
807 assert(!RD->hasFlexibleArrayMember() &&
808 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000809 if (RD->isUnion()) {
810 // Unions can be here only in degenerative cases - all the fields are same
811 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000812 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000813 CharUnits UnionSize = CharUnits::Zero();
814
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000815 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000816 // Skip zero length bitfields.
817 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
818 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000819 assert(!FD->isBitField() &&
820 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000821 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000822 if (UnionSize < FieldSize) {
823 UnionSize = FieldSize;
824 LargestFD = FD;
825 }
826 }
827 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000828 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000829 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000830 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
831 assert(!CXXRD->isDynamicClass() &&
832 "cannot expand vtable pointers in dynamic classes");
833 for (const CXXBaseSpecifier &BS : CXXRD->bases())
834 Bases.push_back(&BS);
835 }
836
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000837 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000838 // Skip zero length bitfields.
839 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
840 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000841 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000842 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000843 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000844 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000845 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000846 return llvm::make_unique<RecordExpansion>(std::move(Bases),
847 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000848 }
849 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
850 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
851 }
852 return llvm::make_unique<NoExpansion>();
853}
854
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000855static int getExpansionSize(QualType Ty, const ASTContext &Context) {
856 auto Exp = getTypeExpansion(Ty, Context);
857 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
858 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
859 }
860 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
861 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000862 for (auto BS : RExp->Bases)
863 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000864 for (auto FD : RExp->Fields)
865 Res += getExpansionSize(FD->getType(), Context);
866 return Res;
867 }
868 if (isa<ComplexExpansion>(Exp.get()))
869 return 2;
870 assert(isa<NoExpansion>(Exp.get()));
871 return 1;
872}
873
Alexey Samsonov153004f2014-09-29 22:08:00 +0000874void
875CodeGenTypes::getExpandedTypes(QualType Ty,
876 SmallVectorImpl<llvm::Type *>::iterator &TI) {
877 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000878 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
879 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000880 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000881 }
882 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000883 for (auto BS : RExp->Bases)
884 getExpandedTypes(BS->getType(), TI);
885 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000886 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000887 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
888 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000889 *TI++ = EltTy;
890 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000891 } else {
892 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000893 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000894 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000895}
896
John McCall7f416cc2015-09-08 08:05:57 +0000897static void forConstantArrayExpansion(CodeGenFunction &CGF,
898 ConstantArrayExpansion *CAE,
899 Address BaseAddr,
900 llvm::function_ref<void(Address)> Fn) {
901 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
902 CharUnits EltAlign =
903 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
904
905 for (int i = 0, n = CAE->NumElts; i < n; i++) {
906 llvm::Value *EltAddr =
907 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
908 Fn(Address(EltAddr, EltAlign));
909 }
910}
911
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000912void CodeGenFunction::ExpandTypeFromArgs(
913 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000914 assert(LV.isSimple() &&
915 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000916
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000917 auto Exp = getTypeExpansion(Ty, getContext());
918 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000919 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
920 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000921 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
922 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000923 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000924 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000925 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000926 for (const CXXBaseSpecifier *BS : RExp->Bases) {
927 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000928 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000929 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
930 /*NullCheckValue=*/false, SourceLocation());
931 LValue SubLV = MakeAddrLValue(Base, BS->getType());
932
933 // Recurse onto bases.
934 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
935 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000936 for (auto FD : RExp->Fields) {
937 // FIXME: What are the right qualifiers here?
938 LValue SubLV = EmitLValueForField(LV, FD);
939 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000940 }
John McCall7f416cc2015-09-08 08:05:57 +0000941 } else if (isa<ComplexExpansion>(Exp.get())) {
942 auto realValue = *AI++;
943 auto imagValue = *AI++;
944 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000945 } else {
946 assert(isa<NoExpansion>(Exp.get()));
947 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000948 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000949}
950
951void CodeGenFunction::ExpandTypeToArgs(
952 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
953 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
954 auto Exp = getTypeExpansion(Ty, getContext());
955 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000956 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
957 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000958 RValue EltRV =
959 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
960 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000961 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000962 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000963 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000964 for (const CXXBaseSpecifier *BS : RExp->Bases) {
965 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000966 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000967 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
968 /*NullCheckValue=*/false, SourceLocation());
969 RValue BaseRV = RValue::getAggregate(Base);
970
971 // Recurse onto bases.
972 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
973 IRCallArgPos);
974 }
975
976 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000977 for (auto FD : RExp->Fields) {
978 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
979 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
980 IRCallArgPos);
981 }
982 } else if (isa<ComplexExpansion>(Exp.get())) {
983 ComplexPairTy CV = RV.getComplexVal();
984 IRCallArgs[IRCallArgPos++] = CV.first;
985 IRCallArgs[IRCallArgPos++] = CV.second;
986 } else {
987 assert(isa<NoExpansion>(Exp.get()));
988 assert(RV.isScalar() &&
989 "Unexpected non-scalar rvalue during struct expansion.");
990
991 // Insert a bitcast as needed.
992 llvm::Value *V = RV.getScalarVal();
993 if (IRCallArgPos < IRFuncTy->getNumParams() &&
994 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
995 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
996
997 IRCallArgs[IRCallArgPos++] = V;
998 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000999}
1000
John McCall7f416cc2015-09-08 08:05:57 +00001001/// Create a temporary allocation for the purposes of coercion.
1002static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1003 CharUnits MinAlign) {
1004 // Don't use an alignment that's worse than what LLVM would prefer.
1005 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1006 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1007
1008 return CGF.CreateTempAlloca(Ty, Align);
1009}
1010
Chris Lattner895c52b2010-06-27 06:04:18 +00001011/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001012/// accessing some number of bytes out of it, try to gep into the struct to get
1013/// at its inner goodness. Dive as deep as possible without entering an element
1014/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001015static Address
1016EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001017 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001018 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001019 // We can't dive into a zero-element struct.
1020 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001021
Chris Lattner2192fe52011-07-18 04:24:23 +00001022 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001023
Chris Lattner1cd66982010-06-27 05:56:15 +00001024 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +00001025 // first element is the same size as the whole struct, we can enter it. The
1026 // comparison must be made on the store size and not the alloca size. Using
1027 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001028 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001029 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001030 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001031 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001032 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001033
Chris Lattner1cd66982010-06-27 05:56:15 +00001034 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001035 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001036
Chris Lattner1cd66982010-06-27 05:56:15 +00001037 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001038 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001039 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001040 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001041
1042 return SrcPtr;
1043}
1044
Chris Lattner055097f2010-06-27 06:26:04 +00001045/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1046/// are either integers or pointers. This does a truncation of the value if it
1047/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001048///
1049/// This behaves as if the value were coerced through memory, so on big-endian
1050/// targets the high bits are preserved in a truncation, while little-endian
1051/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001052static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001053 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001054 CodeGenFunction &CGF) {
1055 if (Val->getType() == Ty)
1056 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001057
Chris Lattner055097f2010-06-27 06:26:04 +00001058 if (isa<llvm::PointerType>(Val->getType())) {
1059 // If this is Pointer->Pointer avoid conversion to and from int.
1060 if (isa<llvm::PointerType>(Ty))
1061 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001062
Chris Lattner055097f2010-06-27 06:26:04 +00001063 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001064 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001065 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001066
Chris Lattner2192fe52011-07-18 04:24:23 +00001067 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001068 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001069 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001071 if (Val->getType() != DestIntTy) {
1072 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1073 if (DL.isBigEndian()) {
1074 // Preserve the high bits on big-endian targets.
1075 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001076 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1077 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1078
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001079 if (SrcSize > DstSize) {
1080 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1081 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1082 } else {
1083 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1084 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1085 }
1086 } else {
1087 // Little-endian targets preserve the low bits. No shifts required.
1088 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1089 }
1090 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001091
Chris Lattner055097f2010-06-27 06:26:04 +00001092 if (isa<llvm::PointerType>(Ty))
1093 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1094 return Val;
1095}
1096
Chris Lattner1cd66982010-06-27 05:56:15 +00001097
1098
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001099/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001100/// a pointer to an object of type \arg Ty, known to be aligned to
1101/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001102///
1103/// This safely handles the case when the src type is smaller than the
1104/// destination type; in this situation the values of bits which not
1105/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001106static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001107 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001108 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001109
Chris Lattnerd200eda2010-06-28 22:51:39 +00001110 // If SrcTy and Ty are the same, just do a load.
1111 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001112 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001113
Micah Villmowdd31ca12012-10-08 16:25:52 +00001114 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001115
Chris Lattner2192fe52011-07-18 04:24:23 +00001116 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001117 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1118 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001119 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001120
Micah Villmowdd31ca12012-10-08 16:25:52 +00001121 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001122
Chris Lattner055097f2010-06-27 06:26:04 +00001123 // If the source and destination are integer or pointer types, just do an
1124 // extension or truncation to the desired type.
1125 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1126 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001127 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001128 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1129 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001130
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001131 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001132 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001133 // Generally SrcSize is never greater than DstSize, since this means we are
1134 // losing bits. However, this can happen in cases where the structure has
1135 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001136 //
Mike Stump18bb9282009-05-16 07:57:57 +00001137 // FIXME: Assert that we aren't truncating non-padding bits when have access
1138 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001139 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1140 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001141 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001142
John McCall7f416cc2015-09-08 08:05:57 +00001143 // Otherwise do coercion through memory. This is stupid, but simple.
1144 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1145 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1146 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001147 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1148 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001149 false);
1150 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001151}
1152
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001153// Function to store a first-class aggregate into memory. We prefer to
1154// store the elements rather than the aggregate to be more friendly to
1155// fast-isel.
1156// FIXME: Do we need to recurse here?
1157static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001158 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001159 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001160 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001161 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001162 const llvm::StructLayout *Layout =
1163 CGF.CGM.getDataLayout().getStructLayout(STy);
1164
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001165 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001166 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1167 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001168 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001169 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001170 }
1171 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001172 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001173 }
1174}
1175
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001176/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001177/// where the source and destination may have different types. The
1178/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001179///
1180/// This safely handles the case when the src type is larger than the
1181/// destination type; the upper bits of the src will be lost.
1182static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001183 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001184 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001185 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001186 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001187 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001188 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001189 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001190 return;
1191 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001192
Micah Villmowdd31ca12012-10-08 16:25:52 +00001193 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001194
Chris Lattner2192fe52011-07-18 04:24:23 +00001195 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001196 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1197 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001198 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001199
Chris Lattner055097f2010-06-27 06:26:04 +00001200 // If the source and destination are integer or pointer types, just do an
1201 // extension or truncation to the desired type.
1202 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1203 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1204 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001205 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001206 return;
1207 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001208
Micah Villmowdd31ca12012-10-08 16:25:52 +00001209 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001210
Daniel Dunbar313321e2009-02-03 05:31:23 +00001211 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001212 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001213 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1214 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001215 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001216 // Otherwise do coercion through memory. This is stupid, but
1217 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001218
1219 // Generally SrcSize is never greater than DstSize, since this means we are
1220 // losing bits. However, this can happen in cases where the structure has
1221 // additional padding, for example due to a user specified alignment.
1222 //
1223 // FIXME: Assert that we aren't truncating non-padding bits when have access
1224 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001225 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1226 CGF.Builder.CreateStore(Src, Tmp);
1227 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1228 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001229 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1230 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001231 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001232 }
1233}
1234
John McCall7f416cc2015-09-08 08:05:57 +00001235static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1236 const ABIArgInfo &info) {
1237 if (unsigned offset = info.getDirectOffset()) {
1238 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1239 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1240 CharUnits::fromQuantity(offset));
1241 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1242 }
1243 return addr;
1244}
1245
Alexey Samsonov153004f2014-09-29 22:08:00 +00001246namespace {
1247
1248/// Encapsulates information about the way function arguments from
1249/// CGFunctionInfo should be passed to actual LLVM IR function.
1250class ClangToLLVMArgMapping {
1251 static const unsigned InvalidIndex = ~0U;
1252 unsigned InallocaArgNo;
1253 unsigned SRetArgNo;
1254 unsigned TotalIRArgs;
1255
1256 /// Arguments of LLVM IR function corresponding to single Clang argument.
1257 struct IRArgs {
1258 unsigned PaddingArgIndex;
1259 // Argument is expanded to IR arguments at positions
1260 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1261 unsigned FirstArgIndex;
1262 unsigned NumberOfArgs;
1263
1264 IRArgs()
1265 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1266 NumberOfArgs(0) {}
1267 };
1268
1269 SmallVector<IRArgs, 8> ArgInfo;
1270
1271public:
1272 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1273 bool OnlyRequiredArgs = false)
1274 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1275 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1276 construct(Context, FI, OnlyRequiredArgs);
1277 }
1278
1279 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1280 unsigned getInallocaArgNo() const {
1281 assert(hasInallocaArg());
1282 return InallocaArgNo;
1283 }
1284
1285 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1286 unsigned getSRetArgNo() const {
1287 assert(hasSRetArg());
1288 return SRetArgNo;
1289 }
1290
1291 unsigned totalIRArgs() const { return TotalIRArgs; }
1292
1293 bool hasPaddingArg(unsigned ArgNo) const {
1294 assert(ArgNo < ArgInfo.size());
1295 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1296 }
1297 unsigned getPaddingArgNo(unsigned ArgNo) const {
1298 assert(hasPaddingArg(ArgNo));
1299 return ArgInfo[ArgNo].PaddingArgIndex;
1300 }
1301
1302 /// Returns index of first IR argument corresponding to ArgNo, and their
1303 /// quantity.
1304 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1305 assert(ArgNo < ArgInfo.size());
1306 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1307 ArgInfo[ArgNo].NumberOfArgs);
1308 }
1309
1310private:
1311 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1312 bool OnlyRequiredArgs);
1313};
1314
1315void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1316 const CGFunctionInfo &FI,
1317 bool OnlyRequiredArgs) {
1318 unsigned IRArgNo = 0;
1319 bool SwapThisWithSRet = false;
1320 const ABIArgInfo &RetAI = FI.getReturnInfo();
1321
1322 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1323 SwapThisWithSRet = RetAI.isSRetAfterThis();
1324 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1325 }
1326
1327 unsigned ArgNo = 0;
1328 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1329 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1330 ++I, ++ArgNo) {
1331 assert(I != FI.arg_end());
1332 QualType ArgType = I->type;
1333 const ABIArgInfo &AI = I->info;
1334 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1335 auto &IRArgs = ArgInfo[ArgNo];
1336
1337 if (AI.getPaddingType())
1338 IRArgs.PaddingArgIndex = IRArgNo++;
1339
1340 switch (AI.getKind()) {
1341 case ABIArgInfo::Extend:
1342 case ABIArgInfo::Direct: {
1343 // FIXME: handle sseregparm someday...
1344 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1345 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1346 IRArgs.NumberOfArgs = STy->getNumElements();
1347 } else {
1348 IRArgs.NumberOfArgs = 1;
1349 }
1350 break;
1351 }
1352 case ABIArgInfo::Indirect:
1353 IRArgs.NumberOfArgs = 1;
1354 break;
1355 case ABIArgInfo::Ignore:
1356 case ABIArgInfo::InAlloca:
1357 // ignore and inalloca doesn't have matching LLVM parameters.
1358 IRArgs.NumberOfArgs = 0;
1359 break;
John McCallf26e73d2016-03-11 04:30:43 +00001360 case ABIArgInfo::CoerceAndExpand:
1361 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1362 break;
1363 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001364 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1365 break;
1366 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001367
1368 if (IRArgs.NumberOfArgs > 0) {
1369 IRArgs.FirstArgIndex = IRArgNo;
1370 IRArgNo += IRArgs.NumberOfArgs;
1371 }
1372
1373 // Skip over the sret parameter when it comes second. We already handled it
1374 // above.
1375 if (IRArgNo == 1 && SwapThisWithSRet)
1376 IRArgNo++;
1377 }
1378 assert(ArgNo == ArgInfo.size());
1379
1380 if (FI.usesInAlloca())
1381 InallocaArgNo = IRArgNo++;
1382
1383 TotalIRArgs = IRArgNo;
1384}
1385} // namespace
1386
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001387/***/
1388
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001389bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001390 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001391}
1392
Tim Northovere77cc392014-03-29 13:28:05 +00001393bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1394 return ReturnTypeUsesSRet(FI) &&
1395 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1396}
1397
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001398bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1399 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1400 switch (BT->getKind()) {
1401 default:
1402 return false;
1403 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001404 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001405 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001406 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001407 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001408 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001409 }
1410 }
1411
1412 return false;
1413}
1414
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001415bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1416 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1417 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1418 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001419 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001420 }
1421 }
1422
1423 return false;
1424}
1425
Chris Lattnera5f58b02011-07-09 17:41:47 +00001426llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001427 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1428 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001429}
1430
Chris Lattnera5f58b02011-07-09 17:41:47 +00001431llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001432CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001433
David Blaikie82e95a32014-11-19 07:49:47 +00001434 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1435 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001436 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001437
Alexey Samsonov153004f2014-09-29 22:08:00 +00001438 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001439 const ABIArgInfo &retAI = FI.getReturnInfo();
1440 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001441 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001442 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001443
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001444 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001445 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001446 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001447 break;
1448
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001449 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001450 if (retAI.getInAllocaSRet()) {
1451 // sret things on win32 aren't void, they return the sret pointer.
1452 QualType ret = FI.getReturnType();
1453 llvm::Type *ty = ConvertType(ret);
1454 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1455 resultType = llvm::PointerType::get(ty, addressSpace);
1456 } else {
1457 resultType = llvm::Type::getVoidTy(getLLVMContext());
1458 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001459 break;
1460
John McCall7f416cc2015-09-08 08:05:57 +00001461 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001462 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001463 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001464 break;
John McCallf26e73d2016-03-11 04:30:43 +00001465
1466 case ABIArgInfo::CoerceAndExpand:
1467 resultType = retAI.getUnpaddedCoerceAndExpandType();
1468 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001469 }
Mike Stump11289f42009-09-09 15:08:12 +00001470
Alexey Samsonov153004f2014-09-29 22:08:00 +00001471 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1472 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1473
1474 // Add type for sret argument.
1475 if (IRFunctionArgs.hasSRetArg()) {
1476 QualType Ret = FI.getReturnType();
1477 llvm::Type *Ty = ConvertType(Ret);
1478 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1479 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1480 llvm::PointerType::get(Ty, AddressSpace);
1481 }
1482
1483 // Add type for inalloca argument.
1484 if (IRFunctionArgs.hasInallocaArg()) {
1485 auto ArgStruct = FI.getArgStruct();
1486 assert(ArgStruct);
1487 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1488 }
1489
John McCallc818bbb2012-12-07 07:03:17 +00001490 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001491 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001492 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1493 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001494 for (; it != ie; ++it, ++ArgNo) {
1495 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001496
Rafael Espindolafad28de2012-10-24 01:59:00 +00001497 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001498 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1499 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1500 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001501
Alexey Samsonov153004f2014-09-29 22:08:00 +00001502 unsigned FirstIRArg, NumIRArgs;
1503 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1504
1505 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001506 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001507 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001508 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001509 break;
1510
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001511 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001512 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001513 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001514 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001515 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001516 break;
1517 }
1518
1519 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001520 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001521 // Fast-isel and the optimizer generally like scalar values better than
1522 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001523 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001524 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001525 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1526 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001527 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001528 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001529 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001530 assert(NumIRArgs == 1);
1531 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001532 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001533 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCallf26e73d2016-03-11 04:30:43 +00001536 case ABIArgInfo::CoerceAndExpand: {
1537 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1538 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1539 *ArgTypesIter++ = EltTy;
1540 }
1541 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1542 break;
1543 }
1544
Daniel Dunbard3674e62008-09-11 01:48:57 +00001545 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001546 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1547 getExpandedTypes(it->type, ArgTypesIter);
1548 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001549 break;
1550 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001551 }
1552
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001553 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1554 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001555
1556 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001557}
1558
Chris Lattner2192fe52011-07-18 04:24:23 +00001559llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001560 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001561 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001562
Chris Lattner8806e322011-07-10 00:18:59 +00001563 if (!isFuncTypeConvertible(FPT))
1564 return llvm::StructType::get(getLLVMContext());
1565
1566 const CGFunctionInfo *Info;
1567 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001568 Info =
1569 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001570 else
John McCalla729c622012-02-17 03:33:10 +00001571 Info = &arrangeCXXMethodDeclaration(MD);
1572 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001573}
1574
Samuel Antao798f11c2015-11-23 22:04:44 +00001575static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1576 llvm::AttrBuilder &FuncAttrs,
1577 const FunctionProtoType *FPT) {
1578 if (!FPT)
1579 return;
1580
1581 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1582 FPT->isNothrow(Ctx))
1583 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1584}
1585
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001586void CodeGenModule::ConstructAttributeList(
1587 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1588 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001589 llvm::AttrBuilder FuncAttrs;
1590 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001591 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001592
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001593 CallingConv = FI.getEffectiveCallingConvention();
1594
John McCallab26cfa2010-02-05 21:31:56 +00001595 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001596 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001597
Samuel Antao798f11c2015-11-23 22:04:44 +00001598 // If we have information about the function prototype, we can learn
1599 // attributes form there.
1600 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1601 CalleeInfo.getCalleeFunctionProtoType());
1602
1603 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1604
Amjad Aboudfaea5602016-03-07 14:22:46 +00001605 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001606 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001607 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001608 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001609 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001610 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001611 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001612 if (TargetDecl->hasAttr<NoReturnAttr>())
1613 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001614 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1615 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001616
1617 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001618 AddAttributesFromFunctionProtoType(
1619 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001620 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1621 // These attributes are not inherited by overloads.
1622 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1623 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001624 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001625 }
1626
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001627 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001628 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001629 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1630 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001631 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001632 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1633 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001634 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1635 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1636 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001637 }
David Majnemer631a90b2015-02-04 07:23:21 +00001638 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001639 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001640 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1641 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001642
Amjad Aboudfaea5602016-03-07 14:22:46 +00001643 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001644 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001645 }
1646
Paul Robinson08556952014-12-11 20:14:04 +00001647 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1648 if (!HasOptnone) {
1649 if (CodeGenOpts.OptimizeSize)
1650 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1651 if (CodeGenOpts.OptimizeSize == 2)
1652 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1653 }
1654
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001655 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001656 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001657 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001658 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001659 if (CodeGenOpts.EnableSegmentedStacks &&
1660 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001661 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001662
Bill Wendling2f81db62013-02-22 20:53:29 +00001663 if (AttrOnCallSite) {
1664 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001665 if (!CodeGenOpts.SimplifyLibCalls ||
1666 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001667 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001668 if (!CodeGenOpts.TrapFuncName.empty())
1669 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001670 } else {
1671 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001672 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001673 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001674 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001675 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001676 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001677 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001678 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001679 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001680 }
1681
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001682 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001683 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001684 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001685 FuncAttrs.addAttribute(
1686 "disable-tail-calls",
1687 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001688
Bill Wendlingdabafea2013-03-13 22:24:33 +00001689 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001690 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001691 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001692 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001693 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001694 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001695 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001696 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001697 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001698 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001699 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001700 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001701
Akira Hatanakaaecca042015-09-11 18:55:09 +00001702 if (CodeGenOpts.StackRealignment)
1703 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001704
Eric Christopher11acf732015-06-12 01:35:52 +00001705 // Add target-cpu and target-features attributes to functions. If
1706 // we have a decl for the function and it has a target attribute then
1707 // parse that and add it to the feature set.
1708 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001709 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001710 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001711 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001712 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001713
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001714 // Produce the canonical string for this set of features.
1715 std::vector<std::string> Features;
1716 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1717 ie = FeatureMap.end();
1718 it != ie; ++it)
1719 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001720
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001721 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001722 // While we populated the feature map above, we still need to
1723 // get and parse the target attribute so we can get the cpu for
1724 // the function.
1725 const auto *TD = FD->getAttr<TargetAttr>();
1726 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1727 if (ParsedAttr.second != "")
1728 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001729 if (TargetCPU != "")
1730 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1731 if (!Features.empty()) {
1732 std::sort(Features.begin(), Features.end());
1733 FuncAttrs.addAttribute(
1734 "target-features",
1735 llvm::join(Features.begin(), Features.end(), ","));
1736 }
1737 } else {
1738 // Otherwise just add the existing target cpu and target features to the
1739 // function.
1740 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1741 if (TargetCPU != "")
1742 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1743 if (!Features.empty()) {
1744 std::sort(Features.begin(), Features.end());
1745 FuncAttrs.addAttribute(
1746 "target-features",
1747 llvm::join(Features.begin(), Features.end(), ","));
1748 }
Eric Christopher70c16652015-03-25 23:14:47 +00001749 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001750 }
1751
Justin Lebarddd97fa2016-02-24 21:55:11 +00001752 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1753 // Conservatively, mark all functions and calls in CUDA as convergent
1754 // (meaning, they may call an intrinsically convergent op, such as
1755 // __syncthreads(), and so can't have certain optimizations applied around
1756 // them). LLVM will remove this attribute where it safely can.
1757 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1758 }
1759
Alexey Samsonov153004f2014-09-29 22:08:00 +00001760 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001761
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001762 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001763 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001764 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001765 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001766 if (RetTy->hasSignedIntegerRepresentation())
1767 RetAttrs.addAttribute(llvm::Attribute::SExt);
1768 else if (RetTy->hasUnsignedIntegerRepresentation())
1769 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001770 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001771 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001772 if (RetAI.getInReg())
1773 RetAttrs.addAttribute(llvm::Attribute::InReg);
1774 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001775 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001776 break;
1777
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001778 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001779 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001780 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001781 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1782 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001783 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001784 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001785
John McCallf26e73d2016-03-11 04:30:43 +00001786 case ABIArgInfo::CoerceAndExpand:
1787 break;
1788
Daniel Dunbard3674e62008-09-11 01:48:57 +00001789 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001790 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001791 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001792
Hal Finkela2347ba2014-07-18 15:52:10 +00001793 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1794 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001795 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001796 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1797 .getQuantity());
1798 else if (getContext().getTargetAddressSpace(PTy) == 0)
1799 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1800 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001801
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001802 // Attach return attributes.
1803 if (RetAttrs.hasAttributes()) {
1804 PAL.push_back(llvm::AttributeSet::get(
1805 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1806 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001807
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001808 // Attach attributes to sret.
1809 if (IRFunctionArgs.hasSRetArg()) {
1810 llvm::AttrBuilder SRETAttrs;
1811 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1812 if (RetAI.getInReg())
1813 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1814 PAL.push_back(llvm::AttributeSet::get(
1815 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1816 }
1817
1818 // Attach attributes to inalloca argument.
1819 if (IRFunctionArgs.hasInallocaArg()) {
1820 llvm::AttrBuilder Attrs;
1821 Attrs.addAttribute(llvm::Attribute::InAlloca);
1822 PAL.push_back(llvm::AttributeSet::get(
1823 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1824 }
1825
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001826 unsigned ArgNo = 0;
1827 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1828 E = FI.arg_end();
1829 I != E; ++I, ++ArgNo) {
1830 QualType ParamType = I->type;
1831 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001832 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001833
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001834 // Add attribute for padding argument, if necessary.
1835 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001836 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001837 PAL.push_back(llvm::AttributeSet::get(
1838 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1839 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001840 }
1841
John McCall39ec71f2010-03-27 00:47:27 +00001842 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1843 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001844 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001845 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001846 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001847 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001848 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001849 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1850 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1851 Attrs.addAttribute(llvm::Attribute::SExt);
1852 else
1853 Attrs.addAttribute(llvm::Attribute::ZExt);
1854 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001855 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001856 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001857 if (ArgNo == 0 && FI.isChainCall())
1858 Attrs.addAttribute(llvm::Attribute::Nest);
1859 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001860 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001861 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001862
James Y Knight71608572015-08-21 18:19:06 +00001863 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001864 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001865 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001866
Anders Carlsson20759ad2009-09-16 15:53:40 +00001867 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001868 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001869
John McCall7f416cc2015-09-08 08:05:57 +00001870 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001871
1872 // In a byval argument, it is important that the required
1873 // alignment of the type is honored, as LLVM might be creating a
1874 // *new* stack object, and needs to know what alignment to give
1875 // it. (Sometimes it can deduce a sensible alignment on its own,
1876 // but not if clang decides it must emit a packed struct, or the
1877 // user specifies increased alignment requirements.)
1878 //
1879 // This is different from indirect *not* byval, where the object
1880 // exists already, and the align attribute is purely
1881 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001882 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001883
John McCall7f416cc2015-09-08 08:05:57 +00001884 // For now, only add this when we have a byval argument.
1885 // TODO: be less lazy about updating test cases.
1886 if (AI.getIndirectByVal())
1887 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001888
Daniel Dunbarc2304432009-03-18 19:51:01 +00001889 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001890 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1891 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001892 break;
James Y Knight71608572015-08-21 18:19:06 +00001893 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001894 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001895 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001896 case ABIArgInfo::CoerceAndExpand:
1897 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001898
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001899 case ABIArgInfo::InAlloca:
1900 // inalloca disables readnone and readonly.
1901 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1902 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001903 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Hal Finkela2347ba2014-07-18 15:52:10 +00001906 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1907 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001908 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001909 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1910 .getQuantity());
1911 else if (getContext().getTargetAddressSpace(PTy) == 0)
1912 Attrs.addAttribute(llvm::Attribute::NonNull);
1913 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001914
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001915 if (Attrs.hasAttributes()) {
1916 unsigned FirstIRArg, NumIRArgs;
1917 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1918 for (unsigned i = 0; i < NumIRArgs; i++)
1919 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1920 FirstIRArg + i + 1, Attrs));
1921 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001922 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001923 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001924
Bill Wendlinga7912f82012-10-10 07:36:56 +00001925 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001926 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001927 AttributeSet::get(getLLVMContext(),
1928 llvm::AttributeSet::FunctionIndex,
1929 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001930}
1931
John McCalla738c252011-03-09 04:27:21 +00001932/// An argument came in as a promoted argument; demote it back to its
1933/// declared type.
1934static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1935 const VarDecl *var,
1936 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001937 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001938
1939 // This can happen with promotions that actually don't change the
1940 // underlying type, like the enum promotions.
1941 if (value->getType() == varType) return value;
1942
1943 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1944 && "unexpected promotion type");
1945
1946 if (isa<llvm::IntegerType>(varType))
1947 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1948
1949 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1950}
1951
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001952/// Returns the attribute (either parameter attribute, or function
1953/// attribute), which declares argument ArgNo to be non-null.
1954static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1955 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001956 // FIXME: __attribute__((nonnull)) can also be applied to:
1957 // - references to pointers, where the pointee is known to be
1958 // nonnull (apparently a Clang extension)
1959 // - transparent unions containing pointers
1960 // In the former case, LLVM IR cannot represent the constraint. In
1961 // the latter case, we have no guarantee that the transparent union
1962 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001963 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1964 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001965 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001966 if (PVD) {
1967 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1968 return ParmNNAttr;
1969 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001970 // Check function attributes.
1971 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001972 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001973 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001974 if (NNAttr->isNonNull(ArgNo))
1975 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001976 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001977 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001978}
1979
Daniel Dunbard931a872009-02-02 22:03:45 +00001980void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1981 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001982 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001983 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1984 // Naked functions don't have prologues.
1985 return;
1986
John McCallcaa19452009-07-28 01:00:58 +00001987 // If this is an implicit-return-zero function, go ahead and
1988 // initialize the return value. TODO: it might be nice to have
1989 // a more general mechanism for this that didn't require synthesized
1990 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001991 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001992 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001993 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001994 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001995 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001996 Builder.CreateStore(Zero, ReturnValue);
1997 }
1998 }
1999
Mike Stump18bb9282009-05-16 07:57:57 +00002000 // FIXME: We no longer need the types from FunctionArgList; lift up and
2001 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002002
Alexey Samsonov153004f2014-09-29 22:08:00 +00002003 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002004 // Flattened function arguments.
2005 SmallVector<llvm::Argument *, 16> FnArgs;
2006 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2007 for (auto &Arg : Fn->args()) {
2008 FnArgs.push_back(&Arg);
2009 }
2010 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002011
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002012 // If we're using inalloca, all the memory arguments are GEPs off of the last
2013 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002014 Address ArgStruct = Address::invalid();
2015 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002016 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002017 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2018 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2019 FI.getArgStructAlignment());
2020
2021 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002022 }
2023
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002024 // Name the struct return parameter.
2025 if (IRFunctionArgs.hasSRetArg()) {
2026 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00002027 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002028 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002029 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002030 }
Mike Stump11289f42009-09-09 15:08:12 +00002031
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002032 // Track if we received the parameter as a pointer (indirect, byval, or
2033 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2034 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002035 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002036 ArgVals.reserve(Args.size());
2037
Reid Kleckner739756c2013-12-04 19:23:12 +00002038 // Create a pointer value for every parameter declaration. This usually
2039 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2040 // any cleanups or do anything that might unwind. We do that separately, so
2041 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002042 assert(FI.arg_size() == Args.size() &&
2043 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002044 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002045 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002046 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002047 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002048 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002049 QualType Ty = info_it->type;
2050 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002051
John McCalla738c252011-03-09 04:27:21 +00002052 bool isPromoted =
2053 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2054
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002055 unsigned FirstIRArg, NumIRArgs;
2056 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002057
Daniel Dunbard3674e62008-09-11 01:48:57 +00002058 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002059 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002060 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002061 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2062 CharUnits FieldOffset =
2063 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2064 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2065 Arg->getName());
2066 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002067 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002068 }
2069
Daniel Dunbar747865a2009-02-05 09:16:39 +00002070 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002071 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002072 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002073
John McCall47fb9502013-03-07 21:37:08 +00002074 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002075 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002076 // need to do is realign the value, if requested.
2077 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002078 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002079 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002080
2081 // Copy from the incoming argument pointer to the temporary with the
2082 // appropriate alignment.
2083 //
2084 // FIXME: We should have a common utility for generating an aggregate
2085 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002086 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002087 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2088 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2089 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2090 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002091 V = AlignedTemp;
2092 }
John McCall7f416cc2015-09-08 08:05:57 +00002093 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002094 } else {
2095 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002096 llvm::Value *V =
2097 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002098
2099 if (isPromoted)
2100 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002101 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002102 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002103 break;
2104 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002105
2106 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002107 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002108
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002109 // If we have the trivial case, handle it with no muss and fuss.
2110 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002111 ArgI.getCoerceToType() == ConvertType(Ty) &&
2112 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002113 assert(NumIRArgs == 1);
2114 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002115 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002116
Hal Finkel48d53e22014-07-19 01:41:07 +00002117 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002118 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2119 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002120 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2121 AI->getArgNo() + 1,
2122 llvm::Attribute::NonNull));
2123
Hal Finkel48d53e22014-07-19 01:41:07 +00002124 QualType OTy = PVD->getOriginalType();
2125 if (const auto *ArrTy =
2126 getContext().getAsConstantArrayType(OTy)) {
2127 // A C99 array parameter declaration with the static keyword also
2128 // indicates dereferenceability, and if the size is constant we can
2129 // use the dereferenceable attribute (which requires the size in
2130 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002131 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002132 QualType ETy = ArrTy->getElementType();
2133 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2134 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2135 ArrSize) {
2136 llvm::AttrBuilder Attrs;
2137 Attrs.addDereferenceableAttr(
2138 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2139 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2140 AI->getArgNo() + 1, Attrs));
2141 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2142 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2143 AI->getArgNo() + 1,
2144 llvm::Attribute::NonNull));
2145 }
2146 }
2147 } else if (const auto *ArrTy =
2148 getContext().getAsVariableArrayType(OTy)) {
2149 // For C99 VLAs with the static keyword, we don't know the size so
2150 // we can't use the dereferenceable attribute, but in addrspace(0)
2151 // we know that it must be nonnull.
2152 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2153 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2154 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2155 AI->getArgNo() + 1,
2156 llvm::Attribute::NonNull));
2157 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002158
2159 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2160 if (!AVAttr)
2161 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2162 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2163 if (AVAttr) {
2164 llvm::Value *AlignmentValue =
2165 EmitScalarExpr(AVAttr->getAlignment());
2166 llvm::ConstantInt *AlignmentCI =
2167 cast<llvm::ConstantInt>(AlignmentValue);
2168 unsigned Alignment =
2169 std::min((unsigned) AlignmentCI->getZExtValue(),
2170 +llvm::Value::MaximumAlignment);
2171
2172 llvm::AttrBuilder Attrs;
2173 Attrs.addAlignmentAttr(Alignment);
2174 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2175 AI->getArgNo() + 1, Attrs));
2176 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002177 }
2178
Bill Wendling507c3512012-10-16 05:23:44 +00002179 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002180 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2181 AI->getArgNo() + 1,
2182 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002183
Chris Lattner7369c142011-07-20 06:29:00 +00002184 // Ensure the argument is the correct type.
2185 if (V->getType() != ArgI.getCoerceToType())
2186 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2187
John McCalla738c252011-03-09 04:27:21 +00002188 if (isPromoted)
2189 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002190
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002191 if (const CXXMethodDecl *MD =
2192 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002193 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002194 V = CGM.getCXXABI().
2195 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002196 }
2197
Rafael Espindola8778c282012-11-29 16:09:03 +00002198 // Because of merging of function types from multiple decls it is
2199 // possible for the type of an argument to not match the corresponding
2200 // type in the function type. Since we are codegening the callee
2201 // in here, add a cast to the argument type.
2202 llvm::Type *LTy = ConvertType(Arg->getType());
2203 if (V->getType() != LTy)
2204 V = Builder.CreateBitCast(V, LTy);
2205
John McCall7f416cc2015-09-08 08:05:57 +00002206 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002207 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
John McCall7f416cc2015-09-08 08:05:57 +00002210 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2211 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002212
John McCall7f416cc2015-09-08 08:05:57 +00002213 // Pointer to store into.
2214 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002215
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002216 // Fast-isel and the optimizer generally like scalar values better than
2217 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002218 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002219 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2220 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002221 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002222 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002223 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002224 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002225
John McCall7f416cc2015-09-08 08:05:57 +00002226 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002227 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002228 AddrToStoreInto =
2229 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002230 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002231 AddrToStoreInto =
2232 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002233 }
John McCall7f416cc2015-09-08 08:05:57 +00002234
2235 assert(STy->getNumElements() == NumIRArgs);
2236 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2237 auto AI = FnArgs[FirstIRArg + i];
2238 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2239 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2240 Address EltPtr =
2241 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2242 Builder.CreateStore(AI, EltPtr);
2243 }
2244
2245 if (SrcSize > DstSize) {
2246 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2247 }
2248
Chris Lattner15ec3612010-06-29 00:06:42 +00002249 } else {
2250 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002251 assert(NumIRArgs == 1);
2252 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002253 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002254 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002255 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002256
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002257 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002258 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002259 llvm::Value *V =
2260 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002261 if (isPromoted)
2262 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002263 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002264 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002265 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002266 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002267 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002268 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002269
John McCallf26e73d2016-03-11 04:30:43 +00002270 case ABIArgInfo::CoerceAndExpand: {
2271 // Reconstruct into a temporary.
2272 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2273 ArgVals.push_back(ParamValue::forIndirect(alloca));
2274
2275 auto coercionType = ArgI.getCoerceAndExpandType();
2276 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2277 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2278
2279 unsigned argIndex = FirstIRArg;
2280 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2281 llvm::Type *eltType = coercionType->getElementType(i);
2282 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2283 continue;
2284
2285 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2286 auto elt = FnArgs[argIndex++];
2287 Builder.CreateStore(elt, eltAddr);
2288 }
2289 assert(argIndex == FirstIRArg + NumIRArgs);
2290 break;
2291 }
2292
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002293 case ABIArgInfo::Expand: {
2294 // If this structure was expanded into multiple arguments then
2295 // we need to create a temporary and reconstruct it from the
2296 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002297 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2298 LValue LV = MakeAddrLValue(Alloca, Ty);
2299 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002300
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002301 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2302 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2303 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2304 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2305 auto AI = FnArgs[FirstIRArg + i];
2306 AI->setName(Arg->getName() + "." + Twine(i));
2307 }
2308 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002309 }
2310
2311 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002312 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002313 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002314 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002315 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002316 } else {
2317 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002318 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002319 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002320 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002321 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002322 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002323
Reid Kleckner739756c2013-12-04 19:23:12 +00002324 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2325 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002326 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002327 } else {
2328 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002329 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002330 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002331}
2332
John McCallffa2c1a2012-01-29 07:46:59 +00002333static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2334 while (insn->use_empty()) {
2335 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2336 if (!bitcast) return;
2337
2338 // This is "safe" because we would have used a ConstantExpr otherwise.
2339 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2340 bitcast->eraseFromParent();
2341 }
2342}
2343
John McCall31168b02011-06-15 23:02:42 +00002344/// Try to emit a fused autorelease of a return result.
2345static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2346 llvm::Value *result) {
2347 // We must be immediately followed the cast.
2348 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002349 if (BB->empty()) return nullptr;
2350 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002351
Chris Lattner2192fe52011-07-18 04:24:23 +00002352 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002353
2354 // result is in a BasicBlock and is therefore an Instruction.
2355 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2356
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002357 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002358
2359 // Look for:
2360 // %generator = bitcast %type1* %generator2 to %type2*
2361 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2362 // We would have emitted this as a constant if the operand weren't
2363 // an Instruction.
2364 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2365
2366 // Require the generator to be immediately followed by the cast.
2367 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002368 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002369
2370 insnsToKill.push_back(bitcast);
2371 }
2372
2373 // Look for:
2374 // %generator = call i8* @objc_retain(i8* %originalResult)
2375 // or
2376 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2377 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002378 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002379
2380 bool doRetainAutorelease;
2381
John McCallb04ecb72015-10-21 18:06:43 +00002382 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002383 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002384 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002385 .objc_retainAutoreleasedReturnValue) {
2386 doRetainAutorelease = false;
2387
John McCallcfa4e9b2012-09-07 23:30:50 +00002388 // If we emitted an assembly marker for this call (and the
2389 // ARCEntrypoints field should have been set if so), go looking
2390 // for that call. If we can't find it, we can't do this
2391 // optimization. But it should always be the immediately previous
2392 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002393 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002394 llvm::Instruction *prev = call->getPrevNode();
2395 assert(prev);
2396 if (isa<llvm::BitCastInst>(prev)) {
2397 prev = prev->getPrevNode();
2398 assert(prev);
2399 }
2400 assert(isa<llvm::CallInst>(prev));
2401 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002402 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002403 insnsToKill.push_back(prev);
2404 }
John McCall31168b02011-06-15 23:02:42 +00002405 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002406 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002407 }
2408
2409 result = call->getArgOperand(0);
2410 insnsToKill.push_back(call);
2411
2412 // Keep killing bitcasts, for sanity. Note that we no longer care
2413 // about precise ordering as long as there's exactly one use.
2414 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2415 if (!bitcast->hasOneUse()) break;
2416 insnsToKill.push_back(bitcast);
2417 result = bitcast->getOperand(0);
2418 }
2419
2420 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002422 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2423 (*i)->eraseFromParent();
2424
2425 // Do the fused retain/autorelease if we were asked to.
2426 if (doRetainAutorelease)
2427 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2428
2429 // Cast back to the result type.
2430 return CGF.Builder.CreateBitCast(result, resultType);
2431}
2432
John McCallffa2c1a2012-01-29 07:46:59 +00002433/// If this is a +1 of the value of an immutable 'self', remove it.
2434static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2435 llvm::Value *result) {
2436 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002437 const ObjCMethodDecl *method =
2438 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002439 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002440 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002441 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002442
2443 // Look for a retain call.
2444 llvm::CallInst *retainCall =
2445 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2446 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002447 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002448 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002449
2450 // Look for an ordinary load of 'self'.
2451 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2452 llvm::LoadInst *load =
2453 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2454 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002455 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002456 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002457
2458 // Okay! Burn it all down. This relies for correctness on the
2459 // assumption that the retain is emitted as part of the return and
2460 // that thereafter everything is used "linearly".
2461 llvm::Type *resultType = result->getType();
2462 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2463 assert(retainCall->use_empty());
2464 retainCall->eraseFromParent();
2465 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2466
2467 return CGF.Builder.CreateBitCast(load, resultType);
2468}
2469
John McCall31168b02011-06-15 23:02:42 +00002470/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002471///
2472/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002473static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2474 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002475 // If we're returning 'self', kill the initial retain. This is a
2476 // heuristic attempt to "encourage correctness" in the really unfortunate
2477 // case where we have a return of self during a dealloc and we desperately
2478 // need to avoid the possible autorelease.
2479 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2480 return self;
2481
John McCall31168b02011-06-15 23:02:42 +00002482 // At -O0, try to emit a fused retain/autorelease.
2483 if (CGF.shouldUseFusedARCCalls())
2484 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2485 return fused;
2486
2487 return CGF.EmitARCAutoreleaseReturnValue(result);
2488}
2489
John McCall6e1c0122012-01-29 02:35:02 +00002490/// Heuristically search for a dominating store to the return-value slot.
2491static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002492 // Check if a User is a store which pointerOperand is the ReturnValue.
2493 // We are looking for stores to the ReturnValue, not for stores of the
2494 // ReturnValue to some other location.
2495 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2496 auto *SI = dyn_cast<llvm::StoreInst>(U);
2497 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2498 return nullptr;
2499 // These aren't actually possible for non-coerced returns, and we
2500 // only care about non-coerced returns on this code path.
2501 assert(!SI->isAtomic() && !SI->isVolatile());
2502 return SI;
2503 };
John McCall6e1c0122012-01-29 02:35:02 +00002504 // If there are multiple uses of the return-value slot, just check
2505 // for something immediately preceding the IP. Sometimes this can
2506 // happen with how we generate implicit-returns; it can also happen
2507 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002508 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002509 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002510 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002511 llvm::Instruction *I = &IP->back();
2512
2513 // Skip lifetime markers
2514 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2515 IE = IP->rend();
2516 II != IE; ++II) {
2517 if (llvm::IntrinsicInst *Intrinsic =
2518 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2519 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2520 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2521 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002522 if (II == IE)
2523 break;
2524 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2525 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002526 }
2527 }
2528 I = &*II;
2529 break;
2530 }
2531
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002532 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002533 }
2534
2535 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002536 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002537 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002538
John McCall6e1c0122012-01-29 02:35:02 +00002539 // Now do a first-and-dirty dominance check: just walk up the
2540 // single-predecessors chain from the current insertion point.
2541 llvm::BasicBlock *StoreBB = store->getParent();
2542 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2543 while (IP != StoreBB) {
2544 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002545 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002546 }
2547
2548 // Okay, the store's basic block dominates the insertion point; we
2549 // can do our thing.
2550 return store;
2551}
2552
Adrian Prantl3be10542013-05-02 17:30:20 +00002553void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002554 bool EmitRetDbgLoc,
2555 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002556 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2557 // Naked functions don't have epilogues.
2558 Builder.CreateUnreachable();
2559 return;
2560 }
2561
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002562 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002563 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002564 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002565 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002566 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002567
Dan Gohman481e40c2010-07-20 20:13:52 +00002568 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002569 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002570 QualType RetTy = FI.getReturnType();
2571 const ABIArgInfo &RetAI = FI.getReturnInfo();
2572
2573 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002574 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002575 // Aggregrates get evaluated directly into the destination. Sometimes we
2576 // need to return the sret value in a register, though.
2577 assert(hasAggregateEvaluationKind(RetTy));
2578 if (RetAI.getInAllocaSRet()) {
2579 llvm::Function::arg_iterator EI = CurFn->arg_end();
2580 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002581 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002582 llvm::Value *SRet = Builder.CreateStructGEP(
2583 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002584 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002585 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002586 break;
2587
Daniel Dunbar03816342010-08-21 02:24:36 +00002588 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002589 auto AI = CurFn->arg_begin();
2590 if (RetAI.isSRetAfterThis())
2591 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002592 switch (getEvaluationKind(RetTy)) {
2593 case TEK_Complex: {
2594 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002595 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002596 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002597 /*isInit*/ true);
2598 break;
2599 }
2600 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002601 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002602 break;
2603 case TEK_Scalar:
2604 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002605 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002606 /*isInit*/ true);
2607 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002608 }
2609 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002610 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002611
2612 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002613 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002614 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2615 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002616 // The internal return value temp always will have pointer-to-return-type
2617 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002618
John McCall6e1c0122012-01-29 02:35:02 +00002619 // If there is a dominating store to ReturnValue, we can elide
2620 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002621 if (llvm::StoreInst *SI =
2622 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002623 // Reuse the debug location from the store unless there is
2624 // cleanup code to be emitted between the store and return
2625 // instruction.
2626 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002627 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002628 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002629 RV = SI->getValueOperand();
2630 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002631
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002632 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002633 auto returnValueInst = ReturnValue.getPointer();
2634 if (returnValueInst->use_empty()) {
2635 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2636 alloca->eraseFromParent();
2637 ReturnValue = Address::invalid();
2638 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002639 }
John McCall6e1c0122012-01-29 02:35:02 +00002640
2641 // Otherwise, we have to do a simple load.
2642 } else {
2643 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002644 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002645 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002646 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002647 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002648
John McCall7f416cc2015-09-08 08:05:57 +00002649 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002650 }
John McCall31168b02011-06-15 23:02:42 +00002651
2652 // In ARC, end functions that return a retainable type with a call
2653 // to objc_autoreleaseReturnValue.
2654 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002655#ifndef NDEBUG
2656 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2657 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2658 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2659 // CurCodeDecl or BlockInfo.
2660 QualType RT;
2661
2662 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2663 RT = FD->getReturnType();
2664 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2665 RT = MD->getReturnType();
2666 else if (isa<BlockDecl>(CurCodeDecl))
2667 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2668 else
2669 llvm_unreachable("Unexpected function/method type");
2670
David Blaikiebbafb8a2012-03-11 07:00:24 +00002671 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002672 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002673 RT->isObjCRetainableType());
2674#endif
John McCall31168b02011-06-15 23:02:42 +00002675 RV = emitAutoreleaseOfResult(*this, RV);
2676 }
2677
Chris Lattner726b3d02010-06-26 23:13:19 +00002678 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002679
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002680 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002681 break;
2682
John McCallf26e73d2016-03-11 04:30:43 +00002683 case ABIArgInfo::CoerceAndExpand: {
2684 auto coercionType = RetAI.getCoerceAndExpandType();
2685 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2686
2687 // Load all of the coerced elements out into results.
2688 llvm::SmallVector<llvm::Value*, 4> results;
2689 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2690 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2691 auto coercedEltType = coercionType->getElementType(i);
2692 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2693 continue;
2694
2695 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2696 auto elt = Builder.CreateLoad(eltAddr);
2697 results.push_back(elt);
2698 }
2699
2700 // If we have one result, it's the single direct result type.
2701 if (results.size() == 1) {
2702 RV = results[0];
2703
2704 // Otherwise, we need to make a first-class aggregate.
2705 } else {
2706 // Construct a return type that lacks padding elements.
2707 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2708
2709 RV = llvm::UndefValue::get(returnType);
2710 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2711 RV = Builder.CreateInsertValue(RV, results[i], i);
2712 }
2713 }
2714 break;
2715 }
2716
Chris Lattner726b3d02010-06-26 23:13:19 +00002717 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002718 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002719 }
2720
Alexey Samsonovde443c52014-08-13 00:26:40 +00002721 llvm::Instruction *Ret;
2722 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002723 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2724 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002725 SanitizerScope SanScope(this);
2726 llvm::Value *Cond = Builder.CreateICmpNE(
2727 RV, llvm::Constant::getNullValue(RV->getType()));
2728 llvm::Constant *StaticData[] = {
2729 EmitCheckSourceLocation(EndLoc),
2730 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2731 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002732 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2733 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002734 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002735 }
2736 Ret = Builder.CreateRet(RV);
2737 } else {
2738 Ret = Builder.CreateRetVoid();
2739 }
2740
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002741 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002742 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002743}
2744
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002745static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2746 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2747 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2748}
2749
John McCall7f416cc2015-09-08 08:05:57 +00002750static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2751 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002752 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2753 // placeholders.
2754 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2755 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002756 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2757 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2758
2759 // FIXME: When we generate this IR in one pass, we shouldn't need
2760 // this win32-specific alignment hack.
2761 CharUnits Align = CharUnits::fromQuantity(4);
2762
2763 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002764 Ty.getQualifiers(),
2765 AggValueSlot::IsNotDestructed,
2766 AggValueSlot::DoesNotNeedGCBarriers,
2767 AggValueSlot::IsNotAliased);
2768}
2769
John McCall32ea9692011-03-11 20:59:21 +00002770void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002771 const VarDecl *param,
2772 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002773 // StartFunction converted the ABI-lowered parameter(s) into a
2774 // local alloca. We need to turn that into an r-value suitable
2775 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002776 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002777
John McCall32ea9692011-03-11 20:59:21 +00002778 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002779
John McCall23f66262010-05-26 22:34:26 +00002780 // For the most part, we just need to load the alloca, except:
2781 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002782 // 2) references to non-scalars are pointers directly to the aggregate.
2783 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002784 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002785 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002786 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002787
2788 // Locals which are references to scalars are represented
2789 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002790 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002791 }
2792
Reid Klecknerab2090d2014-07-26 01:34:32 +00002793 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2794 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002795
Nick Lewycky2d84e842013-10-02 02:29:49 +00002796 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002797}
2798
John McCall31168b02011-06-15 23:02:42 +00002799static bool isProvablyNull(llvm::Value *addr) {
2800 return isa<llvm::ConstantPointerNull>(addr);
2801}
2802
2803static bool isProvablyNonNull(llvm::Value *addr) {
2804 return isa<llvm::AllocaInst>(addr);
2805}
2806
2807/// Emit the actual writing-back of a writeback.
2808static void emitWriteback(CodeGenFunction &CGF,
2809 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002810 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002811 Address srcAddr = srcLV.getAddress();
2812 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002813 "shouldn't have writeback for provably null argument");
2814
Craig Topper8a13c412014-05-21 05:09:00 +00002815 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002816
2817 // If the argument wasn't provably non-null, we need to null check
2818 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002819 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002820 if (!provablyNonNull) {
2821 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2822 contBB = CGF.createBasicBlock("icr.done");
2823
John McCall7f416cc2015-09-08 08:05:57 +00002824 llvm::Value *isNull =
2825 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002826 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2827 CGF.EmitBlock(writebackBB);
2828 }
2829
2830 // Load the value to writeback.
2831 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2832
2833 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002834 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2835 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002836
2837 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002838
2839 // If we have a "to use" value, it's something we need to emit a use
2840 // of. This has to be carefully threaded in: if it's done after the
2841 // release it's potentially undefined behavior (and the optimizer
2842 // will ignore it), and if it happens before the retain then the
2843 // optimizer could move the release there.
2844 if (writeback.ToUse) {
2845 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2846
2847 // Retain the new value. No need to block-copy here: the block's
2848 // being passed up the stack.
2849 value = CGF.EmitARCRetainNonBlock(value);
2850
2851 // Emit the intrinsic use here.
2852 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2853
2854 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002855 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002856
2857 // Put the new value in place (primitively).
2858 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2859
2860 // Release the old value.
2861 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2862
2863 // Otherwise, we can just do a normal lvalue store.
2864 } else {
2865 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2866 }
John McCall31168b02011-06-15 23:02:42 +00002867
2868 // Jump to the continuation block.
2869 if (!provablyNonNull)
2870 CGF.EmitBlock(contBB);
2871}
2872
2873static void emitWritebacks(CodeGenFunction &CGF,
2874 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002875 for (const auto &I : args.writebacks())
2876 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002877}
2878
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002879static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2880 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002881 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002882 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2883 CallArgs.getCleanupsToDeactivate();
2884 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002885 for (const auto &I : llvm::reverse(Cleanups)) {
2886 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2887 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002888 }
2889}
2890
John McCalleff18842013-03-23 02:35:54 +00002891static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2892 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2893 if (uop->getOpcode() == UO_AddrOf)
2894 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002895 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002896}
2897
John McCall31168b02011-06-15 23:02:42 +00002898/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002899/// we are passing the address of an __autoreleased temporary; it
2900/// might be copy-initialized with the current value of the given
2901/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002902static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2903 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002904 LValue srcLV;
2905
2906 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002907 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002908 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2909 srcLV = CGF.EmitLValue(lvExpr);
2910
2911 // Otherwise, just emit it as a scalar.
2912 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002913 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002914
2915 QualType srcAddrType =
2916 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002917 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00002918 }
John McCall7f416cc2015-09-08 08:05:57 +00002919 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002920
2921 // The dest and src types don't necessarily match in LLVM terms
2922 // because of the crazy ObjC compatibility rules.
2923
Chris Lattner2192fe52011-07-18 04:24:23 +00002924 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002925 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2926
2927 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00002928 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00002929 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2930 CRE->getType());
2931 return;
2932 }
2933
John McCall31168b02011-06-15 23:02:42 +00002934 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00002935 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
2936 CGF.getPointerAlign(),
2937 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002938 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2939 // and that cleanup will be conditional if we can't prove that the l-value
2940 // isn't null, so we need to register a dominating point so that the cleanups
2941 // system will make valid IR.
2942 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2943
John McCall31168b02011-06-15 23:02:42 +00002944 // Zero-initialize it if we're not doing a copy-initialization.
2945 bool shouldCopy = CRE->shouldCopy();
2946 if (!shouldCopy) {
2947 llvm::Value *null =
2948 llvm::ConstantPointerNull::get(
2949 cast<llvm::PointerType>(destType->getElementType()));
2950 CGF.Builder.CreateStore(null, temp);
2951 }
Craig Topper8a13c412014-05-21 05:09:00 +00002952
2953 llvm::BasicBlock *contBB = nullptr;
2954 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002955
2956 // If the address is *not* known to be non-null, we need to switch.
2957 llvm::Value *finalArgument;
2958
John McCall7f416cc2015-09-08 08:05:57 +00002959 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002960 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00002961 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00002962 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002963 llvm::Value *isNull =
2964 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002965
2966 finalArgument = CGF.Builder.CreateSelect(isNull,
2967 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00002968 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00002969
2970 // If we need to copy, then the load has to be conditional, which
2971 // means we need control flow.
2972 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002973 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002974 contBB = CGF.createBasicBlock("icr.cont");
2975 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2976 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2977 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002978 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002979 }
2980 }
2981
Craig Topper8a13c412014-05-21 05:09:00 +00002982 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002983
John McCall31168b02011-06-15 23:02:42 +00002984 // Perform a copy if necessary.
2985 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002986 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002987 assert(srcRV.isScalar());
2988
2989 llvm::Value *src = srcRV.getScalarVal();
2990 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2991 "icr.cast");
2992
2993 // Use an ordinary store, not a store-to-lvalue.
2994 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002995
2996 // If optimization is enabled, and the value was held in a
2997 // __strong variable, we need to tell the optimizer that this
2998 // value has to stay alive until we're doing the store back.
2999 // This is because the temporary is effectively unretained,
3000 // and so otherwise we can violate the high-level semantics.
3001 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3002 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3003 valueToUse = src;
3004 }
John McCall31168b02011-06-15 23:02:42 +00003005 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003006
John McCall31168b02011-06-15 23:02:42 +00003007 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003008 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003009 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003010 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003011
3012 // Make a phi for the value to intrinsically use.
3013 if (valueToUse) {
3014 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3015 "icr.to-use");
3016 phiToUse->addIncoming(valueToUse, copyBB);
3017 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3018 originBB);
3019 valueToUse = phiToUse;
3020 }
3021
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003022 condEval.end(CGF);
3023 }
John McCall31168b02011-06-15 23:02:42 +00003024
John McCalleff18842013-03-23 02:35:54 +00003025 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003026 args.add(RValue::get(finalArgument), CRE->getType());
3027}
3028
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003029void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3030 assert(!StackBase && !StackCleanup.isValid());
3031
3032 // Save the stack.
3033 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003034 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003035}
3036
Nico Weber8cdb3f92015-08-25 18:43:32 +00003037void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3038 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003039 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003040 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003041 CGF.Builder.CreateCall(F, StackBase);
3042 }
3043}
3044
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003045void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3046 SourceLocation ArgLoc,
3047 const FunctionDecl *FD,
3048 unsigned ParmNum) {
3049 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003050 return;
3051 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3052 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3053 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3054 if (!NNAttr)
3055 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003056 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003057 assert(RV.isScalar());
3058 llvm::Value *V = RV.getScalarVal();
3059 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003060 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003061 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003062 EmitCheckSourceLocation(ArgLoc),
3063 EmitCheckSourceLocation(NNAttr->getLocation()),
3064 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003065 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003066 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003067 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003068}
3069
David Blaikief05779e2015-07-21 18:37:18 +00003070void CodeGenFunction::EmitCallArgs(
3071 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3072 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3073 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3074 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003075
3076 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3077 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3078 return;
3079 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3080 if (PS == nullptr)
3081 return;
3082
3083 const auto &Context = getContext();
3084 auto SizeTy = Context.getSizeType();
3085 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3086 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3087 Args.add(RValue::get(V), SizeTy);
3088 };
3089
Reid Kleckner739756c2013-12-04 19:23:12 +00003090 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3091 // because arguments are destroyed left to right in the callee.
3092 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003093 // Insert a stack save if we're going to need any inalloca args.
3094 bool HasInAllocaArgs = false;
3095 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3096 I != E && !HasInAllocaArgs; ++I)
3097 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3098 if (HasInAllocaArgs) {
3099 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3100 Args.allocateArgumentMemory(*this);
3101 }
3102
3103 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003104 size_t CallArgsStart = Args.size();
3105 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003106 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00003107 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003108 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003109 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003110 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003111 }
3112
3113 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3114 // IR function.
3115 std::reverse(Args.begin() + CallArgsStart, Args.end());
3116 return;
3117 }
3118
3119 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003120 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3121 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003122 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003123 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003124 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003125 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003126 }
3127}
3128
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003129namespace {
3130
David Blaikie7e70d682015-08-18 22:40:54 +00003131struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003132 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003133 : Addr(Addr), Ty(Ty) {}
3134
John McCall7f416cc2015-09-08 08:05:57 +00003135 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003136 QualType Ty;
3137
Craig Topper4f12f102014-03-12 06:41:41 +00003138 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003139 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3140 assert(!Dtor->isTrivial());
3141 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3142 /*Delegating=*/false, Addr);
3143 }
3144};
3145
David Blaikie38b25912015-02-09 19:13:51 +00003146struct DisableDebugLocationUpdates {
3147 CodeGenFunction &CGF;
3148 bool disabledDebugInfo;
3149 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3150 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3151 CGF.disableDebugInfo();
3152 }
3153 ~DisableDebugLocationUpdates() {
3154 if (disabledDebugInfo)
3155 CGF.enableDebugInfo();
3156 }
3157};
3158
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003159} // end anonymous namespace
3160
John McCall32ea9692011-03-11 20:59:21 +00003161void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3162 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003163 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003164 if (const ObjCIndirectCopyRestoreExpr *CRE
3165 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003166 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003167 assert(getContext().hasSameType(E->getType(), type));
3168 return emitWritebackArg(*this, args, CRE);
3169 }
3170
John McCall0a76c0c2011-08-26 18:42:59 +00003171 assert(type->isReferenceType() == E->isGLValue() &&
3172 "reference binding to unmaterialized r-value!");
3173
John McCall17054bd62011-08-26 21:08:13 +00003174 if (E->isGLValue()) {
3175 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003176 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003177 }
Mike Stump11289f42009-09-09 15:08:12 +00003178
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003179 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3180
3181 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3182 // However, we still have to push an EH-only cleanup in case we unwind before
3183 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003184 if (HasAggregateEvalKind &&
3185 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3186 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003187 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003188 AggValueSlot Slot;
3189 if (args.isUsingInAlloca())
3190 Slot = createPlaceholderSlot(*this, type);
3191 else
3192 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003193
3194 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3195 bool DestroyedInCallee =
3196 RD && RD->hasNonTrivialDestructor() &&
3197 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3198 if (DestroyedInCallee)
3199 Slot.setExternallyDestructed();
3200
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003201 EmitAggExpr(E, Slot);
3202 RValue RV = Slot.asRValue();
3203 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003204
Reid Klecknere39ee212014-05-03 00:33:28 +00003205 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003206 // Create a no-op GEP between the placeholder and the cleanup so we can
3207 // RAUW it successfully. It also serves as a marker of the first
3208 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003209 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3210 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003211 // This unreachable is a temporary marker which will be removed later.
3212 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3213 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003214 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003215 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003216 }
3217
3218 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003219 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3220 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3221 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003222 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3223 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3224 } else {
3225 // We can't represent a misaligned lvalue in the CallArgList, so copy
3226 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003227 Address tmp = CreateMemTemp(type);
3228 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003229 args.add(RValue::getAggregate(tmp), type);
3230 }
Eli Friedmandf968192011-05-26 00:10:27 +00003231 return;
3232 }
3233
John McCall32ea9692011-03-11 20:59:21 +00003234 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003235}
3236
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003237QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3238 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3239 // implicitly widens null pointer constants that are arguments to varargs
3240 // functions to pointer-sized ints.
3241 if (!getTarget().getTriple().isOSWindows())
3242 return Arg->getType();
3243
3244 if (Arg->getType()->isIntegerType() &&
3245 getContext().getTypeSize(Arg->getType()) <
3246 getContext().getTargetInfo().getPointerWidth(0) &&
3247 Arg->isNullPointerConstant(getContext(),
3248 Expr::NPC_ValueDependentIsNotNull)) {
3249 return getContext().getIntPtrType();
3250 }
3251
3252 return Arg->getType();
3253}
3254
Dan Gohman515a60d2012-02-16 00:57:37 +00003255// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3256// optimizer it can aggressively ignore unwind edges.
3257void
3258CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3259 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3260 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3261 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3262 CGM.getNoObjCARCExceptionsMetadata());
3263}
3264
John McCall882987f2013-02-28 19:01:20 +00003265/// Emits a call to the given no-arguments nounwind runtime function.
3266llvm::CallInst *
3267CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3268 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003269 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003270}
3271
3272/// Emits a call to the given nounwind runtime function.
3273llvm::CallInst *
3274CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3275 ArrayRef<llvm::Value*> args,
3276 const llvm::Twine &name) {
3277 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3278 call->setDoesNotThrow();
3279 return call;
3280}
3281
3282/// Emits a simple call (never an invoke) to the given no-arguments
3283/// runtime function.
3284llvm::CallInst *
3285CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3286 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003287 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003288}
3289
David Majnemer0b17d442015-12-15 21:27:59 +00003290// Calls which may throw must have operand bundles indicating which funclet
3291// they are nested within.
3292static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003293getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003294 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003295 // There is no need for a funclet operand bundle if we aren't inside a
3296 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003297 if (!CurrentFuncletPad)
3298 return;
3299
3300 // Skip intrinsics which cannot throw.
3301 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3302 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3303 return;
3304
3305 BundleList.emplace_back("funclet", CurrentFuncletPad);
3306}
3307
David Majnemer971d31b2016-02-24 17:02:45 +00003308/// Emits a simple call (never an invoke) to the given runtime function.
3309llvm::CallInst *
3310CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3311 ArrayRef<llvm::Value*> args,
3312 const llvm::Twine &name) {
3313 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3314 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3315
3316 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3317 call->setCallingConv(getRuntimeCC());
3318 return call;
3319}
3320
John McCall882987f2013-02-28 19:01:20 +00003321/// Emits a call or invoke to the given noreturn runtime function.
3322void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3323 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003324 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3325 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3326
John McCall882987f2013-02-28 19:01:20 +00003327 if (getInvokeDest()) {
3328 llvm::InvokeInst *invoke =
3329 Builder.CreateInvoke(callee,
3330 getUnreachableBlock(),
3331 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003332 args,
3333 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003334 invoke->setDoesNotReturn();
3335 invoke->setCallingConv(getRuntimeCC());
3336 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003337 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003338 call->setDoesNotReturn();
3339 call->setCallingConv(getRuntimeCC());
3340 Builder.CreateUnreachable();
3341 }
3342}
3343
Sanjay Patel846b63b2016-01-18 22:15:33 +00003344/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003345llvm::CallSite
3346CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3347 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003348 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003349}
3350
3351/// Emits a call or invoke instruction to the given runtime function.
3352llvm::CallSite
3353CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3354 ArrayRef<llvm::Value*> args,
3355 const Twine &name) {
3356 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3357 callSite.setCallingConv(getRuntimeCC());
3358 return callSite;
3359}
3360
John McCallbd309292010-07-06 01:34:17 +00003361/// Emits a call or invoke instruction to the given function, depending
3362/// on the current state of the EH stack.
3363llvm::CallSite
3364CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003365 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003366 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003367 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003368 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3369 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003370
Dan Gohman515a60d2012-02-16 00:57:37 +00003371 llvm::Instruction *Inst;
3372 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003373 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003374 else {
3375 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003376 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3377 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003378 EmitBlock(ContBB);
3379 }
3380
3381 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3382 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003383 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003384 AddObjCARCExceptionMetadata(Inst);
3385
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003386 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003387}
3388
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003389/// \brief Store a non-aggregate value to an address to initialize it. For
3390/// initialization, a non-atomic store will be used.
3391static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3392 LValue Dst) {
3393 if (Src.isScalar())
3394 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3395 else
3396 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3397}
3398
3399void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3400 llvm::Value *New) {
3401 DeferredReplacements.push_back(std::make_pair(Old, New));
3402}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003403
Daniel Dunbard931a872009-02-02 22:03:45 +00003404RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003405 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003406 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003407 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003408 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003409 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003410 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003411
3412 // Handle struct-return functions by passing a pointer to the
3413 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003414 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003415 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003416
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003417 llvm::FunctionType *IRFuncTy =
3418 cast<llvm::FunctionType>(
3419 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003420
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003421 // If we're using inalloca, insert the allocation after the stack save.
3422 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003423 Address ArgMemory = Address::invalid();
3424 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003425 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003426 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003427 llvm::Instruction *IP = CallArgs.getStackBase();
3428 llvm::AllocaInst *AI;
3429 if (IP) {
3430 IP = IP->getNextNode();
3431 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3432 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003433 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003434 }
John McCall7f416cc2015-09-08 08:05:57 +00003435 auto Align = CallInfo.getArgStructAlignment();
3436 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003437 AI->setUsedWithInAlloca(true);
3438 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003439 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003440 }
3441
John McCall7f416cc2015-09-08 08:05:57 +00003442 // Helper function to drill into the inalloca allocation.
3443 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3444 auto FieldOffset =
3445 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3446 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3447 };
3448
Alexey Samsonov153004f2014-09-29 22:08:00 +00003449 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003450 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3451
Chris Lattner4ca97c32009-06-13 00:26:38 +00003452 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003453 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003454 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003455 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003456 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003457 if (!ReturnValue.isNull()) {
3458 SRetPtr = ReturnValue.getValue();
3459 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003460 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003461 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3462 uint64_t size =
3463 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003464 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003465 UnusedReturnSize = size;
3466 }
3467 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003468 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003469 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003470 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003471 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3472 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003473 }
Anders Carlsson17490832009-12-24 20:40:36 +00003474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003476 assert(CallInfo.arg_size() == CallArgs.size() &&
3477 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003478 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003479 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003480 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003481 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003482 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003483 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003484
Rafael Espindolafad28de2012-10-24 01:59:00 +00003485 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003486 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3487 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3488 llvm::UndefValue::get(ArgInfo.getPaddingType());
3489
3490 unsigned FirstIRArg, NumIRArgs;
3491 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003492
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003493 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003494 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003495 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003496 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3497 if (RV.isAggregate()) {
3498 // Replace the placeholder with the appropriate argument slot GEP.
3499 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003500 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003501 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3502 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003503 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003504 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003505 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003506 } else {
3507 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003508 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3509 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003510 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3511 // There are some cases where a trivial bitcast is not avoidable. The
3512 // definition of a type later in a translation unit may change it's type
3513 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003514 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003515 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003516 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003517 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3518 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003519 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003520 }
3521
Daniel Dunbar03816342010-08-21 02:24:36 +00003522 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003523 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003524 if (RV.isScalar() || RV.isComplex()) {
3525 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003526 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3527 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003528
John McCall7f416cc2015-09-08 08:05:57 +00003529 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003530 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003531 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003532 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003533 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003534 // 1. If the argument is not byval, and we are required to copy the
3535 // source. (This case doesn't occur on any common architecture.)
3536 // 2. If the argument is byval, RV is not sufficiently aligned, and
3537 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003538 // 3. If the argument is byval, but RV is located in an address space
3539 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003540 Address Addr = RV.getAggregateAddress();
3541 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003542 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003543 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003544 const unsigned ArgAddrSpace =
3545 (FirstIRArg < IRFuncTy->getNumParams()
3546 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3547 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003548 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003549 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3550 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3551 Align.getQuantity(), *TD)
3552 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003553 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003554 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003555 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3556 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003557 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003558 } else {
3559 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003560 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003561 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003562 }
3563 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003564 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003565
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003566 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003567 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003568 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003569
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003570 case ABIArgInfo::Extend:
3571 case ABIArgInfo::Direct: {
3572 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003573 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3574 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003575 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003576 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003577 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003578 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003579 else
John McCall7f416cc2015-09-08 08:05:57 +00003580 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003581
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003582 // We might have to widen integers, but we should never truncate.
3583 if (ArgInfo.getCoerceToType() != V->getType() &&
3584 V->getType()->isIntegerTy())
3585 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3586
Chris Lattner3ce86682011-07-12 04:53:39 +00003587 // If the argument doesn't match, perform a bitcast to coerce it. This
3588 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003589 if (FirstIRArg < IRFuncTy->getNumParams() &&
3590 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3591 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3592 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003593 break;
3594 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003595
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003596 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003597 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003598 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003599 Src = CreateMemTemp(I->Ty, "coerce");
3600 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003601 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003602 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003603 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003604 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003605
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003606 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003607 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003608
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003609 // Fast-isel and the optimizer generally like scalar values better than
3610 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003611 llvm::StructType *STy =
3612 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003613 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003614 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003615 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3616 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3617
3618 // If the source type is smaller than the destination type of the
3619 // coerce-to logic, copy the source value into a temp alloca the size
3620 // of the destination type to allow loading all of it. The bits past
3621 // the source value are left undef.
3622 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003623 Address TempAlloca
3624 = CreateTempAlloca(STy, Src.getAlignment(),
3625 Src.getName() + ".coerce");
3626 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3627 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003628 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003629 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003630 }
3631
John McCall7f416cc2015-09-08 08:05:57 +00003632 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003633 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003634 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003635 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3636 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3637 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003638 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003639 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003640 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003641 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003642 assert(NumIRArgs == 1);
3643 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003644 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003645 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003646
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003647 break;
3648 }
3649
John McCallf26e73d2016-03-11 04:30:43 +00003650 case ABIArgInfo::CoerceAndExpand: {
3651 assert(RV.isAggregate() &&
3652 "CoerceAndExpand does not support non-aggregate types yet");
3653
3654 auto coercionType = ArgInfo.getCoerceAndExpandType();
3655 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3656
3657 Address addr = RV.getAggregateAddress();
3658 addr = Builder.CreateElementBitCast(addr, coercionType);
3659
3660 unsigned IRArgPos = FirstIRArg;
3661 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3662 llvm::Type *eltType = coercionType->getElementType(i);
3663 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3664 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3665 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3666 IRCallArgs[IRArgPos++] = elt;
3667 }
3668 assert(IRArgPos == FirstIRArg + NumIRArgs);
3669
3670 break;
3671 }
3672
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003673 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003674 unsigned IRArgPos = FirstIRArg;
3675 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3676 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003677 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003678 }
3679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCall7f416cc2015-09-08 08:05:57 +00003681 if (ArgMemory.isValid()) {
3682 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003683 if (CallInfo.isVariadic()) {
3684 // When passing non-POD arguments by value to variadic functions, we will
3685 // end up with a variadic prototype and an inalloca call site. In such
3686 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3687 // the callee.
3688 unsigned CalleeAS =
3689 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3690 Callee = Builder.CreateBitCast(
3691 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3692 } else {
3693 llvm::Type *LastParamTy =
3694 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3695 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003696#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003697 // Assert that these structs have equivalent element types.
3698 llvm::StructType *FullTy = CallInfo.getArgStruct();
3699 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3700 cast<llvm::PointerType>(LastParamTy)->getElementType());
3701 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3702 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3703 DE = DeclaredTy->element_end(),
3704 FI = FullTy->element_begin();
3705 DI != DE; ++DI, ++FI)
3706 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003707#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003708 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3709 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003710 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003711 assert(IRFunctionArgs.hasInallocaArg());
3712 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003713 }
3714
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003715 if (!CallArgs.getCleanupsToDeactivate().empty())
3716 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3717
Chris Lattner4ca97c32009-06-13 00:26:38 +00003718 // If the callee is a bitcast of a function to a varargs pointer to function
3719 // type, check to see if we can remove the bitcast. This handles some cases
3720 // with unprototyped functions.
3721 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3722 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003723 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3724 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003725 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003726 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003727
Chris Lattner4ca97c32009-06-13 00:26:38 +00003728 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3729 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003730 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003731 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003732 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003733 bool ArgsMatch = true;
3734 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3735 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3736 ArgsMatch = false;
3737 break;
3738 }
Mike Stump11289f42009-09-09 15:08:12 +00003739
Chris Lattner4ca97c32009-06-13 00:26:38 +00003740 // Strip the cast if we can get away with it. This is a nice cleanup,
3741 // but also allows us to inline the function at -O0 if it is marked
3742 // always_inline.
3743 if (ArgsMatch)
3744 Callee = CalleeF;
3745 }
3746 }
Mike Stump11289f42009-09-09 15:08:12 +00003747
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003748 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3749 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3750 // Inalloca argument can have different type.
3751 if (IRFunctionArgs.hasInallocaArg() &&
3752 i == IRFunctionArgs.getInallocaArgNo())
3753 continue;
3754 if (i < IRFuncTy->getNumParams())
3755 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3756 }
3757
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003758 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003759 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003760 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3761 AttributeList, CallingConv,
3762 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003763 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003764 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003765
David Majnemer4e52d6f2015-12-12 05:39:21 +00003766 bool CannotThrow;
3767 if (currentFunctionUsesSEHTry()) {
3768 // SEH cares about asynchronous exceptions, everything can "throw."
3769 CannotThrow = false;
3770 } else if (isCleanupPadScope() &&
3771 EHPersonality::get(*this).isMSVCXXPersonality()) {
3772 // The MSVC++ personality will implicitly terminate the program if an
3773 // exception is thrown. An unwind edge cannot be reached.
3774 CannotThrow = true;
3775 } else {
3776 // Otherwise, nowunind callsites will never throw.
3777 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3778 llvm::Attribute::NoUnwind);
3779 }
3780 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003781
David Majnemer0b17d442015-12-15 21:27:59 +00003782 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3783 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3784
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003785 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003786 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003787 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003788 } else {
3789 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003790 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3791 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003792 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003793 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003794 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003795 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003796
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003797 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3798 !CS.hasFnAttr(llvm::Attribute::NoInline))
3799 Attrs =
3800 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3801 llvm::Attribute::AlwaysInline);
3802
David Majnemer4e52d6f2015-12-12 05:39:21 +00003803 // Disable inlining inside SEH __try blocks.
3804 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003805 Attrs =
3806 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3807 llvm::Attribute::NoInline);
3808
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003809 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003810 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003811
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003812 // Insert instrumentation or attach profile metadata at indirect call sites
3813 if (!CS.getCalledFunction())
3814 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3815 CS.getInstruction(), Callee);
3816
Dan Gohman515a60d2012-02-16 00:57:37 +00003817 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3818 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003819 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003820 AddObjCARCExceptionMetadata(CS.getInstruction());
3821
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003822 // If the call doesn't return, finish the basic block and clear the
3823 // insertion point; this allows the rest of IRgen to discard
3824 // unreachable code.
3825 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003826 if (UnusedReturnSize)
3827 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003828 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003829
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003830 Builder.CreateUnreachable();
3831 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003832
Mike Stump18bb9282009-05-16 07:57:57 +00003833 // FIXME: For now, emit a dummy basic block because expr emitters in
3834 // generally are not ready to handle emitting expressions at unreachable
3835 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003836 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003837
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003838 // Return a reasonable RValue.
3839 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003840 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003841
3842 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00003843 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003844 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003845
John McCall31168b02011-06-15 23:02:42 +00003846 // Emit any writebacks immediately. Arguably this should happen
3847 // after any return-value munging.
3848 if (CallArgs.hasWritebacks())
3849 emitWritebacks(*this, CallArgs);
3850
Nico Weber8cdb3f92015-08-25 18:43:32 +00003851 // The stack cleanup for inalloca arguments has to run out of the normal
3852 // lexical order, so deactivate it and run it manually here.
3853 CallArgs.freeArgumentMemory(*this);
3854
Samuel Antao798f11c2015-11-23 22:04:44 +00003855 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3856 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003857 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3858 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003859 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003860
Hal Finkelee90a222014-09-26 05:04:30 +00003861 RValue Ret = [&] {
3862 switch (RetAI.getKind()) {
3863 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003864 case ABIArgInfo::Indirect: {
3865 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3866 if (UnusedReturnSize)
3867 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003868 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003869 return ret;
3870 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003871
John McCallf26e73d2016-03-11 04:30:43 +00003872 case ABIArgInfo::CoerceAndExpand: {
3873 auto coercionType = RetAI.getCoerceAndExpandType();
3874 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3875
3876 Address addr = SRetPtr;
3877 addr = Builder.CreateElementBitCast(addr, coercionType);
3878
3879 unsigned unpaddedIndex = 0;
3880 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3881 llvm::Type *eltType = coercionType->getElementType(i);
3882 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3883 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3884 llvm::Value *elt = Builder.CreateExtractValue(CI, unpaddedIndex++);
3885 Builder.CreateStore(elt, eltAddr);
3886 }
3887 break;
3888 }
3889
Hal Finkelee90a222014-09-26 05:04:30 +00003890 case ABIArgInfo::Ignore:
3891 // If we are ignoring an argument that had a result, make sure to
3892 // construct the appropriate return value for our caller.
3893 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003894
Hal Finkelee90a222014-09-26 05:04:30 +00003895 case ABIArgInfo::Extend:
3896 case ABIArgInfo::Direct: {
3897 llvm::Type *RetIRTy = ConvertType(RetTy);
3898 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3899 switch (getEvaluationKind(RetTy)) {
3900 case TEK_Complex: {
3901 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3902 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3903 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003904 }
Hal Finkelee90a222014-09-26 05:04:30 +00003905 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00003906 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003907 bool DestIsVolatile = ReturnValue.isVolatile();
3908
John McCall7f416cc2015-09-08 08:05:57 +00003909 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003910 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3911 DestIsVolatile = false;
3912 }
John McCall7f416cc2015-09-08 08:05:57 +00003913 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00003914 return RValue::getAggregate(DestPtr);
3915 }
3916 case TEK_Scalar: {
3917 // If the argument doesn't match, perform a bitcast to coerce it. This
3918 // can happen due to trivial type mismatches.
3919 llvm::Value *V = CI;
3920 if (V->getType() != RetIRTy)
3921 V = Builder.CreateBitCast(V, RetIRTy);
3922 return RValue::get(V);
3923 }
3924 }
3925 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003926 }
Hal Finkelee90a222014-09-26 05:04:30 +00003927
John McCall7f416cc2015-09-08 08:05:57 +00003928 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003929 bool DestIsVolatile = ReturnValue.isVolatile();
3930
John McCall7f416cc2015-09-08 08:05:57 +00003931 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003932 DestPtr = CreateMemTemp(RetTy, "coerce");
3933 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003934 }
Hal Finkelee90a222014-09-26 05:04:30 +00003935
3936 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003937 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
3938 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00003939
3940 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003941 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003942
Hal Finkelee90a222014-09-26 05:04:30 +00003943 case ABIArgInfo::Expand:
3944 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003945 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003946
Hal Finkelee90a222014-09-26 05:04:30 +00003947 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3948 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003949
Samuel Antao798f11c2015-11-23 22:04:44 +00003950 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3951
Hal Finkelee90a222014-09-26 05:04:30 +00003952 if (Ret.isScalar() && TargetDecl) {
3953 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3954 llvm::Value *OffsetValue = nullptr;
3955 if (const auto *Offset = AA->getOffset())
3956 OffsetValue = EmitScalarExpr(Offset);
3957
3958 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3959 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3960 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3961 OffsetValue);
3962 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003963 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003964
Hal Finkelee90a222014-09-26 05:04:30 +00003965 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003966}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003967
3968/* VarArg handling */
3969
Charles Davisc7d5c942015-09-17 20:55:33 +00003970Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
3971 VAListAddr = VE->isMicrosoftABI()
3972 ? EmitMSVAListRef(VE->getSubExpr())
3973 : EmitVAListRef(VE->getSubExpr());
3974 QualType Ty = VE->getType();
3975 if (VE->isMicrosoftABI())
3976 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003977 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003978}