blob: f118a739fb434afbdc0316e894670598e100950e [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000024#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000026#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000027#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000028#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000030#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000033#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000034#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000035#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000036using namespace clang;
37using namespace CodeGen;
38
39/***/
40
John McCallab26cfa2010-02-05 21:31:56 +000041static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
42 switch (CC) {
43 default: return llvm::CallingConv::C;
44 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
45 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000046 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000047 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
48 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000049 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
50 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000051 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000052 // TODO: Add support for __pascal to LLVM.
53 case CC_X86Pascal: return llvm::CallingConv::C;
54 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000055 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000056 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
57 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000058 }
59}
60
John McCall8ee376f2010-02-24 07:14:12 +000061/// Derives the 'this' type for codegen purposes, i.e. ignoring method
62/// qualification.
63/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000064static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
65 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
66 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000067}
68
John McCall8ee376f2010-02-24 07:14:12 +000069/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000070static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
71 return MD->getType()->getCanonicalTypeUnqualified()
72 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000073}
74
75/// Returns the "extra-canonicalized" return type, which discards
76/// qualifiers on the return type. Codegen doesn't care about them,
77/// and it makes ABI code a little easier to be able to assume that
78/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000079static CanQualType GetReturnType(QualType RetTy) {
80 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000081}
82
John McCall8dda7b22012-07-07 06:41:13 +000083/// Arrange the argument and result information for a value of the given
84/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000085const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000086CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000087 // When translating an unprototyped function type, always use a
88 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000089 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000090 /*instanceMethod=*/false,
91 /*chainCall=*/false, None,
92 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000093}
94
John McCall8dda7b22012-07-07 06:41:13 +000095/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000096/// type, on top of any implicit parameters already stored.
97static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +000098arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000099 SmallVectorImpl<CanQualType> &prefix,
100 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +0000101 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000102 // FIXME: Kill copy.
Benjamin Kramerf9890422015-02-17 16:48:30 +0000103 prefix.append(FTP->param_type_begin(), FTP->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +0000104 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000105 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
106 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000107 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000108}
109
John McCalla729c622012-02-17 03:33:10 +0000110/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000111/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000112const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000113CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000114 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000115 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
116 FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117}
118
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000119static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000120 // Set the appropriate calling convention for the Function.
121 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000122 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000123
124 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000125 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000126
Douglas Gregora941dca2010-05-18 16:57:00 +0000127 if (D->hasAttr<ThisCallAttr>())
128 return CC_X86ThisCall;
129
Reid Klecknerd7857f02014-10-24 17:42:17 +0000130 if (D->hasAttr<VectorCallAttr>())
131 return CC_X86VectorCall;
132
Dawn Perchik335e16b2010-09-03 01:29:35 +0000133 if (D->hasAttr<PascalAttr>())
134 return CC_X86Pascal;
135
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000136 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
137 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
138
Guy Benyeif0a014b2012-12-25 08:53:55 +0000139 if (D->hasAttr<IntelOclBiccAttr>())
140 return CC_IntelOclBicc;
141
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000142 if (D->hasAttr<MSABIAttr>())
143 return IsWindows ? CC_C : CC_X86_64Win64;
144
145 if (D->hasAttr<SysVABIAttr>())
146 return IsWindows ? CC_X86_64SysV : CC_C;
147
John McCallab26cfa2010-02-05 21:31:56 +0000148 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000149}
150
John McCalla729c622012-02-17 03:33:10 +0000151/// Arrange the argument and result information for a call to an
152/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000153/// (Zero value of RD means we don't have any meaningful "this" argument type,
154/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000155/// The member function must be an ordinary function, i.e. not a
156/// constructor or destructor.
157const CGFunctionInfo &
158CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
159 const FunctionProtoType *FTP) {
160 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000161
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000162 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000163 if (RD)
164 argTypes.push_back(GetThisType(Context, RD));
165 else
166 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000167
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000168 return ::arrangeLLVMFunctionInfo(
169 *this, true, argTypes,
170 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171}
172
John McCalla729c622012-02-17 03:33:10 +0000173/// Arrange the argument and result information for a declaration or
174/// definition of the given C++ non-static member function. The
175/// member function must be an ordinary function, i.e. not a
176/// constructor or destructor.
177const CGFunctionInfo &
178CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000179 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000180 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
181
John McCalla729c622012-02-17 03:33:10 +0000182 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalla729c622012-02-17 03:33:10 +0000184 if (MD->isInstance()) {
185 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000186 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000187 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000188 }
189
John McCall8dda7b22012-07-07 06:41:13 +0000190 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000191}
192
John McCalla729c622012-02-17 03:33:10 +0000193const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000194CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
195 StructorType Type) {
196
John McCalla729c622012-02-17 03:33:10 +0000197 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000198 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000199
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000200 GlobalDecl GD;
201 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
202 GD = GlobalDecl(CD, toCXXCtorType(Type));
203 } else {
204 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
205 GD = GlobalDecl(DD, toCXXDtorType(Type));
206 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000207
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000208 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000209
210 // Add the formal parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +0000211 argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
John McCall5d865c322010-08-31 07:33:07 +0000212
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000213 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000214
215 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000216 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000217
John McCall8dda7b22012-07-07 06:41:13 +0000218 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000219 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
220 ? argTypes.front()
221 : TheCXXABI.hasMostDerivedReturn(GD)
222 ? CGM.getContext().VoidPtrTy
223 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
225 /*chainCall=*/false, argTypes, extInfo,
226 required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000227}
228
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000229/// Arrange a call to a C++ method, passing the given arguments.
230const CGFunctionInfo &
231CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
232 const CXXConstructorDecl *D,
233 CXXCtorType CtorKind,
234 unsigned ExtraArgs) {
235 // FIXME: Kill copy.
236 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000237 for (const auto &Arg : args)
238 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000239
240 CanQual<FunctionProtoType> FPT = GetFormalType(D);
241 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
242 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000243 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
244 ? ArgTypes.front()
245 : TheCXXABI.hasMostDerivedReturn(GD)
246 ? CGM.getContext().VoidPtrTy
247 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000248
249 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000250 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
251 /*chainCall=*/false, ArgTypes, Info,
252 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000253}
254
John McCalla729c622012-02-17 03:33:10 +0000255/// Arrange the argument and result information for the declaration or
256/// definition of the given function.
257const CGFunctionInfo &
258CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000259 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000260 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000261 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000262
John McCall2da83a32010-02-26 00:48:12 +0000263 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000264
John McCall2da83a32010-02-26 00:48:12 +0000265 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000266
267 // When declaring a function without a prototype, always use a
268 // non-variadic type.
269 if (isa<FunctionNoProtoType>(FTy)) {
270 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000271 return arrangeLLVMFunctionInfo(
272 noProto->getReturnType(), /*instanceMethod=*/false,
273 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000274 }
275
John McCall2da83a32010-02-26 00:48:12 +0000276 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000277 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000278}
279
John McCalla729c622012-02-17 03:33:10 +0000280/// Arrange the argument and result information for the declaration or
281/// definition of an Objective-C method.
282const CGFunctionInfo &
283CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
284 // It happens that this is the same as a call with no optional
285 // arguments, except also using the formal 'self' type.
286 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
287}
288
289/// Arrange the argument and result information for the function type
290/// through which to perform a send to the given Objective-C method,
291/// using the given receiver type. The receiver type is not always
292/// the 'self' type of the method or even an Objective-C pointer type.
293/// This is *not* the right method for actually performing such a
294/// message send, due to the possibility of optional arguments.
295const CGFunctionInfo &
296CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
297 QualType receiverType) {
298 SmallVector<CanQualType, 16> argTys;
299 argTys.push_back(Context.getCanonicalParamType(receiverType));
300 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000301 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000302 for (const auto *I : MD->params()) {
303 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000304 }
John McCall31168b02011-06-15 23:02:42 +0000305
306 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000307 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
308 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000309
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000311 MD->hasAttr<NSReturnsRetainedAttr>())
312 einfo = einfo.withProducesResult(true);
313
John McCalla729c622012-02-17 03:33:10 +0000314 RequiredArgs required =
315 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
316
Peter Collingbournef7706832014-12-12 23:41:25 +0000317 return arrangeLLVMFunctionInfo(
318 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
319 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000320}
321
John McCalla729c622012-02-17 03:33:10 +0000322const CGFunctionInfo &
323CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000324 // FIXME: Do we need to handle ObjCMethodDecl?
325 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000326
Anders Carlsson6710c532010-02-06 02:44:09 +0000327 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000328 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000329
330 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000331 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000332
John McCalla729c622012-02-17 03:33:10 +0000333 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000334}
335
Reid Klecknerc3473512014-08-29 21:43:29 +0000336/// Arrange a thunk that takes 'this' as the first parameter followed by
337/// varargs. Return a void pointer, regardless of the actual return type.
338/// The body of the thunk will end in a musttail call to a function of the
339/// correct type, and the caller will bitcast the function to the correct
340/// prototype.
341const CGFunctionInfo &
342CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
343 assert(MD->isVirtual() && "only virtual memptrs have thunks");
344 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
345 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000346 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
347 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000348 FTP->getExtInfo(), RequiredArgs(1));
349}
350
David Majnemerdfa6d202015-03-11 18:36:39 +0000351const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000352CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
353 CXXCtorType CT) {
354 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
355
David Majnemerdfa6d202015-03-11 18:36:39 +0000356 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
357 SmallVector<CanQualType, 2> ArgTys;
358 const CXXRecordDecl *RD = CD->getParent();
359 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000360 if (CT == Ctor_CopyingClosure)
361 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000362 if (RD->getNumVBases() > 0)
363 ArgTys.push_back(Context.IntTy);
364 CallingConv CC = Context.getDefaultCallingConvention(
365 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
366 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
367 /*chainCall=*/false, ArgTys,
368 FunctionType::ExtInfo(CC), RequiredArgs::All);
369}
370
John McCallc818bbb2012-12-07 07:03:17 +0000371/// Arrange a call as unto a free function, except possibly with an
372/// additional number of formal parameters considered required.
373static const CGFunctionInfo &
374arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000375 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000376 const CallArgList &args,
377 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000378 unsigned numExtraRequiredArgs,
379 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000380 assert(args.size() >= numExtraRequiredArgs);
381
382 // In most cases, there are no optional arguments.
383 RequiredArgs required = RequiredArgs::All;
384
385 // If we have a variadic prototype, the required arguments are the
386 // extra prefix plus the arguments in the prototype.
387 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
388 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000389 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000390
391 // If we don't have a prototype at all, but we're supposed to
392 // explicitly use the variadic convention for unprototyped calls,
393 // treat all of the arguments as required but preserve the nominal
394 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000395 } else if (CGM.getTargetCodeGenInfo()
396 .isNoProtoCallVariadic(args,
397 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000398 required = RequiredArgs(args.size());
399 }
400
Peter Collingbournef7706832014-12-12 23:41:25 +0000401 // FIXME: Kill copy.
402 SmallVector<CanQualType, 16> argTypes;
403 for (const auto &arg : args)
404 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
405 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
406 /*instanceMethod=*/false, chainCall,
407 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000408}
409
John McCalla729c622012-02-17 03:33:10 +0000410/// Figure out the rules for calling a function with the given formal
411/// type using the given arguments. The arguments are necessary
412/// because the function might be unprototyped, in which case it's
413/// target-dependent in crazy ways.
414const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000415CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000416 const FunctionType *fnType,
417 bool chainCall) {
418 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
419 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000420}
John McCalla729c622012-02-17 03:33:10 +0000421
John McCallc818bbb2012-12-07 07:03:17 +0000422/// A block function call is essentially a free-function call with an
423/// extra implicit argument.
424const CGFunctionInfo &
425CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
426 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000427 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
428 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000429}
430
431const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000432CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
433 const CallArgList &args,
434 FunctionType::ExtInfo info,
435 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000436 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000437 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000438 for (const auto &Arg : args)
439 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000440 return arrangeLLVMFunctionInfo(
441 GetReturnType(resultType), /*instanceMethod=*/false,
442 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000443}
444
445/// Arrange a call to a C++ method, passing the given arguments.
446const CGFunctionInfo &
447CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
448 const FunctionProtoType *FPT,
449 RequiredArgs required) {
450 // FIXME: Kill copy.
451 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000452 for (const auto &Arg : args)
453 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000454
455 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000456 return arrangeLLVMFunctionInfo(
457 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
458 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000459}
460
Reid Kleckner4982b822014-01-31 22:54:50 +0000461const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
462 QualType resultType, const FunctionArgList &args,
463 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000464 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000465 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000466 for (auto Arg : args)
467 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000468
469 RequiredArgs required =
470 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000471 return arrangeLLVMFunctionInfo(
472 GetReturnType(resultType), /*instanceMethod=*/false,
473 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000474}
475
John McCalla729c622012-02-17 03:33:10 +0000476const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000477 return arrangeLLVMFunctionInfo(
478 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
479 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000480}
481
John McCalla729c622012-02-17 03:33:10 +0000482/// Arrange the argument and result information for an abstract value
483/// of a given function type. This is the method which all of the
484/// above functions ultimately defer to.
485const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000486CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000487 bool instanceMethod,
488 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000489 ArrayRef<CanQualType> argTypes,
490 FunctionType::ExtInfo info,
491 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000492 assert(std::all_of(argTypes.begin(), argTypes.end(),
493 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000494
John McCalla729c622012-02-17 03:33:10 +0000495 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000496
Daniel Dunbare0be8292009-02-03 00:07:12 +0000497 // Lookup or create unique function info.
498 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000499 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
500 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000501
Craig Topper8a13c412014-05-21 05:09:00 +0000502 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000503 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000504 if (FI)
505 return *FI;
506
John McCalla729c622012-02-17 03:33:10 +0000507 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000508 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
509 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000510 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000511
David Blaikie82e95a32014-11-19 07:49:47 +0000512 bool inserted = FunctionsBeingProcessed.insert(FI).second;
513 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000514 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000515
Daniel Dunbar313321e2009-02-03 05:31:23 +0000516 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000517 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000518
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000519 // Loop over all of the computed argument and return value info. If any of
520 // them are direct or extend without a specified coerce type, specify the
521 // default now.
John McCalla729c622012-02-17 03:33:10 +0000522 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000523 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000524 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000525
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000526 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000527 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000528 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000529
John McCalla729c622012-02-17 03:33:10 +0000530 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
531 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000532
Daniel Dunbare0be8292009-02-03 00:07:12 +0000533 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000534}
535
John McCalla729c622012-02-17 03:33:10 +0000536CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000537 bool instanceMethod,
538 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000539 const FunctionType::ExtInfo &info,
540 CanQualType resultType,
541 ArrayRef<CanQualType> argTypes,
542 RequiredArgs required) {
543 void *buffer = operator new(sizeof(CGFunctionInfo) +
544 sizeof(ArgInfo) * (argTypes.size() + 1));
545 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
546 FI->CallingConvention = llvmCC;
547 FI->EffectiveCallingConvention = llvmCC;
548 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000549 FI->InstanceMethod = instanceMethod;
550 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000551 FI->NoReturn = info.getNoReturn();
552 FI->ReturnsRetained = info.getProducesResult();
553 FI->Required = required;
554 FI->HasRegParm = info.getHasRegParm();
555 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000556 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000557 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000558 FI->NumArgs = argTypes.size();
559 FI->getArgsBuffer()[0].type = resultType;
560 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
561 FI->getArgsBuffer()[i + 1].type = argTypes[i];
562 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000563}
564
565/***/
566
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000567namespace {
568// ABIArgInfo::Expand implementation.
569
570// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
571struct TypeExpansion {
572 enum TypeExpansionKind {
573 // Elements of constant arrays are expanded recursively.
574 TEK_ConstantArray,
575 // Record fields are expanded recursively (but if record is a union, only
576 // the field with the largest size is expanded).
577 TEK_Record,
578 // For complex types, real and imaginary parts are expanded recursively.
579 TEK_Complex,
580 // All other types are not expandable.
581 TEK_None
582 };
583
584 const TypeExpansionKind Kind;
585
586 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000587 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000588};
589
590struct ConstantArrayExpansion : TypeExpansion {
591 QualType EltTy;
592 uint64_t NumElts;
593
594 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
595 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
596 static bool classof(const TypeExpansion *TE) {
597 return TE->Kind == TEK_ConstantArray;
598 }
599};
600
601struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000602 SmallVector<const CXXBaseSpecifier *, 1> Bases;
603
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000604 SmallVector<const FieldDecl *, 1> Fields;
605
Reid Klecknere9f6a712014-10-31 17:10:41 +0000606 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
607 SmallVector<const FieldDecl *, 1> &&Fields)
608 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000609 static bool classof(const TypeExpansion *TE) {
610 return TE->Kind == TEK_Record;
611 }
612};
613
614struct ComplexExpansion : TypeExpansion {
615 QualType EltTy;
616
617 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
618 static bool classof(const TypeExpansion *TE) {
619 return TE->Kind == TEK_Complex;
620 }
621};
622
623struct NoExpansion : TypeExpansion {
624 NoExpansion() : TypeExpansion(TEK_None) {}
625 static bool classof(const TypeExpansion *TE) {
626 return TE->Kind == TEK_None;
627 }
628};
629} // namespace
630
631static std::unique_ptr<TypeExpansion>
632getTypeExpansion(QualType Ty, const ASTContext &Context) {
633 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
634 return llvm::make_unique<ConstantArrayExpansion>(
635 AT->getElementType(), AT->getSize().getZExtValue());
636 }
637 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000638 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000639 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000640 const RecordDecl *RD = RT->getDecl();
641 assert(!RD->hasFlexibleArrayMember() &&
642 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000643 if (RD->isUnion()) {
644 // Unions can be here only in degenerative cases - all the fields are same
645 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000646 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000647 CharUnits UnionSize = CharUnits::Zero();
648
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000649 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000650 // Skip zero length bitfields.
651 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
652 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000653 assert(!FD->isBitField() &&
654 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000655 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000656 if (UnionSize < FieldSize) {
657 UnionSize = FieldSize;
658 LargestFD = FD;
659 }
660 }
661 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000662 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000663 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000664 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
665 assert(!CXXRD->isDynamicClass() &&
666 "cannot expand vtable pointers in dynamic classes");
667 for (const CXXBaseSpecifier &BS : CXXRD->bases())
668 Bases.push_back(&BS);
669 }
670
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000671 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000672 // Skip zero length bitfields.
673 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
674 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000675 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000676 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000677 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000678 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000679 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000680 return llvm::make_unique<RecordExpansion>(std::move(Bases),
681 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000682 }
683 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
684 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
685 }
686 return llvm::make_unique<NoExpansion>();
687}
688
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000689static int getExpansionSize(QualType Ty, const ASTContext &Context) {
690 auto Exp = getTypeExpansion(Ty, Context);
691 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
692 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
693 }
694 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
695 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000696 for (auto BS : RExp->Bases)
697 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000698 for (auto FD : RExp->Fields)
699 Res += getExpansionSize(FD->getType(), Context);
700 return Res;
701 }
702 if (isa<ComplexExpansion>(Exp.get()))
703 return 2;
704 assert(isa<NoExpansion>(Exp.get()));
705 return 1;
706}
707
Alexey Samsonov153004f2014-09-29 22:08:00 +0000708void
709CodeGenTypes::getExpandedTypes(QualType Ty,
710 SmallVectorImpl<llvm::Type *>::iterator &TI) {
711 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000712 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
713 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000714 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000715 }
716 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000717 for (auto BS : RExp->Bases)
718 getExpandedTypes(BS->getType(), TI);
719 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000720 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000721 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
722 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000723 *TI++ = EltTy;
724 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000725 } else {
726 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000727 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000728 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000729}
730
John McCall7f416cc2015-09-08 08:05:57 +0000731static void forConstantArrayExpansion(CodeGenFunction &CGF,
732 ConstantArrayExpansion *CAE,
733 Address BaseAddr,
734 llvm::function_ref<void(Address)> Fn) {
735 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
736 CharUnits EltAlign =
737 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
738
739 for (int i = 0, n = CAE->NumElts; i < n; i++) {
740 llvm::Value *EltAddr =
741 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
742 Fn(Address(EltAddr, EltAlign));
743 }
744}
745
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000746void CodeGenFunction::ExpandTypeFromArgs(
747 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000748 assert(LV.isSimple() &&
749 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000750
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000751 auto Exp = getTypeExpansion(Ty, getContext());
752 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000753 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
754 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000755 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
756 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000757 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000758 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000759 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000760 for (const CXXBaseSpecifier *BS : RExp->Bases) {
761 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000762 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000763 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
764 /*NullCheckValue=*/false, SourceLocation());
765 LValue SubLV = MakeAddrLValue(Base, BS->getType());
766
767 // Recurse onto bases.
768 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
769 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000770 for (auto FD : RExp->Fields) {
771 // FIXME: What are the right qualifiers here?
772 LValue SubLV = EmitLValueForField(LV, FD);
773 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000774 }
John McCall7f416cc2015-09-08 08:05:57 +0000775 } else if (isa<ComplexExpansion>(Exp.get())) {
776 auto realValue = *AI++;
777 auto imagValue = *AI++;
778 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000779 } else {
780 assert(isa<NoExpansion>(Exp.get()));
781 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000782 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000783}
784
785void CodeGenFunction::ExpandTypeToArgs(
786 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
787 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
788 auto Exp = getTypeExpansion(Ty, getContext());
789 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000790 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
791 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000792 RValue EltRV =
793 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
794 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000795 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000796 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000797 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000798 for (const CXXBaseSpecifier *BS : RExp->Bases) {
799 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000800 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000801 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
802 /*NullCheckValue=*/false, SourceLocation());
803 RValue BaseRV = RValue::getAggregate(Base);
804
805 // Recurse onto bases.
806 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
807 IRCallArgPos);
808 }
809
810 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000811 for (auto FD : RExp->Fields) {
812 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
813 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
814 IRCallArgPos);
815 }
816 } else if (isa<ComplexExpansion>(Exp.get())) {
817 ComplexPairTy CV = RV.getComplexVal();
818 IRCallArgs[IRCallArgPos++] = CV.first;
819 IRCallArgs[IRCallArgPos++] = CV.second;
820 } else {
821 assert(isa<NoExpansion>(Exp.get()));
822 assert(RV.isScalar() &&
823 "Unexpected non-scalar rvalue during struct expansion.");
824
825 // Insert a bitcast as needed.
826 llvm::Value *V = RV.getScalarVal();
827 if (IRCallArgPos < IRFuncTy->getNumParams() &&
828 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
829 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
830
831 IRCallArgs[IRCallArgPos++] = V;
832 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000833}
834
John McCall7f416cc2015-09-08 08:05:57 +0000835/// Create a temporary allocation for the purposes of coercion.
836static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
837 CharUnits MinAlign) {
838 // Don't use an alignment that's worse than what LLVM would prefer.
839 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
840 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
841
842 return CGF.CreateTempAlloca(Ty, Align);
843}
844
Chris Lattner895c52b2010-06-27 06:04:18 +0000845/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000846/// accessing some number of bytes out of it, try to gep into the struct to get
847/// at its inner goodness. Dive as deep as possible without entering an element
848/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +0000849static Address
850EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000851 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000852 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000853 // We can't dive into a zero-element struct.
854 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000855
Chris Lattner2192fe52011-07-18 04:24:23 +0000856 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000857
Chris Lattner1cd66982010-06-27 05:56:15 +0000858 // 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 +0000859 // first element is the same size as the whole struct, we can enter it. The
860 // comparison must be made on the store size and not the alloca size. Using
861 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000862 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000863 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000864 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000865 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000866 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000867
Chris Lattner1cd66982010-06-27 05:56:15 +0000868 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +0000869 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000870
Chris Lattner1cd66982010-06-27 05:56:15 +0000871 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +0000872 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000873 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000874 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000875
876 return SrcPtr;
877}
878
Chris Lattner055097f2010-06-27 06:26:04 +0000879/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
880/// are either integers or pointers. This does a truncation of the value if it
881/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000882///
883/// This behaves as if the value were coerced through memory, so on big-endian
884/// targets the high bits are preserved in a truncation, while little-endian
885/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000886static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000887 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000888 CodeGenFunction &CGF) {
889 if (Val->getType() == Ty)
890 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000891
Chris Lattner055097f2010-06-27 06:26:04 +0000892 if (isa<llvm::PointerType>(Val->getType())) {
893 // If this is Pointer->Pointer avoid conversion to and from int.
894 if (isa<llvm::PointerType>(Ty))
895 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000896
Chris Lattner055097f2010-06-27 06:26:04 +0000897 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000898 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000899 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000900
Chris Lattner2192fe52011-07-18 04:24:23 +0000901 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000902 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000903 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000904
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000905 if (Val->getType() != DestIntTy) {
906 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
907 if (DL.isBigEndian()) {
908 // Preserve the high bits on big-endian targets.
909 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000910 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
911 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
912
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000913 if (SrcSize > DstSize) {
914 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
915 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
916 } else {
917 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
918 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
919 }
920 } else {
921 // Little-endian targets preserve the low bits. No shifts required.
922 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
923 }
924 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000925
Chris Lattner055097f2010-06-27 06:26:04 +0000926 if (isa<llvm::PointerType>(Ty))
927 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
928 return Val;
929}
930
Chris Lattner1cd66982010-06-27 05:56:15 +0000931
932
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000933/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +0000934/// a pointer to an object of type \arg Ty, known to be aligned to
935/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000936///
937/// This safely handles the case when the src type is smaller than the
938/// destination type; in this situation the values of bits which not
939/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +0000940static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000941 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +0000942 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000943
Chris Lattnerd200eda2010-06-28 22:51:39 +0000944 // If SrcTy and Ty are the same, just do a load.
945 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +0000946 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000947
Micah Villmowdd31ca12012-10-08 16:25:52 +0000948 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000949
Chris Lattner2192fe52011-07-18 04:24:23 +0000950 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +0000951 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
952 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +0000953 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000954
Micah Villmowdd31ca12012-10-08 16:25:52 +0000955 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000956
Chris Lattner055097f2010-06-27 06:26:04 +0000957 // If the source and destination are integer or pointer types, just do an
958 // extension or truncation to the desired type.
959 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
960 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +0000961 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +0000962 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
963 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000964
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000965 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000966 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000967 // Generally SrcSize is never greater than DstSize, since this means we are
968 // losing bits. However, this can happen in cases where the structure has
969 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000970 //
Mike Stump18bb9282009-05-16 07:57:57 +0000971 // FIXME: Assert that we aren't truncating non-padding bits when have access
972 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +0000973 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
974 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000975 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000976
John McCall7f416cc2015-09-08 08:05:57 +0000977 // Otherwise do coercion through memory. This is stupid, but simple.
978 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
979 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
980 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +0000981 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
982 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +0000983 false);
984 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000985}
986
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000987// Function to store a first-class aggregate into memory. We prefer to
988// store the elements rather than the aggregate to be more friendly to
989// fast-isel.
990// FIXME: Do we need to recurse here?
991static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +0000992 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000993 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000994 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000995 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +0000996 const llvm::StructLayout *Layout =
997 CGF.CGM.getDataLayout().getStructLayout(STy);
998
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000999 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001000 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1001 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001002 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001003 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001004 }
1005 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001006 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001007 }
1008}
1009
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001010/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001011/// where the source and destination may have different types. The
1012/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001013///
1014/// This safely handles the case when the src type is larger than the
1015/// destination type; the upper bits of the src will be lost.
1016static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001017 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001018 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001019 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001020 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001021 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001022 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001023 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001024 return;
1025 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001026
Micah Villmowdd31ca12012-10-08 16:25:52 +00001027 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001028
Chris Lattner2192fe52011-07-18 04:24:23 +00001029 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001030 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1031 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001032 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001033
Chris Lattner055097f2010-06-27 06:26:04 +00001034 // If the source and destination are integer or pointer types, just do an
1035 // extension or truncation to the desired type.
1036 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1037 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1038 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001039 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001040 return;
1041 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001042
Micah Villmowdd31ca12012-10-08 16:25:52 +00001043 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001044
Daniel Dunbar313321e2009-02-03 05:31:23 +00001045 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001046 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001047 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1048 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001049 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001050 // Otherwise do coercion through memory. This is stupid, but
1051 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001052
1053 // Generally SrcSize is never greater than DstSize, since this means we are
1054 // losing bits. However, this can happen in cases where the structure has
1055 // additional padding, for example due to a user specified alignment.
1056 //
1057 // FIXME: Assert that we aren't truncating non-padding bits when have access
1058 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001059 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1060 CGF.Builder.CreateStore(Src, Tmp);
1061 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1062 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001063 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1064 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001065 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001066 }
1067}
1068
John McCall7f416cc2015-09-08 08:05:57 +00001069static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1070 const ABIArgInfo &info) {
1071 if (unsigned offset = info.getDirectOffset()) {
1072 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1073 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1074 CharUnits::fromQuantity(offset));
1075 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1076 }
1077 return addr;
1078}
1079
Alexey Samsonov153004f2014-09-29 22:08:00 +00001080namespace {
1081
1082/// Encapsulates information about the way function arguments from
1083/// CGFunctionInfo should be passed to actual LLVM IR function.
1084class ClangToLLVMArgMapping {
1085 static const unsigned InvalidIndex = ~0U;
1086 unsigned InallocaArgNo;
1087 unsigned SRetArgNo;
1088 unsigned TotalIRArgs;
1089
1090 /// Arguments of LLVM IR function corresponding to single Clang argument.
1091 struct IRArgs {
1092 unsigned PaddingArgIndex;
1093 // Argument is expanded to IR arguments at positions
1094 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1095 unsigned FirstArgIndex;
1096 unsigned NumberOfArgs;
1097
1098 IRArgs()
1099 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1100 NumberOfArgs(0) {}
1101 };
1102
1103 SmallVector<IRArgs, 8> ArgInfo;
1104
1105public:
1106 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1107 bool OnlyRequiredArgs = false)
1108 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1109 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1110 construct(Context, FI, OnlyRequiredArgs);
1111 }
1112
1113 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1114 unsigned getInallocaArgNo() const {
1115 assert(hasInallocaArg());
1116 return InallocaArgNo;
1117 }
1118
1119 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1120 unsigned getSRetArgNo() const {
1121 assert(hasSRetArg());
1122 return SRetArgNo;
1123 }
1124
1125 unsigned totalIRArgs() const { return TotalIRArgs; }
1126
1127 bool hasPaddingArg(unsigned ArgNo) const {
1128 assert(ArgNo < ArgInfo.size());
1129 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1130 }
1131 unsigned getPaddingArgNo(unsigned ArgNo) const {
1132 assert(hasPaddingArg(ArgNo));
1133 return ArgInfo[ArgNo].PaddingArgIndex;
1134 }
1135
1136 /// Returns index of first IR argument corresponding to ArgNo, and their
1137 /// quantity.
1138 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1139 assert(ArgNo < ArgInfo.size());
1140 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1141 ArgInfo[ArgNo].NumberOfArgs);
1142 }
1143
1144private:
1145 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1146 bool OnlyRequiredArgs);
1147};
1148
1149void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1150 const CGFunctionInfo &FI,
1151 bool OnlyRequiredArgs) {
1152 unsigned IRArgNo = 0;
1153 bool SwapThisWithSRet = false;
1154 const ABIArgInfo &RetAI = FI.getReturnInfo();
1155
1156 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1157 SwapThisWithSRet = RetAI.isSRetAfterThis();
1158 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1159 }
1160
1161 unsigned ArgNo = 0;
1162 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1163 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1164 ++I, ++ArgNo) {
1165 assert(I != FI.arg_end());
1166 QualType ArgType = I->type;
1167 const ABIArgInfo &AI = I->info;
1168 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1169 auto &IRArgs = ArgInfo[ArgNo];
1170
1171 if (AI.getPaddingType())
1172 IRArgs.PaddingArgIndex = IRArgNo++;
1173
1174 switch (AI.getKind()) {
1175 case ABIArgInfo::Extend:
1176 case ABIArgInfo::Direct: {
1177 // FIXME: handle sseregparm someday...
1178 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1179 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1180 IRArgs.NumberOfArgs = STy->getNumElements();
1181 } else {
1182 IRArgs.NumberOfArgs = 1;
1183 }
1184 break;
1185 }
1186 case ABIArgInfo::Indirect:
1187 IRArgs.NumberOfArgs = 1;
1188 break;
1189 case ABIArgInfo::Ignore:
1190 case ABIArgInfo::InAlloca:
1191 // ignore and inalloca doesn't have matching LLVM parameters.
1192 IRArgs.NumberOfArgs = 0;
1193 break;
1194 case ABIArgInfo::Expand: {
1195 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1196 break;
1197 }
1198 }
1199
1200 if (IRArgs.NumberOfArgs > 0) {
1201 IRArgs.FirstArgIndex = IRArgNo;
1202 IRArgNo += IRArgs.NumberOfArgs;
1203 }
1204
1205 // Skip over the sret parameter when it comes second. We already handled it
1206 // above.
1207 if (IRArgNo == 1 && SwapThisWithSRet)
1208 IRArgNo++;
1209 }
1210 assert(ArgNo == ArgInfo.size());
1211
1212 if (FI.usesInAlloca())
1213 InallocaArgNo = IRArgNo++;
1214
1215 TotalIRArgs = IRArgNo;
1216}
1217} // namespace
1218
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001219/***/
1220
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001221bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001222 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001223}
1224
Tim Northovere77cc392014-03-29 13:28:05 +00001225bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1226 return ReturnTypeUsesSRet(FI) &&
1227 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1228}
1229
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001230bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1231 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1232 switch (BT->getKind()) {
1233 default:
1234 return false;
1235 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001236 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001237 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001238 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001239 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001240 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001241 }
1242 }
1243
1244 return false;
1245}
1246
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001247bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1248 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1249 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1250 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001251 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001252 }
1253 }
1254
1255 return false;
1256}
1257
Chris Lattnera5f58b02011-07-09 17:41:47 +00001258llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001259 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1260 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001261}
1262
Chris Lattnera5f58b02011-07-09 17:41:47 +00001263llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001264CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001265
David Blaikie82e95a32014-11-19 07:49:47 +00001266 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1267 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001268 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001269
Alexey Samsonov153004f2014-09-29 22:08:00 +00001270 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001271 const ABIArgInfo &retAI = FI.getReturnInfo();
1272 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001273 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001274 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001275
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001276 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001277 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001278 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001279 break;
1280
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001281 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001282 if (retAI.getInAllocaSRet()) {
1283 // sret things on win32 aren't void, they return the sret pointer.
1284 QualType ret = FI.getReturnType();
1285 llvm::Type *ty = ConvertType(ret);
1286 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1287 resultType = llvm::PointerType::get(ty, addressSpace);
1288 } else {
1289 resultType = llvm::Type::getVoidTy(getLLVMContext());
1290 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001291 break;
1292
John McCall7f416cc2015-09-08 08:05:57 +00001293 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001294 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001295 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001296 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
Alexey Samsonov153004f2014-09-29 22:08:00 +00001299 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1300 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1301
1302 // Add type for sret argument.
1303 if (IRFunctionArgs.hasSRetArg()) {
1304 QualType Ret = FI.getReturnType();
1305 llvm::Type *Ty = ConvertType(Ret);
1306 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1307 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1308 llvm::PointerType::get(Ty, AddressSpace);
1309 }
1310
1311 // Add type for inalloca argument.
1312 if (IRFunctionArgs.hasInallocaArg()) {
1313 auto ArgStruct = FI.getArgStruct();
1314 assert(ArgStruct);
1315 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1316 }
1317
John McCallc818bbb2012-12-07 07:03:17 +00001318 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001319 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001320 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1321 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001322 for (; it != ie; ++it, ++ArgNo) {
1323 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001324
Rafael Espindolafad28de2012-10-24 01:59:00 +00001325 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001326 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1327 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1328 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001329
Alexey Samsonov153004f2014-09-29 22:08:00 +00001330 unsigned FirstIRArg, NumIRArgs;
1331 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1332
1333 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001334 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001335 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001336 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001337 break;
1338
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001339 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001340 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001341 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001342 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001343 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001344 break;
1345 }
1346
1347 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001348 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001349 // Fast-isel and the optimizer generally like scalar values better than
1350 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001351 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001352 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001353 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1354 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001355 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001356 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001357 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001358 assert(NumIRArgs == 1);
1359 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001360 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001361 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Daniel Dunbard3674e62008-09-11 01:48:57 +00001364 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001365 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1366 getExpandedTypes(it->type, ArgTypesIter);
1367 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001368 break;
1369 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001370 }
1371
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001372 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1373 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001374
1375 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001376}
1377
Chris Lattner2192fe52011-07-18 04:24:23 +00001378llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001379 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001380 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001381
Chris Lattner8806e322011-07-10 00:18:59 +00001382 if (!isFuncTypeConvertible(FPT))
1383 return llvm::StructType::get(getLLVMContext());
1384
1385 const CGFunctionInfo *Info;
1386 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001387 Info =
1388 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001389 else
John McCalla729c622012-02-17 03:33:10 +00001390 Info = &arrangeCXXMethodDeclaration(MD);
1391 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001392}
1393
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001394void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001395 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001396 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001397 unsigned &CallingConv,
1398 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001399 llvm::AttrBuilder FuncAttrs;
1400 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001401 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001402
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001403 CallingConv = FI.getEffectiveCallingConvention();
1404
John McCallab26cfa2010-02-05 21:31:56 +00001405 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001406 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001407
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001408 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001409 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001410 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001411 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001412 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001413 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001414 if (TargetDecl->hasAttr<NoReturnAttr>())
1415 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001416 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1417 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001418
1419 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001420 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001421 if (FPT && !isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1422 FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001423 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001424 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1425 // These attributes are not inherited by overloads.
1426 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1427 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001428 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001429 }
1430
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001431 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001432 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001433 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1434 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001435 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001436 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1437 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001438 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1439 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1440 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001441 }
David Majnemer631a90b2015-02-04 07:23:21 +00001442 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001443 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001444 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1445 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001446
1447 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001448 }
1449
Paul Robinson08556952014-12-11 20:14:04 +00001450 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1451 if (!HasOptnone) {
1452 if (CodeGenOpts.OptimizeSize)
1453 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1454 if (CodeGenOpts.OptimizeSize == 2)
1455 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1456 }
1457
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001458 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001459 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001460 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001461 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001462 if (CodeGenOpts.EnableSegmentedStacks &&
1463 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001464 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001465
Bill Wendling2f81db62013-02-22 20:53:29 +00001466 if (AttrOnCallSite) {
1467 // Attributes that should go on the call site only.
1468 if (!CodeGenOpts.SimplifyLibCalls)
1469 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001470 if (!CodeGenOpts.TrapFuncName.empty())
1471 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001472 } else {
1473 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001474 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001475 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001476 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001477 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001478 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001479 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001480 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001481 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001482 }
1483
Akira Hatanaka262a4c42015-06-09 19:04:36 +00001484 FuncAttrs.addAttribute("disable-tail-calls",
1485 llvm::toStringRef(CodeGenOpts.DisableTailCalls));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001486 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001487 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001488 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001489 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001490 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001491 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001492 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001493 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001494 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001495 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001496 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001497 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001498
Akira Hatanakaaecca042015-09-11 18:55:09 +00001499 if (CodeGenOpts.StackRealignment)
1500 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001501
Eric Christopher11acf732015-06-12 01:35:52 +00001502 // Add target-cpu and target-features attributes to functions. If
1503 // we have a decl for the function and it has a target attribute then
1504 // parse that and add it to the feature set.
1505 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001506 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001507 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001508 llvm::StringMap<bool> FeatureMap;
Eric Christopher86fdc852015-09-02 20:40:12 +00001509 const auto *TD = FD->getAttr<TargetAttr>();
1510 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
Eric Christopher11acf732015-06-12 01:35:52 +00001511
Eric Christopher86fdc852015-09-02 20:40:12 +00001512 // Make a copy of the features as passed on the command line into the
1513 // beginning of the additional features from the function to override.
1514 ParsedAttr.first.insert(
1515 ParsedAttr.first.begin(),
1516 getTarget().getTargetOpts().FeaturesAsWritten.begin(),
1517 getTarget().getTargetOpts().FeaturesAsWritten.end());
Eric Christopherdec31be2015-08-31 23:19:55 +00001518
Eric Christopher86fdc852015-09-02 20:40:12 +00001519 if (ParsedAttr.second != "")
1520 TargetCPU = ParsedAttr.second;
Eric Christopherdec31be2015-08-31 23:19:55 +00001521
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001522 // Now populate the feature map, first with the TargetCPU which is either
1523 // the default or a new one from the target attribute string. Then we'll
1524 // use the passed in features (FeaturesAsWritten) along with the new ones
1525 // from the attribute.
Eric Christopher86fdc852015-09-02 20:40:12 +00001526 getTarget().initFeatureMap(FeatureMap, Diags, TargetCPU, ParsedAttr.first);
Eric Christopher11acf732015-06-12 01:35:52 +00001527
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001528 // Produce the canonical string for this set of features.
1529 std::vector<std::string> Features;
1530 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1531 ie = FeatureMap.end();
1532 it != ie; ++it)
1533 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001534
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001535 // Now add the target-cpu and target-features to the function.
1536 if (TargetCPU != "")
1537 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1538 if (!Features.empty()) {
1539 std::sort(Features.begin(), Features.end());
1540 FuncAttrs.addAttribute(
1541 "target-features",
1542 llvm::join(Features.begin(), Features.end(), ","));
1543 }
1544 } else {
1545 // Otherwise just add the existing target cpu and target features to the
1546 // function.
1547 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1548 if (TargetCPU != "")
1549 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1550 if (!Features.empty()) {
1551 std::sort(Features.begin(), Features.end());
1552 FuncAttrs.addAttribute(
1553 "target-features",
1554 llvm::join(Features.begin(), Features.end(), ","));
1555 }
Eric Christopher70c16652015-03-25 23:14:47 +00001556 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001557 }
1558
Alexey Samsonov153004f2014-09-29 22:08:00 +00001559 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001560
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001561 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001562 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001563 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001564 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001565 if (RetTy->hasSignedIntegerRepresentation())
1566 RetAttrs.addAttribute(llvm::Attribute::SExt);
1567 else if (RetTy->hasUnsignedIntegerRepresentation())
1568 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001569 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001570 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001571 if (RetAI.getInReg())
1572 RetAttrs.addAttribute(llvm::Attribute::InReg);
1573 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001574 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001575 break;
1576
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001577 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001578 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001579 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001580 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1581 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001582 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001583 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001584
Daniel Dunbard3674e62008-09-11 01:48:57 +00001585 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001586 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001587 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001588
Hal Finkela2347ba2014-07-18 15:52:10 +00001589 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1590 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001591 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001592 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1593 .getQuantity());
1594 else if (getContext().getTargetAddressSpace(PTy) == 0)
1595 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1596 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001597
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001598 // Attach return attributes.
1599 if (RetAttrs.hasAttributes()) {
1600 PAL.push_back(llvm::AttributeSet::get(
1601 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1602 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001603
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001604 // Attach attributes to sret.
1605 if (IRFunctionArgs.hasSRetArg()) {
1606 llvm::AttrBuilder SRETAttrs;
1607 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1608 if (RetAI.getInReg())
1609 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1610 PAL.push_back(llvm::AttributeSet::get(
1611 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1612 }
1613
1614 // Attach attributes to inalloca argument.
1615 if (IRFunctionArgs.hasInallocaArg()) {
1616 llvm::AttrBuilder Attrs;
1617 Attrs.addAttribute(llvm::Attribute::InAlloca);
1618 PAL.push_back(llvm::AttributeSet::get(
1619 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1620 }
1621
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001622 unsigned ArgNo = 0;
1623 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1624 E = FI.arg_end();
1625 I != E; ++I, ++ArgNo) {
1626 QualType ParamType = I->type;
1627 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001628 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001629
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001630 // Add attribute for padding argument, if necessary.
1631 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001632 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001633 PAL.push_back(llvm::AttributeSet::get(
1634 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1635 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001636 }
1637
John McCall39ec71f2010-03-27 00:47:27 +00001638 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1639 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001640 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001641 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001642 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001643 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001644 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001645 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1646 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1647 Attrs.addAttribute(llvm::Attribute::SExt);
1648 else
1649 Attrs.addAttribute(llvm::Attribute::ZExt);
1650 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001651 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001652 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001653 if (ArgNo == 0 && FI.isChainCall())
1654 Attrs.addAttribute(llvm::Attribute::Nest);
1655 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001656 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001657 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001658
James Y Knight71608572015-08-21 18:19:06 +00001659 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001660 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001661 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001662
Anders Carlsson20759ad2009-09-16 15:53:40 +00001663 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001664 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001665
John McCall7f416cc2015-09-08 08:05:57 +00001666 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001667
1668 // In a byval argument, it is important that the required
1669 // alignment of the type is honored, as LLVM might be creating a
1670 // *new* stack object, and needs to know what alignment to give
1671 // it. (Sometimes it can deduce a sensible alignment on its own,
1672 // but not if clang decides it must emit a packed struct, or the
1673 // user specifies increased alignment requirements.)
1674 //
1675 // This is different from indirect *not* byval, where the object
1676 // exists already, and the align attribute is purely
1677 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001678 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001679
John McCall7f416cc2015-09-08 08:05:57 +00001680 // For now, only add this when we have a byval argument.
1681 // TODO: be less lazy about updating test cases.
1682 if (AI.getIndirectByVal())
1683 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001684
Daniel Dunbarc2304432009-03-18 19:51:01 +00001685 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001686 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1687 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001688 break;
James Y Knight71608572015-08-21 18:19:06 +00001689 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001690 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001691 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001692 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001693
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001694 case ABIArgInfo::InAlloca:
1695 // inalloca disables readnone and readonly.
1696 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1697 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001698 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Hal Finkela2347ba2014-07-18 15:52:10 +00001701 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1702 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001703 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001704 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1705 .getQuantity());
1706 else if (getContext().getTargetAddressSpace(PTy) == 0)
1707 Attrs.addAttribute(llvm::Attribute::NonNull);
1708 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001709
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001710 if (Attrs.hasAttributes()) {
1711 unsigned FirstIRArg, NumIRArgs;
1712 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1713 for (unsigned i = 0; i < NumIRArgs; i++)
1714 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1715 FirstIRArg + i + 1, Attrs));
1716 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001717 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001718 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001719
Bill Wendlinga7912f82012-10-10 07:36:56 +00001720 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001721 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001722 AttributeSet::get(getLLVMContext(),
1723 llvm::AttributeSet::FunctionIndex,
1724 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001725}
1726
John McCalla738c252011-03-09 04:27:21 +00001727/// An argument came in as a promoted argument; demote it back to its
1728/// declared type.
1729static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1730 const VarDecl *var,
1731 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001732 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001733
1734 // This can happen with promotions that actually don't change the
1735 // underlying type, like the enum promotions.
1736 if (value->getType() == varType) return value;
1737
1738 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1739 && "unexpected promotion type");
1740
1741 if (isa<llvm::IntegerType>(varType))
1742 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1743
1744 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1745}
1746
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001747/// Returns the attribute (either parameter attribute, or function
1748/// attribute), which declares argument ArgNo to be non-null.
1749static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1750 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001751 // FIXME: __attribute__((nonnull)) can also be applied to:
1752 // - references to pointers, where the pointee is known to be
1753 // nonnull (apparently a Clang extension)
1754 // - transparent unions containing pointers
1755 // In the former case, LLVM IR cannot represent the constraint. In
1756 // the latter case, we have no guarantee that the transparent union
1757 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001758 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1759 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001760 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001761 if (PVD) {
1762 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1763 return ParmNNAttr;
1764 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001765 // Check function attributes.
1766 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001767 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001768 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001769 if (NNAttr->isNonNull(ArgNo))
1770 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001771 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001772 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001773}
1774
Daniel Dunbard931a872009-02-02 22:03:45 +00001775void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1776 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001777 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001778 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1779 // Naked functions don't have prologues.
1780 return;
1781
John McCallcaa19452009-07-28 01:00:58 +00001782 // If this is an implicit-return-zero function, go ahead and
1783 // initialize the return value. TODO: it might be nice to have
1784 // a more general mechanism for this that didn't require synthesized
1785 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001786 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001787 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001788 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001789 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001790 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001791 Builder.CreateStore(Zero, ReturnValue);
1792 }
1793 }
1794
Mike Stump18bb9282009-05-16 07:57:57 +00001795 // FIXME: We no longer need the types from FunctionArgList; lift up and
1796 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001797
Alexey Samsonov153004f2014-09-29 22:08:00 +00001798 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001799 // Flattened function arguments.
1800 SmallVector<llvm::Argument *, 16> FnArgs;
1801 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1802 for (auto &Arg : Fn->args()) {
1803 FnArgs.push_back(&Arg);
1804 }
1805 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001806
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001807 // If we're using inalloca, all the memory arguments are GEPs off of the last
1808 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00001809 Address ArgStruct = Address::invalid();
1810 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001811 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00001812 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
1813 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
1814 FI.getArgStructAlignment());
1815
1816 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001817 }
1818
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001819 // Name the struct return parameter.
1820 if (IRFunctionArgs.hasSRetArg()) {
1821 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001822 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001823 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001824 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001827 // Track if we received the parameter as a pointer (indirect, byval, or
1828 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1829 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00001830 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001831 ArgVals.reserve(Args.size());
1832
Reid Kleckner739756c2013-12-04 19:23:12 +00001833 // Create a pointer value for every parameter declaration. This usually
1834 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1835 // any cleanups or do anything that might unwind. We do that separately, so
1836 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001837 assert(FI.arg_size() == Args.size() &&
1838 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001839 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001840 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001841 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001842 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001843 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001844 QualType Ty = info_it->type;
1845 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001846
John McCalla738c252011-03-09 04:27:21 +00001847 bool isPromoted =
1848 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1849
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001850 unsigned FirstIRArg, NumIRArgs;
1851 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001852
Daniel Dunbard3674e62008-09-11 01:48:57 +00001853 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001854 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001855 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00001856 auto FieldIndex = ArgI.getInAllocaFieldIndex();
1857 CharUnits FieldOffset =
1858 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
1859 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
1860 Arg->getName());
1861 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001862 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001863 }
1864
Daniel Dunbar747865a2009-02-05 09:16:39 +00001865 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001866 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00001867 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001868
John McCall47fb9502013-03-07 21:37:08 +00001869 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001870 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00001871 // need to do is realign the value, if requested.
1872 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001873 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00001874 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001875
1876 // Copy from the incoming argument pointer to the temporary with the
1877 // appropriate alignment.
1878 //
1879 // FIXME: We should have a common utility for generating an aggregate
1880 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00001881 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00001882 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
1883 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
1884 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
1885 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001886 V = AlignedTemp;
1887 }
John McCall7f416cc2015-09-08 08:05:57 +00001888 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001889 } else {
1890 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00001891 llvm::Value *V =
1892 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001893
1894 if (isPromoted)
1895 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00001896 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001897 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001898 break;
1899 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001900
1901 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001902 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001903
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001904 // If we have the trivial case, handle it with no muss and fuss.
1905 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001906 ArgI.getCoerceToType() == ConvertType(Ty) &&
1907 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001908 assert(NumIRArgs == 1);
1909 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001910 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001911
Hal Finkel48d53e22014-07-19 01:41:07 +00001912 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001913 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1914 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001915 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1916 AI->getArgNo() + 1,
1917 llvm::Attribute::NonNull));
1918
Hal Finkel48d53e22014-07-19 01:41:07 +00001919 QualType OTy = PVD->getOriginalType();
1920 if (const auto *ArrTy =
1921 getContext().getAsConstantArrayType(OTy)) {
1922 // A C99 array parameter declaration with the static keyword also
1923 // indicates dereferenceability, and if the size is constant we can
1924 // use the dereferenceable attribute (which requires the size in
1925 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001926 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001927 QualType ETy = ArrTy->getElementType();
1928 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1929 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1930 ArrSize) {
1931 llvm::AttrBuilder Attrs;
1932 Attrs.addDereferenceableAttr(
1933 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1934 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1935 AI->getArgNo() + 1, Attrs));
1936 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1937 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1938 AI->getArgNo() + 1,
1939 llvm::Attribute::NonNull));
1940 }
1941 }
1942 } else if (const auto *ArrTy =
1943 getContext().getAsVariableArrayType(OTy)) {
1944 // For C99 VLAs with the static keyword, we don't know the size so
1945 // we can't use the dereferenceable attribute, but in addrspace(0)
1946 // we know that it must be nonnull.
1947 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1948 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1949 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1950 AI->getArgNo() + 1,
1951 llvm::Attribute::NonNull));
1952 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001953
1954 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1955 if (!AVAttr)
1956 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1957 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1958 if (AVAttr) {
1959 llvm::Value *AlignmentValue =
1960 EmitScalarExpr(AVAttr->getAlignment());
1961 llvm::ConstantInt *AlignmentCI =
1962 cast<llvm::ConstantInt>(AlignmentValue);
1963 unsigned Alignment =
1964 std::min((unsigned) AlignmentCI->getZExtValue(),
1965 +llvm::Value::MaximumAlignment);
1966
1967 llvm::AttrBuilder Attrs;
1968 Attrs.addAlignmentAttr(Alignment);
1969 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1970 AI->getArgNo() + 1, Attrs));
1971 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001972 }
1973
Bill Wendling507c3512012-10-16 05:23:44 +00001974 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001975 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1976 AI->getArgNo() + 1,
1977 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001978
Chris Lattner7369c142011-07-20 06:29:00 +00001979 // Ensure the argument is the correct type.
1980 if (V->getType() != ArgI.getCoerceToType())
1981 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1982
John McCalla738c252011-03-09 04:27:21 +00001983 if (isPromoted)
1984 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001985
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001986 if (const CXXMethodDecl *MD =
1987 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001988 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001989 V = CGM.getCXXABI().
1990 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001991 }
1992
Rafael Espindola8778c282012-11-29 16:09:03 +00001993 // Because of merging of function types from multiple decls it is
1994 // possible for the type of an argument to not match the corresponding
1995 // type in the function type. Since we are codegening the callee
1996 // in here, add a cast to the argument type.
1997 llvm::Type *LTy = ConvertType(Arg->getType());
1998 if (V->getType() != LTy)
1999 V = Builder.CreateBitCast(V, LTy);
2000
John McCall7f416cc2015-09-08 08:05:57 +00002001 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002002 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002003 }
Mike Stump11289f42009-09-09 15:08:12 +00002004
John McCall7f416cc2015-09-08 08:05:57 +00002005 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2006 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002007
John McCall7f416cc2015-09-08 08:05:57 +00002008 // Pointer to store into.
2009 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002010
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002011 // Fast-isel and the optimizer generally like scalar values better than
2012 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002013 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002014 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2015 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002016 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002017 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002018 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002019 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002020
John McCall7f416cc2015-09-08 08:05:57 +00002021 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002022 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002023 AddrToStoreInto =
2024 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002025 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002026 AddrToStoreInto =
2027 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002028 }
John McCall7f416cc2015-09-08 08:05:57 +00002029
2030 assert(STy->getNumElements() == NumIRArgs);
2031 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2032 auto AI = FnArgs[FirstIRArg + i];
2033 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2034 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2035 Address EltPtr =
2036 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2037 Builder.CreateStore(AI, EltPtr);
2038 }
2039
2040 if (SrcSize > DstSize) {
2041 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2042 }
2043
Chris Lattner15ec3612010-06-29 00:06:42 +00002044 } else {
2045 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002046 assert(NumIRArgs == 1);
2047 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002048 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002049 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002050 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002051
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002052 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002053 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002054 llvm::Value *V =
2055 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002056 if (isPromoted)
2057 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002058 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002059 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002060 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002061 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002062 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002063 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002064
2065 case ABIArgInfo::Expand: {
2066 // If this structure was expanded into multiple arguments then
2067 // we need to create a temporary and reconstruct it from the
2068 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002069 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2070 LValue LV = MakeAddrLValue(Alloca, Ty);
2071 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002072
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002073 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2074 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2075 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2076 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2077 auto AI = FnArgs[FirstIRArg + i];
2078 AI->setName(Arg->getName() + "." + Twine(i));
2079 }
2080 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002081 }
2082
2083 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002084 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002085 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002086 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002087 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002088 } else {
2089 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002090 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002091 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002092 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002093 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002094 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002095
Reid Kleckner739756c2013-12-04 19:23:12 +00002096 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2097 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002098 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002099 } else {
2100 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002101 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002102 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002103}
2104
John McCallffa2c1a2012-01-29 07:46:59 +00002105static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2106 while (insn->use_empty()) {
2107 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2108 if (!bitcast) return;
2109
2110 // This is "safe" because we would have used a ConstantExpr otherwise.
2111 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2112 bitcast->eraseFromParent();
2113 }
2114}
2115
John McCall31168b02011-06-15 23:02:42 +00002116/// Try to emit a fused autorelease of a return result.
2117static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2118 llvm::Value *result) {
2119 // We must be immediately followed the cast.
2120 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002121 if (BB->empty()) return nullptr;
2122 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002123
Chris Lattner2192fe52011-07-18 04:24:23 +00002124 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002125
2126 // result is in a BasicBlock and is therefore an Instruction.
2127 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2128
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002129 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002130
2131 // Look for:
2132 // %generator = bitcast %type1* %generator2 to %type2*
2133 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2134 // We would have emitted this as a constant if the operand weren't
2135 // an Instruction.
2136 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2137
2138 // Require the generator to be immediately followed by the cast.
2139 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002140 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002141
2142 insnsToKill.push_back(bitcast);
2143 }
2144
2145 // Look for:
2146 // %generator = call i8* @objc_retain(i8* %originalResult)
2147 // or
2148 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2149 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002150 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002151
2152 bool doRetainAutorelease;
2153
John McCallb04ecb72015-10-21 18:06:43 +00002154 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002155 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002156 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002157 .objc_retainAutoreleasedReturnValue) {
2158 doRetainAutorelease = false;
2159
John McCallcfa4e9b2012-09-07 23:30:50 +00002160 // If we emitted an assembly marker for this call (and the
2161 // ARCEntrypoints field should have been set if so), go looking
2162 // for that call. If we can't find it, we can't do this
2163 // optimization. But it should always be the immediately previous
2164 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002165 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002166 llvm::Instruction *prev = call->getPrevNode();
2167 assert(prev);
2168 if (isa<llvm::BitCastInst>(prev)) {
2169 prev = prev->getPrevNode();
2170 assert(prev);
2171 }
2172 assert(isa<llvm::CallInst>(prev));
2173 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002174 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002175 insnsToKill.push_back(prev);
2176 }
John McCall31168b02011-06-15 23:02:42 +00002177 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002178 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002179 }
2180
2181 result = call->getArgOperand(0);
2182 insnsToKill.push_back(call);
2183
2184 // Keep killing bitcasts, for sanity. Note that we no longer care
2185 // about precise ordering as long as there's exactly one use.
2186 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2187 if (!bitcast->hasOneUse()) break;
2188 insnsToKill.push_back(bitcast);
2189 result = bitcast->getOperand(0);
2190 }
2191
2192 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002193 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002194 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2195 (*i)->eraseFromParent();
2196
2197 // Do the fused retain/autorelease if we were asked to.
2198 if (doRetainAutorelease)
2199 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2200
2201 // Cast back to the result type.
2202 return CGF.Builder.CreateBitCast(result, resultType);
2203}
2204
John McCallffa2c1a2012-01-29 07:46:59 +00002205/// If this is a +1 of the value of an immutable 'self', remove it.
2206static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2207 llvm::Value *result) {
2208 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002209 const ObjCMethodDecl *method =
2210 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002211 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002212 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002213 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002214
2215 // Look for a retain call.
2216 llvm::CallInst *retainCall =
2217 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2218 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002219 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002220 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002221
2222 // Look for an ordinary load of 'self'.
2223 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2224 llvm::LoadInst *load =
2225 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2226 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002227 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002228 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002229
2230 // Okay! Burn it all down. This relies for correctness on the
2231 // assumption that the retain is emitted as part of the return and
2232 // that thereafter everything is used "linearly".
2233 llvm::Type *resultType = result->getType();
2234 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2235 assert(retainCall->use_empty());
2236 retainCall->eraseFromParent();
2237 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2238
2239 return CGF.Builder.CreateBitCast(load, resultType);
2240}
2241
John McCall31168b02011-06-15 23:02:42 +00002242/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002243///
2244/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002245static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2246 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002247 // If we're returning 'self', kill the initial retain. This is a
2248 // heuristic attempt to "encourage correctness" in the really unfortunate
2249 // case where we have a return of self during a dealloc and we desperately
2250 // need to avoid the possible autorelease.
2251 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2252 return self;
2253
John McCall31168b02011-06-15 23:02:42 +00002254 // At -O0, try to emit a fused retain/autorelease.
2255 if (CGF.shouldUseFusedARCCalls())
2256 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2257 return fused;
2258
2259 return CGF.EmitARCAutoreleaseReturnValue(result);
2260}
2261
John McCall6e1c0122012-01-29 02:35:02 +00002262/// Heuristically search for a dominating store to the return-value slot.
2263static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002264 // Check if a User is a store which pointerOperand is the ReturnValue.
2265 // We are looking for stores to the ReturnValue, not for stores of the
2266 // ReturnValue to some other location.
2267 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2268 auto *SI = dyn_cast<llvm::StoreInst>(U);
2269 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2270 return nullptr;
2271 // These aren't actually possible for non-coerced returns, and we
2272 // only care about non-coerced returns on this code path.
2273 assert(!SI->isAtomic() && !SI->isVolatile());
2274 return SI;
2275 };
John McCall6e1c0122012-01-29 02:35:02 +00002276 // If there are multiple uses of the return-value slot, just check
2277 // for something immediately preceding the IP. Sometimes this can
2278 // happen with how we generate implicit-returns; it can also happen
2279 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002280 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002281 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002282 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002283 llvm::Instruction *I = &IP->back();
2284
2285 // Skip lifetime markers
2286 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2287 IE = IP->rend();
2288 II != IE; ++II) {
2289 if (llvm::IntrinsicInst *Intrinsic =
2290 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2291 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2292 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2293 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002294 if (II == IE)
2295 break;
2296 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2297 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002298 }
2299 }
2300 I = &*II;
2301 break;
2302 }
2303
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002304 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002305 }
2306
2307 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002308 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002309 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002310
John McCall6e1c0122012-01-29 02:35:02 +00002311 // Now do a first-and-dirty dominance check: just walk up the
2312 // single-predecessors chain from the current insertion point.
2313 llvm::BasicBlock *StoreBB = store->getParent();
2314 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2315 while (IP != StoreBB) {
2316 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002317 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002318 }
2319
2320 // Okay, the store's basic block dominates the insertion point; we
2321 // can do our thing.
2322 return store;
2323}
2324
Adrian Prantl3be10542013-05-02 17:30:20 +00002325void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002326 bool EmitRetDbgLoc,
2327 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002328 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2329 // Naked functions don't have epilogues.
2330 Builder.CreateUnreachable();
2331 return;
2332 }
2333
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002334 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002335 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002336 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002337 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002338 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002339
Dan Gohman481e40c2010-07-20 20:13:52 +00002340 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002341 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002342 QualType RetTy = FI.getReturnType();
2343 const ABIArgInfo &RetAI = FI.getReturnInfo();
2344
2345 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002346 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002347 // Aggregrates get evaluated directly into the destination. Sometimes we
2348 // need to return the sret value in a register, though.
2349 assert(hasAggregateEvaluationKind(RetTy));
2350 if (RetAI.getInAllocaSRet()) {
2351 llvm::Function::arg_iterator EI = CurFn->arg_end();
2352 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002353 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002354 llvm::Value *SRet = Builder.CreateStructGEP(
2355 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002356 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002357 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002358 break;
2359
Daniel Dunbar03816342010-08-21 02:24:36 +00002360 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002361 auto AI = CurFn->arg_begin();
2362 if (RetAI.isSRetAfterThis())
2363 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002364 switch (getEvaluationKind(RetTy)) {
2365 case TEK_Complex: {
2366 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002367 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002368 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002369 /*isInit*/ true);
2370 break;
2371 }
2372 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002373 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002374 break;
2375 case TEK_Scalar:
2376 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002377 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002378 /*isInit*/ true);
2379 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002380 }
2381 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002382 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002383
2384 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002385 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002386 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2387 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002388 // The internal return value temp always will have pointer-to-return-type
2389 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002390
John McCall6e1c0122012-01-29 02:35:02 +00002391 // If there is a dominating store to ReturnValue, we can elide
2392 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002393 if (llvm::StoreInst *SI =
2394 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002395 // Reuse the debug location from the store unless there is
2396 // cleanup code to be emitted between the store and return
2397 // instruction.
2398 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002399 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002400 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002401 RV = SI->getValueOperand();
2402 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002403
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002404 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002405 auto returnValueInst = ReturnValue.getPointer();
2406 if (returnValueInst->use_empty()) {
2407 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2408 alloca->eraseFromParent();
2409 ReturnValue = Address::invalid();
2410 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002411 }
John McCall6e1c0122012-01-29 02:35:02 +00002412
2413 // Otherwise, we have to do a simple load.
2414 } else {
2415 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002416 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002417 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002418 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002419 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002420
John McCall7f416cc2015-09-08 08:05:57 +00002421 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002422 }
John McCall31168b02011-06-15 23:02:42 +00002423
2424 // In ARC, end functions that return a retainable type with a call
2425 // to objc_autoreleaseReturnValue.
2426 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002427 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002428 !FI.isReturnsRetained() &&
2429 RetTy->isObjCRetainableType());
2430 RV = emitAutoreleaseOfResult(*this, RV);
2431 }
2432
Chris Lattner726b3d02010-06-26 23:13:19 +00002433 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002434
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002435 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002436 break;
2437
2438 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002439 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002440 }
2441
Alexey Samsonovde443c52014-08-13 00:26:40 +00002442 llvm::Instruction *Ret;
2443 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002444 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2445 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002446 SanitizerScope SanScope(this);
2447 llvm::Value *Cond = Builder.CreateICmpNE(
2448 RV, llvm::Constant::getNullValue(RV->getType()));
2449 llvm::Constant *StaticData[] = {
2450 EmitCheckSourceLocation(EndLoc),
2451 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2452 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002453 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2454 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002455 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002456 }
2457 Ret = Builder.CreateRet(RV);
2458 } else {
2459 Ret = Builder.CreateRetVoid();
2460 }
2461
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002462 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002463 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002464}
2465
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002466static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2467 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2468 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2469}
2470
John McCall7f416cc2015-09-08 08:05:57 +00002471static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2472 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002473 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2474 // placeholders.
2475 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2476 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002477 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2478 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2479
2480 // FIXME: When we generate this IR in one pass, we shouldn't need
2481 // this win32-specific alignment hack.
2482 CharUnits Align = CharUnits::fromQuantity(4);
2483
2484 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002485 Ty.getQualifiers(),
2486 AggValueSlot::IsNotDestructed,
2487 AggValueSlot::DoesNotNeedGCBarriers,
2488 AggValueSlot::IsNotAliased);
2489}
2490
John McCall32ea9692011-03-11 20:59:21 +00002491void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002492 const VarDecl *param,
2493 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002494 // StartFunction converted the ABI-lowered parameter(s) into a
2495 // local alloca. We need to turn that into an r-value suitable
2496 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002497 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002498
John McCall32ea9692011-03-11 20:59:21 +00002499 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002500
John McCall23f66262010-05-26 22:34:26 +00002501 // For the most part, we just need to load the alloca, except:
2502 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002503 // 2) references to non-scalars are pointers directly to the aggregate.
2504 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002505 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002506 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002507 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002508
2509 // Locals which are references to scalars are represented
2510 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002511 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002512 }
2513
Reid Klecknerab2090d2014-07-26 01:34:32 +00002514 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2515 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002516
Nick Lewycky2d84e842013-10-02 02:29:49 +00002517 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002518}
2519
John McCall31168b02011-06-15 23:02:42 +00002520static bool isProvablyNull(llvm::Value *addr) {
2521 return isa<llvm::ConstantPointerNull>(addr);
2522}
2523
2524static bool isProvablyNonNull(llvm::Value *addr) {
2525 return isa<llvm::AllocaInst>(addr);
2526}
2527
2528/// Emit the actual writing-back of a writeback.
2529static void emitWriteback(CodeGenFunction &CGF,
2530 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002531 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002532 Address srcAddr = srcLV.getAddress();
2533 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002534 "shouldn't have writeback for provably null argument");
2535
Craig Topper8a13c412014-05-21 05:09:00 +00002536 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002537
2538 // If the argument wasn't provably non-null, we need to null check
2539 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002540 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002541 if (!provablyNonNull) {
2542 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2543 contBB = CGF.createBasicBlock("icr.done");
2544
John McCall7f416cc2015-09-08 08:05:57 +00002545 llvm::Value *isNull =
2546 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002547 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2548 CGF.EmitBlock(writebackBB);
2549 }
2550
2551 // Load the value to writeback.
2552 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2553
2554 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002555 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2556 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002557
2558 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002559
2560 // If we have a "to use" value, it's something we need to emit a use
2561 // of. This has to be carefully threaded in: if it's done after the
2562 // release it's potentially undefined behavior (and the optimizer
2563 // will ignore it), and if it happens before the retain then the
2564 // optimizer could move the release there.
2565 if (writeback.ToUse) {
2566 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2567
2568 // Retain the new value. No need to block-copy here: the block's
2569 // being passed up the stack.
2570 value = CGF.EmitARCRetainNonBlock(value);
2571
2572 // Emit the intrinsic use here.
2573 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2574
2575 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002576 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002577
2578 // Put the new value in place (primitively).
2579 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2580
2581 // Release the old value.
2582 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2583
2584 // Otherwise, we can just do a normal lvalue store.
2585 } else {
2586 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2587 }
John McCall31168b02011-06-15 23:02:42 +00002588
2589 // Jump to the continuation block.
2590 if (!provablyNonNull)
2591 CGF.EmitBlock(contBB);
2592}
2593
2594static void emitWritebacks(CodeGenFunction &CGF,
2595 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002596 for (const auto &I : args.writebacks())
2597 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002598}
2599
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002600static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2601 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002602 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002603 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2604 CallArgs.getCleanupsToDeactivate();
2605 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002606 for (const auto &I : llvm::reverse(Cleanups)) {
2607 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2608 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002609 }
2610}
2611
John McCalleff18842013-03-23 02:35:54 +00002612static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2613 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2614 if (uop->getOpcode() == UO_AddrOf)
2615 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002616 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002617}
2618
John McCall31168b02011-06-15 23:02:42 +00002619/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002620/// we are passing the address of an __autoreleased temporary; it
2621/// might be copy-initialized with the current value of the given
2622/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002623static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2624 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002625 LValue srcLV;
2626
2627 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002628 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002629 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2630 srcLV = CGF.EmitLValue(lvExpr);
2631
2632 // Otherwise, just emit it as a scalar.
2633 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002634 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002635
2636 QualType srcAddrType =
2637 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002638 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00002639 }
John McCall7f416cc2015-09-08 08:05:57 +00002640 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002641
2642 // The dest and src types don't necessarily match in LLVM terms
2643 // because of the crazy ObjC compatibility rules.
2644
Chris Lattner2192fe52011-07-18 04:24:23 +00002645 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002646 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2647
2648 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00002649 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00002650 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2651 CRE->getType());
2652 return;
2653 }
2654
John McCall31168b02011-06-15 23:02:42 +00002655 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00002656 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
2657 CGF.getPointerAlign(),
2658 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002659 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2660 // and that cleanup will be conditional if we can't prove that the l-value
2661 // isn't null, so we need to register a dominating point so that the cleanups
2662 // system will make valid IR.
2663 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2664
John McCall31168b02011-06-15 23:02:42 +00002665 // Zero-initialize it if we're not doing a copy-initialization.
2666 bool shouldCopy = CRE->shouldCopy();
2667 if (!shouldCopy) {
2668 llvm::Value *null =
2669 llvm::ConstantPointerNull::get(
2670 cast<llvm::PointerType>(destType->getElementType()));
2671 CGF.Builder.CreateStore(null, temp);
2672 }
Craig Topper8a13c412014-05-21 05:09:00 +00002673
2674 llvm::BasicBlock *contBB = nullptr;
2675 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002676
2677 // If the address is *not* known to be non-null, we need to switch.
2678 llvm::Value *finalArgument;
2679
John McCall7f416cc2015-09-08 08:05:57 +00002680 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002681 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00002682 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00002683 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002684 llvm::Value *isNull =
2685 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002686
2687 finalArgument = CGF.Builder.CreateSelect(isNull,
2688 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00002689 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00002690
2691 // If we need to copy, then the load has to be conditional, which
2692 // means we need control flow.
2693 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002694 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002695 contBB = CGF.createBasicBlock("icr.cont");
2696 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2697 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2698 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002699 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002700 }
2701 }
2702
Craig Topper8a13c412014-05-21 05:09:00 +00002703 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002704
John McCall31168b02011-06-15 23:02:42 +00002705 // Perform a copy if necessary.
2706 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002707 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002708 assert(srcRV.isScalar());
2709
2710 llvm::Value *src = srcRV.getScalarVal();
2711 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2712 "icr.cast");
2713
2714 // Use an ordinary store, not a store-to-lvalue.
2715 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002716
2717 // If optimization is enabled, and the value was held in a
2718 // __strong variable, we need to tell the optimizer that this
2719 // value has to stay alive until we're doing the store back.
2720 // This is because the temporary is effectively unretained,
2721 // and so otherwise we can violate the high-level semantics.
2722 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2723 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2724 valueToUse = src;
2725 }
John McCall31168b02011-06-15 23:02:42 +00002726 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002727
John McCall31168b02011-06-15 23:02:42 +00002728 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002729 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002730 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002731 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002732
2733 // Make a phi for the value to intrinsically use.
2734 if (valueToUse) {
2735 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2736 "icr.to-use");
2737 phiToUse->addIncoming(valueToUse, copyBB);
2738 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2739 originBB);
2740 valueToUse = phiToUse;
2741 }
2742
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002743 condEval.end(CGF);
2744 }
John McCall31168b02011-06-15 23:02:42 +00002745
John McCalleff18842013-03-23 02:35:54 +00002746 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002747 args.add(RValue::get(finalArgument), CRE->getType());
2748}
2749
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002750void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2751 assert(!StackBase && !StackCleanup.isValid());
2752
2753 // Save the stack.
2754 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00002755 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002756}
2757
Nico Weber8cdb3f92015-08-25 18:43:32 +00002758void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2759 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00002760 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00002761 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00002762 CGF.Builder.CreateCall(F, StackBase);
2763 }
2764}
2765
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002766void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
2767 SourceLocation ArgLoc,
2768 const FunctionDecl *FD,
2769 unsigned ParmNum) {
2770 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002771 return;
2772 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2773 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2774 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2775 if (!NNAttr)
2776 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002777 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002778 assert(RV.isScalar());
2779 llvm::Value *V = RV.getScalarVal();
2780 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002781 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002782 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002783 EmitCheckSourceLocation(ArgLoc),
2784 EmitCheckSourceLocation(NNAttr->getLocation()),
2785 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002786 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002787 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002788 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002789}
2790
David Blaikief05779e2015-07-21 18:37:18 +00002791void CodeGenFunction::EmitCallArgs(
2792 CallArgList &Args, ArrayRef<QualType> ArgTypes,
2793 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
2794 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
2795 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
Reid Kleckner739756c2013-12-04 19:23:12 +00002796 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2797 // because arguments are destroyed left to right in the callee.
2798 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002799 // Insert a stack save if we're going to need any inalloca args.
2800 bool HasInAllocaArgs = false;
2801 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2802 I != E && !HasInAllocaArgs; ++I)
2803 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2804 if (HasInAllocaArgs) {
2805 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2806 Args.allocateArgumentMemory(*this);
2807 }
2808
2809 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002810 size_t CallArgsStart = Args.size();
2811 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00002812 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00002813 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002814 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002815 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002816 }
2817
2818 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2819 // IR function.
2820 std::reverse(Args.begin() + CallArgsStart, Args.end());
2821 return;
2822 }
2823
2824 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00002825 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
2826 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00002827 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002828 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002829 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002830 }
2831}
2832
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002833namespace {
2834
David Blaikie7e70d682015-08-18 22:40:54 +00002835struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00002836 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002837 : Addr(Addr), Ty(Ty) {}
2838
John McCall7f416cc2015-09-08 08:05:57 +00002839 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002840 QualType Ty;
2841
Craig Topper4f12f102014-03-12 06:41:41 +00002842 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002843 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2844 assert(!Dtor->isTrivial());
2845 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2846 /*Delegating=*/false, Addr);
2847 }
2848};
2849
David Blaikie38b25912015-02-09 19:13:51 +00002850struct DisableDebugLocationUpdates {
2851 CodeGenFunction &CGF;
2852 bool disabledDebugInfo;
2853 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2854 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2855 CGF.disableDebugInfo();
2856 }
2857 ~DisableDebugLocationUpdates() {
2858 if (disabledDebugInfo)
2859 CGF.enableDebugInfo();
2860 }
2861};
2862
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002863} // end anonymous namespace
2864
John McCall32ea9692011-03-11 20:59:21 +00002865void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2866 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002867 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002868 if (const ObjCIndirectCopyRestoreExpr *CRE
2869 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002870 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002871 assert(getContext().hasSameType(E->getType(), type));
2872 return emitWritebackArg(*this, args, CRE);
2873 }
2874
John McCall0a76c0c2011-08-26 18:42:59 +00002875 assert(type->isReferenceType() == E->isGLValue() &&
2876 "reference binding to unmaterialized r-value!");
2877
John McCall17054bd62011-08-26 21:08:13 +00002878 if (E->isGLValue()) {
2879 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002880 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002881 }
Mike Stump11289f42009-09-09 15:08:12 +00002882
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002883 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2884
2885 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2886 // However, we still have to push an EH-only cleanup in case we unwind before
2887 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002888 if (HasAggregateEvalKind &&
2889 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2890 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002891 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002892 AggValueSlot Slot;
2893 if (args.isUsingInAlloca())
2894 Slot = createPlaceholderSlot(*this, type);
2895 else
2896 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002897
2898 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2899 bool DestroyedInCallee =
2900 RD && RD->hasNonTrivialDestructor() &&
2901 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2902 if (DestroyedInCallee)
2903 Slot.setExternallyDestructed();
2904
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002905 EmitAggExpr(E, Slot);
2906 RValue RV = Slot.asRValue();
2907 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002908
Reid Klecknere39ee212014-05-03 00:33:28 +00002909 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002910 // Create a no-op GEP between the placeholder and the cleanup so we can
2911 // RAUW it successfully. It also serves as a marker of the first
2912 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00002913 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
2914 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002915 // This unreachable is a temporary marker which will be removed later.
2916 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2917 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002918 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002919 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002920 }
2921
2922 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002923 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2924 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2925 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002926 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2927 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2928 } else {
2929 // We can't represent a misaligned lvalue in the CallArgList, so copy
2930 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00002931 Address tmp = CreateMemTemp(type);
2932 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00002933 args.add(RValue::getAggregate(tmp), type);
2934 }
Eli Friedmandf968192011-05-26 00:10:27 +00002935 return;
2936 }
2937
John McCall32ea9692011-03-11 20:59:21 +00002938 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002939}
2940
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002941QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2942 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2943 // implicitly widens null pointer constants that are arguments to varargs
2944 // functions to pointer-sized ints.
2945 if (!getTarget().getTriple().isOSWindows())
2946 return Arg->getType();
2947
2948 if (Arg->getType()->isIntegerType() &&
2949 getContext().getTypeSize(Arg->getType()) <
2950 getContext().getTargetInfo().getPointerWidth(0) &&
2951 Arg->isNullPointerConstant(getContext(),
2952 Expr::NPC_ValueDependentIsNotNull)) {
2953 return getContext().getIntPtrType();
2954 }
2955
2956 return Arg->getType();
2957}
2958
Dan Gohman515a60d2012-02-16 00:57:37 +00002959// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2960// optimizer it can aggressively ignore unwind edges.
2961void
2962CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2963 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2964 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2965 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2966 CGM.getNoObjCARCExceptionsMetadata());
2967}
2968
John McCall882987f2013-02-28 19:01:20 +00002969/// Emits a call to the given no-arguments nounwind runtime function.
2970llvm::CallInst *
2971CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2972 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002973 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002974}
2975
2976/// Emits a call to the given nounwind runtime function.
2977llvm::CallInst *
2978CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2979 ArrayRef<llvm::Value*> args,
2980 const llvm::Twine &name) {
2981 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2982 call->setDoesNotThrow();
2983 return call;
2984}
2985
2986/// Emits a simple call (never an invoke) to the given no-arguments
2987/// runtime function.
2988llvm::CallInst *
2989CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2990 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002991 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002992}
2993
2994/// Emits a simple call (never an invoke) to the given runtime
2995/// function.
2996llvm::CallInst *
2997CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2998 ArrayRef<llvm::Value*> args,
2999 const llvm::Twine &name) {
3000 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
3001 call->setCallingConv(getRuntimeCC());
3002 return call;
3003}
3004
3005/// Emits a call or invoke to the given noreturn runtime function.
3006void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3007 ArrayRef<llvm::Value*> args) {
3008 if (getInvokeDest()) {
3009 llvm::InvokeInst *invoke =
3010 Builder.CreateInvoke(callee,
3011 getUnreachableBlock(),
3012 getInvokeDest(),
3013 args);
3014 invoke->setDoesNotReturn();
3015 invoke->setCallingConv(getRuntimeCC());
3016 } else {
3017 llvm::CallInst *call = Builder.CreateCall(callee, args);
3018 call->setDoesNotReturn();
3019 call->setCallingConv(getRuntimeCC());
3020 Builder.CreateUnreachable();
3021 }
3022}
3023
3024/// Emits a call or invoke instruction to the given nullary runtime
3025/// function.
3026llvm::CallSite
3027CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3028 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003029 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003030}
3031
3032/// Emits a call or invoke instruction to the given runtime function.
3033llvm::CallSite
3034CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3035 ArrayRef<llvm::Value*> args,
3036 const Twine &name) {
3037 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3038 callSite.setCallingConv(getRuntimeCC());
3039 return callSite;
3040}
3041
John McCallbd309292010-07-06 01:34:17 +00003042/// Emits a call or invoke instruction to the given function, depending
3043/// on the current state of the EH stack.
3044llvm::CallSite
3045CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003046 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003047 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003048 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003049
Dan Gohman515a60d2012-02-16 00:57:37 +00003050 llvm::Instruction *Inst;
3051 if (!InvokeDest)
3052 Inst = Builder.CreateCall(Callee, Args, Name);
3053 else {
3054 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
3055 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
3056 EmitBlock(ContBB);
3057 }
3058
3059 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3060 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003061 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003062 AddObjCARCExceptionMetadata(Inst);
3063
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003064 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003065}
3066
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003067/// \brief Store a non-aggregate value to an address to initialize it. For
3068/// initialization, a non-atomic store will be used.
3069static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3070 LValue Dst) {
3071 if (Src.isScalar())
3072 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3073 else
3074 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3075}
3076
3077void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3078 llvm::Value *New) {
3079 DeferredReplacements.push_back(std::make_pair(Old, New));
3080}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003081
Daniel Dunbard931a872009-02-02 22:03:45 +00003082RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003083 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003084 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003085 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00003086 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00003087 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003088 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003089
3090 // Handle struct-return functions by passing a pointer to the
3091 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003092 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003093 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003094
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003095 llvm::FunctionType *IRFuncTy =
3096 cast<llvm::FunctionType>(
3097 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003098
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003099 // If we're using inalloca, insert the allocation after the stack save.
3100 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003101 Address ArgMemory = Address::invalid();
3102 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003103 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003104 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003105 llvm::Instruction *IP = CallArgs.getStackBase();
3106 llvm::AllocaInst *AI;
3107 if (IP) {
3108 IP = IP->getNextNode();
3109 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3110 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003111 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003112 }
John McCall7f416cc2015-09-08 08:05:57 +00003113 auto Align = CallInfo.getArgStructAlignment();
3114 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003115 AI->setUsedWithInAlloca(true);
3116 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003117 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003118 }
3119
John McCall7f416cc2015-09-08 08:05:57 +00003120 // Helper function to drill into the inalloca allocation.
3121 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3122 auto FieldOffset =
3123 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3124 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3125 };
3126
Alexey Samsonov153004f2014-09-29 22:08:00 +00003127 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003128 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3129
Chris Lattner4ca97c32009-06-13 00:26:38 +00003130 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003131 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003132 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003133 size_t UnusedReturnSize = 0;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003134 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003135 if (!ReturnValue.isNull()) {
3136 SRetPtr = ReturnValue.getValue();
3137 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003138 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003139 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3140 uint64_t size =
3141 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003142 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003143 UnusedReturnSize = size;
3144 }
3145 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003146 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003147 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003148 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003149 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3150 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003151 }
Anders Carlsson17490832009-12-24 20:40:36 +00003152 }
Mike Stump11289f42009-09-09 15:08:12 +00003153
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003154 assert(CallInfo.arg_size() == CallArgs.size() &&
3155 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003156 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003157 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003158 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003159 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003160 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003161 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003162
Rafael Espindolafad28de2012-10-24 01:59:00 +00003163 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003164 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3165 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3166 llvm::UndefValue::get(ArgInfo.getPaddingType());
3167
3168 unsigned FirstIRArg, NumIRArgs;
3169 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003170
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003171 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003172 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003173 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003174 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3175 if (RV.isAggregate()) {
3176 // Replace the placeholder with the appropriate argument slot GEP.
3177 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003178 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003179 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3180 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003181 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003182 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003183 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003184 } else {
3185 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003186 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3187 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003188 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3189 // There are some cases where a trivial bitcast is not avoidable. The
3190 // definition of a type later in a translation unit may change it's type
3191 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003192 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003193 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003194 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003195 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3196 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003197 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003198 }
3199
Daniel Dunbar03816342010-08-21 02:24:36 +00003200 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003201 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003202 if (RV.isScalar() || RV.isComplex()) {
3203 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003204 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3205 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003206
John McCall7f416cc2015-09-08 08:05:57 +00003207 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003208 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003209 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003210 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003211 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003212 // 1. If the argument is not byval, and we are required to copy the
3213 // source. (This case doesn't occur on any common architecture.)
3214 // 2. If the argument is byval, RV is not sufficiently aligned, and
3215 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003216 // 3. If the argument is byval, but RV is located in an address space
3217 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003218 Address Addr = RV.getAggregateAddress();
3219 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003220 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003221 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003222 const unsigned ArgAddrSpace =
3223 (FirstIRArg < IRFuncTy->getNumParams()
3224 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3225 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003226 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003227 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3228 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3229 Align.getQuantity(), *TD)
3230 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003231 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003232 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003233 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3234 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003235 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003236 } else {
3237 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003238 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003239 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003240 }
3241 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003242 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003243
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003244 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003245 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003246 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003247
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003248 case ABIArgInfo::Extend:
3249 case ABIArgInfo::Direct: {
3250 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003251 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3252 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003253 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003254 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003255 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003256 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003257 else
John McCall7f416cc2015-09-08 08:05:57 +00003258 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003259
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003260 // We might have to widen integers, but we should never truncate.
3261 if (ArgInfo.getCoerceToType() != V->getType() &&
3262 V->getType()->isIntegerTy())
3263 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3264
Chris Lattner3ce86682011-07-12 04:53:39 +00003265 // If the argument doesn't match, perform a bitcast to coerce it. This
3266 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003267 if (FirstIRArg < IRFuncTy->getNumParams() &&
3268 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3269 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3270 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003271 break;
3272 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003273
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003274 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003275 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003276 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003277 Src = CreateMemTemp(I->Ty, "coerce");
3278 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003279 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003280 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003281 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003282 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003283
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003284 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003285 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003286
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003287 // Fast-isel and the optimizer generally like scalar values better than
3288 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003289 llvm::StructType *STy =
3290 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003291 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003292 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003293 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3294 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3295
3296 // If the source type is smaller than the destination type of the
3297 // coerce-to logic, copy the source value into a temp alloca the size
3298 // of the destination type to allow loading all of it. The bits past
3299 // the source value are left undef.
3300 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003301 Address TempAlloca
3302 = CreateTempAlloca(STy, Src.getAlignment(),
3303 Src.getName() + ".coerce");
3304 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3305 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003306 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003307 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003308 }
3309
John McCall7f416cc2015-09-08 08:05:57 +00003310 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003311 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003312 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003313 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3314 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3315 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003316 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003317 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003318 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003319 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003320 assert(NumIRArgs == 1);
3321 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003322 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003323 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003324
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003325 break;
3326 }
3327
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003328 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003329 unsigned IRArgPos = FirstIRArg;
3330 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3331 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003332 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003333 }
3334 }
Mike Stump11289f42009-09-09 15:08:12 +00003335
John McCall7f416cc2015-09-08 08:05:57 +00003336 if (ArgMemory.isValid()) {
3337 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003338 if (CallInfo.isVariadic()) {
3339 // When passing non-POD arguments by value to variadic functions, we will
3340 // end up with a variadic prototype and an inalloca call site. In such
3341 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3342 // the callee.
3343 unsigned CalleeAS =
3344 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3345 Callee = Builder.CreateBitCast(
3346 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3347 } else {
3348 llvm::Type *LastParamTy =
3349 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3350 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003351#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003352 // Assert that these structs have equivalent element types.
3353 llvm::StructType *FullTy = CallInfo.getArgStruct();
3354 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3355 cast<llvm::PointerType>(LastParamTy)->getElementType());
3356 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3357 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3358 DE = DeclaredTy->element_end(),
3359 FI = FullTy->element_begin();
3360 DI != DE; ++DI, ++FI)
3361 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003362#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003363 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3364 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003365 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003366 assert(IRFunctionArgs.hasInallocaArg());
3367 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003368 }
3369
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003370 if (!CallArgs.getCleanupsToDeactivate().empty())
3371 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3372
Chris Lattner4ca97c32009-06-13 00:26:38 +00003373 // If the callee is a bitcast of a function to a varargs pointer to function
3374 // type, check to see if we can remove the bitcast. This handles some cases
3375 // with unprototyped functions.
3376 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3377 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003378 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3379 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003380 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003381 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003382
Chris Lattner4ca97c32009-06-13 00:26:38 +00003383 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3384 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003385 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003386 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003387 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003388 bool ArgsMatch = true;
3389 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3390 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3391 ArgsMatch = false;
3392 break;
3393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Chris Lattner4ca97c32009-06-13 00:26:38 +00003395 // Strip the cast if we can get away with it. This is a nice cleanup,
3396 // but also allows us to inline the function at -O0 if it is marked
3397 // always_inline.
3398 if (ArgsMatch)
3399 Callee = CalleeF;
3400 }
3401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003403 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3404 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3405 // Inalloca argument can have different type.
3406 if (IRFunctionArgs.hasInallocaArg() &&
3407 i == IRFunctionArgs.getInallocaArgNo())
3408 continue;
3409 if (i < IRFuncTy->getNumParams())
3410 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3411 }
3412
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003413 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003414 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003415 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3416 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003417 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003418 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003419
Craig Topper8a13c412014-05-21 05:09:00 +00003420 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003421 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00003422 llvm::Attribute::NoUnwind) ||
3423 currentFunctionUsesSEHTry())
John McCallbd309292010-07-06 01:34:17 +00003424 InvokeDest = getInvokeDest();
3425
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003426 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003427 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003428 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003429 } else {
3430 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003431 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003432 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003433 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003434 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003435 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003436
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003437 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3438 !CS.hasFnAttr(llvm::Attribute::NoInline))
3439 Attrs =
3440 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3441 llvm::Attribute::AlwaysInline);
3442
Reid Klecknera002bd52015-10-28 23:06:42 +00003443 // Disable inlining inside SEH __try blocks and cleanup funclets. None of the
3444 // funclet EH personalities that clang supports have tables that are
3445 // expressive enough to describe catching an exception inside a cleanup.
3446 // __CxxFrameHandler3, for example, will terminate the program without
3447 // catching it.
3448 // FIXME: Move this decision to the LLVM inliner. Before we can do that, the
3449 // inliner needs to know if a given call site is part of a cleanuppad.
3450 if (isSEHTryScope() || isCleanupPadScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003451 Attrs =
3452 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3453 llvm::Attribute::NoInline);
3454
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003455 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003456 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003457
Dan Gohman515a60d2012-02-16 00:57:37 +00003458 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3459 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003460 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003461 AddObjCARCExceptionMetadata(CS.getInstruction());
3462
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003463 // If the call doesn't return, finish the basic block and clear the
3464 // insertion point; this allows the rest of IRgen to discard
3465 // unreachable code.
3466 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003467 if (UnusedReturnSize)
3468 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003469 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003470
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003471 Builder.CreateUnreachable();
3472 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003473
Mike Stump18bb9282009-05-16 07:57:57 +00003474 // FIXME: For now, emit a dummy basic block because expr emitters in
3475 // generally are not ready to handle emitting expressions at unreachable
3476 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003477 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003478
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003479 // Return a reasonable RValue.
3480 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003481 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003482
3483 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003484 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003485 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003486
John McCall31168b02011-06-15 23:02:42 +00003487 // Emit any writebacks immediately. Arguably this should happen
3488 // after any return-value munging.
3489 if (CallArgs.hasWritebacks())
3490 emitWritebacks(*this, CallArgs);
3491
Nico Weber8cdb3f92015-08-25 18:43:32 +00003492 // The stack cleanup for inalloca arguments has to run out of the normal
3493 // lexical order, so deactivate it and run it manually here.
3494 CallArgs.freeArgumentMemory(*this);
3495
Akira Hatanakac8667622015-11-06 23:56:15 +00003496 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI))
3497 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3498 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
3499
Hal Finkelee90a222014-09-26 05:04:30 +00003500 RValue Ret = [&] {
3501 switch (RetAI.getKind()) {
3502 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003503 case ABIArgInfo::Indirect: {
3504 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3505 if (UnusedReturnSize)
3506 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003507 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003508 return ret;
3509 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003510
Hal Finkelee90a222014-09-26 05:04:30 +00003511 case ABIArgInfo::Ignore:
3512 // If we are ignoring an argument that had a result, make sure to
3513 // construct the appropriate return value for our caller.
3514 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003515
Hal Finkelee90a222014-09-26 05:04:30 +00003516 case ABIArgInfo::Extend:
3517 case ABIArgInfo::Direct: {
3518 llvm::Type *RetIRTy = ConvertType(RetTy);
3519 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3520 switch (getEvaluationKind(RetTy)) {
3521 case TEK_Complex: {
3522 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3523 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3524 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003525 }
Hal Finkelee90a222014-09-26 05:04:30 +00003526 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00003527 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003528 bool DestIsVolatile = ReturnValue.isVolatile();
3529
John McCall7f416cc2015-09-08 08:05:57 +00003530 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003531 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3532 DestIsVolatile = false;
3533 }
John McCall7f416cc2015-09-08 08:05:57 +00003534 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00003535 return RValue::getAggregate(DestPtr);
3536 }
3537 case TEK_Scalar: {
3538 // If the argument doesn't match, perform a bitcast to coerce it. This
3539 // can happen due to trivial type mismatches.
3540 llvm::Value *V = CI;
3541 if (V->getType() != RetIRTy)
3542 V = Builder.CreateBitCast(V, RetIRTy);
3543 return RValue::get(V);
3544 }
3545 }
3546 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003547 }
Hal Finkelee90a222014-09-26 05:04:30 +00003548
John McCall7f416cc2015-09-08 08:05:57 +00003549 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003550 bool DestIsVolatile = ReturnValue.isVolatile();
3551
John McCall7f416cc2015-09-08 08:05:57 +00003552 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003553 DestPtr = CreateMemTemp(RetTy, "coerce");
3554 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003555 }
Hal Finkelee90a222014-09-26 05:04:30 +00003556
3557 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003558 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
3559 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00003560
3561 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003562 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003563
Hal Finkelee90a222014-09-26 05:04:30 +00003564 case ABIArgInfo::Expand:
3565 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003566 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003567
Hal Finkelee90a222014-09-26 05:04:30 +00003568 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3569 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003570
Hal Finkelee90a222014-09-26 05:04:30 +00003571 if (Ret.isScalar() && TargetDecl) {
3572 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3573 llvm::Value *OffsetValue = nullptr;
3574 if (const auto *Offset = AA->getOffset())
3575 OffsetValue = EmitScalarExpr(Offset);
3576
3577 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3578 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3579 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3580 OffsetValue);
3581 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003582 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003583
Hal Finkelee90a222014-09-26 05:04:30 +00003584 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003585}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003586
3587/* VarArg handling */
3588
Charles Davisc7d5c942015-09-17 20:55:33 +00003589Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
3590 VAListAddr = VE->isMicrosoftABI()
3591 ? EmitMSVAListRef(VE->getSubExpr())
3592 : EmitVAListRef(VE->getSubExpr());
3593 QualType Ty = VE->getType();
3594 if (VE->isMicrosoftABI())
3595 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003596 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003597}