blob: 932b53e44dc86caa255939596a98746ce9460fd9 [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000029#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000035#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000036#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000037#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000038using namespace clang;
39using namespace CodeGen;
40
41/***/
42
John McCallab26cfa2010-02-05 21:31:56 +000043static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
44 switch (CC) {
45 default: return llvm::CallingConv::C;
46 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
47 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000048 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000049 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
50 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000051 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
52 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000053 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000054 // TODO: Add support for __pascal to LLVM.
55 case CC_X86Pascal: return llvm::CallingConv::C;
56 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000057 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000058 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
59 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000060 }
61}
62
John McCall8ee376f2010-02-24 07:14:12 +000063/// Derives the 'this' type for codegen purposes, i.e. ignoring method
64/// qualification.
65/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000066static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
67 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
68 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000069}
70
John McCall8ee376f2010-02-24 07:14:12 +000071/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
73 return MD->getType()->getCanonicalTypeUnqualified()
74 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000075}
76
77/// Returns the "extra-canonicalized" return type, which discards
78/// qualifiers on the return type. Codegen doesn't care about them,
79/// and it makes ABI code a little easier to be able to assume that
80/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000081static CanQualType GetReturnType(QualType RetTy) {
82 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000083}
84
John McCall8dda7b22012-07-07 06:41:13 +000085/// Arrange the argument and result information for a value of the given
86/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000087const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000088CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000089 // When translating an unprototyped function type, always use a
90 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000091 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000092 /*instanceMethod=*/false,
93 /*chainCall=*/false, None,
94 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000095}
96
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000097/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
98/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
99static void appendParameterTypes(const CodeGenTypes &CGT,
100 SmallVectorImpl<CanQualType> &prefix,
101 const CanQual<FunctionProtoType> &FPT,
102 const FunctionDecl *FD) {
103 // Fast path: unknown target.
104 if (FD == nullptr) {
105 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
106 return;
107 }
108
109 // In the vast majority cases, we'll have precisely FPT->getNumParams()
110 // parameters; the only thing that can change this is the presence of
111 // pass_object_size. So, we preallocate for the common case.
112 prefix.reserve(prefix.size() + FPT->getNumParams());
113
114 assert(FD->getNumParams() == FPT->getNumParams());
115 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
116 prefix.push_back(FPT->getParamType(I));
117 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
118 prefix.push_back(CGT.getContext().getSizeType());
119 }
120}
121
John McCall8dda7b22012-07-07 06:41:13 +0000122/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000123/// type, on top of any implicit parameters already stored.
124static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000125arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000126 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000127 CanQual<FunctionProtoType> FTP,
128 const FunctionDecl *FD) {
John McCall8dda7b22012-07-07 06:41:13 +0000129 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000130 // FIXME: Kill copy.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000131 appendParameterTypes(CGT, prefix, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000132 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000133 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
134 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000135 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000136}
137
John McCalla729c622012-02-17 03:33:10 +0000138/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000139/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000140const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000141CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
142 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000143 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000144 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000145 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000146}
147
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000148static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000149 // Set the appropriate calling convention for the Function.
150 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000151 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000152
153 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000154 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000155
Douglas Gregora941dca2010-05-18 16:57:00 +0000156 if (D->hasAttr<ThisCallAttr>())
157 return CC_X86ThisCall;
158
Reid Klecknerd7857f02014-10-24 17:42:17 +0000159 if (D->hasAttr<VectorCallAttr>())
160 return CC_X86VectorCall;
161
Dawn Perchik335e16b2010-09-03 01:29:35 +0000162 if (D->hasAttr<PascalAttr>())
163 return CC_X86Pascal;
164
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000165 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
166 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
167
Guy Benyeif0a014b2012-12-25 08:53:55 +0000168 if (D->hasAttr<IntelOclBiccAttr>())
169 return CC_IntelOclBicc;
170
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000171 if (D->hasAttr<MSABIAttr>())
172 return IsWindows ? CC_C : CC_X86_64Win64;
173
174 if (D->hasAttr<SysVABIAttr>())
175 return IsWindows ? CC_X86_64SysV : CC_C;
176
John McCallab26cfa2010-02-05 21:31:56 +0000177 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000178}
179
John McCalla729c622012-02-17 03:33:10 +0000180/// Arrange the argument and result information for a call to an
181/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000182/// (Zero value of RD means we don't have any meaningful "this" argument type,
183/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000184/// The member function must be an ordinary function, i.e. not a
185/// constructor or destructor.
186const CGFunctionInfo &
187CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000188 const FunctionProtoType *FTP,
189 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000190 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000191
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000192 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000193 if (RD)
194 argTypes.push_back(GetThisType(Context, RD));
195 else
196 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000197
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000198 return ::arrangeLLVMFunctionInfo(
199 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000200 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000201}
202
John McCalla729c622012-02-17 03:33:10 +0000203/// Arrange the argument and result information for a declaration or
204/// definition of the given C++ non-static member function. The
205/// member function must be an ordinary function, i.e. not a
206/// constructor or destructor.
207const CGFunctionInfo &
208CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000209 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000210 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
211
John McCalla729c622012-02-17 03:33:10 +0000212 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000213
John McCalla729c622012-02-17 03:33:10 +0000214 if (MD->isInstance()) {
215 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000216 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000217 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000218 }
219
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000220 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000221}
222
John McCalla729c622012-02-17 03:33:10 +0000223const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000224CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
225 StructorType Type) {
226
John McCalla729c622012-02-17 03:33:10 +0000227 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000228 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000229
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000230 GlobalDecl GD;
231 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
232 GD = GlobalDecl(CD, toCXXCtorType(Type));
233 } else {
234 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
235 GD = GlobalDecl(DD, toCXXDtorType(Type));
236 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000237
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000238 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000239
240 // Add the formal parameters.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000241 appendParameterTypes(*this, argTypes, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000242
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000243 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000244
245 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000246 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000247
John McCall8dda7b22012-07-07 06:41:13 +0000248 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000249 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
250 ? argTypes.front()
251 : TheCXXABI.hasMostDerivedReturn(GD)
252 ? CGM.getContext().VoidPtrTy
253 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000254 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
255 /*chainCall=*/false, argTypes, extInfo,
256 required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000257}
258
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000259/// Arrange a call to a C++ method, passing the given arguments.
260const CGFunctionInfo &
261CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
262 const CXXConstructorDecl *D,
263 CXXCtorType CtorKind,
264 unsigned ExtraArgs) {
265 // FIXME: Kill copy.
266 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000267 for (const auto &Arg : args)
268 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000269
270 CanQual<FunctionProtoType> FPT = GetFormalType(D);
271 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
272 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000273 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
274 ? ArgTypes.front()
275 : TheCXXABI.hasMostDerivedReturn(GD)
276 ? CGM.getContext().VoidPtrTy
277 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000278
279 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000280 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
281 /*chainCall=*/false, ArgTypes, Info,
282 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000283}
284
John McCalla729c622012-02-17 03:33:10 +0000285/// Arrange the argument and result information for the declaration or
286/// definition of the given function.
287const CGFunctionInfo &
288CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000289 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000290 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000291 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000292
John McCall2da83a32010-02-26 00:48:12 +0000293 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000294
John McCall2da83a32010-02-26 00:48:12 +0000295 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000296
297 // When declaring a function without a prototype, always use a
298 // non-variadic type.
299 if (isa<FunctionNoProtoType>(FTy)) {
300 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000301 return arrangeLLVMFunctionInfo(
302 noProto->getReturnType(), /*instanceMethod=*/false,
303 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000304 }
305
John McCall2da83a32010-02-26 00:48:12 +0000306 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000307 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000308}
309
John McCalla729c622012-02-17 03:33:10 +0000310/// Arrange the argument and result information for the declaration or
311/// definition of an Objective-C method.
312const CGFunctionInfo &
313CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
314 // It happens that this is the same as a call with no optional
315 // arguments, except also using the formal 'self' type.
316 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
317}
318
319/// Arrange the argument and result information for the function type
320/// through which to perform a send to the given Objective-C method,
321/// using the given receiver type. The receiver type is not always
322/// the 'self' type of the method or even an Objective-C pointer type.
323/// This is *not* the right method for actually performing such a
324/// message send, due to the possibility of optional arguments.
325const CGFunctionInfo &
326CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
327 QualType receiverType) {
328 SmallVector<CanQualType, 16> argTys;
329 argTys.push_back(Context.getCanonicalParamType(receiverType));
330 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000331 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000332 for (const auto *I : MD->params()) {
333 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000334 }
John McCall31168b02011-06-15 23:02:42 +0000335
336 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000337 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
338 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000339
David Blaikiebbafb8a2012-03-11 07:00:24 +0000340 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000341 MD->hasAttr<NSReturnsRetainedAttr>())
342 einfo = einfo.withProducesResult(true);
343
John McCalla729c622012-02-17 03:33:10 +0000344 RequiredArgs required =
345 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
346
Peter Collingbournef7706832014-12-12 23:41:25 +0000347 return arrangeLLVMFunctionInfo(
348 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
349 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000350}
351
John McCalla729c622012-02-17 03:33:10 +0000352const CGFunctionInfo &
353CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000354 // FIXME: Do we need to handle ObjCMethodDecl?
355 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000356
Anders Carlsson6710c532010-02-06 02:44:09 +0000357 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000358 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000359
360 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000361 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000362
John McCalla729c622012-02-17 03:33:10 +0000363 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000364}
365
Reid Klecknerc3473512014-08-29 21:43:29 +0000366/// Arrange a thunk that takes 'this' as the first parameter followed by
367/// varargs. Return a void pointer, regardless of the actual return type.
368/// The body of the thunk will end in a musttail call to a function of the
369/// correct type, and the caller will bitcast the function to the correct
370/// prototype.
371const CGFunctionInfo &
372CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
373 assert(MD->isVirtual() && "only virtual memptrs have thunks");
374 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
375 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000376 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
377 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000378 FTP->getExtInfo(), RequiredArgs(1));
379}
380
David Majnemerdfa6d202015-03-11 18:36:39 +0000381const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000382CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
383 CXXCtorType CT) {
384 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
385
David Majnemerdfa6d202015-03-11 18:36:39 +0000386 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
387 SmallVector<CanQualType, 2> ArgTys;
388 const CXXRecordDecl *RD = CD->getParent();
389 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000390 if (CT == Ctor_CopyingClosure)
391 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000392 if (RD->getNumVBases() > 0)
393 ArgTys.push_back(Context.IntTy);
394 CallingConv CC = Context.getDefaultCallingConvention(
395 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
396 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
397 /*chainCall=*/false, ArgTys,
398 FunctionType::ExtInfo(CC), RequiredArgs::All);
399}
400
John McCallc818bbb2012-12-07 07:03:17 +0000401/// Arrange a call as unto a free function, except possibly with an
402/// additional number of formal parameters considered required.
403static const CGFunctionInfo &
404arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000405 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000406 const CallArgList &args,
407 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000408 unsigned numExtraRequiredArgs,
409 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000410 assert(args.size() >= numExtraRequiredArgs);
411
412 // In most cases, there are no optional arguments.
413 RequiredArgs required = RequiredArgs::All;
414
415 // If we have a variadic prototype, the required arguments are the
416 // extra prefix plus the arguments in the prototype.
417 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
418 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000419 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000420
421 // If we don't have a prototype at all, but we're supposed to
422 // explicitly use the variadic convention for unprototyped calls,
423 // treat all of the arguments as required but preserve the nominal
424 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000425 } else if (CGM.getTargetCodeGenInfo()
426 .isNoProtoCallVariadic(args,
427 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000428 required = RequiredArgs(args.size());
429 }
430
Peter Collingbournef7706832014-12-12 23:41:25 +0000431 // FIXME: Kill copy.
432 SmallVector<CanQualType, 16> argTypes;
433 for (const auto &arg : args)
434 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
435 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
436 /*instanceMethod=*/false, chainCall,
437 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000438}
439
John McCalla729c622012-02-17 03:33:10 +0000440/// Figure out the rules for calling a function with the given formal
441/// type using the given arguments. The arguments are necessary
442/// because the function might be unprototyped, in which case it's
443/// target-dependent in crazy ways.
444const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000445CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000446 const FunctionType *fnType,
447 bool chainCall) {
448 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
449 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000450}
John McCalla729c622012-02-17 03:33:10 +0000451
John McCallc818bbb2012-12-07 07:03:17 +0000452/// A block function call is essentially a free-function call with an
453/// extra implicit argument.
454const CGFunctionInfo &
455CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
456 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000457 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
458 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000459}
460
461const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000462CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
463 const CallArgList &args,
464 FunctionType::ExtInfo info,
465 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000466 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000467 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000468 for (const auto &Arg : args)
469 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000470 return arrangeLLVMFunctionInfo(
471 GetReturnType(resultType), /*instanceMethod=*/false,
472 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000473}
474
475/// Arrange a call to a C++ method, passing the given arguments.
476const CGFunctionInfo &
477CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
478 const FunctionProtoType *FPT,
479 RequiredArgs required) {
480 // FIXME: Kill copy.
481 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000482 for (const auto &Arg : args)
483 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000484
485 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000486 return arrangeLLVMFunctionInfo(
487 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
488 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000489}
490
Reid Kleckner4982b822014-01-31 22:54:50 +0000491const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
492 QualType resultType, const FunctionArgList &args,
493 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000494 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000495 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000496 for (auto Arg : args)
497 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000498
499 RequiredArgs required =
500 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000501 return arrangeLLVMFunctionInfo(
502 GetReturnType(resultType), /*instanceMethod=*/false,
503 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000504}
505
John McCalla729c622012-02-17 03:33:10 +0000506const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000507 return arrangeLLVMFunctionInfo(
508 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
509 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000510}
511
John McCalla729c622012-02-17 03:33:10 +0000512/// Arrange the argument and result information for an abstract value
513/// of a given function type. This is the method which all of the
514/// above functions ultimately defer to.
515const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000516CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000517 bool instanceMethod,
518 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000519 ArrayRef<CanQualType> argTypes,
520 FunctionType::ExtInfo info,
521 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000522 assert(std::all_of(argTypes.begin(), argTypes.end(),
523 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000524
John McCalla729c622012-02-17 03:33:10 +0000525 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000526
Daniel Dunbare0be8292009-02-03 00:07:12 +0000527 // Lookup or create unique function info.
528 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000529 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
530 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000531
Craig Topper8a13c412014-05-21 05:09:00 +0000532 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000533 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000534 if (FI)
535 return *FI;
536
John McCalla729c622012-02-17 03:33:10 +0000537 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000538 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
539 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000540 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000541
David Blaikie82e95a32014-11-19 07:49:47 +0000542 bool inserted = FunctionsBeingProcessed.insert(FI).second;
543 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000544 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000545
Daniel Dunbar313321e2009-02-03 05:31:23 +0000546 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000547 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000548
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000549 // Loop over all of the computed argument and return value info. If any of
550 // them are direct or extend without a specified coerce type, specify the
551 // default now.
John McCalla729c622012-02-17 03:33:10 +0000552 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000553 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000554 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000555
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000556 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000557 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000558 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000559
John McCalla729c622012-02-17 03:33:10 +0000560 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
561 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000562
Daniel Dunbare0be8292009-02-03 00:07:12 +0000563 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000564}
565
John McCalla729c622012-02-17 03:33:10 +0000566CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000567 bool instanceMethod,
568 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000569 const FunctionType::ExtInfo &info,
570 CanQualType resultType,
571 ArrayRef<CanQualType> argTypes,
572 RequiredArgs required) {
Richard Smithc99f11b2016-02-09 01:05:04 +0000573 void *buffer = operator new(totalSizeToAlloc<ArgInfo>(argTypes.size() + 1));
John McCalla729c622012-02-17 03:33:10 +0000574 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
575 FI->CallingConvention = llvmCC;
576 FI->EffectiveCallingConvention = llvmCC;
577 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000578 FI->InstanceMethod = instanceMethod;
579 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000580 FI->NoReturn = info.getNoReturn();
581 FI->ReturnsRetained = info.getProducesResult();
582 FI->Required = required;
583 FI->HasRegParm = info.getHasRegParm();
584 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000585 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000586 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000587 FI->NumArgs = argTypes.size();
588 FI->getArgsBuffer()[0].type = resultType;
589 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
590 FI->getArgsBuffer()[i + 1].type = argTypes[i];
591 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000592}
593
594/***/
595
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000596namespace {
597// ABIArgInfo::Expand implementation.
598
599// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
600struct TypeExpansion {
601 enum TypeExpansionKind {
602 // Elements of constant arrays are expanded recursively.
603 TEK_ConstantArray,
604 // Record fields are expanded recursively (but if record is a union, only
605 // the field with the largest size is expanded).
606 TEK_Record,
607 // For complex types, real and imaginary parts are expanded recursively.
608 TEK_Complex,
609 // All other types are not expandable.
610 TEK_None
611 };
612
613 const TypeExpansionKind Kind;
614
615 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000616 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000617};
618
619struct ConstantArrayExpansion : TypeExpansion {
620 QualType EltTy;
621 uint64_t NumElts;
622
623 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
624 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
625 static bool classof(const TypeExpansion *TE) {
626 return TE->Kind == TEK_ConstantArray;
627 }
628};
629
630struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000631 SmallVector<const CXXBaseSpecifier *, 1> Bases;
632
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000633 SmallVector<const FieldDecl *, 1> Fields;
634
Reid Klecknere9f6a712014-10-31 17:10:41 +0000635 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
636 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000637 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
638 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000639 static bool classof(const TypeExpansion *TE) {
640 return TE->Kind == TEK_Record;
641 }
642};
643
644struct ComplexExpansion : TypeExpansion {
645 QualType EltTy;
646
647 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
648 static bool classof(const TypeExpansion *TE) {
649 return TE->Kind == TEK_Complex;
650 }
651};
652
653struct NoExpansion : TypeExpansion {
654 NoExpansion() : TypeExpansion(TEK_None) {}
655 static bool classof(const TypeExpansion *TE) {
656 return TE->Kind == TEK_None;
657 }
658};
659} // namespace
660
661static std::unique_ptr<TypeExpansion>
662getTypeExpansion(QualType Ty, const ASTContext &Context) {
663 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
664 return llvm::make_unique<ConstantArrayExpansion>(
665 AT->getElementType(), AT->getSize().getZExtValue());
666 }
667 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000668 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000669 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000670 const RecordDecl *RD = RT->getDecl();
671 assert(!RD->hasFlexibleArrayMember() &&
672 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000673 if (RD->isUnion()) {
674 // Unions can be here only in degenerative cases - all the fields are same
675 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000676 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000677 CharUnits UnionSize = CharUnits::Zero();
678
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000679 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000680 // Skip zero length bitfields.
681 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
682 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000683 assert(!FD->isBitField() &&
684 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000685 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000686 if (UnionSize < FieldSize) {
687 UnionSize = FieldSize;
688 LargestFD = FD;
689 }
690 }
691 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000692 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000693 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000694 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
695 assert(!CXXRD->isDynamicClass() &&
696 "cannot expand vtable pointers in dynamic classes");
697 for (const CXXBaseSpecifier &BS : CXXRD->bases())
698 Bases.push_back(&BS);
699 }
700
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000701 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000702 // Skip zero length bitfields.
703 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
704 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000705 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000706 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000707 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000708 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000709 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000710 return llvm::make_unique<RecordExpansion>(std::move(Bases),
711 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000712 }
713 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
714 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
715 }
716 return llvm::make_unique<NoExpansion>();
717}
718
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000719static int getExpansionSize(QualType Ty, const ASTContext &Context) {
720 auto Exp = getTypeExpansion(Ty, Context);
721 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
722 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
723 }
724 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
725 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000726 for (auto BS : RExp->Bases)
727 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000728 for (auto FD : RExp->Fields)
729 Res += getExpansionSize(FD->getType(), Context);
730 return Res;
731 }
732 if (isa<ComplexExpansion>(Exp.get()))
733 return 2;
734 assert(isa<NoExpansion>(Exp.get()));
735 return 1;
736}
737
Alexey Samsonov153004f2014-09-29 22:08:00 +0000738void
739CodeGenTypes::getExpandedTypes(QualType Ty,
740 SmallVectorImpl<llvm::Type *>::iterator &TI) {
741 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000742 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
743 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000744 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000745 }
746 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000747 for (auto BS : RExp->Bases)
748 getExpandedTypes(BS->getType(), TI);
749 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000750 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000751 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
752 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000753 *TI++ = EltTy;
754 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000755 } else {
756 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000757 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000758 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000759}
760
John McCall7f416cc2015-09-08 08:05:57 +0000761static void forConstantArrayExpansion(CodeGenFunction &CGF,
762 ConstantArrayExpansion *CAE,
763 Address BaseAddr,
764 llvm::function_ref<void(Address)> Fn) {
765 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
766 CharUnits EltAlign =
767 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
768
769 for (int i = 0, n = CAE->NumElts; i < n; i++) {
770 llvm::Value *EltAddr =
771 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
772 Fn(Address(EltAddr, EltAlign));
773 }
774}
775
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000776void CodeGenFunction::ExpandTypeFromArgs(
777 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000778 assert(LV.isSimple() &&
779 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000780
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000781 auto Exp = getTypeExpansion(Ty, getContext());
782 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000783 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
784 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000785 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
786 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000787 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000788 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000789 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000790 for (const CXXBaseSpecifier *BS : RExp->Bases) {
791 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000792 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000793 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
794 /*NullCheckValue=*/false, SourceLocation());
795 LValue SubLV = MakeAddrLValue(Base, BS->getType());
796
797 // Recurse onto bases.
798 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
799 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000800 for (auto FD : RExp->Fields) {
801 // FIXME: What are the right qualifiers here?
802 LValue SubLV = EmitLValueForField(LV, FD);
803 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000804 }
John McCall7f416cc2015-09-08 08:05:57 +0000805 } else if (isa<ComplexExpansion>(Exp.get())) {
806 auto realValue = *AI++;
807 auto imagValue = *AI++;
808 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000809 } else {
810 assert(isa<NoExpansion>(Exp.get()));
811 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000812 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000813}
814
815void CodeGenFunction::ExpandTypeToArgs(
816 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
817 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
818 auto Exp = getTypeExpansion(Ty, getContext());
819 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000820 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
821 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000822 RValue EltRV =
823 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
824 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000825 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000826 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000827 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000828 for (const CXXBaseSpecifier *BS : RExp->Bases) {
829 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000830 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000831 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
832 /*NullCheckValue=*/false, SourceLocation());
833 RValue BaseRV = RValue::getAggregate(Base);
834
835 // Recurse onto bases.
836 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
837 IRCallArgPos);
838 }
839
840 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000841 for (auto FD : RExp->Fields) {
842 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
843 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
844 IRCallArgPos);
845 }
846 } else if (isa<ComplexExpansion>(Exp.get())) {
847 ComplexPairTy CV = RV.getComplexVal();
848 IRCallArgs[IRCallArgPos++] = CV.first;
849 IRCallArgs[IRCallArgPos++] = CV.second;
850 } else {
851 assert(isa<NoExpansion>(Exp.get()));
852 assert(RV.isScalar() &&
853 "Unexpected non-scalar rvalue during struct expansion.");
854
855 // Insert a bitcast as needed.
856 llvm::Value *V = RV.getScalarVal();
857 if (IRCallArgPos < IRFuncTy->getNumParams() &&
858 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
859 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
860
861 IRCallArgs[IRCallArgPos++] = V;
862 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000863}
864
John McCall7f416cc2015-09-08 08:05:57 +0000865/// Create a temporary allocation for the purposes of coercion.
866static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
867 CharUnits MinAlign) {
868 // Don't use an alignment that's worse than what LLVM would prefer.
869 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
870 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
871
872 return CGF.CreateTempAlloca(Ty, Align);
873}
874
Chris Lattner895c52b2010-06-27 06:04:18 +0000875/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000876/// accessing some number of bytes out of it, try to gep into the struct to get
877/// at its inner goodness. Dive as deep as possible without entering an element
878/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +0000879static Address
880EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000881 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000882 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000883 // We can't dive into a zero-element struct.
884 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000885
Chris Lattner2192fe52011-07-18 04:24:23 +0000886 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000887
Chris Lattner1cd66982010-06-27 05:56:15 +0000888 // 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 +0000889 // first element is the same size as the whole struct, we can enter it. The
890 // comparison must be made on the store size and not the alloca size. Using
891 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000892 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000893 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000894 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000895 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000896 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000897
Chris Lattner1cd66982010-06-27 05:56:15 +0000898 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +0000899 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000900
Chris Lattner1cd66982010-06-27 05:56:15 +0000901 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +0000902 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000903 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000904 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000905
906 return SrcPtr;
907}
908
Chris Lattner055097f2010-06-27 06:26:04 +0000909/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
910/// are either integers or pointers. This does a truncation of the value if it
911/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000912///
913/// This behaves as if the value were coerced through memory, so on big-endian
914/// targets the high bits are preserved in a truncation, while little-endian
915/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000916static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000917 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000918 CodeGenFunction &CGF) {
919 if (Val->getType() == Ty)
920 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000921
Chris Lattner055097f2010-06-27 06:26:04 +0000922 if (isa<llvm::PointerType>(Val->getType())) {
923 // If this is Pointer->Pointer avoid conversion to and from int.
924 if (isa<llvm::PointerType>(Ty))
925 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000926
Chris Lattner055097f2010-06-27 06:26:04 +0000927 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000928 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000929 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000930
Chris Lattner2192fe52011-07-18 04:24:23 +0000931 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000932 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000933 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000934
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000935 if (Val->getType() != DestIntTy) {
936 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
937 if (DL.isBigEndian()) {
938 // Preserve the high bits on big-endian targets.
939 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000940 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
941 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
942
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000943 if (SrcSize > DstSize) {
944 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
945 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
946 } else {
947 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
948 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
949 }
950 } else {
951 // Little-endian targets preserve the low bits. No shifts required.
952 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
953 }
954 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000955
Chris Lattner055097f2010-06-27 06:26:04 +0000956 if (isa<llvm::PointerType>(Ty))
957 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
958 return Val;
959}
960
Chris Lattner1cd66982010-06-27 05:56:15 +0000961
962
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000963/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +0000964/// a pointer to an object of type \arg Ty, known to be aligned to
965/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000966///
967/// This safely handles the case when the src type is smaller than the
968/// destination type; in this situation the values of bits which not
969/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +0000970static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000971 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +0000972 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000973
Chris Lattnerd200eda2010-06-28 22:51:39 +0000974 // If SrcTy and Ty are the same, just do a load.
975 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +0000976 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000977
Micah Villmowdd31ca12012-10-08 16:25:52 +0000978 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000979
Chris Lattner2192fe52011-07-18 04:24:23 +0000980 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +0000981 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
982 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +0000983 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000984
Micah Villmowdd31ca12012-10-08 16:25:52 +0000985 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000986
Chris Lattner055097f2010-06-27 06:26:04 +0000987 // If the source and destination are integer or pointer types, just do an
988 // extension or truncation to the desired type.
989 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
990 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +0000991 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +0000992 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
993 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000994
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000995 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000996 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000997 // Generally SrcSize is never greater than DstSize, since this means we are
998 // losing bits. However, this can happen in cases where the structure has
999 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001000 //
Mike Stump18bb9282009-05-16 07:57:57 +00001001 // FIXME: Assert that we aren't truncating non-padding bits when have access
1002 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001003 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1004 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001005 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001006
John McCall7f416cc2015-09-08 08:05:57 +00001007 // Otherwise do coercion through memory. This is stupid, but simple.
1008 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1009 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1010 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001011 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1012 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001013 false);
1014 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001015}
1016
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001017// Function to store a first-class aggregate into memory. We prefer to
1018// store the elements rather than the aggregate to be more friendly to
1019// fast-isel.
1020// FIXME: Do we need to recurse here?
1021static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001022 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001023 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001024 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001025 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001026 const llvm::StructLayout *Layout =
1027 CGF.CGM.getDataLayout().getStructLayout(STy);
1028
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001029 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001030 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1031 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001032 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001033 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001034 }
1035 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001036 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001037 }
1038}
1039
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001040/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001041/// where the source and destination may have different types. The
1042/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001043///
1044/// This safely handles the case when the src type is larger than the
1045/// destination type; the upper bits of the src will be lost.
1046static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001047 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001048 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001049 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001050 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001051 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001052 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001053 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001054 return;
1055 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001056
Micah Villmowdd31ca12012-10-08 16:25:52 +00001057 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001058
Chris Lattner2192fe52011-07-18 04:24:23 +00001059 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001060 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1061 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001062 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001063
Chris Lattner055097f2010-06-27 06:26:04 +00001064 // If the source and destination are integer or pointer types, just do an
1065 // extension or truncation to the desired type.
1066 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1067 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1068 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001069 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001070 return;
1071 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001072
Micah Villmowdd31ca12012-10-08 16:25:52 +00001073 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001074
Daniel Dunbar313321e2009-02-03 05:31:23 +00001075 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001076 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001077 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1078 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001079 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001080 // Otherwise do coercion through memory. This is stupid, but
1081 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001082
1083 // Generally SrcSize is never greater than DstSize, since this means we are
1084 // losing bits. However, this can happen in cases where the structure has
1085 // additional padding, for example due to a user specified alignment.
1086 //
1087 // FIXME: Assert that we aren't truncating non-padding bits when have access
1088 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001089 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1090 CGF.Builder.CreateStore(Src, Tmp);
1091 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1092 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001093 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1094 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001095 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001096 }
1097}
1098
John McCall7f416cc2015-09-08 08:05:57 +00001099static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1100 const ABIArgInfo &info) {
1101 if (unsigned offset = info.getDirectOffset()) {
1102 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1103 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1104 CharUnits::fromQuantity(offset));
1105 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1106 }
1107 return addr;
1108}
1109
Alexey Samsonov153004f2014-09-29 22:08:00 +00001110namespace {
1111
1112/// Encapsulates information about the way function arguments from
1113/// CGFunctionInfo should be passed to actual LLVM IR function.
1114class ClangToLLVMArgMapping {
1115 static const unsigned InvalidIndex = ~0U;
1116 unsigned InallocaArgNo;
1117 unsigned SRetArgNo;
1118 unsigned TotalIRArgs;
1119
1120 /// Arguments of LLVM IR function corresponding to single Clang argument.
1121 struct IRArgs {
1122 unsigned PaddingArgIndex;
1123 // Argument is expanded to IR arguments at positions
1124 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1125 unsigned FirstArgIndex;
1126 unsigned NumberOfArgs;
1127
1128 IRArgs()
1129 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1130 NumberOfArgs(0) {}
1131 };
1132
1133 SmallVector<IRArgs, 8> ArgInfo;
1134
1135public:
1136 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1137 bool OnlyRequiredArgs = false)
1138 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1139 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1140 construct(Context, FI, OnlyRequiredArgs);
1141 }
1142
1143 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1144 unsigned getInallocaArgNo() const {
1145 assert(hasInallocaArg());
1146 return InallocaArgNo;
1147 }
1148
1149 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1150 unsigned getSRetArgNo() const {
1151 assert(hasSRetArg());
1152 return SRetArgNo;
1153 }
1154
1155 unsigned totalIRArgs() const { return TotalIRArgs; }
1156
1157 bool hasPaddingArg(unsigned ArgNo) const {
1158 assert(ArgNo < ArgInfo.size());
1159 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1160 }
1161 unsigned getPaddingArgNo(unsigned ArgNo) const {
1162 assert(hasPaddingArg(ArgNo));
1163 return ArgInfo[ArgNo].PaddingArgIndex;
1164 }
1165
1166 /// Returns index of first IR argument corresponding to ArgNo, and their
1167 /// quantity.
1168 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1169 assert(ArgNo < ArgInfo.size());
1170 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1171 ArgInfo[ArgNo].NumberOfArgs);
1172 }
1173
1174private:
1175 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1176 bool OnlyRequiredArgs);
1177};
1178
1179void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1180 const CGFunctionInfo &FI,
1181 bool OnlyRequiredArgs) {
1182 unsigned IRArgNo = 0;
1183 bool SwapThisWithSRet = false;
1184 const ABIArgInfo &RetAI = FI.getReturnInfo();
1185
1186 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1187 SwapThisWithSRet = RetAI.isSRetAfterThis();
1188 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1189 }
1190
1191 unsigned ArgNo = 0;
1192 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1193 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1194 ++I, ++ArgNo) {
1195 assert(I != FI.arg_end());
1196 QualType ArgType = I->type;
1197 const ABIArgInfo &AI = I->info;
1198 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1199 auto &IRArgs = ArgInfo[ArgNo];
1200
1201 if (AI.getPaddingType())
1202 IRArgs.PaddingArgIndex = IRArgNo++;
1203
1204 switch (AI.getKind()) {
1205 case ABIArgInfo::Extend:
1206 case ABIArgInfo::Direct: {
1207 // FIXME: handle sseregparm someday...
1208 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1209 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1210 IRArgs.NumberOfArgs = STy->getNumElements();
1211 } else {
1212 IRArgs.NumberOfArgs = 1;
1213 }
1214 break;
1215 }
1216 case ABIArgInfo::Indirect:
1217 IRArgs.NumberOfArgs = 1;
1218 break;
1219 case ABIArgInfo::Ignore:
1220 case ABIArgInfo::InAlloca:
1221 // ignore and inalloca doesn't have matching LLVM parameters.
1222 IRArgs.NumberOfArgs = 0;
1223 break;
1224 case ABIArgInfo::Expand: {
1225 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1226 break;
1227 }
1228 }
1229
1230 if (IRArgs.NumberOfArgs > 0) {
1231 IRArgs.FirstArgIndex = IRArgNo;
1232 IRArgNo += IRArgs.NumberOfArgs;
1233 }
1234
1235 // Skip over the sret parameter when it comes second. We already handled it
1236 // above.
1237 if (IRArgNo == 1 && SwapThisWithSRet)
1238 IRArgNo++;
1239 }
1240 assert(ArgNo == ArgInfo.size());
1241
1242 if (FI.usesInAlloca())
1243 InallocaArgNo = IRArgNo++;
1244
1245 TotalIRArgs = IRArgNo;
1246}
1247} // namespace
1248
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001249/***/
1250
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001251bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001252 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001253}
1254
Tim Northovere77cc392014-03-29 13:28:05 +00001255bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1256 return ReturnTypeUsesSRet(FI) &&
1257 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1258}
1259
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001260bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1261 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1262 switch (BT->getKind()) {
1263 default:
1264 return false;
1265 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001266 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001267 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001268 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001269 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001270 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001271 }
1272 }
1273
1274 return false;
1275}
1276
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001277bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1278 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1279 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1280 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001281 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001282 }
1283 }
1284
1285 return false;
1286}
1287
Chris Lattnera5f58b02011-07-09 17:41:47 +00001288llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001289 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1290 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001291}
1292
Chris Lattnera5f58b02011-07-09 17:41:47 +00001293llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001294CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001295
David Blaikie82e95a32014-11-19 07:49:47 +00001296 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1297 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001298 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001299
Alexey Samsonov153004f2014-09-29 22:08:00 +00001300 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001301 const ABIArgInfo &retAI = FI.getReturnInfo();
1302 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001303 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001304 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001305
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001306 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001307 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001308 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001309 break;
1310
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001311 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001312 if (retAI.getInAllocaSRet()) {
1313 // sret things on win32 aren't void, they return the sret pointer.
1314 QualType ret = FI.getReturnType();
1315 llvm::Type *ty = ConvertType(ret);
1316 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1317 resultType = llvm::PointerType::get(ty, addressSpace);
1318 } else {
1319 resultType = llvm::Type::getVoidTy(getLLVMContext());
1320 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001321 break;
1322
John McCall7f416cc2015-09-08 08:05:57 +00001323 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001324 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001325 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001326 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Alexey Samsonov153004f2014-09-29 22:08:00 +00001329 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1330 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1331
1332 // Add type for sret argument.
1333 if (IRFunctionArgs.hasSRetArg()) {
1334 QualType Ret = FI.getReturnType();
1335 llvm::Type *Ty = ConvertType(Ret);
1336 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1337 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1338 llvm::PointerType::get(Ty, AddressSpace);
1339 }
1340
1341 // Add type for inalloca argument.
1342 if (IRFunctionArgs.hasInallocaArg()) {
1343 auto ArgStruct = FI.getArgStruct();
1344 assert(ArgStruct);
1345 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1346 }
1347
John McCallc818bbb2012-12-07 07:03:17 +00001348 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001349 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001350 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1351 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001352 for (; it != ie; ++it, ++ArgNo) {
1353 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001354
Rafael Espindolafad28de2012-10-24 01:59:00 +00001355 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001356 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1357 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1358 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001359
Alexey Samsonov153004f2014-09-29 22:08:00 +00001360 unsigned FirstIRArg, NumIRArgs;
1361 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1362
1363 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001364 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001365 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001366 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001367 break;
1368
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001369 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001370 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001371 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001372 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001373 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001374 break;
1375 }
1376
1377 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001378 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001379 // Fast-isel and the optimizer generally like scalar values better than
1380 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001381 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001382 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001383 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1384 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001385 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001386 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001387 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001388 assert(NumIRArgs == 1);
1389 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001390 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001391 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Daniel Dunbard3674e62008-09-11 01:48:57 +00001394 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001395 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1396 getExpandedTypes(it->type, ArgTypesIter);
1397 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001398 break;
1399 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001400 }
1401
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001402 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1403 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001404
1405 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001406}
1407
Chris Lattner2192fe52011-07-18 04:24:23 +00001408llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001409 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001410 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001411
Chris Lattner8806e322011-07-10 00:18:59 +00001412 if (!isFuncTypeConvertible(FPT))
1413 return llvm::StructType::get(getLLVMContext());
1414
1415 const CGFunctionInfo *Info;
1416 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001417 Info =
1418 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001419 else
John McCalla729c622012-02-17 03:33:10 +00001420 Info = &arrangeCXXMethodDeclaration(MD);
1421 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001422}
1423
Samuel Antao798f11c2015-11-23 22:04:44 +00001424static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1425 llvm::AttrBuilder &FuncAttrs,
1426 const FunctionProtoType *FPT) {
1427 if (!FPT)
1428 return;
1429
1430 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1431 FPT->isNothrow(Ctx))
1432 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1433}
1434
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001435void CodeGenModule::ConstructAttributeList(
1436 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1437 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001438 llvm::AttrBuilder FuncAttrs;
1439 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001440 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001441
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001442 CallingConv = FI.getEffectiveCallingConvention();
1443
John McCallab26cfa2010-02-05 21:31:56 +00001444 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001445 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001446
Samuel Antao798f11c2015-11-23 22:04:44 +00001447 // If we have information about the function prototype, we can learn
1448 // attributes form there.
1449 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1450 CalleeInfo.getCalleeFunctionProtoType());
1451
1452 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1453
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001454 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001455 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001456 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001457 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001458 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001459 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001460 if (TargetDecl->hasAttr<NoReturnAttr>())
1461 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001462 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1463 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001464
1465 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001466 AddAttributesFromFunctionProtoType(
1467 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001468 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1469 // These attributes are not inherited by overloads.
1470 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1471 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001472 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001473 }
1474
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001475 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001476 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001477 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1478 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001479 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001480 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1481 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001482 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1483 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1484 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001485 }
David Majnemer631a90b2015-02-04 07:23:21 +00001486 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001487 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001488 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1489 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001490
1491 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001492 }
1493
Paul Robinson08556952014-12-11 20:14:04 +00001494 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1495 if (!HasOptnone) {
1496 if (CodeGenOpts.OptimizeSize)
1497 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1498 if (CodeGenOpts.OptimizeSize == 2)
1499 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1500 }
1501
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001502 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001503 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001504 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001505 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001506 if (CodeGenOpts.EnableSegmentedStacks &&
1507 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001508 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001509
Bill Wendling2f81db62013-02-22 20:53:29 +00001510 if (AttrOnCallSite) {
1511 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001512 if (!CodeGenOpts.SimplifyLibCalls ||
1513 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001514 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001515 if (!CodeGenOpts.TrapFuncName.empty())
1516 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001517 } else {
1518 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001519 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001520 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001521 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001522 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001523 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001524 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001525 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001526 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001527 }
1528
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001529 bool DisableTailCalls =
1530 CodeGenOpts.DisableTailCalls ||
1531 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Akira Hatanaka262a4c42015-06-09 19:04:36 +00001532 FuncAttrs.addAttribute("disable-tail-calls",
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001533 llvm::toStringRef(DisableTailCalls));
1534
Bill Wendlingdabafea2013-03-13 22:24:33 +00001535 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001536 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001537 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001538 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001539 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001540 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001541 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001542 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001543 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001544 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001545 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001546 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001547
Akira Hatanakaaecca042015-09-11 18:55:09 +00001548 if (CodeGenOpts.StackRealignment)
1549 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001550
Eric Christopher11acf732015-06-12 01:35:52 +00001551 // Add target-cpu and target-features attributes to functions. If
1552 // we have a decl for the function and it has a target attribute then
1553 // parse that and add it to the feature set.
1554 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001555 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001556 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001557 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001558 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001559
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001560 // Produce the canonical string for this set of features.
1561 std::vector<std::string> Features;
1562 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1563 ie = FeatureMap.end();
1564 it != ie; ++it)
1565 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001566
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001567 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001568 // While we populated the feature map above, we still need to
1569 // get and parse the target attribute so we can get the cpu for
1570 // the function.
1571 const auto *TD = FD->getAttr<TargetAttr>();
1572 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1573 if (ParsedAttr.second != "")
1574 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001575 if (TargetCPU != "")
1576 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1577 if (!Features.empty()) {
1578 std::sort(Features.begin(), Features.end());
1579 FuncAttrs.addAttribute(
1580 "target-features",
1581 llvm::join(Features.begin(), Features.end(), ","));
1582 }
1583 } else {
1584 // Otherwise just add the existing target cpu and target features to the
1585 // function.
1586 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1587 if (TargetCPU != "")
1588 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1589 if (!Features.empty()) {
1590 std::sort(Features.begin(), Features.end());
1591 FuncAttrs.addAttribute(
1592 "target-features",
1593 llvm::join(Features.begin(), Features.end(), ","));
1594 }
Eric Christopher70c16652015-03-25 23:14:47 +00001595 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001596 }
1597
Justin Lebarddd97fa2016-02-24 21:55:11 +00001598 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1599 // Conservatively, mark all functions and calls in CUDA as convergent
1600 // (meaning, they may call an intrinsically convergent op, such as
1601 // __syncthreads(), and so can't have certain optimizations applied around
1602 // them). LLVM will remove this attribute where it safely can.
1603 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1604 }
1605
Alexey Samsonov153004f2014-09-29 22:08:00 +00001606 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001607
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001608 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001609 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001610 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001611 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001612 if (RetTy->hasSignedIntegerRepresentation())
1613 RetAttrs.addAttribute(llvm::Attribute::SExt);
1614 else if (RetTy->hasUnsignedIntegerRepresentation())
1615 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001616 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001617 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001618 if (RetAI.getInReg())
1619 RetAttrs.addAttribute(llvm::Attribute::InReg);
1620 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001621 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001622 break;
1623
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001624 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001625 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001626 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001627 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1628 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001629 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001630 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001631
Daniel Dunbard3674e62008-09-11 01:48:57 +00001632 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001633 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001634 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001635
Hal Finkela2347ba2014-07-18 15:52:10 +00001636 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1637 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001638 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001639 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1640 .getQuantity());
1641 else if (getContext().getTargetAddressSpace(PTy) == 0)
1642 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1643 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001644
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001645 // Attach return attributes.
1646 if (RetAttrs.hasAttributes()) {
1647 PAL.push_back(llvm::AttributeSet::get(
1648 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1649 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001650
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001651 // Attach attributes to sret.
1652 if (IRFunctionArgs.hasSRetArg()) {
1653 llvm::AttrBuilder SRETAttrs;
1654 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1655 if (RetAI.getInReg())
1656 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1657 PAL.push_back(llvm::AttributeSet::get(
1658 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1659 }
1660
1661 // Attach attributes to inalloca argument.
1662 if (IRFunctionArgs.hasInallocaArg()) {
1663 llvm::AttrBuilder Attrs;
1664 Attrs.addAttribute(llvm::Attribute::InAlloca);
1665 PAL.push_back(llvm::AttributeSet::get(
1666 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1667 }
1668
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001669 unsigned ArgNo = 0;
1670 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1671 E = FI.arg_end();
1672 I != E; ++I, ++ArgNo) {
1673 QualType ParamType = I->type;
1674 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001675 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001676
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001677 // Add attribute for padding argument, if necessary.
1678 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001679 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001680 PAL.push_back(llvm::AttributeSet::get(
1681 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1682 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001683 }
1684
John McCall39ec71f2010-03-27 00:47:27 +00001685 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1686 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001687 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001688 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001689 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001690 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001691 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001692 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1693 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1694 Attrs.addAttribute(llvm::Attribute::SExt);
1695 else
1696 Attrs.addAttribute(llvm::Attribute::ZExt);
1697 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001698 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001699 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001700 if (ArgNo == 0 && FI.isChainCall())
1701 Attrs.addAttribute(llvm::Attribute::Nest);
1702 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001703 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001704 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001705
James Y Knight71608572015-08-21 18:19:06 +00001706 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001707 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001708 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001709
Anders Carlsson20759ad2009-09-16 15:53:40 +00001710 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001711 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001712
John McCall7f416cc2015-09-08 08:05:57 +00001713 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001714
1715 // In a byval argument, it is important that the required
1716 // alignment of the type is honored, as LLVM might be creating a
1717 // *new* stack object, and needs to know what alignment to give
1718 // it. (Sometimes it can deduce a sensible alignment on its own,
1719 // but not if clang decides it must emit a packed struct, or the
1720 // user specifies increased alignment requirements.)
1721 //
1722 // This is different from indirect *not* byval, where the object
1723 // exists already, and the align attribute is purely
1724 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001725 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001726
John McCall7f416cc2015-09-08 08:05:57 +00001727 // For now, only add this when we have a byval argument.
1728 // TODO: be less lazy about updating test cases.
1729 if (AI.getIndirectByVal())
1730 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001731
Daniel Dunbarc2304432009-03-18 19:51:01 +00001732 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001733 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1734 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001735 break;
James Y Knight71608572015-08-21 18:19:06 +00001736 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001737 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001738 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001739 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001740
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001741 case ABIArgInfo::InAlloca:
1742 // inalloca disables readnone and readonly.
1743 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1744 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001745 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
Hal Finkela2347ba2014-07-18 15:52:10 +00001748 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1749 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001750 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001751 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1752 .getQuantity());
1753 else if (getContext().getTargetAddressSpace(PTy) == 0)
1754 Attrs.addAttribute(llvm::Attribute::NonNull);
1755 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001756
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001757 if (Attrs.hasAttributes()) {
1758 unsigned FirstIRArg, NumIRArgs;
1759 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1760 for (unsigned i = 0; i < NumIRArgs; i++)
1761 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1762 FirstIRArg + i + 1, Attrs));
1763 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001764 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001765 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001766
Bill Wendlinga7912f82012-10-10 07:36:56 +00001767 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001768 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001769 AttributeSet::get(getLLVMContext(),
1770 llvm::AttributeSet::FunctionIndex,
1771 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001772}
1773
John McCalla738c252011-03-09 04:27:21 +00001774/// An argument came in as a promoted argument; demote it back to its
1775/// declared type.
1776static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1777 const VarDecl *var,
1778 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001779 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001780
1781 // This can happen with promotions that actually don't change the
1782 // underlying type, like the enum promotions.
1783 if (value->getType() == varType) return value;
1784
1785 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1786 && "unexpected promotion type");
1787
1788 if (isa<llvm::IntegerType>(varType))
1789 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1790
1791 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1792}
1793
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001794/// Returns the attribute (either parameter attribute, or function
1795/// attribute), which declares argument ArgNo to be non-null.
1796static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1797 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001798 // FIXME: __attribute__((nonnull)) can also be applied to:
1799 // - references to pointers, where the pointee is known to be
1800 // nonnull (apparently a Clang extension)
1801 // - transparent unions containing pointers
1802 // In the former case, LLVM IR cannot represent the constraint. In
1803 // the latter case, we have no guarantee that the transparent union
1804 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001805 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1806 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001807 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001808 if (PVD) {
1809 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1810 return ParmNNAttr;
1811 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001812 // Check function attributes.
1813 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001814 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001815 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001816 if (NNAttr->isNonNull(ArgNo))
1817 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001818 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001819 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001820}
1821
Daniel Dunbard931a872009-02-02 22:03:45 +00001822void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1823 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001824 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001825 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1826 // Naked functions don't have prologues.
1827 return;
1828
John McCallcaa19452009-07-28 01:00:58 +00001829 // If this is an implicit-return-zero function, go ahead and
1830 // initialize the return value. TODO: it might be nice to have
1831 // a more general mechanism for this that didn't require synthesized
1832 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001833 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001834 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001835 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001836 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001837 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001838 Builder.CreateStore(Zero, ReturnValue);
1839 }
1840 }
1841
Mike Stump18bb9282009-05-16 07:57:57 +00001842 // FIXME: We no longer need the types from FunctionArgList; lift up and
1843 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001844
Alexey Samsonov153004f2014-09-29 22:08:00 +00001845 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001846 // Flattened function arguments.
1847 SmallVector<llvm::Argument *, 16> FnArgs;
1848 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1849 for (auto &Arg : Fn->args()) {
1850 FnArgs.push_back(&Arg);
1851 }
1852 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001853
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001854 // If we're using inalloca, all the memory arguments are GEPs off of the last
1855 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00001856 Address ArgStruct = Address::invalid();
1857 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001858 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00001859 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
1860 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
1861 FI.getArgStructAlignment());
1862
1863 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001864 }
1865
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001866 // Name the struct return parameter.
1867 if (IRFunctionArgs.hasSRetArg()) {
1868 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001869 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001870 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001871 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001874 // Track if we received the parameter as a pointer (indirect, byval, or
1875 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1876 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00001877 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001878 ArgVals.reserve(Args.size());
1879
Reid Kleckner739756c2013-12-04 19:23:12 +00001880 // Create a pointer value for every parameter declaration. This usually
1881 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1882 // any cleanups or do anything that might unwind. We do that separately, so
1883 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001884 assert(FI.arg_size() == Args.size() &&
1885 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001886 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001887 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001888 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001889 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001890 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001891 QualType Ty = info_it->type;
1892 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001893
John McCalla738c252011-03-09 04:27:21 +00001894 bool isPromoted =
1895 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1896
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001897 unsigned FirstIRArg, NumIRArgs;
1898 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001899
Daniel Dunbard3674e62008-09-11 01:48:57 +00001900 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001901 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001902 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00001903 auto FieldIndex = ArgI.getInAllocaFieldIndex();
1904 CharUnits FieldOffset =
1905 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
1906 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
1907 Arg->getName());
1908 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001909 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001910 }
1911
Daniel Dunbar747865a2009-02-05 09:16:39 +00001912 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001913 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00001914 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001915
John McCall47fb9502013-03-07 21:37:08 +00001916 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001917 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00001918 // need to do is realign the value, if requested.
1919 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001920 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00001921 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001922
1923 // Copy from the incoming argument pointer to the temporary with the
1924 // appropriate alignment.
1925 //
1926 // FIXME: We should have a common utility for generating an aggregate
1927 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00001928 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00001929 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
1930 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
1931 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
1932 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001933 V = AlignedTemp;
1934 }
John McCall7f416cc2015-09-08 08:05:57 +00001935 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001936 } else {
1937 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00001938 llvm::Value *V =
1939 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001940
1941 if (isPromoted)
1942 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00001943 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001944 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001945 break;
1946 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001947
1948 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001949 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001950
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001951 // If we have the trivial case, handle it with no muss and fuss.
1952 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001953 ArgI.getCoerceToType() == ConvertType(Ty) &&
1954 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001955 assert(NumIRArgs == 1);
1956 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001957 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001958
Hal Finkel48d53e22014-07-19 01:41:07 +00001959 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001960 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1961 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001962 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1963 AI->getArgNo() + 1,
1964 llvm::Attribute::NonNull));
1965
Hal Finkel48d53e22014-07-19 01:41:07 +00001966 QualType OTy = PVD->getOriginalType();
1967 if (const auto *ArrTy =
1968 getContext().getAsConstantArrayType(OTy)) {
1969 // A C99 array parameter declaration with the static keyword also
1970 // indicates dereferenceability, and if the size is constant we can
1971 // use the dereferenceable attribute (which requires the size in
1972 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001973 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001974 QualType ETy = ArrTy->getElementType();
1975 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1976 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1977 ArrSize) {
1978 llvm::AttrBuilder Attrs;
1979 Attrs.addDereferenceableAttr(
1980 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1981 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1982 AI->getArgNo() + 1, Attrs));
1983 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1984 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1985 AI->getArgNo() + 1,
1986 llvm::Attribute::NonNull));
1987 }
1988 }
1989 } else if (const auto *ArrTy =
1990 getContext().getAsVariableArrayType(OTy)) {
1991 // For C99 VLAs with the static keyword, we don't know the size so
1992 // we can't use the dereferenceable attribute, but in addrspace(0)
1993 // we know that it must be nonnull.
1994 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1995 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1996 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1997 AI->getArgNo() + 1,
1998 llvm::Attribute::NonNull));
1999 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002000
2001 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2002 if (!AVAttr)
2003 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2004 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2005 if (AVAttr) {
2006 llvm::Value *AlignmentValue =
2007 EmitScalarExpr(AVAttr->getAlignment());
2008 llvm::ConstantInt *AlignmentCI =
2009 cast<llvm::ConstantInt>(AlignmentValue);
2010 unsigned Alignment =
2011 std::min((unsigned) AlignmentCI->getZExtValue(),
2012 +llvm::Value::MaximumAlignment);
2013
2014 llvm::AttrBuilder Attrs;
2015 Attrs.addAlignmentAttr(Alignment);
2016 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2017 AI->getArgNo() + 1, Attrs));
2018 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002019 }
2020
Bill Wendling507c3512012-10-16 05:23:44 +00002021 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002022 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2023 AI->getArgNo() + 1,
2024 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002025
Chris Lattner7369c142011-07-20 06:29:00 +00002026 // Ensure the argument is the correct type.
2027 if (V->getType() != ArgI.getCoerceToType())
2028 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2029
John McCalla738c252011-03-09 04:27:21 +00002030 if (isPromoted)
2031 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002032
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002033 if (const CXXMethodDecl *MD =
2034 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002035 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002036 V = CGM.getCXXABI().
2037 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002038 }
2039
Rafael Espindola8778c282012-11-29 16:09:03 +00002040 // Because of merging of function types from multiple decls it is
2041 // possible for the type of an argument to not match the corresponding
2042 // type in the function type. Since we are codegening the callee
2043 // in here, add a cast to the argument type.
2044 llvm::Type *LTy = ConvertType(Arg->getType());
2045 if (V->getType() != LTy)
2046 V = Builder.CreateBitCast(V, LTy);
2047
John McCall7f416cc2015-09-08 08:05:57 +00002048 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002049 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
John McCall7f416cc2015-09-08 08:05:57 +00002052 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2053 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002054
John McCall7f416cc2015-09-08 08:05:57 +00002055 // Pointer to store into.
2056 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002057
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002058 // Fast-isel and the optimizer generally like scalar values better than
2059 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002060 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002061 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2062 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002063 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002064 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002065 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002066 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002067
John McCall7f416cc2015-09-08 08:05:57 +00002068 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002069 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002070 AddrToStoreInto =
2071 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002072 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002073 AddrToStoreInto =
2074 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002075 }
John McCall7f416cc2015-09-08 08:05:57 +00002076
2077 assert(STy->getNumElements() == NumIRArgs);
2078 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2079 auto AI = FnArgs[FirstIRArg + i];
2080 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2081 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2082 Address EltPtr =
2083 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2084 Builder.CreateStore(AI, EltPtr);
2085 }
2086
2087 if (SrcSize > DstSize) {
2088 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2089 }
2090
Chris Lattner15ec3612010-06-29 00:06:42 +00002091 } else {
2092 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002093 assert(NumIRArgs == 1);
2094 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002095 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002096 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002097 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002098
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002099 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002100 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002101 llvm::Value *V =
2102 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002103 if (isPromoted)
2104 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002105 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002106 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002107 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002108 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002109 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002110 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002111
2112 case ABIArgInfo::Expand: {
2113 // If this structure was expanded into multiple arguments then
2114 // we need to create a temporary and reconstruct it from the
2115 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002116 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2117 LValue LV = MakeAddrLValue(Alloca, Ty);
2118 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002119
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002120 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2121 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2122 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2123 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2124 auto AI = FnArgs[FirstIRArg + i];
2125 AI->setName(Arg->getName() + "." + Twine(i));
2126 }
2127 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002128 }
2129
2130 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002131 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002132 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002133 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002134 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002135 } else {
2136 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002137 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002138 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002139 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002140 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002141 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002142
Reid Kleckner739756c2013-12-04 19:23:12 +00002143 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2144 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002145 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002146 } else {
2147 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002148 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002149 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002150}
2151
John McCallffa2c1a2012-01-29 07:46:59 +00002152static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2153 while (insn->use_empty()) {
2154 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2155 if (!bitcast) return;
2156
2157 // This is "safe" because we would have used a ConstantExpr otherwise.
2158 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2159 bitcast->eraseFromParent();
2160 }
2161}
2162
John McCall31168b02011-06-15 23:02:42 +00002163/// Try to emit a fused autorelease of a return result.
2164static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2165 llvm::Value *result) {
2166 // We must be immediately followed the cast.
2167 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002168 if (BB->empty()) return nullptr;
2169 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002170
Chris Lattner2192fe52011-07-18 04:24:23 +00002171 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002172
2173 // result is in a BasicBlock and is therefore an Instruction.
2174 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2175
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002176 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002177
2178 // Look for:
2179 // %generator = bitcast %type1* %generator2 to %type2*
2180 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2181 // We would have emitted this as a constant if the operand weren't
2182 // an Instruction.
2183 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2184
2185 // Require the generator to be immediately followed by the cast.
2186 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002187 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002188
2189 insnsToKill.push_back(bitcast);
2190 }
2191
2192 // Look for:
2193 // %generator = call i8* @objc_retain(i8* %originalResult)
2194 // or
2195 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2196 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002197 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002198
2199 bool doRetainAutorelease;
2200
John McCallb04ecb72015-10-21 18:06:43 +00002201 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002202 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002203 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002204 .objc_retainAutoreleasedReturnValue) {
2205 doRetainAutorelease = false;
2206
John McCallcfa4e9b2012-09-07 23:30:50 +00002207 // If we emitted an assembly marker for this call (and the
2208 // ARCEntrypoints field should have been set if so), go looking
2209 // for that call. If we can't find it, we can't do this
2210 // optimization. But it should always be the immediately previous
2211 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002212 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002213 llvm::Instruction *prev = call->getPrevNode();
2214 assert(prev);
2215 if (isa<llvm::BitCastInst>(prev)) {
2216 prev = prev->getPrevNode();
2217 assert(prev);
2218 }
2219 assert(isa<llvm::CallInst>(prev));
2220 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002221 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002222 insnsToKill.push_back(prev);
2223 }
John McCall31168b02011-06-15 23:02:42 +00002224 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002225 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002226 }
2227
2228 result = call->getArgOperand(0);
2229 insnsToKill.push_back(call);
2230
2231 // Keep killing bitcasts, for sanity. Note that we no longer care
2232 // about precise ordering as long as there's exactly one use.
2233 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2234 if (!bitcast->hasOneUse()) break;
2235 insnsToKill.push_back(bitcast);
2236 result = bitcast->getOperand(0);
2237 }
2238
2239 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002240 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002241 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2242 (*i)->eraseFromParent();
2243
2244 // Do the fused retain/autorelease if we were asked to.
2245 if (doRetainAutorelease)
2246 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2247
2248 // Cast back to the result type.
2249 return CGF.Builder.CreateBitCast(result, resultType);
2250}
2251
John McCallffa2c1a2012-01-29 07:46:59 +00002252/// If this is a +1 of the value of an immutable 'self', remove it.
2253static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2254 llvm::Value *result) {
2255 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002256 const ObjCMethodDecl *method =
2257 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002258 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002259 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002260 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002261
2262 // Look for a retain call.
2263 llvm::CallInst *retainCall =
2264 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2265 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002266 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002267 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002268
2269 // Look for an ordinary load of 'self'.
2270 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2271 llvm::LoadInst *load =
2272 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2273 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002274 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002275 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002276
2277 // Okay! Burn it all down. This relies for correctness on the
2278 // assumption that the retain is emitted as part of the return and
2279 // that thereafter everything is used "linearly".
2280 llvm::Type *resultType = result->getType();
2281 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2282 assert(retainCall->use_empty());
2283 retainCall->eraseFromParent();
2284 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2285
2286 return CGF.Builder.CreateBitCast(load, resultType);
2287}
2288
John McCall31168b02011-06-15 23:02:42 +00002289/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002290///
2291/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002292static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2293 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002294 // If we're returning 'self', kill the initial retain. This is a
2295 // heuristic attempt to "encourage correctness" in the really unfortunate
2296 // case where we have a return of self during a dealloc and we desperately
2297 // need to avoid the possible autorelease.
2298 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2299 return self;
2300
John McCall31168b02011-06-15 23:02:42 +00002301 // At -O0, try to emit a fused retain/autorelease.
2302 if (CGF.shouldUseFusedARCCalls())
2303 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2304 return fused;
2305
2306 return CGF.EmitARCAutoreleaseReturnValue(result);
2307}
2308
John McCall6e1c0122012-01-29 02:35:02 +00002309/// Heuristically search for a dominating store to the return-value slot.
2310static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002311 // Check if a User is a store which pointerOperand is the ReturnValue.
2312 // We are looking for stores to the ReturnValue, not for stores of the
2313 // ReturnValue to some other location.
2314 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2315 auto *SI = dyn_cast<llvm::StoreInst>(U);
2316 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2317 return nullptr;
2318 // These aren't actually possible for non-coerced returns, and we
2319 // only care about non-coerced returns on this code path.
2320 assert(!SI->isAtomic() && !SI->isVolatile());
2321 return SI;
2322 };
John McCall6e1c0122012-01-29 02:35:02 +00002323 // If there are multiple uses of the return-value slot, just check
2324 // for something immediately preceding the IP. Sometimes this can
2325 // happen with how we generate implicit-returns; it can also happen
2326 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002327 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002328 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002329 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002330 llvm::Instruction *I = &IP->back();
2331
2332 // Skip lifetime markers
2333 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2334 IE = IP->rend();
2335 II != IE; ++II) {
2336 if (llvm::IntrinsicInst *Intrinsic =
2337 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2338 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2339 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2340 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002341 if (II == IE)
2342 break;
2343 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2344 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002345 }
2346 }
2347 I = &*II;
2348 break;
2349 }
2350
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002351 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002352 }
2353
2354 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002355 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002356 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002357
John McCall6e1c0122012-01-29 02:35:02 +00002358 // Now do a first-and-dirty dominance check: just walk up the
2359 // single-predecessors chain from the current insertion point.
2360 llvm::BasicBlock *StoreBB = store->getParent();
2361 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2362 while (IP != StoreBB) {
2363 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002364 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002365 }
2366
2367 // Okay, the store's basic block dominates the insertion point; we
2368 // can do our thing.
2369 return store;
2370}
2371
Adrian Prantl3be10542013-05-02 17:30:20 +00002372void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002373 bool EmitRetDbgLoc,
2374 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002375 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2376 // Naked functions don't have epilogues.
2377 Builder.CreateUnreachable();
2378 return;
2379 }
2380
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002381 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002382 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002383 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002384 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002385 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002386
Dan Gohman481e40c2010-07-20 20:13:52 +00002387 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002388 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002389 QualType RetTy = FI.getReturnType();
2390 const ABIArgInfo &RetAI = FI.getReturnInfo();
2391
2392 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002393 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002394 // Aggregrates get evaluated directly into the destination. Sometimes we
2395 // need to return the sret value in a register, though.
2396 assert(hasAggregateEvaluationKind(RetTy));
2397 if (RetAI.getInAllocaSRet()) {
2398 llvm::Function::arg_iterator EI = CurFn->arg_end();
2399 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002400 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002401 llvm::Value *SRet = Builder.CreateStructGEP(
2402 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002403 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002404 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002405 break;
2406
Daniel Dunbar03816342010-08-21 02:24:36 +00002407 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002408 auto AI = CurFn->arg_begin();
2409 if (RetAI.isSRetAfterThis())
2410 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002411 switch (getEvaluationKind(RetTy)) {
2412 case TEK_Complex: {
2413 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002414 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002415 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002416 /*isInit*/ true);
2417 break;
2418 }
2419 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002420 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002421 break;
2422 case TEK_Scalar:
2423 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002424 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002425 /*isInit*/ true);
2426 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002427 }
2428 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002429 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002430
2431 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002432 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002433 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2434 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002435 // The internal return value temp always will have pointer-to-return-type
2436 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002437
John McCall6e1c0122012-01-29 02:35:02 +00002438 // If there is a dominating store to ReturnValue, we can elide
2439 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002440 if (llvm::StoreInst *SI =
2441 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002442 // Reuse the debug location from the store unless there is
2443 // cleanup code to be emitted between the store and return
2444 // instruction.
2445 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002446 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002447 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002448 RV = SI->getValueOperand();
2449 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002450
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002451 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002452 auto returnValueInst = ReturnValue.getPointer();
2453 if (returnValueInst->use_empty()) {
2454 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2455 alloca->eraseFromParent();
2456 ReturnValue = Address::invalid();
2457 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002458 }
John McCall6e1c0122012-01-29 02:35:02 +00002459
2460 // Otherwise, we have to do a simple load.
2461 } else {
2462 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002463 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002464 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002465 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002466 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002467
John McCall7f416cc2015-09-08 08:05:57 +00002468 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002469 }
John McCall31168b02011-06-15 23:02:42 +00002470
2471 // In ARC, end functions that return a retainable type with a call
2472 // to objc_autoreleaseReturnValue.
2473 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002474#ifndef NDEBUG
2475 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2476 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2477 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2478 // CurCodeDecl or BlockInfo.
2479 QualType RT;
2480
2481 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2482 RT = FD->getReturnType();
2483 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2484 RT = MD->getReturnType();
2485 else if (isa<BlockDecl>(CurCodeDecl))
2486 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2487 else
2488 llvm_unreachable("Unexpected function/method type");
2489
David Blaikiebbafb8a2012-03-11 07:00:24 +00002490 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002491 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002492 RT->isObjCRetainableType());
2493#endif
John McCall31168b02011-06-15 23:02:42 +00002494 RV = emitAutoreleaseOfResult(*this, RV);
2495 }
2496
Chris Lattner726b3d02010-06-26 23:13:19 +00002497 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002498
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002499 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002500 break;
2501
2502 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002503 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002504 }
2505
Alexey Samsonovde443c52014-08-13 00:26:40 +00002506 llvm::Instruction *Ret;
2507 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002508 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2509 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002510 SanitizerScope SanScope(this);
2511 llvm::Value *Cond = Builder.CreateICmpNE(
2512 RV, llvm::Constant::getNullValue(RV->getType()));
2513 llvm::Constant *StaticData[] = {
2514 EmitCheckSourceLocation(EndLoc),
2515 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2516 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002517 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2518 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002519 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002520 }
2521 Ret = Builder.CreateRet(RV);
2522 } else {
2523 Ret = Builder.CreateRetVoid();
2524 }
2525
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002526 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002527 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002528}
2529
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002530static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2531 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2532 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2533}
2534
John McCall7f416cc2015-09-08 08:05:57 +00002535static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2536 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002537 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2538 // placeholders.
2539 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2540 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002541 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2542 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2543
2544 // FIXME: When we generate this IR in one pass, we shouldn't need
2545 // this win32-specific alignment hack.
2546 CharUnits Align = CharUnits::fromQuantity(4);
2547
2548 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002549 Ty.getQualifiers(),
2550 AggValueSlot::IsNotDestructed,
2551 AggValueSlot::DoesNotNeedGCBarriers,
2552 AggValueSlot::IsNotAliased);
2553}
2554
John McCall32ea9692011-03-11 20:59:21 +00002555void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002556 const VarDecl *param,
2557 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002558 // StartFunction converted the ABI-lowered parameter(s) into a
2559 // local alloca. We need to turn that into an r-value suitable
2560 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002561 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002562
John McCall32ea9692011-03-11 20:59:21 +00002563 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002564
John McCall23f66262010-05-26 22:34:26 +00002565 // For the most part, we just need to load the alloca, except:
2566 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002567 // 2) references to non-scalars are pointers directly to the aggregate.
2568 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002569 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002570 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002571 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002572
2573 // Locals which are references to scalars are represented
2574 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002575 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002576 }
2577
Reid Klecknerab2090d2014-07-26 01:34:32 +00002578 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2579 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002580
Nick Lewycky2d84e842013-10-02 02:29:49 +00002581 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002582}
2583
John McCall31168b02011-06-15 23:02:42 +00002584static bool isProvablyNull(llvm::Value *addr) {
2585 return isa<llvm::ConstantPointerNull>(addr);
2586}
2587
2588static bool isProvablyNonNull(llvm::Value *addr) {
2589 return isa<llvm::AllocaInst>(addr);
2590}
2591
2592/// Emit the actual writing-back of a writeback.
2593static void emitWriteback(CodeGenFunction &CGF,
2594 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002595 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002596 Address srcAddr = srcLV.getAddress();
2597 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002598 "shouldn't have writeback for provably null argument");
2599
Craig Topper8a13c412014-05-21 05:09:00 +00002600 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002601
2602 // If the argument wasn't provably non-null, we need to null check
2603 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002604 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002605 if (!provablyNonNull) {
2606 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2607 contBB = CGF.createBasicBlock("icr.done");
2608
John McCall7f416cc2015-09-08 08:05:57 +00002609 llvm::Value *isNull =
2610 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002611 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2612 CGF.EmitBlock(writebackBB);
2613 }
2614
2615 // Load the value to writeback.
2616 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2617
2618 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002619 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2620 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002621
2622 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002623
2624 // If we have a "to use" value, it's something we need to emit a use
2625 // of. This has to be carefully threaded in: if it's done after the
2626 // release it's potentially undefined behavior (and the optimizer
2627 // will ignore it), and if it happens before the retain then the
2628 // optimizer could move the release there.
2629 if (writeback.ToUse) {
2630 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2631
2632 // Retain the new value. No need to block-copy here: the block's
2633 // being passed up the stack.
2634 value = CGF.EmitARCRetainNonBlock(value);
2635
2636 // Emit the intrinsic use here.
2637 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2638
2639 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002640 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002641
2642 // Put the new value in place (primitively).
2643 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2644
2645 // Release the old value.
2646 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2647
2648 // Otherwise, we can just do a normal lvalue store.
2649 } else {
2650 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2651 }
John McCall31168b02011-06-15 23:02:42 +00002652
2653 // Jump to the continuation block.
2654 if (!provablyNonNull)
2655 CGF.EmitBlock(contBB);
2656}
2657
2658static void emitWritebacks(CodeGenFunction &CGF,
2659 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002660 for (const auto &I : args.writebacks())
2661 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002662}
2663
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002664static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2665 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002666 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002667 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2668 CallArgs.getCleanupsToDeactivate();
2669 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002670 for (const auto &I : llvm::reverse(Cleanups)) {
2671 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2672 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002673 }
2674}
2675
John McCalleff18842013-03-23 02:35:54 +00002676static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2677 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2678 if (uop->getOpcode() == UO_AddrOf)
2679 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002680 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002681}
2682
John McCall31168b02011-06-15 23:02:42 +00002683/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002684/// we are passing the address of an __autoreleased temporary; it
2685/// might be copy-initialized with the current value of the given
2686/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002687static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2688 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002689 LValue srcLV;
2690
2691 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002692 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002693 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2694 srcLV = CGF.EmitLValue(lvExpr);
2695
2696 // Otherwise, just emit it as a scalar.
2697 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002698 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002699
2700 QualType srcAddrType =
2701 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002702 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00002703 }
John McCall7f416cc2015-09-08 08:05:57 +00002704 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002705
2706 // The dest and src types don't necessarily match in LLVM terms
2707 // because of the crazy ObjC compatibility rules.
2708
Chris Lattner2192fe52011-07-18 04:24:23 +00002709 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002710 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2711
2712 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00002713 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00002714 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2715 CRE->getType());
2716 return;
2717 }
2718
John McCall31168b02011-06-15 23:02:42 +00002719 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00002720 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
2721 CGF.getPointerAlign(),
2722 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002723 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2724 // and that cleanup will be conditional if we can't prove that the l-value
2725 // isn't null, so we need to register a dominating point so that the cleanups
2726 // system will make valid IR.
2727 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2728
John McCall31168b02011-06-15 23:02:42 +00002729 // Zero-initialize it if we're not doing a copy-initialization.
2730 bool shouldCopy = CRE->shouldCopy();
2731 if (!shouldCopy) {
2732 llvm::Value *null =
2733 llvm::ConstantPointerNull::get(
2734 cast<llvm::PointerType>(destType->getElementType()));
2735 CGF.Builder.CreateStore(null, temp);
2736 }
Craig Topper8a13c412014-05-21 05:09:00 +00002737
2738 llvm::BasicBlock *contBB = nullptr;
2739 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002740
2741 // If the address is *not* known to be non-null, we need to switch.
2742 llvm::Value *finalArgument;
2743
John McCall7f416cc2015-09-08 08:05:57 +00002744 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002745 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00002746 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00002747 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002748 llvm::Value *isNull =
2749 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002750
2751 finalArgument = CGF.Builder.CreateSelect(isNull,
2752 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00002753 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00002754
2755 // If we need to copy, then the load has to be conditional, which
2756 // means we need control flow.
2757 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002758 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002759 contBB = CGF.createBasicBlock("icr.cont");
2760 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2761 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2762 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002763 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002764 }
2765 }
2766
Craig Topper8a13c412014-05-21 05:09:00 +00002767 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002768
John McCall31168b02011-06-15 23:02:42 +00002769 // Perform a copy if necessary.
2770 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002771 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002772 assert(srcRV.isScalar());
2773
2774 llvm::Value *src = srcRV.getScalarVal();
2775 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2776 "icr.cast");
2777
2778 // Use an ordinary store, not a store-to-lvalue.
2779 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002780
2781 // If optimization is enabled, and the value was held in a
2782 // __strong variable, we need to tell the optimizer that this
2783 // value has to stay alive until we're doing the store back.
2784 // This is because the temporary is effectively unretained,
2785 // and so otherwise we can violate the high-level semantics.
2786 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2787 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2788 valueToUse = src;
2789 }
John McCall31168b02011-06-15 23:02:42 +00002790 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002791
John McCall31168b02011-06-15 23:02:42 +00002792 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002793 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002794 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002795 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002796
2797 // Make a phi for the value to intrinsically use.
2798 if (valueToUse) {
2799 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2800 "icr.to-use");
2801 phiToUse->addIncoming(valueToUse, copyBB);
2802 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2803 originBB);
2804 valueToUse = phiToUse;
2805 }
2806
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002807 condEval.end(CGF);
2808 }
John McCall31168b02011-06-15 23:02:42 +00002809
John McCalleff18842013-03-23 02:35:54 +00002810 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002811 args.add(RValue::get(finalArgument), CRE->getType());
2812}
2813
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002814void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2815 assert(!StackBase && !StackCleanup.isValid());
2816
2817 // Save the stack.
2818 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00002819 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002820}
2821
Nico Weber8cdb3f92015-08-25 18:43:32 +00002822void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2823 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00002824 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00002825 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00002826 CGF.Builder.CreateCall(F, StackBase);
2827 }
2828}
2829
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002830void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
2831 SourceLocation ArgLoc,
2832 const FunctionDecl *FD,
2833 unsigned ParmNum) {
2834 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002835 return;
2836 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2837 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2838 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2839 if (!NNAttr)
2840 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002841 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002842 assert(RV.isScalar());
2843 llvm::Value *V = RV.getScalarVal();
2844 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002845 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002846 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002847 EmitCheckSourceLocation(ArgLoc),
2848 EmitCheckSourceLocation(NNAttr->getLocation()),
2849 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002850 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002851 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002852 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002853}
2854
David Blaikief05779e2015-07-21 18:37:18 +00002855void CodeGenFunction::EmitCallArgs(
2856 CallArgList &Args, ArrayRef<QualType> ArgTypes,
2857 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
2858 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
2859 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002860
2861 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
2862 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
2863 return;
2864 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
2865 if (PS == nullptr)
2866 return;
2867
2868 const auto &Context = getContext();
2869 auto SizeTy = Context.getSizeType();
2870 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
2871 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
2872 Args.add(RValue::get(V), SizeTy);
2873 };
2874
Reid Kleckner739756c2013-12-04 19:23:12 +00002875 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2876 // because arguments are destroyed left to right in the callee.
2877 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002878 // Insert a stack save if we're going to need any inalloca args.
2879 bool HasInAllocaArgs = false;
2880 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2881 I != E && !HasInAllocaArgs; ++I)
2882 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2883 if (HasInAllocaArgs) {
2884 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2885 Args.allocateArgumentMemory(*this);
2886 }
2887
2888 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002889 size_t CallArgsStart = Args.size();
2890 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00002891 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00002892 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002893 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002894 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002895 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00002896 }
2897
2898 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2899 // IR function.
2900 std::reverse(Args.begin() + CallArgsStart, Args.end());
2901 return;
2902 }
2903
2904 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00002905 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
2906 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00002907 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002908 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002909 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002910 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00002911 }
2912}
2913
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002914namespace {
2915
David Blaikie7e70d682015-08-18 22:40:54 +00002916struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00002917 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002918 : Addr(Addr), Ty(Ty) {}
2919
John McCall7f416cc2015-09-08 08:05:57 +00002920 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002921 QualType Ty;
2922
Craig Topper4f12f102014-03-12 06:41:41 +00002923 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002924 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2925 assert(!Dtor->isTrivial());
2926 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2927 /*Delegating=*/false, Addr);
2928 }
2929};
2930
David Blaikie38b25912015-02-09 19:13:51 +00002931struct DisableDebugLocationUpdates {
2932 CodeGenFunction &CGF;
2933 bool disabledDebugInfo;
2934 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2935 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2936 CGF.disableDebugInfo();
2937 }
2938 ~DisableDebugLocationUpdates() {
2939 if (disabledDebugInfo)
2940 CGF.enableDebugInfo();
2941 }
2942};
2943
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002944} // end anonymous namespace
2945
John McCall32ea9692011-03-11 20:59:21 +00002946void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2947 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002948 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002949 if (const ObjCIndirectCopyRestoreExpr *CRE
2950 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002951 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002952 assert(getContext().hasSameType(E->getType(), type));
2953 return emitWritebackArg(*this, args, CRE);
2954 }
2955
John McCall0a76c0c2011-08-26 18:42:59 +00002956 assert(type->isReferenceType() == E->isGLValue() &&
2957 "reference binding to unmaterialized r-value!");
2958
John McCall17054bd62011-08-26 21:08:13 +00002959 if (E->isGLValue()) {
2960 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002961 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002964 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2965
2966 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2967 // However, we still have to push an EH-only cleanup in case we unwind before
2968 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002969 if (HasAggregateEvalKind &&
2970 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2971 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002972 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002973 AggValueSlot Slot;
2974 if (args.isUsingInAlloca())
2975 Slot = createPlaceholderSlot(*this, type);
2976 else
2977 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002978
2979 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2980 bool DestroyedInCallee =
2981 RD && RD->hasNonTrivialDestructor() &&
2982 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2983 if (DestroyedInCallee)
2984 Slot.setExternallyDestructed();
2985
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002986 EmitAggExpr(E, Slot);
2987 RValue RV = Slot.asRValue();
2988 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002989
Reid Klecknere39ee212014-05-03 00:33:28 +00002990 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002991 // Create a no-op GEP between the placeholder and the cleanup so we can
2992 // RAUW it successfully. It also serves as a marker of the first
2993 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00002994 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
2995 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002996 // This unreachable is a temporary marker which will be removed later.
2997 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2998 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002999 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003000 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003001 }
3002
3003 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003004 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3005 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3006 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003007 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3008 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3009 } else {
3010 // We can't represent a misaligned lvalue in the CallArgList, so copy
3011 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003012 Address tmp = CreateMemTemp(type);
3013 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003014 args.add(RValue::getAggregate(tmp), type);
3015 }
Eli Friedmandf968192011-05-26 00:10:27 +00003016 return;
3017 }
3018
John McCall32ea9692011-03-11 20:59:21 +00003019 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003020}
3021
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003022QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3023 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3024 // implicitly widens null pointer constants that are arguments to varargs
3025 // functions to pointer-sized ints.
3026 if (!getTarget().getTriple().isOSWindows())
3027 return Arg->getType();
3028
3029 if (Arg->getType()->isIntegerType() &&
3030 getContext().getTypeSize(Arg->getType()) <
3031 getContext().getTargetInfo().getPointerWidth(0) &&
3032 Arg->isNullPointerConstant(getContext(),
3033 Expr::NPC_ValueDependentIsNotNull)) {
3034 return getContext().getIntPtrType();
3035 }
3036
3037 return Arg->getType();
3038}
3039
Dan Gohman515a60d2012-02-16 00:57:37 +00003040// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3041// optimizer it can aggressively ignore unwind edges.
3042void
3043CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3044 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3045 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3046 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3047 CGM.getNoObjCARCExceptionsMetadata());
3048}
3049
John McCall882987f2013-02-28 19:01:20 +00003050/// Emits a call to the given no-arguments nounwind runtime function.
3051llvm::CallInst *
3052CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3053 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003054 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003055}
3056
3057/// Emits a call to the given nounwind runtime function.
3058llvm::CallInst *
3059CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3060 ArrayRef<llvm::Value*> args,
3061 const llvm::Twine &name) {
3062 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3063 call->setDoesNotThrow();
3064 return call;
3065}
3066
3067/// Emits a simple call (never an invoke) to the given no-arguments
3068/// runtime function.
3069llvm::CallInst *
3070CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3071 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003072 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003073}
3074
David Majnemer0b17d442015-12-15 21:27:59 +00003075// Calls which may throw must have operand bundles indicating which funclet
3076// they are nested within.
3077static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003078getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003079 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003080 // There is no need for a funclet operand bundle if we aren't inside a
3081 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003082 if (!CurrentFuncletPad)
3083 return;
3084
3085 // Skip intrinsics which cannot throw.
3086 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3087 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3088 return;
3089
3090 BundleList.emplace_back("funclet", CurrentFuncletPad);
3091}
3092
David Majnemer971d31b2016-02-24 17:02:45 +00003093/// Emits a simple call (never an invoke) to the given runtime function.
3094llvm::CallInst *
3095CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3096 ArrayRef<llvm::Value*> args,
3097 const llvm::Twine &name) {
3098 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3099 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3100
3101 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3102 call->setCallingConv(getRuntimeCC());
3103 return call;
3104}
3105
John McCall882987f2013-02-28 19:01:20 +00003106/// Emits a call or invoke to the given noreturn runtime function.
3107void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3108 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003109 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3110 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3111
John McCall882987f2013-02-28 19:01:20 +00003112 if (getInvokeDest()) {
3113 llvm::InvokeInst *invoke =
3114 Builder.CreateInvoke(callee,
3115 getUnreachableBlock(),
3116 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003117 args,
3118 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003119 invoke->setDoesNotReturn();
3120 invoke->setCallingConv(getRuntimeCC());
3121 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003122 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003123 call->setDoesNotReturn();
3124 call->setCallingConv(getRuntimeCC());
3125 Builder.CreateUnreachable();
3126 }
3127}
3128
Sanjay Patel846b63b2016-01-18 22:15:33 +00003129/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003130llvm::CallSite
3131CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3132 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003133 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003134}
3135
3136/// Emits a call or invoke instruction to the given runtime function.
3137llvm::CallSite
3138CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3139 ArrayRef<llvm::Value*> args,
3140 const Twine &name) {
3141 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3142 callSite.setCallingConv(getRuntimeCC());
3143 return callSite;
3144}
3145
John McCallbd309292010-07-06 01:34:17 +00003146/// Emits a call or invoke instruction to the given function, depending
3147/// on the current state of the EH stack.
3148llvm::CallSite
3149CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003150 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003152 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003153 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3154 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003155
Dan Gohman515a60d2012-02-16 00:57:37 +00003156 llvm::Instruction *Inst;
3157 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003158 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003159 else {
3160 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003161 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3162 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003163 EmitBlock(ContBB);
3164 }
3165
3166 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3167 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003168 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003169 AddObjCARCExceptionMetadata(Inst);
3170
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003171 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003172}
3173
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003174/// \brief Store a non-aggregate value to an address to initialize it. For
3175/// initialization, a non-atomic store will be used.
3176static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3177 LValue Dst) {
3178 if (Src.isScalar())
3179 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3180 else
3181 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3182}
3183
3184void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3185 llvm::Value *New) {
3186 DeferredReplacements.push_back(std::make_pair(Old, New));
3187}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003188
Daniel Dunbard931a872009-02-02 22:03:45 +00003189RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003190 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003191 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003192 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003193 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003194 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003195 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003196
3197 // Handle struct-return functions by passing a pointer to the
3198 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003199 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003200 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003201
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003202 llvm::FunctionType *IRFuncTy =
3203 cast<llvm::FunctionType>(
3204 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003205
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003206 // If we're using inalloca, insert the allocation after the stack save.
3207 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003208 Address ArgMemory = Address::invalid();
3209 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003210 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003211 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003212 llvm::Instruction *IP = CallArgs.getStackBase();
3213 llvm::AllocaInst *AI;
3214 if (IP) {
3215 IP = IP->getNextNode();
3216 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3217 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003218 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003219 }
John McCall7f416cc2015-09-08 08:05:57 +00003220 auto Align = CallInfo.getArgStructAlignment();
3221 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003222 AI->setUsedWithInAlloca(true);
3223 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003224 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003225 }
3226
John McCall7f416cc2015-09-08 08:05:57 +00003227 // Helper function to drill into the inalloca allocation.
3228 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3229 auto FieldOffset =
3230 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3231 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3232 };
3233
Alexey Samsonov153004f2014-09-29 22:08:00 +00003234 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003235 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3236
Chris Lattner4ca97c32009-06-13 00:26:38 +00003237 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003238 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003239 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003240 size_t UnusedReturnSize = 0;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003241 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003242 if (!ReturnValue.isNull()) {
3243 SRetPtr = ReturnValue.getValue();
3244 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003245 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003246 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3247 uint64_t size =
3248 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003249 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003250 UnusedReturnSize = size;
3251 }
3252 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003253 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003254 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003255 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003256 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3257 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003258 }
Anders Carlsson17490832009-12-24 20:40:36 +00003259 }
Mike Stump11289f42009-09-09 15:08:12 +00003260
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003261 assert(CallInfo.arg_size() == CallArgs.size() &&
3262 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003263 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003264 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003265 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003266 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003267 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003268 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003269
Rafael Espindolafad28de2012-10-24 01:59:00 +00003270 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003271 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3272 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3273 llvm::UndefValue::get(ArgInfo.getPaddingType());
3274
3275 unsigned FirstIRArg, NumIRArgs;
3276 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003277
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003278 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003279 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003280 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003281 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3282 if (RV.isAggregate()) {
3283 // Replace the placeholder with the appropriate argument slot GEP.
3284 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003285 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003286 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3287 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003288 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003289 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003290 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003291 } else {
3292 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003293 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3294 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003295 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3296 // There are some cases where a trivial bitcast is not avoidable. The
3297 // definition of a type later in a translation unit may change it's type
3298 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003299 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003300 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003301 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003302 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3303 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003304 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003305 }
3306
Daniel Dunbar03816342010-08-21 02:24:36 +00003307 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003308 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003309 if (RV.isScalar() || RV.isComplex()) {
3310 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003311 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3312 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003313
John McCall7f416cc2015-09-08 08:05:57 +00003314 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003315 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003316 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003317 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003318 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003319 // 1. If the argument is not byval, and we are required to copy the
3320 // source. (This case doesn't occur on any common architecture.)
3321 // 2. If the argument is byval, RV is not sufficiently aligned, and
3322 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003323 // 3. If the argument is byval, but RV is located in an address space
3324 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003325 Address Addr = RV.getAggregateAddress();
3326 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003327 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003328 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003329 const unsigned ArgAddrSpace =
3330 (FirstIRArg < IRFuncTy->getNumParams()
3331 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3332 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003333 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003334 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3335 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3336 Align.getQuantity(), *TD)
3337 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003338 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003339 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003340 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3341 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003342 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003343 } else {
3344 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003345 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003346 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003347 }
3348 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003349 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003350
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003351 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003352 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003353 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003354
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003355 case ABIArgInfo::Extend:
3356 case ABIArgInfo::Direct: {
3357 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003358 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3359 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003360 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003361 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003362 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003363 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003364 else
John McCall7f416cc2015-09-08 08:05:57 +00003365 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003366
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003367 // We might have to widen integers, but we should never truncate.
3368 if (ArgInfo.getCoerceToType() != V->getType() &&
3369 V->getType()->isIntegerTy())
3370 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3371
Chris Lattner3ce86682011-07-12 04:53:39 +00003372 // If the argument doesn't match, perform a bitcast to coerce it. This
3373 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003374 if (FirstIRArg < IRFuncTy->getNumParams() &&
3375 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3376 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3377 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003378 break;
3379 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003380
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003381 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003382 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003383 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003384 Src = CreateMemTemp(I->Ty, "coerce");
3385 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003386 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003387 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003388 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003389 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003390
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003391 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003392 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003393
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003394 // Fast-isel and the optimizer generally like scalar values better than
3395 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003396 llvm::StructType *STy =
3397 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003398 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003399 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003400 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3401 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3402
3403 // If the source type is smaller than the destination type of the
3404 // coerce-to logic, copy the source value into a temp alloca the size
3405 // of the destination type to allow loading all of it. The bits past
3406 // the source value are left undef.
3407 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003408 Address TempAlloca
3409 = CreateTempAlloca(STy, Src.getAlignment(),
3410 Src.getName() + ".coerce");
3411 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3412 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003413 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003414 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003415 }
3416
John McCall7f416cc2015-09-08 08:05:57 +00003417 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003418 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003419 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003420 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3421 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3422 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003423 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003424 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003425 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003426 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003427 assert(NumIRArgs == 1);
3428 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003429 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003430 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003431
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003432 break;
3433 }
3434
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003435 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003436 unsigned IRArgPos = FirstIRArg;
3437 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3438 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003439 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003440 }
3441 }
Mike Stump11289f42009-09-09 15:08:12 +00003442
John McCall7f416cc2015-09-08 08:05:57 +00003443 if (ArgMemory.isValid()) {
3444 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003445 if (CallInfo.isVariadic()) {
3446 // When passing non-POD arguments by value to variadic functions, we will
3447 // end up with a variadic prototype and an inalloca call site. In such
3448 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3449 // the callee.
3450 unsigned CalleeAS =
3451 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3452 Callee = Builder.CreateBitCast(
3453 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3454 } else {
3455 llvm::Type *LastParamTy =
3456 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3457 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003458#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003459 // Assert that these structs have equivalent element types.
3460 llvm::StructType *FullTy = CallInfo.getArgStruct();
3461 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3462 cast<llvm::PointerType>(LastParamTy)->getElementType());
3463 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3464 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3465 DE = DeclaredTy->element_end(),
3466 FI = FullTy->element_begin();
3467 DI != DE; ++DI, ++FI)
3468 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003469#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003470 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3471 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003472 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003473 assert(IRFunctionArgs.hasInallocaArg());
3474 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003475 }
3476
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003477 if (!CallArgs.getCleanupsToDeactivate().empty())
3478 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3479
Chris Lattner4ca97c32009-06-13 00:26:38 +00003480 // If the callee is a bitcast of a function to a varargs pointer to function
3481 // type, check to see if we can remove the bitcast. This handles some cases
3482 // with unprototyped functions.
3483 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3484 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003485 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3486 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003487 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003488 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003489
Chris Lattner4ca97c32009-06-13 00:26:38 +00003490 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3491 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003492 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003493 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003494 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003495 bool ArgsMatch = true;
3496 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3497 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3498 ArgsMatch = false;
3499 break;
3500 }
Mike Stump11289f42009-09-09 15:08:12 +00003501
Chris Lattner4ca97c32009-06-13 00:26:38 +00003502 // Strip the cast if we can get away with it. This is a nice cleanup,
3503 // but also allows us to inline the function at -O0 if it is marked
3504 // always_inline.
3505 if (ArgsMatch)
3506 Callee = CalleeF;
3507 }
3508 }
Mike Stump11289f42009-09-09 15:08:12 +00003509
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003510 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3511 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3512 // Inalloca argument can have different type.
3513 if (IRFunctionArgs.hasInallocaArg() &&
3514 i == IRFunctionArgs.getInallocaArgNo())
3515 continue;
3516 if (i < IRFuncTy->getNumParams())
3517 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3518 }
3519
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003520 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003521 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003522 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3523 AttributeList, CallingConv,
3524 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003525 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003526 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003527
David Majnemer4e52d6f2015-12-12 05:39:21 +00003528 bool CannotThrow;
3529 if (currentFunctionUsesSEHTry()) {
3530 // SEH cares about asynchronous exceptions, everything can "throw."
3531 CannotThrow = false;
3532 } else if (isCleanupPadScope() &&
3533 EHPersonality::get(*this).isMSVCXXPersonality()) {
3534 // The MSVC++ personality will implicitly terminate the program if an
3535 // exception is thrown. An unwind edge cannot be reached.
3536 CannotThrow = true;
3537 } else {
3538 // Otherwise, nowunind callsites will never throw.
3539 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3540 llvm::Attribute::NoUnwind);
3541 }
3542 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003543
David Majnemer0b17d442015-12-15 21:27:59 +00003544 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3545 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3546
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003547 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003548 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003549 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003550 } else {
3551 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003552 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3553 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003554 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003555 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003556 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003557 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003558
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003559 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3560 !CS.hasFnAttr(llvm::Attribute::NoInline))
3561 Attrs =
3562 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3563 llvm::Attribute::AlwaysInline);
3564
David Majnemer4e52d6f2015-12-12 05:39:21 +00003565 // Disable inlining inside SEH __try blocks.
3566 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003567 Attrs =
3568 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3569 llvm::Attribute::NoInline);
3570
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003571 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003572 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003573
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003574 // Insert instrumentation or attach profile metadata at indirect call sites
3575 if (!CS.getCalledFunction())
3576 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3577 CS.getInstruction(), Callee);
3578
Dan Gohman515a60d2012-02-16 00:57:37 +00003579 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3580 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003582 AddObjCARCExceptionMetadata(CS.getInstruction());
3583
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003584 // If the call doesn't return, finish the basic block and clear the
3585 // insertion point; this allows the rest of IRgen to discard
3586 // unreachable code.
3587 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003588 if (UnusedReturnSize)
3589 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003590 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003591
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003592 Builder.CreateUnreachable();
3593 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003594
Mike Stump18bb9282009-05-16 07:57:57 +00003595 // FIXME: For now, emit a dummy basic block because expr emitters in
3596 // generally are not ready to handle emitting expressions at unreachable
3597 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003598 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003599
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003600 // Return a reasonable RValue.
3601 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003602 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003603
3604 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003605 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003606 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003607
John McCall31168b02011-06-15 23:02:42 +00003608 // Emit any writebacks immediately. Arguably this should happen
3609 // after any return-value munging.
3610 if (CallArgs.hasWritebacks())
3611 emitWritebacks(*this, CallArgs);
3612
Nico Weber8cdb3f92015-08-25 18:43:32 +00003613 // The stack cleanup for inalloca arguments has to run out of the normal
3614 // lexical order, so deactivate it and run it manually here.
3615 CallArgs.freeArgumentMemory(*this);
3616
Samuel Antao798f11c2015-11-23 22:04:44 +00003617 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3618 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003619 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3620 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003621 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003622
Hal Finkelee90a222014-09-26 05:04:30 +00003623 RValue Ret = [&] {
3624 switch (RetAI.getKind()) {
3625 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003626 case ABIArgInfo::Indirect: {
3627 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3628 if (UnusedReturnSize)
3629 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003630 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003631 return ret;
3632 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003633
Hal Finkelee90a222014-09-26 05:04:30 +00003634 case ABIArgInfo::Ignore:
3635 // If we are ignoring an argument that had a result, make sure to
3636 // construct the appropriate return value for our caller.
3637 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003638
Hal Finkelee90a222014-09-26 05:04:30 +00003639 case ABIArgInfo::Extend:
3640 case ABIArgInfo::Direct: {
3641 llvm::Type *RetIRTy = ConvertType(RetTy);
3642 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3643 switch (getEvaluationKind(RetTy)) {
3644 case TEK_Complex: {
3645 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3646 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3647 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003648 }
Hal Finkelee90a222014-09-26 05:04:30 +00003649 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00003650 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003651 bool DestIsVolatile = ReturnValue.isVolatile();
3652
John McCall7f416cc2015-09-08 08:05:57 +00003653 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003654 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3655 DestIsVolatile = false;
3656 }
John McCall7f416cc2015-09-08 08:05:57 +00003657 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00003658 return RValue::getAggregate(DestPtr);
3659 }
3660 case TEK_Scalar: {
3661 // If the argument doesn't match, perform a bitcast to coerce it. This
3662 // can happen due to trivial type mismatches.
3663 llvm::Value *V = CI;
3664 if (V->getType() != RetIRTy)
3665 V = Builder.CreateBitCast(V, RetIRTy);
3666 return RValue::get(V);
3667 }
3668 }
3669 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003670 }
Hal Finkelee90a222014-09-26 05:04:30 +00003671
John McCall7f416cc2015-09-08 08:05:57 +00003672 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003673 bool DestIsVolatile = ReturnValue.isVolatile();
3674
John McCall7f416cc2015-09-08 08:05:57 +00003675 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003676 DestPtr = CreateMemTemp(RetTy, "coerce");
3677 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003678 }
Hal Finkelee90a222014-09-26 05:04:30 +00003679
3680 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003681 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
3682 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00003683
3684 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003685 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003686
Hal Finkelee90a222014-09-26 05:04:30 +00003687 case ABIArgInfo::Expand:
3688 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003689 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003690
Hal Finkelee90a222014-09-26 05:04:30 +00003691 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3692 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003693
Samuel Antao798f11c2015-11-23 22:04:44 +00003694 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3695
Hal Finkelee90a222014-09-26 05:04:30 +00003696 if (Ret.isScalar() && TargetDecl) {
3697 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3698 llvm::Value *OffsetValue = nullptr;
3699 if (const auto *Offset = AA->getOffset())
3700 OffsetValue = EmitScalarExpr(Offset);
3701
3702 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3703 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3704 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3705 OffsetValue);
3706 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003707 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003708
Hal Finkelee90a222014-09-26 05:04:30 +00003709 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003710}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003711
3712/* VarArg handling */
3713
Charles Davisc7d5c942015-09-17 20:55:33 +00003714Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
3715 VAListAddr = VE->isMicrosoftABI()
3716 ? EmitMSVAListRef(VE->getSubExpr())
3717 : EmitVAListRef(VE->getSubExpr());
3718 QualType Ty = VE->getType();
3719 if (VE->isMicrosoftABI())
3720 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003721 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003722}