blob: c562602d96b7029a8ce457d7556685160b41cec5 [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"
John McCall12f23522016-04-04 18:33:08 +000029#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000033#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000036#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000037#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000038#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000039using namespace clang;
40using namespace CodeGen;
41
42/***/
43
John McCallab26cfa2010-02-05 21:31:56 +000044static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
45 switch (CC) {
46 default: return llvm::CallingConv::C;
47 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
48 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000049 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000050 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
51 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000052 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
53 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000054 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000055 // TODO: Add support for __pascal to LLVM.
56 case CC_X86Pascal: return llvm::CallingConv::C;
57 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000058 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000059 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
60 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000061 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
62 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000063 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000064 }
65}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Derives the 'this' type for codegen purposes, i.e. ignoring method
68/// qualification.
69/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000070static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
71 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
72 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000073}
74
John McCall8ee376f2010-02-24 07:14:12 +000075/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000076static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
77 return MD->getType()->getCanonicalTypeUnqualified()
78 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
81/// Returns the "extra-canonicalized" return type, which discards
82/// qualifiers on the return type. Codegen doesn't care about them,
83/// and it makes ABI code a little easier to be able to assume that
84/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000085static CanQualType GetReturnType(QualType RetTy) {
86 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000087}
88
John McCall8dda7b22012-07-07 06:41:13 +000089/// Arrange the argument and result information for a value of the given
90/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000091const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000092CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000093 // When translating an unprototyped function type, always use a
94 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000095 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000096 /*instanceMethod=*/false,
97 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000098 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000099}
100
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000101/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
102/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
103static void appendParameterTypes(const CodeGenTypes &CGT,
104 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000105 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000107 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000108 // Fill out paramInfos.
109 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
110 assert(paramInfos.size() <= prefix.size());
111 auto protoParamInfos = FPT->getExtParameterInfos();
112 paramInfos.reserve(prefix.size() + protoParamInfos.size());
113 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000114 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000115 }
116
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000117 // Fast path: unknown target.
118 if (FD == nullptr) {
119 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
120 return;
121 }
122
123 // In the vast majority cases, we'll have precisely FPT->getNumParams()
124 // parameters; the only thing that can change this is the presence of
125 // pass_object_size. So, we preallocate for the common case.
126 prefix.reserve(prefix.size() + FPT->getNumParams());
127
128 assert(FD->getNumParams() == FPT->getNumParams());
129 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
130 prefix.push_back(FPT->getParamType(I));
131 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
132 prefix.push_back(CGT.getContext().getSizeType());
133 }
134}
135
John McCall8dda7b22012-07-07 06:41:13 +0000136/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000137/// type, on top of any implicit parameters already stored.
138static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000139arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000141 CanQual<FunctionProtoType> FTP,
142 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000143 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000144 RequiredArgs Required =
145 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000146 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000147 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000148 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000149
Peter Collingbournef7706832014-12-12 23:41:25 +0000150 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
151 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000152 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000153 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000154}
155
John McCalla729c622012-02-17 03:33:10 +0000156/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000157/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000158const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000159CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
160 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000161 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000162 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000163 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000164}
165
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000166static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167 // Set the appropriate calling convention for the Function.
168 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000169 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170
171 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000172 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000173
Douglas Gregora941dca2010-05-18 16:57:00 +0000174 if (D->hasAttr<ThisCallAttr>())
175 return CC_X86ThisCall;
176
Reid Klecknerd7857f02014-10-24 17:42:17 +0000177 if (D->hasAttr<VectorCallAttr>())
178 return CC_X86VectorCall;
179
Dawn Perchik335e16b2010-09-03 01:29:35 +0000180 if (D->hasAttr<PascalAttr>())
181 return CC_X86Pascal;
182
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000183 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
184 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
185
Guy Benyeif0a014b2012-12-25 08:53:55 +0000186 if (D->hasAttr<IntelOclBiccAttr>())
187 return CC_IntelOclBicc;
188
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000189 if (D->hasAttr<MSABIAttr>())
190 return IsWindows ? CC_C : CC_X86_64Win64;
191
192 if (D->hasAttr<SysVABIAttr>())
193 return IsWindows ? CC_X86_64SysV : CC_C;
194
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000195 if (D->hasAttr<PreserveMostAttr>())
196 return CC_PreserveMost;
197
198 if (D->hasAttr<PreserveAllAttr>())
199 return CC_PreserveAll;
200
John McCallab26cfa2010-02-05 21:31:56 +0000201 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000202}
203
John McCalla729c622012-02-17 03:33:10 +0000204/// Arrange the argument and result information for a call to an
205/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000206/// (Zero value of RD means we don't have any meaningful "this" argument type,
207/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000208/// The member function must be an ordinary function, i.e. not a
209/// constructor or destructor.
210const CGFunctionInfo &
211CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000212 const FunctionProtoType *FTP,
213 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000214 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000215
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000216 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000217 if (RD)
218 argTypes.push_back(GetThisType(Context, RD));
219 else
220 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000221
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000222 return ::arrangeLLVMFunctionInfo(
223 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000224 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000225}
226
John McCalla729c622012-02-17 03:33:10 +0000227/// Arrange the argument and result information for a declaration or
228/// definition of the given C++ non-static member function. The
229/// member function must be an ordinary function, i.e. not a
230/// constructor or destructor.
231const CGFunctionInfo &
232CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000233 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000234 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
235
John McCalla729c622012-02-17 03:33:10 +0000236 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000237
John McCalla729c622012-02-17 03:33:10 +0000238 if (MD->isInstance()) {
239 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000240 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000241 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000242 }
243
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000244 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000245}
246
John McCalla729c622012-02-17 03:33:10 +0000247const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000248CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
249 StructorType Type) {
250
John McCalla729c622012-02-17 03:33:10 +0000251 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000252 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000253 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000254
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000255 GlobalDecl GD;
256 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
257 GD = GlobalDecl(CD, toCXXCtorType(Type));
258 } else {
259 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
260 GD = GlobalDecl(DD, toCXXDtorType(Type));
261 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000262
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000263 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000264
265 // Add the formal parameters.
John McCallc56a8b32016-03-11 04:30:31 +0000266 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000267
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000269
270 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000271 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000272
John McCall8dda7b22012-07-07 06:41:13 +0000273 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000274 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
275 ? argTypes.front()
276 : TheCXXABI.hasMostDerivedReturn(GD)
277 ? CGM.getContext().VoidPtrTy
278 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000279 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
280 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000281 paramInfos, required);
282}
283
284static SmallVector<CanQualType, 16>
285getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
286 SmallVector<CanQualType, 16> argTypes;
287 for (auto &arg : args)
288 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
289 return argTypes;
290}
291
292static SmallVector<CanQualType, 16>
293getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
294 SmallVector<CanQualType, 16> argTypes;
295 for (auto &arg : args)
296 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
297 return argTypes;
298}
299
300static void addExtParameterInfosForCall(
301 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
302 const FunctionProtoType *proto,
303 unsigned prefixArgs,
304 unsigned totalArgs) {
305 assert(proto->hasExtParameterInfos());
306 assert(paramInfos.size() <= prefixArgs);
307 assert(proto->getNumParams() + prefixArgs <= totalArgs);
308
309 // Add default infos for any prefix args that don't already have infos.
310 paramInfos.resize(prefixArgs);
311
312 // Add infos for the prototype.
313 auto protoInfos = proto->getExtParameterInfos();
314 paramInfos.append(protoInfos.begin(), protoInfos.end());
315
316 // Add default infos for the variadic arguments.
317 paramInfos.resize(totalArgs);
318}
319
320static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
321getExtParameterInfosForCall(const FunctionProtoType *proto,
322 unsigned prefixArgs, unsigned totalArgs) {
323 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
324 if (proto->hasExtParameterInfos()) {
325 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
326 }
327 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000328}
329
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000330/// Arrange a call to a C++ method, passing the given arguments.
331const CGFunctionInfo &
332CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
333 const CXXConstructorDecl *D,
334 CXXCtorType CtorKind,
335 unsigned ExtraArgs) {
336 // FIXME: Kill copy.
337 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000338 for (const auto &Arg : args)
339 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000340
341 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000342 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000343 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000344 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
345 ? ArgTypes.front()
346 : TheCXXABI.hasMostDerivedReturn(GD)
347 ? CGM.getContext().VoidPtrTy
348 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000349
350 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000351 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
352 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000353 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
354 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000355 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000356}
357
John McCalla729c622012-02-17 03:33:10 +0000358/// Arrange the argument and result information for the declaration or
359/// definition of the given function.
360const CGFunctionInfo &
361CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000362 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000363 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000364 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000365
John McCall2da83a32010-02-26 00:48:12 +0000366 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000367
John McCall2da83a32010-02-26 00:48:12 +0000368 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000369
370 // When declaring a function without a prototype, always use a
371 // non-variadic type.
372 if (isa<FunctionNoProtoType>(FTy)) {
373 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000374 return arrangeLLVMFunctionInfo(
375 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000376 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000377 }
378
John McCall2da83a32010-02-26 00:48:12 +0000379 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000380 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000381}
382
John McCalla729c622012-02-17 03:33:10 +0000383/// Arrange the argument and result information for the declaration or
384/// definition of an Objective-C method.
385const CGFunctionInfo &
386CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
387 // It happens that this is the same as a call with no optional
388 // arguments, except also using the formal 'self' type.
389 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
390}
391
392/// Arrange the argument and result information for the function type
393/// through which to perform a send to the given Objective-C method,
394/// using the given receiver type. The receiver type is not always
395/// the 'self' type of the method or even an Objective-C pointer type.
396/// This is *not* the right method for actually performing such a
397/// message send, due to the possibility of optional arguments.
398const CGFunctionInfo &
399CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
400 QualType receiverType) {
401 SmallVector<CanQualType, 16> argTys;
402 argTys.push_back(Context.getCanonicalParamType(receiverType));
403 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000404 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000405 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000406 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000407 }
John McCall31168b02011-06-15 23:02:42 +0000408
409 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000410 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
411 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000412
David Blaikiebbafb8a2012-03-11 07:00:24 +0000413 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000414 MD->hasAttr<NSReturnsRetainedAttr>())
415 einfo = einfo.withProducesResult(true);
416
John McCalla729c622012-02-17 03:33:10 +0000417 RequiredArgs required =
418 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
419
Peter Collingbournef7706832014-12-12 23:41:25 +0000420 return arrangeLLVMFunctionInfo(
421 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000422 /*chainCall=*/false, argTys, einfo, {}, required);
423}
424
425const CGFunctionInfo &
426CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
427 const CallArgList &args) {
428 auto argTypes = getArgTypesForCall(Context, args);
429 FunctionType::ExtInfo einfo;
430
431 return arrangeLLVMFunctionInfo(
432 GetReturnType(returnType), /*instanceMethod=*/false,
433 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000434}
435
John McCalla729c622012-02-17 03:33:10 +0000436const CGFunctionInfo &
437CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000438 // FIXME: Do we need to handle ObjCMethodDecl?
439 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000440
Anders Carlsson6710c532010-02-06 02:44:09 +0000441 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000442 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000443
444 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000445 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000446
John McCalla729c622012-02-17 03:33:10 +0000447 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000448}
449
Reid Klecknerc3473512014-08-29 21:43:29 +0000450/// Arrange a thunk that takes 'this' as the first parameter followed by
451/// varargs. Return a void pointer, regardless of the actual return type.
452/// The body of the thunk will end in a musttail call to a function of the
453/// correct type, and the caller will bitcast the function to the correct
454/// prototype.
455const CGFunctionInfo &
456CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
457 assert(MD->isVirtual() && "only virtual memptrs have thunks");
458 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
459 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000460 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
461 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000462 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000463}
464
David Majnemerdfa6d202015-03-11 18:36:39 +0000465const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000466CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
467 CXXCtorType CT) {
468 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
469
David Majnemerdfa6d202015-03-11 18:36:39 +0000470 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
471 SmallVector<CanQualType, 2> ArgTys;
472 const CXXRecordDecl *RD = CD->getParent();
473 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000474 if (CT == Ctor_CopyingClosure)
475 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000476 if (RD->getNumVBases() > 0)
477 ArgTys.push_back(Context.IntTy);
478 CallingConv CC = Context.getDefaultCallingConvention(
479 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
480 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
481 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000482 FunctionType::ExtInfo(CC), {},
483 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000484}
485
John McCallc818bbb2012-12-07 07:03:17 +0000486/// Arrange a call as unto a free function, except possibly with an
487/// additional number of formal parameters considered required.
488static const CGFunctionInfo &
489arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000490 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000491 const CallArgList &args,
492 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000493 unsigned numExtraRequiredArgs,
494 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000495 assert(args.size() >= numExtraRequiredArgs);
496
John McCallc56a8b32016-03-11 04:30:31 +0000497 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
498
John McCallc818bbb2012-12-07 07:03:17 +0000499 // In most cases, there are no optional arguments.
500 RequiredArgs required = RequiredArgs::All;
501
502 // If we have a variadic prototype, the required arguments are the
503 // extra prefix plus the arguments in the prototype.
504 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
505 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000506 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000507
John McCallc56a8b32016-03-11 04:30:31 +0000508 if (proto->hasExtParameterInfos())
509 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
510 args.size());
511
John McCallc818bbb2012-12-07 07:03:17 +0000512 // If we don't have a prototype at all, but we're supposed to
513 // explicitly use the variadic convention for unprototyped calls,
514 // treat all of the arguments as required but preserve the nominal
515 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000516 } else if (CGM.getTargetCodeGenInfo()
517 .isNoProtoCallVariadic(args,
518 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000519 required = RequiredArgs(args.size());
520 }
521
Peter Collingbournef7706832014-12-12 23:41:25 +0000522 // FIXME: Kill copy.
523 SmallVector<CanQualType, 16> argTypes;
524 for (const auto &arg : args)
525 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
526 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
527 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000528 argTypes, fnType->getExtInfo(), paramInfos,
529 required);
John McCallc818bbb2012-12-07 07:03:17 +0000530}
531
John McCalla729c622012-02-17 03:33:10 +0000532/// Figure out the rules for calling a function with the given formal
533/// type using the given arguments. The arguments are necessary
534/// because the function might be unprototyped, in which case it's
535/// target-dependent in crazy ways.
536const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000537CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000538 const FunctionType *fnType,
539 bool chainCall) {
540 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
541 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000542}
John McCalla729c622012-02-17 03:33:10 +0000543
John McCallc56a8b32016-03-11 04:30:31 +0000544/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000545/// extra implicit argument.
546const CGFunctionInfo &
547CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
548 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000549 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
550 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000551}
552
553const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000554CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
555 const FunctionArgList &params) {
556 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
557 auto argTypes = getArgTypesForDeclaration(Context, params);
558
George Burgess IV419996c2016-06-16 23:06:04 +0000559 return arrangeLLVMFunctionInfo(
560 GetReturnType(proto->getReturnType()),
561 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
562 proto->getExtInfo(), paramInfos,
563 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000564}
565
566const CGFunctionInfo &
567CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
568 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000569 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000570 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000571 for (const auto &Arg : args)
572 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000573 return arrangeLLVMFunctionInfo(
574 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000575 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
576 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000577}
578
John McCallc56a8b32016-03-11 04:30:31 +0000579const CGFunctionInfo &
580CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
581 const FunctionArgList &args) {
582 auto argTypes = getArgTypesForDeclaration(Context, args);
583
584 return arrangeLLVMFunctionInfo(
585 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
586 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
587}
588
589const CGFunctionInfo &
590CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
591 ArrayRef<CanQualType> argTypes) {
592 return arrangeLLVMFunctionInfo(
593 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
594 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
595}
596
John McCall8dda7b22012-07-07 06:41:13 +0000597/// Arrange a call to a C++ method, passing the given arguments.
598const CGFunctionInfo &
599CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000600 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000601 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000602 unsigned numRequiredArgs =
603 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
604 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
605 auto paramInfos =
606 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
607
John McCall8dda7b22012-07-07 06:41:13 +0000608 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000609 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000610
John McCallc56a8b32016-03-11 04:30:31 +0000611 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000612 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000613 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
614 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000615}
616
John McCalla729c622012-02-17 03:33:10 +0000617const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000618 return arrangeLLVMFunctionInfo(
619 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000620 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
621}
622
623const CGFunctionInfo &
624CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
625 const CallArgList &args) {
626 assert(signature.arg_size() <= args.size());
627 if (signature.arg_size() == args.size())
628 return signature;
629
630 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
631 auto sigParamInfos = signature.getExtParameterInfos();
632 if (!sigParamInfos.empty()) {
633 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
634 paramInfos.resize(args.size());
635 }
636
637 auto argTypes = getArgTypesForCall(Context, args);
638
639 assert(signature.getRequiredArgs().allowsOptionalArgs());
640 return arrangeLLVMFunctionInfo(signature.getReturnType(),
641 signature.isInstanceMethod(),
642 signature.isChainCall(),
643 argTypes,
644 signature.getExtInfo(),
645 paramInfos,
646 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000647}
648
John McCalla729c622012-02-17 03:33:10 +0000649/// Arrange the argument and result information for an abstract value
650/// of a given function type. This is the method which all of the
651/// above functions ultimately defer to.
652const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000653CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000654 bool instanceMethod,
655 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000656 ArrayRef<CanQualType> argTypes,
657 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000658 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000659 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000660 assert(std::all_of(argTypes.begin(), argTypes.end(),
661 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000662
Daniel Dunbare0be8292009-02-03 00:07:12 +0000663 // Lookup or create unique function info.
664 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000665 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
666 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000667
Craig Topper8a13c412014-05-21 05:09:00 +0000668 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000669 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000670 if (FI)
671 return *FI;
672
John McCallc56a8b32016-03-11 04:30:31 +0000673 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
674
John McCalla729c622012-02-17 03:33:10 +0000675 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000676 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000677 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000678 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000679
David Blaikie82e95a32014-11-19 07:49:47 +0000680 bool inserted = FunctionsBeingProcessed.insert(FI).second;
681 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000682 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000683
Daniel Dunbar313321e2009-02-03 05:31:23 +0000684 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000685 if (info.getCC() != CC_Swift) {
686 getABIInfo().computeInfo(*FI);
687 } else {
688 swiftcall::computeABIInfo(CGM, *FI);
689 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000690
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000691 // Loop over all of the computed argument and return value info. If any of
692 // them are direct or extend without a specified coerce type, specify the
693 // default now.
John McCalla729c622012-02-17 03:33:10 +0000694 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000695 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000696 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000697
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000698 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000699 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000700 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000701
John McCalla729c622012-02-17 03:33:10 +0000702 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
703 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000704
Daniel Dunbare0be8292009-02-03 00:07:12 +0000705 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000706}
707
John McCalla729c622012-02-17 03:33:10 +0000708CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000709 bool instanceMethod,
710 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000711 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000712 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000713 CanQualType resultType,
714 ArrayRef<CanQualType> argTypes,
715 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000716 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
717
718 void *buffer =
719 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
720 argTypes.size() + 1, paramInfos.size()));
721
John McCalla729c622012-02-17 03:33:10 +0000722 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
723 FI->CallingConvention = llvmCC;
724 FI->EffectiveCallingConvention = llvmCC;
725 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000726 FI->InstanceMethod = instanceMethod;
727 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000728 FI->NoReturn = info.getNoReturn();
729 FI->ReturnsRetained = info.getProducesResult();
730 FI->Required = required;
731 FI->HasRegParm = info.getHasRegParm();
732 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000733 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000734 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000735 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000736 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000737 FI->getArgsBuffer()[0].type = resultType;
738 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
739 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000740 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
741 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000742 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000743}
744
745/***/
746
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000747namespace {
748// ABIArgInfo::Expand implementation.
749
750// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
751struct TypeExpansion {
752 enum TypeExpansionKind {
753 // Elements of constant arrays are expanded recursively.
754 TEK_ConstantArray,
755 // Record fields are expanded recursively (but if record is a union, only
756 // the field with the largest size is expanded).
757 TEK_Record,
758 // For complex types, real and imaginary parts are expanded recursively.
759 TEK_Complex,
760 // All other types are not expandable.
761 TEK_None
762 };
763
764 const TypeExpansionKind Kind;
765
766 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000767 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000768};
769
770struct ConstantArrayExpansion : TypeExpansion {
771 QualType EltTy;
772 uint64_t NumElts;
773
774 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
775 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
776 static bool classof(const TypeExpansion *TE) {
777 return TE->Kind == TEK_ConstantArray;
778 }
779};
780
781struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000782 SmallVector<const CXXBaseSpecifier *, 1> Bases;
783
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000784 SmallVector<const FieldDecl *, 1> Fields;
785
Reid Klecknere9f6a712014-10-31 17:10:41 +0000786 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
787 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000788 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
789 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000790 static bool classof(const TypeExpansion *TE) {
791 return TE->Kind == TEK_Record;
792 }
793};
794
795struct ComplexExpansion : TypeExpansion {
796 QualType EltTy;
797
798 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
799 static bool classof(const TypeExpansion *TE) {
800 return TE->Kind == TEK_Complex;
801 }
802};
803
804struct NoExpansion : TypeExpansion {
805 NoExpansion() : TypeExpansion(TEK_None) {}
806 static bool classof(const TypeExpansion *TE) {
807 return TE->Kind == TEK_None;
808 }
809};
810} // namespace
811
812static std::unique_ptr<TypeExpansion>
813getTypeExpansion(QualType Ty, const ASTContext &Context) {
814 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
815 return llvm::make_unique<ConstantArrayExpansion>(
816 AT->getElementType(), AT->getSize().getZExtValue());
817 }
818 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000819 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000820 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000821 const RecordDecl *RD = RT->getDecl();
822 assert(!RD->hasFlexibleArrayMember() &&
823 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000824 if (RD->isUnion()) {
825 // Unions can be here only in degenerative cases - all the fields are same
826 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000827 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000828 CharUnits UnionSize = CharUnits::Zero();
829
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000830 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000831 // Skip zero length bitfields.
832 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
833 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000834 assert(!FD->isBitField() &&
835 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000836 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000837 if (UnionSize < FieldSize) {
838 UnionSize = FieldSize;
839 LargestFD = FD;
840 }
841 }
842 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000843 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000844 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000845 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
846 assert(!CXXRD->isDynamicClass() &&
847 "cannot expand vtable pointers in dynamic classes");
848 for (const CXXBaseSpecifier &BS : CXXRD->bases())
849 Bases.push_back(&BS);
850 }
851
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000852 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000853 // Skip zero length bitfields.
854 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
855 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000856 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000857 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000858 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000859 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000860 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000861 return llvm::make_unique<RecordExpansion>(std::move(Bases),
862 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000863 }
864 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
865 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
866 }
867 return llvm::make_unique<NoExpansion>();
868}
869
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000870static int getExpansionSize(QualType Ty, const ASTContext &Context) {
871 auto Exp = getTypeExpansion(Ty, Context);
872 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
873 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
874 }
875 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
876 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000877 for (auto BS : RExp->Bases)
878 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000879 for (auto FD : RExp->Fields)
880 Res += getExpansionSize(FD->getType(), Context);
881 return Res;
882 }
883 if (isa<ComplexExpansion>(Exp.get()))
884 return 2;
885 assert(isa<NoExpansion>(Exp.get()));
886 return 1;
887}
888
Alexey Samsonov153004f2014-09-29 22:08:00 +0000889void
890CodeGenTypes::getExpandedTypes(QualType Ty,
891 SmallVectorImpl<llvm::Type *>::iterator &TI) {
892 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000893 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
894 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000895 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000896 }
897 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000898 for (auto BS : RExp->Bases)
899 getExpandedTypes(BS->getType(), TI);
900 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000901 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000902 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
903 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000904 *TI++ = EltTy;
905 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000906 } else {
907 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000908 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000909 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000910}
911
John McCall7f416cc2015-09-08 08:05:57 +0000912static void forConstantArrayExpansion(CodeGenFunction &CGF,
913 ConstantArrayExpansion *CAE,
914 Address BaseAddr,
915 llvm::function_ref<void(Address)> Fn) {
916 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
917 CharUnits EltAlign =
918 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
919
920 for (int i = 0, n = CAE->NumElts; i < n; i++) {
921 llvm::Value *EltAddr =
922 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
923 Fn(Address(EltAddr, EltAlign));
924 }
925}
926
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000927void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000928 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000929 assert(LV.isSimple() &&
930 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000931
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000932 auto Exp = getTypeExpansion(Ty, getContext());
933 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000934 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
935 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000936 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
937 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000938 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000939 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000940 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000941 for (const CXXBaseSpecifier *BS : RExp->Bases) {
942 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000943 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000944 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
945 /*NullCheckValue=*/false, SourceLocation());
946 LValue SubLV = MakeAddrLValue(Base, BS->getType());
947
948 // Recurse onto bases.
949 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
950 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000951 for (auto FD : RExp->Fields) {
952 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000953 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000954 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000955 }
John McCall7f416cc2015-09-08 08:05:57 +0000956 } else if (isa<ComplexExpansion>(Exp.get())) {
957 auto realValue = *AI++;
958 auto imagValue = *AI++;
959 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000960 } else {
961 assert(isa<NoExpansion>(Exp.get()));
962 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000963 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000964}
965
966void CodeGenFunction::ExpandTypeToArgs(
967 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
968 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
969 auto Exp = getTypeExpansion(Ty, getContext());
970 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000971 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
972 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000973 RValue EltRV =
974 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
975 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000976 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000977 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000978 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000979 for (const CXXBaseSpecifier *BS : RExp->Bases) {
980 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000981 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000982 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
983 /*NullCheckValue=*/false, SourceLocation());
984 RValue BaseRV = RValue::getAggregate(Base);
985
986 // Recurse onto bases.
987 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
988 IRCallArgPos);
989 }
990
991 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000992 for (auto FD : RExp->Fields) {
993 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
994 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
995 IRCallArgPos);
996 }
997 } else if (isa<ComplexExpansion>(Exp.get())) {
998 ComplexPairTy CV = RV.getComplexVal();
999 IRCallArgs[IRCallArgPos++] = CV.first;
1000 IRCallArgs[IRCallArgPos++] = CV.second;
1001 } else {
1002 assert(isa<NoExpansion>(Exp.get()));
1003 assert(RV.isScalar() &&
1004 "Unexpected non-scalar rvalue during struct expansion.");
1005
1006 // Insert a bitcast as needed.
1007 llvm::Value *V = RV.getScalarVal();
1008 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1009 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1010 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1011
1012 IRCallArgs[IRCallArgPos++] = V;
1013 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001014}
1015
John McCall7f416cc2015-09-08 08:05:57 +00001016/// Create a temporary allocation for the purposes of coercion.
1017static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1018 CharUnits MinAlign) {
1019 // Don't use an alignment that's worse than what LLVM would prefer.
1020 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1021 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1022
1023 return CGF.CreateTempAlloca(Ty, Align);
1024}
1025
Chris Lattner895c52b2010-06-27 06:04:18 +00001026/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001027/// accessing some number of bytes out of it, try to gep into the struct to get
1028/// at its inner goodness. Dive as deep as possible without entering an element
1029/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001030static Address
1031EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001032 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001033 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001034 // We can't dive into a zero-element struct.
1035 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001036
Chris Lattner2192fe52011-07-18 04:24:23 +00001037 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001038
Chris Lattner1cd66982010-06-27 05:56:15 +00001039 // 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 +00001040 // first element is the same size as the whole struct, we can enter it. The
1041 // comparison must be made on the store size and not the alloca size. Using
1042 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001043 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001044 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001045 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001046 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001047 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001048
Chris Lattner1cd66982010-06-27 05:56:15 +00001049 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001050 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001051
Chris Lattner1cd66982010-06-27 05:56:15 +00001052 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001053 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001054 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001055 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001056
1057 return SrcPtr;
1058}
1059
Chris Lattner055097f2010-06-27 06:26:04 +00001060/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1061/// are either integers or pointers. This does a truncation of the value if it
1062/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001063///
1064/// This behaves as if the value were coerced through memory, so on big-endian
1065/// targets the high bits are preserved in a truncation, while little-endian
1066/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001067static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001068 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001069 CodeGenFunction &CGF) {
1070 if (Val->getType() == Ty)
1071 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001072
Chris Lattner055097f2010-06-27 06:26:04 +00001073 if (isa<llvm::PointerType>(Val->getType())) {
1074 // If this is Pointer->Pointer avoid conversion to and from int.
1075 if (isa<llvm::PointerType>(Ty))
1076 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001077
Chris Lattner055097f2010-06-27 06:26:04 +00001078 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001079 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001080 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001081
Chris Lattner2192fe52011-07-18 04:24:23 +00001082 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001083 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001084 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001085
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001086 if (Val->getType() != DestIntTy) {
1087 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1088 if (DL.isBigEndian()) {
1089 // Preserve the high bits on big-endian targets.
1090 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001091 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1092 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1093
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001094 if (SrcSize > DstSize) {
1095 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1096 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1097 } else {
1098 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1099 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1100 }
1101 } else {
1102 // Little-endian targets preserve the low bits. No shifts required.
1103 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1104 }
1105 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001106
Chris Lattner055097f2010-06-27 06:26:04 +00001107 if (isa<llvm::PointerType>(Ty))
1108 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1109 return Val;
1110}
1111
Chris Lattner1cd66982010-06-27 05:56:15 +00001112
1113
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001114/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001115/// a pointer to an object of type \arg Ty, known to be aligned to
1116/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001117///
1118/// This safely handles the case when the src type is smaller than the
1119/// destination type; in this situation the values of bits which not
1120/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001121static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001122 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001123 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001124
Chris Lattnerd200eda2010-06-28 22:51:39 +00001125 // If SrcTy and Ty are the same, just do a load.
1126 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001127 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001128
Micah Villmowdd31ca12012-10-08 16:25:52 +00001129 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001130
Chris Lattner2192fe52011-07-18 04:24:23 +00001131 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001132 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1133 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001134 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001135
Micah Villmowdd31ca12012-10-08 16:25:52 +00001136 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001137
Chris Lattner055097f2010-06-27 06:26:04 +00001138 // If the source and destination are integer or pointer types, just do an
1139 // extension or truncation to the desired type.
1140 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1141 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001142 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001143 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1144 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001145
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001146 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001147 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001148 // Generally SrcSize is never greater than DstSize, since this means we are
1149 // losing bits. However, this can happen in cases where the structure has
1150 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001151 //
Mike Stump18bb9282009-05-16 07:57:57 +00001152 // FIXME: Assert that we aren't truncating non-padding bits when have access
1153 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001154 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1155 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001156 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001157
John McCall7f416cc2015-09-08 08:05:57 +00001158 // Otherwise do coercion through memory. This is stupid, but simple.
1159 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1160 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1161 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001162 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1163 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001164 false);
1165 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001166}
1167
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001168// Function to store a first-class aggregate into memory. We prefer to
1169// store the elements rather than the aggregate to be more friendly to
1170// fast-isel.
1171// FIXME: Do we need to recurse here?
1172static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001173 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001174 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001175 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001176 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001177 const llvm::StructLayout *Layout =
1178 CGF.CGM.getDataLayout().getStructLayout(STy);
1179
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001180 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001181 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1182 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001183 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001184 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001185 }
1186 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001187 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001188 }
1189}
1190
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001191/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001192/// where the source and destination may have different types. The
1193/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001194///
1195/// This safely handles the case when the src type is larger than the
1196/// destination type; the upper bits of the src will be lost.
1197static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001198 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001199 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001200 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001201 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001202 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001203 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001204 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001205 return;
1206 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001207
Micah Villmowdd31ca12012-10-08 16:25:52 +00001208 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001209
Chris Lattner2192fe52011-07-18 04:24:23 +00001210 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001211 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1212 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001213 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001214
Chris Lattner055097f2010-06-27 06:26:04 +00001215 // If the source and destination are integer or pointer types, just do an
1216 // extension or truncation to the desired type.
1217 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1218 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1219 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001220 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001221 return;
1222 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001223
Micah Villmowdd31ca12012-10-08 16:25:52 +00001224 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001225
Daniel Dunbar313321e2009-02-03 05:31:23 +00001226 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001227 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001228 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1229 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001230 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001231 // Otherwise do coercion through memory. This is stupid, but
1232 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001233
1234 // Generally SrcSize is never greater than DstSize, since this means we are
1235 // losing bits. However, this can happen in cases where the structure has
1236 // additional padding, for example due to a user specified alignment.
1237 //
1238 // FIXME: Assert that we aren't truncating non-padding bits when have access
1239 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001240 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1241 CGF.Builder.CreateStore(Src, Tmp);
1242 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1243 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001244 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1245 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001246 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001247 }
1248}
1249
John McCall7f416cc2015-09-08 08:05:57 +00001250static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1251 const ABIArgInfo &info) {
1252 if (unsigned offset = info.getDirectOffset()) {
1253 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1254 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1255 CharUnits::fromQuantity(offset));
1256 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1257 }
1258 return addr;
1259}
1260
Alexey Samsonov153004f2014-09-29 22:08:00 +00001261namespace {
1262
1263/// Encapsulates information about the way function arguments from
1264/// CGFunctionInfo should be passed to actual LLVM IR function.
1265class ClangToLLVMArgMapping {
1266 static const unsigned InvalidIndex = ~0U;
1267 unsigned InallocaArgNo;
1268 unsigned SRetArgNo;
1269 unsigned TotalIRArgs;
1270
1271 /// Arguments of LLVM IR function corresponding to single Clang argument.
1272 struct IRArgs {
1273 unsigned PaddingArgIndex;
1274 // Argument is expanded to IR arguments at positions
1275 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1276 unsigned FirstArgIndex;
1277 unsigned NumberOfArgs;
1278
1279 IRArgs()
1280 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1281 NumberOfArgs(0) {}
1282 };
1283
1284 SmallVector<IRArgs, 8> ArgInfo;
1285
1286public:
1287 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1288 bool OnlyRequiredArgs = false)
1289 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1290 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1291 construct(Context, FI, OnlyRequiredArgs);
1292 }
1293
1294 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1295 unsigned getInallocaArgNo() const {
1296 assert(hasInallocaArg());
1297 return InallocaArgNo;
1298 }
1299
1300 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1301 unsigned getSRetArgNo() const {
1302 assert(hasSRetArg());
1303 return SRetArgNo;
1304 }
1305
1306 unsigned totalIRArgs() const { return TotalIRArgs; }
1307
1308 bool hasPaddingArg(unsigned ArgNo) const {
1309 assert(ArgNo < ArgInfo.size());
1310 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1311 }
1312 unsigned getPaddingArgNo(unsigned ArgNo) const {
1313 assert(hasPaddingArg(ArgNo));
1314 return ArgInfo[ArgNo].PaddingArgIndex;
1315 }
1316
1317 /// Returns index of first IR argument corresponding to ArgNo, and their
1318 /// quantity.
1319 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1320 assert(ArgNo < ArgInfo.size());
1321 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1322 ArgInfo[ArgNo].NumberOfArgs);
1323 }
1324
1325private:
1326 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1327 bool OnlyRequiredArgs);
1328};
1329
1330void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1331 const CGFunctionInfo &FI,
1332 bool OnlyRequiredArgs) {
1333 unsigned IRArgNo = 0;
1334 bool SwapThisWithSRet = false;
1335 const ABIArgInfo &RetAI = FI.getReturnInfo();
1336
1337 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1338 SwapThisWithSRet = RetAI.isSRetAfterThis();
1339 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1340 }
1341
1342 unsigned ArgNo = 0;
1343 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1344 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1345 ++I, ++ArgNo) {
1346 assert(I != FI.arg_end());
1347 QualType ArgType = I->type;
1348 const ABIArgInfo &AI = I->info;
1349 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1350 auto &IRArgs = ArgInfo[ArgNo];
1351
1352 if (AI.getPaddingType())
1353 IRArgs.PaddingArgIndex = IRArgNo++;
1354
1355 switch (AI.getKind()) {
1356 case ABIArgInfo::Extend:
1357 case ABIArgInfo::Direct: {
1358 // FIXME: handle sseregparm someday...
1359 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1360 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1361 IRArgs.NumberOfArgs = STy->getNumElements();
1362 } else {
1363 IRArgs.NumberOfArgs = 1;
1364 }
1365 break;
1366 }
1367 case ABIArgInfo::Indirect:
1368 IRArgs.NumberOfArgs = 1;
1369 break;
1370 case ABIArgInfo::Ignore:
1371 case ABIArgInfo::InAlloca:
1372 // ignore and inalloca doesn't have matching LLVM parameters.
1373 IRArgs.NumberOfArgs = 0;
1374 break;
John McCallf26e73d2016-03-11 04:30:43 +00001375 case ABIArgInfo::CoerceAndExpand:
1376 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1377 break;
1378 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001379 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1380 break;
1381 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001382
1383 if (IRArgs.NumberOfArgs > 0) {
1384 IRArgs.FirstArgIndex = IRArgNo;
1385 IRArgNo += IRArgs.NumberOfArgs;
1386 }
1387
1388 // Skip over the sret parameter when it comes second. We already handled it
1389 // above.
1390 if (IRArgNo == 1 && SwapThisWithSRet)
1391 IRArgNo++;
1392 }
1393 assert(ArgNo == ArgInfo.size());
1394
1395 if (FI.usesInAlloca())
1396 InallocaArgNo = IRArgNo++;
1397
1398 TotalIRArgs = IRArgNo;
1399}
1400} // namespace
1401
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001402/***/
1403
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001404bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001405 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001406}
1407
Tim Northovere77cc392014-03-29 13:28:05 +00001408bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1409 return ReturnTypeUsesSRet(FI) &&
1410 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1411}
1412
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001413bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1414 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1415 switch (BT->getKind()) {
1416 default:
1417 return false;
1418 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001419 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001420 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001421 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001422 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001423 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001424 }
1425 }
1426
1427 return false;
1428}
1429
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001430bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1431 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1432 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1433 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001434 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001435 }
1436 }
1437
1438 return false;
1439}
1440
Chris Lattnera5f58b02011-07-09 17:41:47 +00001441llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001442 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1443 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001444}
1445
Chris Lattnera5f58b02011-07-09 17:41:47 +00001446llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001447CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001448
David Blaikie82e95a32014-11-19 07:49:47 +00001449 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1450 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001451 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001452
Alexey Samsonov153004f2014-09-29 22:08:00 +00001453 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001454 const ABIArgInfo &retAI = FI.getReturnInfo();
1455 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001456 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001457 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001458
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001459 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001460 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001461 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001462 break;
1463
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001464 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001465 if (retAI.getInAllocaSRet()) {
1466 // sret things on win32 aren't void, they return the sret pointer.
1467 QualType ret = FI.getReturnType();
1468 llvm::Type *ty = ConvertType(ret);
1469 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1470 resultType = llvm::PointerType::get(ty, addressSpace);
1471 } else {
1472 resultType = llvm::Type::getVoidTy(getLLVMContext());
1473 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001474 break;
1475
John McCall7f416cc2015-09-08 08:05:57 +00001476 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001477 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001478 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001479 break;
John McCallf26e73d2016-03-11 04:30:43 +00001480
1481 case ABIArgInfo::CoerceAndExpand:
1482 resultType = retAI.getUnpaddedCoerceAndExpandType();
1483 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Alexey Samsonov153004f2014-09-29 22:08:00 +00001486 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1487 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1488
1489 // Add type for sret argument.
1490 if (IRFunctionArgs.hasSRetArg()) {
1491 QualType Ret = FI.getReturnType();
1492 llvm::Type *Ty = ConvertType(Ret);
1493 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1494 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1495 llvm::PointerType::get(Ty, AddressSpace);
1496 }
1497
1498 // Add type for inalloca argument.
1499 if (IRFunctionArgs.hasInallocaArg()) {
1500 auto ArgStruct = FI.getArgStruct();
1501 assert(ArgStruct);
1502 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1503 }
1504
John McCallc818bbb2012-12-07 07:03:17 +00001505 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001506 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001507 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1508 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001509 for (; it != ie; ++it, ++ArgNo) {
1510 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001511
Rafael Espindolafad28de2012-10-24 01:59:00 +00001512 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001513 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1514 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1515 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001516
Alexey Samsonov153004f2014-09-29 22:08:00 +00001517 unsigned FirstIRArg, NumIRArgs;
1518 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1519
1520 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001521 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001522 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001523 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001524 break;
1525
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001526 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001527 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001528 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001529 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001530 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001531 break;
1532 }
1533
1534 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001535 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001536 // Fast-isel and the optimizer generally like scalar values better than
1537 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001538 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001539 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001540 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1541 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001542 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001543 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001544 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001545 assert(NumIRArgs == 1);
1546 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001547 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001548 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
John McCallf26e73d2016-03-11 04:30:43 +00001551 case ABIArgInfo::CoerceAndExpand: {
1552 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1553 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1554 *ArgTypesIter++ = EltTy;
1555 }
1556 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1557 break;
1558 }
1559
Daniel Dunbard3674e62008-09-11 01:48:57 +00001560 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001561 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1562 getExpandedTypes(it->type, ArgTypesIter);
1563 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001564 break;
1565 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001566 }
1567
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001568 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1569 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001570
1571 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001572}
1573
Chris Lattner2192fe52011-07-18 04:24:23 +00001574llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001575 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001576 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001577
Chris Lattner8806e322011-07-10 00:18:59 +00001578 if (!isFuncTypeConvertible(FPT))
1579 return llvm::StructType::get(getLLVMContext());
1580
1581 const CGFunctionInfo *Info;
1582 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001583 Info =
1584 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001585 else
John McCalla729c622012-02-17 03:33:10 +00001586 Info = &arrangeCXXMethodDeclaration(MD);
1587 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001588}
1589
Samuel Antao798f11c2015-11-23 22:04:44 +00001590static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1591 llvm::AttrBuilder &FuncAttrs,
1592 const FunctionProtoType *FPT) {
1593 if (!FPT)
1594 return;
1595
1596 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1597 FPT->isNothrow(Ctx))
1598 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1599}
1600
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001601void CodeGenModule::ConstructAttributeList(
1602 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1603 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001604 llvm::AttrBuilder FuncAttrs;
1605 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001606 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001607
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001608 CallingConv = FI.getEffectiveCallingConvention();
1609
John McCallab26cfa2010-02-05 21:31:56 +00001610 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001611 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001612
Samuel Antao798f11c2015-11-23 22:04:44 +00001613 // If we have information about the function prototype, we can learn
1614 // attributes form there.
1615 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1616 CalleeInfo.getCalleeFunctionProtoType());
1617
1618 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1619
Amjad Aboudfaea5602016-03-07 14:22:46 +00001620 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001621 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001622 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001623 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001624 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001625 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001626 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001627 if (TargetDecl->hasAttr<NoReturnAttr>())
1628 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001629 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1630 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001631
1632 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001633 AddAttributesFromFunctionProtoType(
1634 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001635 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1636 // These attributes are not inherited by overloads.
1637 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1638 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001639 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001640 }
1641
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001642 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001643 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001644 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1645 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001646 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001647 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1648 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001649 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1650 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1651 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001652 }
David Majnemer631a90b2015-02-04 07:23:21 +00001653 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001654 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001655 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1656 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001657
Amjad Aboudfaea5602016-03-07 14:22:46 +00001658 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001659 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001660 }
1661
Paul Robinson08556952014-12-11 20:14:04 +00001662 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1663 if (!HasOptnone) {
1664 if (CodeGenOpts.OptimizeSize)
1665 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1666 if (CodeGenOpts.OptimizeSize == 2)
1667 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1668 }
1669
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001670 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001671 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001672 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001673 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001674 if (CodeGenOpts.EnableSegmentedStacks &&
1675 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001676 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001677
Bill Wendling2f81db62013-02-22 20:53:29 +00001678 if (AttrOnCallSite) {
1679 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001680 if (!CodeGenOpts.SimplifyLibCalls ||
1681 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001682 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001683 if (!CodeGenOpts.TrapFuncName.empty())
1684 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001685 } else {
1686 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001687 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001688 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001689 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001690 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001691 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001692 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001693 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001694 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001695 }
1696
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001697 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001698 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001699 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001700 FuncAttrs.addAttribute(
1701 "disable-tail-calls",
1702 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001703
Bill Wendlingdabafea2013-03-13 22:24:33 +00001704 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001705 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001706 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001707 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001708 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001709 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001710 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001711 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001712 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001713 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001714 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001715 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001716
Akira Hatanakaaecca042015-09-11 18:55:09 +00001717 if (CodeGenOpts.StackRealignment)
1718 FuncAttrs.addAttribute("stackrealign");
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001719 if (CodeGenOpts.Backchain)
1720 FuncAttrs.addAttribute("backchain");
Eric Christopher70c16652015-03-25 23:14:47 +00001721
Eric Christopher11acf732015-06-12 01:35:52 +00001722 // Add target-cpu and target-features attributes to functions. If
1723 // we have a decl for the function and it has a target attribute then
1724 // parse that and add it to the feature set.
1725 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001726 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001727 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001728 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001729 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001730
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001731 // Produce the canonical string for this set of features.
1732 std::vector<std::string> Features;
1733 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1734 ie = FeatureMap.end();
1735 it != ie; ++it)
1736 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001737
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001738 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001739 // While we populated the feature map above, we still need to
1740 // get and parse the target attribute so we can get the cpu for
1741 // the function.
1742 const auto *TD = FD->getAttr<TargetAttr>();
1743 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1744 if (ParsedAttr.second != "")
1745 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001746 if (TargetCPU != "")
1747 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1748 if (!Features.empty()) {
1749 std::sort(Features.begin(), Features.end());
1750 FuncAttrs.addAttribute(
1751 "target-features",
1752 llvm::join(Features.begin(), Features.end(), ","));
1753 }
1754 } else {
1755 // Otherwise just add the existing target cpu and target features to the
1756 // function.
1757 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1758 if (TargetCPU != "")
1759 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1760 if (!Features.empty()) {
1761 std::sort(Features.begin(), Features.end());
1762 FuncAttrs.addAttribute(
1763 "target-features",
1764 llvm::join(Features.begin(), Features.end(), ","));
1765 }
Eric Christopher70c16652015-03-25 23:14:47 +00001766 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001767 }
1768
Justin Lebarddd97fa2016-02-24 21:55:11 +00001769 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1770 // Conservatively, mark all functions and calls in CUDA as convergent
1771 // (meaning, they may call an intrinsically convergent op, such as
1772 // __syncthreads(), and so can't have certain optimizations applied around
1773 // them). LLVM will remove this attribute where it safely can.
1774 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Justin Lebard3a44f62016-04-05 18:26:20 +00001775
1776 // Respect -fcuda-flush-denormals-to-zero.
1777 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1778 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
Justin Lebarddd97fa2016-02-24 21:55:11 +00001779 }
1780
Alexey Samsonov153004f2014-09-29 22:08:00 +00001781 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001782
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001783 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001784 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001785 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001786 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001787 if (RetTy->hasSignedIntegerRepresentation())
1788 RetAttrs.addAttribute(llvm::Attribute::SExt);
1789 else if (RetTy->hasUnsignedIntegerRepresentation())
1790 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001791 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001792 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001793 if (RetAI.getInReg())
1794 RetAttrs.addAttribute(llvm::Attribute::InReg);
1795 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001796 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001797 break;
1798
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001799 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001800 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001801 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001802 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1803 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001804 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001805 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001806
John McCallf26e73d2016-03-11 04:30:43 +00001807 case ABIArgInfo::CoerceAndExpand:
1808 break;
1809
Daniel Dunbard3674e62008-09-11 01:48:57 +00001810 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001811 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001812 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001813
Hal Finkela2347ba2014-07-18 15:52:10 +00001814 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1815 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001816 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001817 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1818 .getQuantity());
1819 else if (getContext().getTargetAddressSpace(PTy) == 0)
1820 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1821 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001822
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001823 // Attach return attributes.
1824 if (RetAttrs.hasAttributes()) {
1825 PAL.push_back(llvm::AttributeSet::get(
1826 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1827 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001828
John McCall12f23522016-04-04 18:33:08 +00001829 bool hasUsedSRet = false;
1830
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001831 // Attach attributes to sret.
1832 if (IRFunctionArgs.hasSRetArg()) {
1833 llvm::AttrBuilder SRETAttrs;
1834 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001835 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001836 if (RetAI.getInReg())
1837 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1838 PAL.push_back(llvm::AttributeSet::get(
1839 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1840 }
1841
1842 // Attach attributes to inalloca argument.
1843 if (IRFunctionArgs.hasInallocaArg()) {
1844 llvm::AttrBuilder Attrs;
1845 Attrs.addAttribute(llvm::Attribute::InAlloca);
1846 PAL.push_back(llvm::AttributeSet::get(
1847 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1848 }
1849
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001850 unsigned ArgNo = 0;
1851 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1852 E = FI.arg_end();
1853 I != E; ++I, ++ArgNo) {
1854 QualType ParamType = I->type;
1855 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001856 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001857
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001858 // Add attribute for padding argument, if necessary.
1859 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001860 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001861 PAL.push_back(llvm::AttributeSet::get(
1862 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1863 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001864 }
1865
John McCall39ec71f2010-03-27 00:47:27 +00001866 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1867 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001868 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001869 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001870 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001871 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001872 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001873 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1874 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1875 Attrs.addAttribute(llvm::Attribute::SExt);
1876 else
1877 Attrs.addAttribute(llvm::Attribute::ZExt);
1878 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001879 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001880 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001881 if (ArgNo == 0 && FI.isChainCall())
1882 Attrs.addAttribute(llvm::Attribute::Nest);
1883 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001884 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001885 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001886
James Y Knight71608572015-08-21 18:19:06 +00001887 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001888 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001889 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001890
Anders Carlsson20759ad2009-09-16 15:53:40 +00001891 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001892 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001895
1896 // In a byval argument, it is important that the required
1897 // alignment of the type is honored, as LLVM might be creating a
1898 // *new* stack object, and needs to know what alignment to give
1899 // it. (Sometimes it can deduce a sensible alignment on its own,
1900 // but not if clang decides it must emit a packed struct, or the
1901 // user specifies increased alignment requirements.)
1902 //
1903 // This is different from indirect *not* byval, where the object
1904 // exists already, and the align attribute is purely
1905 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001906 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001907
John McCall7f416cc2015-09-08 08:05:57 +00001908 // For now, only add this when we have a byval argument.
1909 // TODO: be less lazy about updating test cases.
1910 if (AI.getIndirectByVal())
1911 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001912
Daniel Dunbarc2304432009-03-18 19:51:01 +00001913 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001914 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1915 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001916 break;
James Y Knight71608572015-08-21 18:19:06 +00001917 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001918 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001919 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001920 case ABIArgInfo::CoerceAndExpand:
1921 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001922
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001923 case ABIArgInfo::InAlloca:
1924 // inalloca disables readnone and readonly.
1925 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1926 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001927 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001928 }
Mike Stump11289f42009-09-09 15:08:12 +00001929
Hal Finkela2347ba2014-07-18 15:52:10 +00001930 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1931 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001932 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001933 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1934 .getQuantity());
1935 else if (getContext().getTargetAddressSpace(PTy) == 0)
1936 Attrs.addAttribute(llvm::Attribute::NonNull);
1937 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001938
John McCall12f23522016-04-04 18:33:08 +00001939 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
1940 case ParameterABI::Ordinary:
1941 break;
1942
1943 case ParameterABI::SwiftIndirectResult: {
1944 // Add 'sret' if we haven't already used it for something, but
1945 // only if the result is void.
1946 if (!hasUsedSRet && RetTy->isVoidType()) {
1947 Attrs.addAttribute(llvm::Attribute::StructRet);
1948 hasUsedSRet = true;
1949 }
1950
1951 // Add 'noalias' in either case.
1952 Attrs.addAttribute(llvm::Attribute::NoAlias);
1953
1954 // Add 'dereferenceable' and 'alignment'.
1955 auto PTy = ParamType->getPointeeType();
1956 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
1957 auto info = getContext().getTypeInfoInChars(PTy);
1958 Attrs.addDereferenceableAttr(info.first.getQuantity());
1959 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
1960 info.second.getQuantity()));
1961 }
1962 break;
1963 }
1964
1965 case ParameterABI::SwiftErrorResult:
1966 Attrs.addAttribute(llvm::Attribute::SwiftError);
1967 break;
1968
1969 case ParameterABI::SwiftContext:
1970 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
1971 break;
1972 }
1973
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001974 if (Attrs.hasAttributes()) {
1975 unsigned FirstIRArg, NumIRArgs;
1976 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1977 for (unsigned i = 0; i < NumIRArgs; i++)
1978 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1979 FirstIRArg + i + 1, Attrs));
1980 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001981 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001982 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001983
Bill Wendlinga7912f82012-10-10 07:36:56 +00001984 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001985 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001986 AttributeSet::get(getLLVMContext(),
1987 llvm::AttributeSet::FunctionIndex,
1988 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001989}
1990
John McCalla738c252011-03-09 04:27:21 +00001991/// An argument came in as a promoted argument; demote it back to its
1992/// declared type.
1993static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1994 const VarDecl *var,
1995 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001996 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001997
1998 // This can happen with promotions that actually don't change the
1999 // underlying type, like the enum promotions.
2000 if (value->getType() == varType) return value;
2001
2002 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2003 && "unexpected promotion type");
2004
2005 if (isa<llvm::IntegerType>(varType))
2006 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2007
2008 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2009}
2010
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002011/// Returns the attribute (either parameter attribute, or function
2012/// attribute), which declares argument ArgNo to be non-null.
2013static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2014 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002015 // FIXME: __attribute__((nonnull)) can also be applied to:
2016 // - references to pointers, where the pointee is known to be
2017 // nonnull (apparently a Clang extension)
2018 // - transparent unions containing pointers
2019 // In the former case, LLVM IR cannot represent the constraint. In
2020 // the latter case, we have no guarantee that the transparent union
2021 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002022 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2023 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002024 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002025 if (PVD) {
2026 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2027 return ParmNNAttr;
2028 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002029 // Check function attributes.
2030 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002031 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002032 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002033 if (NNAttr->isNonNull(ArgNo))
2034 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002035 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002036 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002037}
2038
John McCall12f23522016-04-04 18:33:08 +00002039namespace {
2040 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2041 Address Temp;
2042 Address Arg;
2043 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2044 void Emit(CodeGenFunction &CGF, Flags flags) override {
2045 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2046 CGF.Builder.CreateStore(errorValue, Arg);
2047 }
2048 };
2049}
2050
Daniel Dunbard931a872009-02-02 22:03:45 +00002051void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2052 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002053 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002054 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2055 // Naked functions don't have prologues.
2056 return;
2057
John McCallcaa19452009-07-28 01:00:58 +00002058 // If this is an implicit-return-zero function, go ahead and
2059 // initialize the return value. TODO: it might be nice to have
2060 // a more general mechanism for this that didn't require synthesized
2061 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002062 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002063 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002064 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002065 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002066 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002067 Builder.CreateStore(Zero, ReturnValue);
2068 }
2069 }
2070
Mike Stump18bb9282009-05-16 07:57:57 +00002071 // FIXME: We no longer need the types from FunctionArgList; lift up and
2072 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002073
Alexey Samsonov153004f2014-09-29 22:08:00 +00002074 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002075 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002076 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002077 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2078 for (auto &Arg : Fn->args()) {
2079 FnArgs.push_back(&Arg);
2080 }
2081 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002082
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002083 // If we're using inalloca, all the memory arguments are GEPs off of the last
2084 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002085 Address ArgStruct = Address::invalid();
2086 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002087 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002088 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2089 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2090 FI.getArgStructAlignment());
2091
2092 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002093 }
2094
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002095 // Name the struct return parameter.
2096 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002097 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002098 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002099 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002100 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002103 // Track if we received the parameter as a pointer (indirect, byval, or
2104 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2105 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002106 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002107 ArgVals.reserve(Args.size());
2108
Reid Kleckner739756c2013-12-04 19:23:12 +00002109 // Create a pointer value for every parameter declaration. This usually
2110 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2111 // any cleanups or do anything that might unwind. We do that separately, so
2112 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002113 assert(FI.arg_size() == Args.size() &&
2114 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002115 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002116 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002117 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002118 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002119 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002120 QualType Ty = info_it->type;
2121 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002122
John McCalla738c252011-03-09 04:27:21 +00002123 bool isPromoted =
2124 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2125
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002126 unsigned FirstIRArg, NumIRArgs;
2127 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002128
Daniel Dunbard3674e62008-09-11 01:48:57 +00002129 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002130 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002131 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002132 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2133 CharUnits FieldOffset =
2134 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2135 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2136 Arg->getName());
2137 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002138 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002139 }
2140
Daniel Dunbar747865a2009-02-05 09:16:39 +00002141 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002142 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002143 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002144
John McCall47fb9502013-03-07 21:37:08 +00002145 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002146 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002147 // need to do is realign the value, if requested.
2148 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002149 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002150 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002151
2152 // Copy from the incoming argument pointer to the temporary with the
2153 // appropriate alignment.
2154 //
2155 // FIXME: We should have a common utility for generating an aggregate
2156 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002157 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002158 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2159 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2160 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2161 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002162 V = AlignedTemp;
2163 }
John McCall7f416cc2015-09-08 08:05:57 +00002164 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002165 } else {
2166 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002167 llvm::Value *V =
2168 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002169
2170 if (isPromoted)
2171 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002172 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002173 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002174 break;
2175 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002176
2177 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002178 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002179
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002180 // If we have the trivial case, handle it with no muss and fuss.
2181 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002182 ArgI.getCoerceToType() == ConvertType(Ty) &&
2183 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002184 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002185 llvm::Value *V = FnArgs[FirstIRArg];
2186 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002187
Hal Finkel48d53e22014-07-19 01:41:07 +00002188 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002189 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2190 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002191 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2192 AI->getArgNo() + 1,
2193 llvm::Attribute::NonNull));
2194
Hal Finkel48d53e22014-07-19 01:41:07 +00002195 QualType OTy = PVD->getOriginalType();
2196 if (const auto *ArrTy =
2197 getContext().getAsConstantArrayType(OTy)) {
2198 // A C99 array parameter declaration with the static keyword also
2199 // indicates dereferenceability, and if the size is constant we can
2200 // use the dereferenceable attribute (which requires the size in
2201 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002202 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002203 QualType ETy = ArrTy->getElementType();
2204 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2205 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2206 ArrSize) {
2207 llvm::AttrBuilder Attrs;
2208 Attrs.addDereferenceableAttr(
2209 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2210 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2211 AI->getArgNo() + 1, Attrs));
2212 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2213 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2214 AI->getArgNo() + 1,
2215 llvm::Attribute::NonNull));
2216 }
2217 }
2218 } else if (const auto *ArrTy =
2219 getContext().getAsVariableArrayType(OTy)) {
2220 // For C99 VLAs with the static keyword, we don't know the size so
2221 // we can't use the dereferenceable attribute, but in addrspace(0)
2222 // we know that it must be nonnull.
2223 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2224 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2225 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2226 AI->getArgNo() + 1,
2227 llvm::Attribute::NonNull));
2228 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002229
2230 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2231 if (!AVAttr)
2232 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2233 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2234 if (AVAttr) {
2235 llvm::Value *AlignmentValue =
2236 EmitScalarExpr(AVAttr->getAlignment());
2237 llvm::ConstantInt *AlignmentCI =
2238 cast<llvm::ConstantInt>(AlignmentValue);
2239 unsigned Alignment =
2240 std::min((unsigned) AlignmentCI->getZExtValue(),
2241 +llvm::Value::MaximumAlignment);
2242
2243 llvm::AttrBuilder Attrs;
2244 Attrs.addAlignmentAttr(Alignment);
2245 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2246 AI->getArgNo() + 1, Attrs));
2247 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002248 }
2249
Bill Wendling507c3512012-10-16 05:23:44 +00002250 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002251 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2252 AI->getArgNo() + 1,
2253 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002254
John McCall12f23522016-04-04 18:33:08 +00002255 // LLVM expects swifterror parameters to be used in very restricted
2256 // ways. Copy the value into a less-restricted temporary.
2257 if (FI.getExtParameterInfo(ArgNo).getABI()
2258 == ParameterABI::SwiftErrorResult) {
2259 QualType pointeeTy = Ty->getPointeeType();
2260 assert(pointeeTy->isPointerType());
2261 Address temp =
2262 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2263 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2264 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2265 Builder.CreateStore(incomingErrorValue, temp);
2266 V = temp.getPointer();
2267
2268 // Push a cleanup to copy the value back at the end of the function.
2269 // The convention does not guarantee that the value will be written
2270 // back if the function exits with an unwind exception.
2271 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2272 }
2273
Chris Lattner7369c142011-07-20 06:29:00 +00002274 // Ensure the argument is the correct type.
2275 if (V->getType() != ArgI.getCoerceToType())
2276 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2277
John McCalla738c252011-03-09 04:27:21 +00002278 if (isPromoted)
2279 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002280
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002281 if (const CXXMethodDecl *MD =
2282 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002283 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002284 V = CGM.getCXXABI().
2285 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002286 }
2287
Rafael Espindola8778c282012-11-29 16:09:03 +00002288 // Because of merging of function types from multiple decls it is
2289 // possible for the type of an argument to not match the corresponding
2290 // type in the function type. Since we are codegening the callee
2291 // in here, add a cast to the argument type.
2292 llvm::Type *LTy = ConvertType(Arg->getType());
2293 if (V->getType() != LTy)
2294 V = Builder.CreateBitCast(V, LTy);
2295
John McCall7f416cc2015-09-08 08:05:57 +00002296 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002297 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002298 }
Mike Stump11289f42009-09-09 15:08:12 +00002299
John McCall7f416cc2015-09-08 08:05:57 +00002300 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2301 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002302
John McCall7f416cc2015-09-08 08:05:57 +00002303 // Pointer to store into.
2304 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002305
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002306 // Fast-isel and the optimizer generally like scalar values better than
2307 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002308 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002309 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2310 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002311 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002312 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002313 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002314 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002315
John McCall7f416cc2015-09-08 08:05:57 +00002316 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002317 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002318 AddrToStoreInto =
2319 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002320 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002321 AddrToStoreInto =
2322 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002323 }
John McCall7f416cc2015-09-08 08:05:57 +00002324
2325 assert(STy->getNumElements() == NumIRArgs);
2326 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2327 auto AI = FnArgs[FirstIRArg + i];
2328 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2329 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2330 Address EltPtr =
2331 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2332 Builder.CreateStore(AI, EltPtr);
2333 }
2334
2335 if (SrcSize > DstSize) {
2336 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2337 }
2338
Chris Lattner15ec3612010-06-29 00:06:42 +00002339 } else {
2340 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002341 assert(NumIRArgs == 1);
2342 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002343 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002344 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002345 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002346
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002347 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002348 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002349 llvm::Value *V =
2350 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002351 if (isPromoted)
2352 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002353 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002354 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002355 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002356 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002357 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002358 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002359
John McCallf26e73d2016-03-11 04:30:43 +00002360 case ABIArgInfo::CoerceAndExpand: {
2361 // Reconstruct into a temporary.
2362 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2363 ArgVals.push_back(ParamValue::forIndirect(alloca));
2364
2365 auto coercionType = ArgI.getCoerceAndExpandType();
2366 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2367 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2368
2369 unsigned argIndex = FirstIRArg;
2370 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2371 llvm::Type *eltType = coercionType->getElementType(i);
2372 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2373 continue;
2374
2375 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2376 auto elt = FnArgs[argIndex++];
2377 Builder.CreateStore(elt, eltAddr);
2378 }
2379 assert(argIndex == FirstIRArg + NumIRArgs);
2380 break;
2381 }
2382
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002383 case ABIArgInfo::Expand: {
2384 // If this structure was expanded into multiple arguments then
2385 // we need to create a temporary and reconstruct it from the
2386 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002387 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2388 LValue LV = MakeAddrLValue(Alloca, Ty);
2389 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002390
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002391 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2392 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2393 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2394 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2395 auto AI = FnArgs[FirstIRArg + i];
2396 AI->setName(Arg->getName() + "." + Twine(i));
2397 }
2398 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002399 }
2400
2401 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002402 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002403 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002404 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002405 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002406 } else {
2407 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002408 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002409 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002410 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002411 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002412 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002413
Reid Kleckner739756c2013-12-04 19:23:12 +00002414 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2415 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002416 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002417 } else {
2418 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002419 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002420 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002421}
2422
John McCallffa2c1a2012-01-29 07:46:59 +00002423static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2424 while (insn->use_empty()) {
2425 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2426 if (!bitcast) return;
2427
2428 // This is "safe" because we would have used a ConstantExpr otherwise.
2429 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2430 bitcast->eraseFromParent();
2431 }
2432}
2433
John McCall31168b02011-06-15 23:02:42 +00002434/// Try to emit a fused autorelease of a return result.
2435static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2436 llvm::Value *result) {
2437 // We must be immediately followed the cast.
2438 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002439 if (BB->empty()) return nullptr;
2440 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002441
Chris Lattner2192fe52011-07-18 04:24:23 +00002442 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002443
2444 // result is in a BasicBlock and is therefore an Instruction.
2445 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2446
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002448
2449 // Look for:
2450 // %generator = bitcast %type1* %generator2 to %type2*
2451 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2452 // We would have emitted this as a constant if the operand weren't
2453 // an Instruction.
2454 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2455
2456 // Require the generator to be immediately followed by the cast.
2457 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002458 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002459
2460 insnsToKill.push_back(bitcast);
2461 }
2462
2463 // Look for:
2464 // %generator = call i8* @objc_retain(i8* %originalResult)
2465 // or
2466 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2467 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002468 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002469
2470 bool doRetainAutorelease;
2471
John McCallb04ecb72015-10-21 18:06:43 +00002472 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002473 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002474 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002475 .objc_retainAutoreleasedReturnValue) {
2476 doRetainAutorelease = false;
2477
John McCallcfa4e9b2012-09-07 23:30:50 +00002478 // If we emitted an assembly marker for this call (and the
2479 // ARCEntrypoints field should have been set if so), go looking
2480 // for that call. If we can't find it, we can't do this
2481 // optimization. But it should always be the immediately previous
2482 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002483 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002484 llvm::Instruction *prev = call->getPrevNode();
2485 assert(prev);
2486 if (isa<llvm::BitCastInst>(prev)) {
2487 prev = prev->getPrevNode();
2488 assert(prev);
2489 }
2490 assert(isa<llvm::CallInst>(prev));
2491 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002492 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002493 insnsToKill.push_back(prev);
2494 }
John McCall31168b02011-06-15 23:02:42 +00002495 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002496 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002497 }
2498
2499 result = call->getArgOperand(0);
2500 insnsToKill.push_back(call);
2501
2502 // Keep killing bitcasts, for sanity. Note that we no longer care
2503 // about precise ordering as long as there's exactly one use.
2504 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2505 if (!bitcast->hasOneUse()) break;
2506 insnsToKill.push_back(bitcast);
2507 result = bitcast->getOperand(0);
2508 }
2509
2510 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002511 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002512 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2513 (*i)->eraseFromParent();
2514
2515 // Do the fused retain/autorelease if we were asked to.
2516 if (doRetainAutorelease)
2517 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2518
2519 // Cast back to the result type.
2520 return CGF.Builder.CreateBitCast(result, resultType);
2521}
2522
John McCallffa2c1a2012-01-29 07:46:59 +00002523/// If this is a +1 of the value of an immutable 'self', remove it.
2524static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2525 llvm::Value *result) {
2526 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002527 const ObjCMethodDecl *method =
2528 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002529 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002530 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002531 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002532
2533 // Look for a retain call.
2534 llvm::CallInst *retainCall =
2535 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2536 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002537 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002538 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002539
2540 // Look for an ordinary load of 'self'.
2541 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2542 llvm::LoadInst *load =
2543 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2544 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002545 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002546 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002547
2548 // Okay! Burn it all down. This relies for correctness on the
2549 // assumption that the retain is emitted as part of the return and
2550 // that thereafter everything is used "linearly".
2551 llvm::Type *resultType = result->getType();
2552 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2553 assert(retainCall->use_empty());
2554 retainCall->eraseFromParent();
2555 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2556
2557 return CGF.Builder.CreateBitCast(load, resultType);
2558}
2559
John McCall31168b02011-06-15 23:02:42 +00002560/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002561///
2562/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002563static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2564 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002565 // If we're returning 'self', kill the initial retain. This is a
2566 // heuristic attempt to "encourage correctness" in the really unfortunate
2567 // case where we have a return of self during a dealloc and we desperately
2568 // need to avoid the possible autorelease.
2569 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2570 return self;
2571
John McCall31168b02011-06-15 23:02:42 +00002572 // At -O0, try to emit a fused retain/autorelease.
2573 if (CGF.shouldUseFusedARCCalls())
2574 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2575 return fused;
2576
2577 return CGF.EmitARCAutoreleaseReturnValue(result);
2578}
2579
John McCall6e1c0122012-01-29 02:35:02 +00002580/// Heuristically search for a dominating store to the return-value slot.
2581static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002582 // Check if a User is a store which pointerOperand is the ReturnValue.
2583 // We are looking for stores to the ReturnValue, not for stores of the
2584 // ReturnValue to some other location.
2585 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2586 auto *SI = dyn_cast<llvm::StoreInst>(U);
2587 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2588 return nullptr;
2589 // These aren't actually possible for non-coerced returns, and we
2590 // only care about non-coerced returns on this code path.
2591 assert(!SI->isAtomic() && !SI->isVolatile());
2592 return SI;
2593 };
John McCall6e1c0122012-01-29 02:35:02 +00002594 // If there are multiple uses of the return-value slot, just check
2595 // for something immediately preceding the IP. Sometimes this can
2596 // happen with how we generate implicit-returns; it can also happen
2597 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002598 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002599 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002600 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002601 llvm::Instruction *I = &IP->back();
2602
2603 // Skip lifetime markers
2604 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2605 IE = IP->rend();
2606 II != IE; ++II) {
2607 if (llvm::IntrinsicInst *Intrinsic =
2608 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2609 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2610 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2611 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002612 if (II == IE)
2613 break;
2614 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2615 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002616 }
2617 }
2618 I = &*II;
2619 break;
2620 }
2621
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002622 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002623 }
2624
2625 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002626 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002627 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002628
John McCall6e1c0122012-01-29 02:35:02 +00002629 // Now do a first-and-dirty dominance check: just walk up the
2630 // single-predecessors chain from the current insertion point.
2631 llvm::BasicBlock *StoreBB = store->getParent();
2632 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2633 while (IP != StoreBB) {
2634 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002635 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002636 }
2637
2638 // Okay, the store's basic block dominates the insertion point; we
2639 // can do our thing.
2640 return store;
2641}
2642
Adrian Prantl3be10542013-05-02 17:30:20 +00002643void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002644 bool EmitRetDbgLoc,
2645 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002646 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2647 // Naked functions don't have epilogues.
2648 Builder.CreateUnreachable();
2649 return;
2650 }
2651
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002652 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002653 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002654 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002655 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002656 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002657
Dan Gohman481e40c2010-07-20 20:13:52 +00002658 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002659 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002660 QualType RetTy = FI.getReturnType();
2661 const ABIArgInfo &RetAI = FI.getReturnInfo();
2662
2663 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002664 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002665 // Aggregrates get evaluated directly into the destination. Sometimes we
2666 // need to return the sret value in a register, though.
2667 assert(hasAggregateEvaluationKind(RetTy));
2668 if (RetAI.getInAllocaSRet()) {
2669 llvm::Function::arg_iterator EI = CurFn->arg_end();
2670 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002671 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002672 llvm::Value *SRet = Builder.CreateStructGEP(
2673 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002674 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002675 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002676 break;
2677
Daniel Dunbar03816342010-08-21 02:24:36 +00002678 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002679 auto AI = CurFn->arg_begin();
2680 if (RetAI.isSRetAfterThis())
2681 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002682 switch (getEvaluationKind(RetTy)) {
2683 case TEK_Complex: {
2684 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002685 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002686 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002687 /*isInit*/ true);
2688 break;
2689 }
2690 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002691 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002692 break;
2693 case TEK_Scalar:
2694 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002695 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002696 /*isInit*/ true);
2697 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002698 }
2699 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002700 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002701
2702 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002703 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002704 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2705 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002706 // The internal return value temp always will have pointer-to-return-type
2707 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002708
John McCall6e1c0122012-01-29 02:35:02 +00002709 // If there is a dominating store to ReturnValue, we can elide
2710 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002711 if (llvm::StoreInst *SI =
2712 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002713 // Reuse the debug location from the store unless there is
2714 // cleanup code to be emitted between the store and return
2715 // instruction.
2716 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002717 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002718 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002719 RV = SI->getValueOperand();
2720 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002721
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002722 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002723 auto returnValueInst = ReturnValue.getPointer();
2724 if (returnValueInst->use_empty()) {
2725 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2726 alloca->eraseFromParent();
2727 ReturnValue = Address::invalid();
2728 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002729 }
John McCall6e1c0122012-01-29 02:35:02 +00002730
2731 // Otherwise, we have to do a simple load.
2732 } else {
2733 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002734 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002735 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002736 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002737 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002738
John McCall7f416cc2015-09-08 08:05:57 +00002739 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002740 }
John McCall31168b02011-06-15 23:02:42 +00002741
2742 // In ARC, end functions that return a retainable type with a call
2743 // to objc_autoreleaseReturnValue.
2744 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002745#ifndef NDEBUG
2746 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2747 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2748 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2749 // CurCodeDecl or BlockInfo.
2750 QualType RT;
2751
2752 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2753 RT = FD->getReturnType();
2754 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2755 RT = MD->getReturnType();
2756 else if (isa<BlockDecl>(CurCodeDecl))
2757 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2758 else
2759 llvm_unreachable("Unexpected function/method type");
2760
David Blaikiebbafb8a2012-03-11 07:00:24 +00002761 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002762 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002763 RT->isObjCRetainableType());
2764#endif
John McCall31168b02011-06-15 23:02:42 +00002765 RV = emitAutoreleaseOfResult(*this, RV);
2766 }
2767
Chris Lattner726b3d02010-06-26 23:13:19 +00002768 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002769
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002770 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002771 break;
2772
John McCallf26e73d2016-03-11 04:30:43 +00002773 case ABIArgInfo::CoerceAndExpand: {
2774 auto coercionType = RetAI.getCoerceAndExpandType();
2775 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2776
2777 // Load all of the coerced elements out into results.
2778 llvm::SmallVector<llvm::Value*, 4> results;
2779 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2780 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2781 auto coercedEltType = coercionType->getElementType(i);
2782 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2783 continue;
2784
2785 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2786 auto elt = Builder.CreateLoad(eltAddr);
2787 results.push_back(elt);
2788 }
2789
2790 // If we have one result, it's the single direct result type.
2791 if (results.size() == 1) {
2792 RV = results[0];
2793
2794 // Otherwise, we need to make a first-class aggregate.
2795 } else {
2796 // Construct a return type that lacks padding elements.
2797 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2798
2799 RV = llvm::UndefValue::get(returnType);
2800 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2801 RV = Builder.CreateInsertValue(RV, results[i], i);
2802 }
2803 }
2804 break;
2805 }
2806
Chris Lattner726b3d02010-06-26 23:13:19 +00002807 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002808 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002809 }
2810
Alexey Samsonovde443c52014-08-13 00:26:40 +00002811 llvm::Instruction *Ret;
2812 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002813 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2814 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002815 SanitizerScope SanScope(this);
2816 llvm::Value *Cond = Builder.CreateICmpNE(
2817 RV, llvm::Constant::getNullValue(RV->getType()));
2818 llvm::Constant *StaticData[] = {
2819 EmitCheckSourceLocation(EndLoc),
2820 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2821 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002822 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2823 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002824 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002825 }
2826 Ret = Builder.CreateRet(RV);
2827 } else {
2828 Ret = Builder.CreateRetVoid();
2829 }
2830
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002831 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002832 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002833}
2834
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002835static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2836 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2837 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2838}
2839
John McCall7f416cc2015-09-08 08:05:57 +00002840static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2841 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002842 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2843 // placeholders.
2844 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2845 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002846 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2847 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2848
2849 // FIXME: When we generate this IR in one pass, we shouldn't need
2850 // this win32-specific alignment hack.
2851 CharUnits Align = CharUnits::fromQuantity(4);
2852
2853 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002854 Ty.getQualifiers(),
2855 AggValueSlot::IsNotDestructed,
2856 AggValueSlot::DoesNotNeedGCBarriers,
2857 AggValueSlot::IsNotAliased);
2858}
2859
John McCall32ea9692011-03-11 20:59:21 +00002860void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002861 const VarDecl *param,
2862 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002863 // StartFunction converted the ABI-lowered parameter(s) into a
2864 // local alloca. We need to turn that into an r-value suitable
2865 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002866 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002867
John McCall32ea9692011-03-11 20:59:21 +00002868 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002869
Reid Klecknerab2090d2014-07-26 01:34:32 +00002870 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2871 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002872
Richard Smithd62d4982016-06-14 01:13:21 +00002873 // For the most part, we just need to load the alloca, except that
2874 // aggregate r-values are actually pointers to temporaries.
2875 if (type->isReferenceType())
2876 args.add(RValue::get(Builder.CreateLoad(local)), type);
2877 else
2878 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002879}
2880
John McCall31168b02011-06-15 23:02:42 +00002881static bool isProvablyNull(llvm::Value *addr) {
2882 return isa<llvm::ConstantPointerNull>(addr);
2883}
2884
2885static bool isProvablyNonNull(llvm::Value *addr) {
2886 return isa<llvm::AllocaInst>(addr);
2887}
2888
2889/// Emit the actual writing-back of a writeback.
2890static void emitWriteback(CodeGenFunction &CGF,
2891 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002892 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002893 Address srcAddr = srcLV.getAddress();
2894 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002895 "shouldn't have writeback for provably null argument");
2896
Craig Topper8a13c412014-05-21 05:09:00 +00002897 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002898
2899 // If the argument wasn't provably non-null, we need to null check
2900 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002901 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002902 if (!provablyNonNull) {
2903 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2904 contBB = CGF.createBasicBlock("icr.done");
2905
John McCall7f416cc2015-09-08 08:05:57 +00002906 llvm::Value *isNull =
2907 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002908 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2909 CGF.EmitBlock(writebackBB);
2910 }
2911
2912 // Load the value to writeback.
2913 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2914
2915 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002916 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2917 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002918
2919 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002920
2921 // If we have a "to use" value, it's something we need to emit a use
2922 // of. This has to be carefully threaded in: if it's done after the
2923 // release it's potentially undefined behavior (and the optimizer
2924 // will ignore it), and if it happens before the retain then the
2925 // optimizer could move the release there.
2926 if (writeback.ToUse) {
2927 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2928
2929 // Retain the new value. No need to block-copy here: the block's
2930 // being passed up the stack.
2931 value = CGF.EmitARCRetainNonBlock(value);
2932
2933 // Emit the intrinsic use here.
2934 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2935
2936 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002937 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002938
2939 // Put the new value in place (primitively).
2940 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2941
2942 // Release the old value.
2943 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2944
2945 // Otherwise, we can just do a normal lvalue store.
2946 } else {
2947 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2948 }
John McCall31168b02011-06-15 23:02:42 +00002949
2950 // Jump to the continuation block.
2951 if (!provablyNonNull)
2952 CGF.EmitBlock(contBB);
2953}
2954
2955static void emitWritebacks(CodeGenFunction &CGF,
2956 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002957 for (const auto &I : args.writebacks())
2958 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002959}
2960
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002961static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2962 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002963 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002964 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2965 CallArgs.getCleanupsToDeactivate();
2966 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002967 for (const auto &I : llvm::reverse(Cleanups)) {
2968 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2969 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002970 }
2971}
2972
John McCalleff18842013-03-23 02:35:54 +00002973static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2974 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2975 if (uop->getOpcode() == UO_AddrOf)
2976 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002977 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002978}
2979
John McCall31168b02011-06-15 23:02:42 +00002980/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002981/// we are passing the address of an __autoreleased temporary; it
2982/// might be copy-initialized with the current value of the given
2983/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002984static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2985 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002986 LValue srcLV;
2987
2988 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002989 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002990 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2991 srcLV = CGF.EmitLValue(lvExpr);
2992
2993 // Otherwise, just emit it as a scalar.
2994 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002995 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002996
2997 QualType srcAddrType =
2998 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002999 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003000 }
John McCall7f416cc2015-09-08 08:05:57 +00003001 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003002
3003 // The dest and src types don't necessarily match in LLVM terms
3004 // because of the crazy ObjC compatibility rules.
3005
Chris Lattner2192fe52011-07-18 04:24:23 +00003006 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003007 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3008
3009 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003010 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003011 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3012 CRE->getType());
3013 return;
3014 }
3015
John McCall31168b02011-06-15 23:02:42 +00003016 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003017 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3018 CGF.getPointerAlign(),
3019 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003020 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3021 // and that cleanup will be conditional if we can't prove that the l-value
3022 // isn't null, so we need to register a dominating point so that the cleanups
3023 // system will make valid IR.
3024 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3025
John McCall31168b02011-06-15 23:02:42 +00003026 // Zero-initialize it if we're not doing a copy-initialization.
3027 bool shouldCopy = CRE->shouldCopy();
3028 if (!shouldCopy) {
3029 llvm::Value *null =
3030 llvm::ConstantPointerNull::get(
3031 cast<llvm::PointerType>(destType->getElementType()));
3032 CGF.Builder.CreateStore(null, temp);
3033 }
Craig Topper8a13c412014-05-21 05:09:00 +00003034
3035 llvm::BasicBlock *contBB = nullptr;
3036 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003037
3038 // If the address is *not* known to be non-null, we need to switch.
3039 llvm::Value *finalArgument;
3040
John McCall7f416cc2015-09-08 08:05:57 +00003041 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003042 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003043 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003044 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003045 llvm::Value *isNull =
3046 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003047
3048 finalArgument = CGF.Builder.CreateSelect(isNull,
3049 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003050 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003051
3052 // If we need to copy, then the load has to be conditional, which
3053 // means we need control flow.
3054 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003055 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003056 contBB = CGF.createBasicBlock("icr.cont");
3057 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3058 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3059 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003060 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003061 }
3062 }
3063
Craig Topper8a13c412014-05-21 05:09:00 +00003064 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003065
John McCall31168b02011-06-15 23:02:42 +00003066 // Perform a copy if necessary.
3067 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003068 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003069 assert(srcRV.isScalar());
3070
3071 llvm::Value *src = srcRV.getScalarVal();
3072 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3073 "icr.cast");
3074
3075 // Use an ordinary store, not a store-to-lvalue.
3076 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003077
3078 // If optimization is enabled, and the value was held in a
3079 // __strong variable, we need to tell the optimizer that this
3080 // value has to stay alive until we're doing the store back.
3081 // This is because the temporary is effectively unretained,
3082 // and so otherwise we can violate the high-level semantics.
3083 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3084 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3085 valueToUse = src;
3086 }
John McCall31168b02011-06-15 23:02:42 +00003087 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003088
John McCall31168b02011-06-15 23:02:42 +00003089 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003090 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003091 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003092 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003093
3094 // Make a phi for the value to intrinsically use.
3095 if (valueToUse) {
3096 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3097 "icr.to-use");
3098 phiToUse->addIncoming(valueToUse, copyBB);
3099 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3100 originBB);
3101 valueToUse = phiToUse;
3102 }
3103
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003104 condEval.end(CGF);
3105 }
John McCall31168b02011-06-15 23:02:42 +00003106
John McCalleff18842013-03-23 02:35:54 +00003107 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003108 args.add(RValue::get(finalArgument), CRE->getType());
3109}
3110
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003111void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3112 assert(!StackBase && !StackCleanup.isValid());
3113
3114 // Save the stack.
3115 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003116 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003117}
3118
Nico Weber8cdb3f92015-08-25 18:43:32 +00003119void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3120 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003121 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003122 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003123 CGF.Builder.CreateCall(F, StackBase);
3124 }
3125}
3126
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003127void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3128 SourceLocation ArgLoc,
3129 const FunctionDecl *FD,
3130 unsigned ParmNum) {
3131 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003132 return;
3133 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3134 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3135 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3136 if (!NNAttr)
3137 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003138 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003139 assert(RV.isScalar());
3140 llvm::Value *V = RV.getScalarVal();
3141 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003142 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003143 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003144 EmitCheckSourceLocation(ArgLoc),
3145 EmitCheckSourceLocation(NNAttr->getLocation()),
3146 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003147 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003148 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003149 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003150}
3151
David Blaikief05779e2015-07-21 18:37:18 +00003152void CodeGenFunction::EmitCallArgs(
3153 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3154 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3155 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3156 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003157
3158 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3159 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3160 return;
3161 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3162 if (PS == nullptr)
3163 return;
3164
3165 const auto &Context = getContext();
3166 auto SizeTy = Context.getSizeType();
3167 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3168 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3169 Args.add(RValue::get(V), SizeTy);
3170 };
3171
Reid Kleckner739756c2013-12-04 19:23:12 +00003172 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3173 // because arguments are destroyed left to right in the callee.
3174 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003175 // Insert a stack save if we're going to need any inalloca args.
3176 bool HasInAllocaArgs = false;
3177 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3178 I != E && !HasInAllocaArgs; ++I)
3179 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3180 if (HasInAllocaArgs) {
3181 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3182 Args.allocateArgumentMemory(*this);
3183 }
3184
3185 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003186 size_t CallArgsStart = Args.size();
3187 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003188 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00003189 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003190 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003191 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003192 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003193 }
3194
3195 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3196 // IR function.
3197 std::reverse(Args.begin() + CallArgsStart, Args.end());
3198 return;
3199 }
3200
3201 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003202 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3203 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003204 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003205 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003206 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003207 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003208 }
3209}
3210
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003211namespace {
3212
David Blaikie7e70d682015-08-18 22:40:54 +00003213struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003214 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003215 : Addr(Addr), Ty(Ty) {}
3216
John McCall7f416cc2015-09-08 08:05:57 +00003217 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003218 QualType Ty;
3219
Craig Topper4f12f102014-03-12 06:41:41 +00003220 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003221 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3222 assert(!Dtor->isTrivial());
3223 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3224 /*Delegating=*/false, Addr);
3225 }
3226};
3227
David Blaikie38b25912015-02-09 19:13:51 +00003228struct DisableDebugLocationUpdates {
3229 CodeGenFunction &CGF;
3230 bool disabledDebugInfo;
3231 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3232 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3233 CGF.disableDebugInfo();
3234 }
3235 ~DisableDebugLocationUpdates() {
3236 if (disabledDebugInfo)
3237 CGF.enableDebugInfo();
3238 }
3239};
3240
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003241} // end anonymous namespace
3242
John McCall32ea9692011-03-11 20:59:21 +00003243void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3244 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003245 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003246 if (const ObjCIndirectCopyRestoreExpr *CRE
3247 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003248 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003249 assert(getContext().hasSameType(E->getType(), type));
3250 return emitWritebackArg(*this, args, CRE);
3251 }
3252
John McCall0a76c0c2011-08-26 18:42:59 +00003253 assert(type->isReferenceType() == E->isGLValue() &&
3254 "reference binding to unmaterialized r-value!");
3255
John McCall17054bd62011-08-26 21:08:13 +00003256 if (E->isGLValue()) {
3257 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003258 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003259 }
Mike Stump11289f42009-09-09 15:08:12 +00003260
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003261 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3262
3263 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3264 // However, we still have to push an EH-only cleanup in case we unwind before
3265 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003266 if (HasAggregateEvalKind &&
3267 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3268 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003269 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003270 AggValueSlot Slot;
3271 if (args.isUsingInAlloca())
3272 Slot = createPlaceholderSlot(*this, type);
3273 else
3274 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003275
3276 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3277 bool DestroyedInCallee =
3278 RD && RD->hasNonTrivialDestructor() &&
3279 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3280 if (DestroyedInCallee)
3281 Slot.setExternallyDestructed();
3282
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003283 EmitAggExpr(E, Slot);
3284 RValue RV = Slot.asRValue();
3285 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003286
Reid Klecknere39ee212014-05-03 00:33:28 +00003287 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003288 // Create a no-op GEP between the placeholder and the cleanup so we can
3289 // RAUW it successfully. It also serves as a marker of the first
3290 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003291 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3292 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003293 // This unreachable is a temporary marker which will be removed later.
3294 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3295 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003296 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003297 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003298 }
3299
3300 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003301 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3302 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3303 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003304 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3305 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3306 } else {
3307 // We can't represent a misaligned lvalue in the CallArgList, so copy
3308 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003309 Address tmp = CreateMemTemp(type);
3310 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003311 args.add(RValue::getAggregate(tmp), type);
3312 }
Eli Friedmandf968192011-05-26 00:10:27 +00003313 return;
3314 }
3315
John McCall32ea9692011-03-11 20:59:21 +00003316 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003317}
3318
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003319QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3320 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3321 // implicitly widens null pointer constants that are arguments to varargs
3322 // functions to pointer-sized ints.
3323 if (!getTarget().getTriple().isOSWindows())
3324 return Arg->getType();
3325
3326 if (Arg->getType()->isIntegerType() &&
3327 getContext().getTypeSize(Arg->getType()) <
3328 getContext().getTargetInfo().getPointerWidth(0) &&
3329 Arg->isNullPointerConstant(getContext(),
3330 Expr::NPC_ValueDependentIsNotNull)) {
3331 return getContext().getIntPtrType();
3332 }
3333
3334 return Arg->getType();
3335}
3336
Dan Gohman515a60d2012-02-16 00:57:37 +00003337// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3338// optimizer it can aggressively ignore unwind edges.
3339void
3340CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3341 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3342 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3343 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3344 CGM.getNoObjCARCExceptionsMetadata());
3345}
3346
John McCall882987f2013-02-28 19:01:20 +00003347/// Emits a call to the given no-arguments nounwind runtime function.
3348llvm::CallInst *
3349CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3350 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003351 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003352}
3353
3354/// Emits a call to the given nounwind runtime function.
3355llvm::CallInst *
3356CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3357 ArrayRef<llvm::Value*> args,
3358 const llvm::Twine &name) {
3359 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3360 call->setDoesNotThrow();
3361 return call;
3362}
3363
3364/// Emits a simple call (never an invoke) to the given no-arguments
3365/// runtime function.
3366llvm::CallInst *
3367CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3368 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003369 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003370}
3371
David Majnemer0b17d442015-12-15 21:27:59 +00003372// Calls which may throw must have operand bundles indicating which funclet
3373// they are nested within.
3374static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003375getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003376 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003377 // There is no need for a funclet operand bundle if we aren't inside a
3378 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003379 if (!CurrentFuncletPad)
3380 return;
3381
3382 // Skip intrinsics which cannot throw.
3383 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3384 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3385 return;
3386
3387 BundleList.emplace_back("funclet", CurrentFuncletPad);
3388}
3389
David Majnemer971d31b2016-02-24 17:02:45 +00003390/// Emits a simple call (never an invoke) to the given runtime function.
3391llvm::CallInst *
3392CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3393 ArrayRef<llvm::Value*> args,
3394 const llvm::Twine &name) {
3395 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3396 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3397
3398 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3399 call->setCallingConv(getRuntimeCC());
3400 return call;
3401}
3402
John McCall882987f2013-02-28 19:01:20 +00003403/// Emits a call or invoke to the given noreturn runtime function.
3404void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3405 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003406 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3407 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3408
John McCall882987f2013-02-28 19:01:20 +00003409 if (getInvokeDest()) {
3410 llvm::InvokeInst *invoke =
3411 Builder.CreateInvoke(callee,
3412 getUnreachableBlock(),
3413 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003414 args,
3415 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003416 invoke->setDoesNotReturn();
3417 invoke->setCallingConv(getRuntimeCC());
3418 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003419 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003420 call->setDoesNotReturn();
3421 call->setCallingConv(getRuntimeCC());
3422 Builder.CreateUnreachable();
3423 }
3424}
3425
Sanjay Patel846b63b2016-01-18 22:15:33 +00003426/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003427llvm::CallSite
3428CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3429 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003430 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003431}
3432
3433/// Emits a call or invoke instruction to the given runtime function.
3434llvm::CallSite
3435CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3436 ArrayRef<llvm::Value*> args,
3437 const Twine &name) {
3438 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3439 callSite.setCallingConv(getRuntimeCC());
3440 return callSite;
3441}
3442
John McCallbd309292010-07-06 01:34:17 +00003443/// Emits a call or invoke instruction to the given function, depending
3444/// on the current state of the EH stack.
3445llvm::CallSite
3446CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003447 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003449 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003450 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3451 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003452
Dan Gohman515a60d2012-02-16 00:57:37 +00003453 llvm::Instruction *Inst;
3454 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003455 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003456 else {
3457 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003458 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3459 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003460 EmitBlock(ContBB);
3461 }
3462
3463 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3464 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003465 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003466 AddObjCARCExceptionMetadata(Inst);
3467
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003468 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003469}
3470
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003471/// \brief Store a non-aggregate value to an address to initialize it. For
3472/// initialization, a non-atomic store will be used.
3473static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3474 LValue Dst) {
3475 if (Src.isScalar())
3476 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3477 else
3478 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3479}
3480
3481void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3482 llvm::Value *New) {
3483 DeferredReplacements.push_back(std::make_pair(Old, New));
3484}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003485
Daniel Dunbard931a872009-02-02 22:03:45 +00003486RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003487 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003488 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003489 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003490 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003491 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003492 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003493
3494 // Handle struct-return functions by passing a pointer to the
3495 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003496 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003497 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003498
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003499 llvm::FunctionType *IRFuncTy =
3500 cast<llvm::FunctionType>(
3501 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003502
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003503 // If we're using inalloca, insert the allocation after the stack save.
3504 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003505 Address ArgMemory = Address::invalid();
3506 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003507 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003508 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003509 llvm::Instruction *IP = CallArgs.getStackBase();
3510 llvm::AllocaInst *AI;
3511 if (IP) {
3512 IP = IP->getNextNode();
3513 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3514 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003515 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003516 }
John McCall7f416cc2015-09-08 08:05:57 +00003517 auto Align = CallInfo.getArgStructAlignment();
3518 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003519 AI->setUsedWithInAlloca(true);
3520 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003521 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003522 }
3523
John McCall7f416cc2015-09-08 08:05:57 +00003524 // Helper function to drill into the inalloca allocation.
3525 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3526 auto FieldOffset =
3527 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3528 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3529 };
3530
Alexey Samsonov153004f2014-09-29 22:08:00 +00003531 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003532 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3533
Chris Lattner4ca97c32009-06-13 00:26:38 +00003534 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003535 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003536 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003537 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003538 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003539 if (!ReturnValue.isNull()) {
3540 SRetPtr = ReturnValue.getValue();
3541 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003542 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003543 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3544 uint64_t size =
3545 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003546 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003547 UnusedReturnSize = size;
3548 }
3549 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003550 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003551 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003552 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003553 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3554 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003555 }
Anders Carlsson17490832009-12-24 20:40:36 +00003556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
John McCall12f23522016-04-04 18:33:08 +00003558 Address swiftErrorTemp = Address::invalid();
3559 Address swiftErrorArg = Address::invalid();
3560
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003561 assert(CallInfo.arg_size() == CallArgs.size() &&
3562 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003563 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003564 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003565 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003566 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003567 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003568 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003569
Rafael Espindolafad28de2012-10-24 01:59:00 +00003570 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003571 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3572 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3573 llvm::UndefValue::get(ArgInfo.getPaddingType());
3574
3575 unsigned FirstIRArg, NumIRArgs;
3576 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003577
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003578 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003579 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003580 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003581 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3582 if (RV.isAggregate()) {
3583 // Replace the placeholder with the appropriate argument slot GEP.
3584 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003585 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003586 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3587 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003588 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003589 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003590 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003591 } else {
3592 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003593 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3594 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003595 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3596 // There are some cases where a trivial bitcast is not avoidable. The
3597 // definition of a type later in a translation unit may change it's type
3598 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003599 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003600 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003601 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003602 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3603 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003604 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003605 }
3606
Daniel Dunbar03816342010-08-21 02:24:36 +00003607 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003608 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003609 if (RV.isScalar() || RV.isComplex()) {
3610 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003611 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3612 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003613
John McCall7f416cc2015-09-08 08:05:57 +00003614 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003615 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003616 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003617 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003618 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003619 // 1. If the argument is not byval, and we are required to copy the
3620 // source. (This case doesn't occur on any common architecture.)
3621 // 2. If the argument is byval, RV is not sufficiently aligned, and
3622 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003623 // 3. If the argument is byval, but RV is located in an address space
3624 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003625 Address Addr = RV.getAggregateAddress();
3626 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003627 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003628 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003629 const unsigned ArgAddrSpace =
3630 (FirstIRArg < IRFuncTy->getNumParams()
3631 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3632 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003633 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003634 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3635 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3636 Align.getQuantity(), *TD)
3637 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003638 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003639 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003640 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3641 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003642 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003643 } else {
3644 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003645 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003646 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003647 }
3648 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003649 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003650
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003651 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003652 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003653 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003654
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003655 case ABIArgInfo::Extend:
3656 case ABIArgInfo::Direct: {
3657 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003658 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3659 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003660 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003661 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003662 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003663 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003664 else
John McCall7f416cc2015-09-08 08:05:57 +00003665 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003666
John McCall12f23522016-04-04 18:33:08 +00003667 // Implement swifterror by copying into a new swifterror argument.
3668 // We'll write back in the normal path out of the call.
3669 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3670 == ParameterABI::SwiftErrorResult) {
3671 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3672
3673 QualType pointeeTy = I->Ty->getPointeeType();
3674 swiftErrorArg =
3675 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3676
3677 swiftErrorTemp =
3678 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3679 V = swiftErrorTemp.getPointer();
3680 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3681
3682 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3683 Builder.CreateStore(errorValue, swiftErrorTemp);
3684 }
3685
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003686 // We might have to widen integers, but we should never truncate.
3687 if (ArgInfo.getCoerceToType() != V->getType() &&
3688 V->getType()->isIntegerTy())
3689 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3690
Chris Lattner3ce86682011-07-12 04:53:39 +00003691 // If the argument doesn't match, perform a bitcast to coerce it. This
3692 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003693 if (FirstIRArg < IRFuncTy->getNumParams() &&
3694 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3695 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003696
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003697 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003698 break;
3699 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003700
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003701 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003702 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003703 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003704 Src = CreateMemTemp(I->Ty, "coerce");
3705 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003706 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003707 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003708 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003709 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003710
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003711 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003712 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003713
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003714 // Fast-isel and the optimizer generally like scalar values better than
3715 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003716 llvm::StructType *STy =
3717 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003718 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003719 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003720 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3721 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3722
3723 // If the source type is smaller than the destination type of the
3724 // coerce-to logic, copy the source value into a temp alloca the size
3725 // of the destination type to allow loading all of it. The bits past
3726 // the source value are left undef.
3727 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003728 Address TempAlloca
3729 = CreateTempAlloca(STy, Src.getAlignment(),
3730 Src.getName() + ".coerce");
3731 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3732 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003733 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003734 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003735 }
3736
John McCall7f416cc2015-09-08 08:05:57 +00003737 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003738 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003739 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003740 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3741 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3742 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003743 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003744 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003745 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003746 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003747 assert(NumIRArgs == 1);
3748 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003749 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003750 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003751
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003752 break;
3753 }
3754
John McCallf26e73d2016-03-11 04:30:43 +00003755 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003756 auto coercionType = ArgInfo.getCoerceAndExpandType();
3757 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3758
John McCall12f23522016-04-04 18:33:08 +00003759 llvm::Value *tempSize = nullptr;
3760 Address addr = Address::invalid();
3761 if (RV.isAggregate()) {
3762 addr = RV.getAggregateAddress();
3763 } else {
3764 assert(RV.isScalar()); // complex should always just be direct
3765
3766 llvm::Type *scalarType = RV.getScalarVal()->getType();
3767 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3768 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3769
3770 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3771
3772 // Materialize to a temporary.
3773 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3774 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3775 scalarAlign)));
3776 EmitLifetimeStart(scalarSize, addr.getPointer());
3777
3778 Builder.CreateStore(RV.getScalarVal(), addr);
3779 }
3780
John McCallf26e73d2016-03-11 04:30:43 +00003781 addr = Builder.CreateElementBitCast(addr, coercionType);
3782
3783 unsigned IRArgPos = FirstIRArg;
3784 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3785 llvm::Type *eltType = coercionType->getElementType(i);
3786 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3787 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3788 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3789 IRCallArgs[IRArgPos++] = elt;
3790 }
3791 assert(IRArgPos == FirstIRArg + NumIRArgs);
3792
John McCall12f23522016-04-04 18:33:08 +00003793 if (tempSize) {
3794 EmitLifetimeEnd(tempSize, addr.getPointer());
3795 }
3796
John McCallf26e73d2016-03-11 04:30:43 +00003797 break;
3798 }
3799
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003800 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003801 unsigned IRArgPos = FirstIRArg;
3802 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3803 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003804 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003805 }
3806 }
Mike Stump11289f42009-09-09 15:08:12 +00003807
John McCall7f416cc2015-09-08 08:05:57 +00003808 if (ArgMemory.isValid()) {
3809 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003810 if (CallInfo.isVariadic()) {
3811 // When passing non-POD arguments by value to variadic functions, we will
3812 // end up with a variadic prototype and an inalloca call site. In such
3813 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3814 // the callee.
3815 unsigned CalleeAS =
3816 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3817 Callee = Builder.CreateBitCast(
3818 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3819 } else {
3820 llvm::Type *LastParamTy =
3821 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3822 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003823#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003824 // Assert that these structs have equivalent element types.
3825 llvm::StructType *FullTy = CallInfo.getArgStruct();
3826 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3827 cast<llvm::PointerType>(LastParamTy)->getElementType());
3828 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3829 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3830 DE = DeclaredTy->element_end(),
3831 FI = FullTy->element_begin();
3832 DI != DE; ++DI, ++FI)
3833 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003834#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003835 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3836 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003837 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003838 assert(IRFunctionArgs.hasInallocaArg());
3839 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003840 }
3841
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003842 if (!CallArgs.getCleanupsToDeactivate().empty())
3843 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3844
Chris Lattner4ca97c32009-06-13 00:26:38 +00003845 // If the callee is a bitcast of a function to a varargs pointer to function
3846 // type, check to see if we can remove the bitcast. This handles some cases
3847 // with unprototyped functions.
3848 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3849 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003850 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3851 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003852 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003853 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003854
Chris Lattner4ca97c32009-06-13 00:26:38 +00003855 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3856 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003857 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003858 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003859 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003860 bool ArgsMatch = true;
3861 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3862 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3863 ArgsMatch = false;
3864 break;
3865 }
Mike Stump11289f42009-09-09 15:08:12 +00003866
Chris Lattner4ca97c32009-06-13 00:26:38 +00003867 // Strip the cast if we can get away with it. This is a nice cleanup,
3868 // but also allows us to inline the function at -O0 if it is marked
3869 // always_inline.
3870 if (ArgsMatch)
3871 Callee = CalleeF;
3872 }
3873 }
Mike Stump11289f42009-09-09 15:08:12 +00003874
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003875 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3876 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3877 // Inalloca argument can have different type.
3878 if (IRFunctionArgs.hasInallocaArg() &&
3879 i == IRFunctionArgs.getInallocaArgNo())
3880 continue;
3881 if (i < IRFuncTy->getNumParams())
3882 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3883 }
3884
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003885 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003886 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003887 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3888 AttributeList, CallingConv,
3889 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003890 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003891 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003892
David Majnemer4e52d6f2015-12-12 05:39:21 +00003893 bool CannotThrow;
3894 if (currentFunctionUsesSEHTry()) {
3895 // SEH cares about asynchronous exceptions, everything can "throw."
3896 CannotThrow = false;
3897 } else if (isCleanupPadScope() &&
3898 EHPersonality::get(*this).isMSVCXXPersonality()) {
3899 // The MSVC++ personality will implicitly terminate the program if an
3900 // exception is thrown. An unwind edge cannot be reached.
3901 CannotThrow = true;
3902 } else {
3903 // Otherwise, nowunind callsites will never throw.
3904 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3905 llvm::Attribute::NoUnwind);
3906 }
3907 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003908
David Majnemer0b17d442015-12-15 21:27:59 +00003909 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3910 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3911
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003912 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003913 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003914 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003915 } else {
3916 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003917 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3918 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003919 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003920 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003921 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003922 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003923
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003924 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3925 !CS.hasFnAttr(llvm::Attribute::NoInline))
3926 Attrs =
3927 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3928 llvm::Attribute::AlwaysInline);
3929
David Majnemer4e52d6f2015-12-12 05:39:21 +00003930 // Disable inlining inside SEH __try blocks.
3931 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003932 Attrs =
3933 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3934 llvm::Attribute::NoInline);
3935
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003936 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003937 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003938
Adam Nemet1e217bc2016-03-28 22:18:53 +00003939 // Insert instrumentation or attach profile metadata at indirect call sites.
3940 // For more details, see the comment before the definition of
3941 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003942 if (!CS.getCalledFunction())
3943 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3944 CS.getInstruction(), Callee);
3945
Dan Gohman515a60d2012-02-16 00:57:37 +00003946 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3947 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003948 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003949 AddObjCARCExceptionMetadata(CS.getInstruction());
3950
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003951 // If the call doesn't return, finish the basic block and clear the
3952 // insertion point; this allows the rest of IRgen to discard
3953 // unreachable code.
3954 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003955 if (UnusedReturnSize)
3956 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003957 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003958
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003959 Builder.CreateUnreachable();
3960 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003961
Mike Stump18bb9282009-05-16 07:57:57 +00003962 // FIXME: For now, emit a dummy basic block because expr emitters in
3963 // generally are not ready to handle emitting expressions at unreachable
3964 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003965 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003966
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003967 // Return a reasonable RValue.
3968 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003969 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003970
3971 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00003972 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003973 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003974
John McCall12f23522016-04-04 18:33:08 +00003975 // Perform the swifterror writeback.
3976 if (swiftErrorTemp.isValid()) {
3977 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
3978 Builder.CreateStore(errorResult, swiftErrorArg);
3979 }
3980
John McCall31168b02011-06-15 23:02:42 +00003981 // Emit any writebacks immediately. Arguably this should happen
3982 // after any return-value munging.
3983 if (CallArgs.hasWritebacks())
3984 emitWritebacks(*this, CallArgs);
3985
Nico Weber8cdb3f92015-08-25 18:43:32 +00003986 // The stack cleanup for inalloca arguments has to run out of the normal
3987 // lexical order, so deactivate it and run it manually here.
3988 CallArgs.freeArgumentMemory(*this);
3989
Samuel Antao798f11c2015-11-23 22:04:44 +00003990 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3991 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003992 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3993 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003994 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003995
Hal Finkelee90a222014-09-26 05:04:30 +00003996 RValue Ret = [&] {
3997 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00003998 case ABIArgInfo::CoerceAndExpand: {
3999 auto coercionType = RetAI.getCoerceAndExpandType();
4000 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4001
4002 Address addr = SRetPtr;
4003 addr = Builder.CreateElementBitCast(addr, coercionType);
4004
John McCall12f23522016-04-04 18:33:08 +00004005 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4006 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4007
John McCallf26e73d2016-03-11 04:30:43 +00004008 unsigned unpaddedIndex = 0;
4009 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4010 llvm::Type *eltType = coercionType->getElementType(i);
4011 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4012 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004013 llvm::Value *elt = CI;
4014 if (requiresExtract)
4015 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4016 else
4017 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004018 Builder.CreateStore(elt, eltAddr);
4019 }
John McCall12f23522016-04-04 18:33:08 +00004020 // FALLTHROUGH
4021 }
4022
4023 case ABIArgInfo::InAlloca:
4024 case ABIArgInfo::Indirect: {
4025 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4026 if (UnusedReturnSize)
4027 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4028 SRetPtr.getPointer());
4029 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004030 }
4031
Hal Finkelee90a222014-09-26 05:04:30 +00004032 case ABIArgInfo::Ignore:
4033 // If we are ignoring an argument that had a result, make sure to
4034 // construct the appropriate return value for our caller.
4035 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004036
Hal Finkelee90a222014-09-26 05:04:30 +00004037 case ABIArgInfo::Extend:
4038 case ABIArgInfo::Direct: {
4039 llvm::Type *RetIRTy = ConvertType(RetTy);
4040 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4041 switch (getEvaluationKind(RetTy)) {
4042 case TEK_Complex: {
4043 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4044 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4045 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004046 }
Hal Finkelee90a222014-09-26 05:04:30 +00004047 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004048 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004049 bool DestIsVolatile = ReturnValue.isVolatile();
4050
John McCall7f416cc2015-09-08 08:05:57 +00004051 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004052 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4053 DestIsVolatile = false;
4054 }
John McCall7f416cc2015-09-08 08:05:57 +00004055 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004056 return RValue::getAggregate(DestPtr);
4057 }
4058 case TEK_Scalar: {
4059 // If the argument doesn't match, perform a bitcast to coerce it. This
4060 // can happen due to trivial type mismatches.
4061 llvm::Value *V = CI;
4062 if (V->getType() != RetIRTy)
4063 V = Builder.CreateBitCast(V, RetIRTy);
4064 return RValue::get(V);
4065 }
4066 }
4067 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004068 }
Hal Finkelee90a222014-09-26 05:04:30 +00004069
John McCall7f416cc2015-09-08 08:05:57 +00004070 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004071 bool DestIsVolatile = ReturnValue.isVolatile();
4072
John McCall7f416cc2015-09-08 08:05:57 +00004073 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004074 DestPtr = CreateMemTemp(RetTy, "coerce");
4075 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004076 }
Hal Finkelee90a222014-09-26 05:04:30 +00004077
4078 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004079 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4080 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004081
4082 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004083 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004084
Hal Finkelee90a222014-09-26 05:04:30 +00004085 case ABIArgInfo::Expand:
4086 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004087 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004088
Hal Finkelee90a222014-09-26 05:04:30 +00004089 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4090 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004091
Samuel Antao798f11c2015-11-23 22:04:44 +00004092 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4093
Hal Finkelee90a222014-09-26 05:04:30 +00004094 if (Ret.isScalar() && TargetDecl) {
4095 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4096 llvm::Value *OffsetValue = nullptr;
4097 if (const auto *Offset = AA->getOffset())
4098 OffsetValue = EmitScalarExpr(Offset);
4099
4100 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4101 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4102 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4103 OffsetValue);
4104 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004105 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004106
Hal Finkelee90a222014-09-26 05:04:30 +00004107 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004108}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004109
4110/* VarArg handling */
4111
Charles Davisc7d5c942015-09-17 20:55:33 +00004112Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4113 VAListAddr = VE->isMicrosoftABI()
4114 ? EmitMSVAListRef(VE->getSubExpr())
4115 : EmitVAListRef(VE->getSubExpr());
4116 QualType Ty = VE->getType();
4117 if (VE->isMicrosoftABI())
4118 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004119 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004120}