blob: c2e1e57463ad156d0d4e599113582f234cb4c080 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000033#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000034#include "llvm/Transforms/Utils/Local.h"
Eric Christopher70c16652015-03-25 23:14:47 +000035#include <sstream>
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 McCalla729c622012-02-17 03:33:10 +0000557 FI->NumArgs = argTypes.size();
558 FI->getArgsBuffer()[0].type = resultType;
559 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
560 FI->getArgsBuffer()[i + 1].type = argTypes[i];
561 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000562}
563
564/***/
565
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000566namespace {
567// ABIArgInfo::Expand implementation.
568
569// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
570struct TypeExpansion {
571 enum TypeExpansionKind {
572 // Elements of constant arrays are expanded recursively.
573 TEK_ConstantArray,
574 // Record fields are expanded recursively (but if record is a union, only
575 // the field with the largest size is expanded).
576 TEK_Record,
577 // For complex types, real and imaginary parts are expanded recursively.
578 TEK_Complex,
579 // All other types are not expandable.
580 TEK_None
581 };
582
583 const TypeExpansionKind Kind;
584
585 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
586 virtual ~TypeExpansion() {}
587};
588
589struct ConstantArrayExpansion : TypeExpansion {
590 QualType EltTy;
591 uint64_t NumElts;
592
593 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
594 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
595 static bool classof(const TypeExpansion *TE) {
596 return TE->Kind == TEK_ConstantArray;
597 }
598};
599
600struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000601 SmallVector<const CXXBaseSpecifier *, 1> Bases;
602
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000603 SmallVector<const FieldDecl *, 1> Fields;
604
Reid Klecknere9f6a712014-10-31 17:10:41 +0000605 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
606 SmallVector<const FieldDecl *, 1> &&Fields)
607 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000608 static bool classof(const TypeExpansion *TE) {
609 return TE->Kind == TEK_Record;
610 }
611};
612
613struct ComplexExpansion : TypeExpansion {
614 QualType EltTy;
615
616 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
617 static bool classof(const TypeExpansion *TE) {
618 return TE->Kind == TEK_Complex;
619 }
620};
621
622struct NoExpansion : TypeExpansion {
623 NoExpansion() : TypeExpansion(TEK_None) {}
624 static bool classof(const TypeExpansion *TE) {
625 return TE->Kind == TEK_None;
626 }
627};
628} // namespace
629
630static std::unique_ptr<TypeExpansion>
631getTypeExpansion(QualType Ty, const ASTContext &Context) {
632 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
633 return llvm::make_unique<ConstantArrayExpansion>(
634 AT->getElementType(), AT->getSize().getZExtValue());
635 }
636 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000637 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000638 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000639 const RecordDecl *RD = RT->getDecl();
640 assert(!RD->hasFlexibleArrayMember() &&
641 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000642 if (RD->isUnion()) {
643 // Unions can be here only in degenerative cases - all the fields are same
644 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000645 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000646 CharUnits UnionSize = CharUnits::Zero();
647
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000648 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000649 // Skip zero length bitfields.
650 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
651 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000652 assert(!FD->isBitField() &&
653 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000654 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000655 if (UnionSize < FieldSize) {
656 UnionSize = FieldSize;
657 LargestFD = FD;
658 }
659 }
660 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000661 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000662 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000663 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
664 assert(!CXXRD->isDynamicClass() &&
665 "cannot expand vtable pointers in dynamic classes");
666 for (const CXXBaseSpecifier &BS : CXXRD->bases())
667 Bases.push_back(&BS);
668 }
669
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000670 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000671 // Skip zero length bitfields.
672 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
673 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000674 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000675 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000676 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000677 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000678 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000679 return llvm::make_unique<RecordExpansion>(std::move(Bases),
680 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000681 }
682 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
683 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
684 }
685 return llvm::make_unique<NoExpansion>();
686}
687
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000688static int getExpansionSize(QualType Ty, const ASTContext &Context) {
689 auto Exp = getTypeExpansion(Ty, Context);
690 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
691 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
692 }
693 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
694 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000695 for (auto BS : RExp->Bases)
696 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000697 for (auto FD : RExp->Fields)
698 Res += getExpansionSize(FD->getType(), Context);
699 return Res;
700 }
701 if (isa<ComplexExpansion>(Exp.get()))
702 return 2;
703 assert(isa<NoExpansion>(Exp.get()));
704 return 1;
705}
706
Alexey Samsonov153004f2014-09-29 22:08:00 +0000707void
708CodeGenTypes::getExpandedTypes(QualType Ty,
709 SmallVectorImpl<llvm::Type *>::iterator &TI) {
710 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000711 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
712 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000713 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000714 }
715 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000716 for (auto BS : RExp->Bases)
717 getExpandedTypes(BS->getType(), TI);
718 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000719 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000720 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
721 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000722 *TI++ = EltTy;
723 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000724 } else {
725 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000726 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000727 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000728}
729
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000730void CodeGenFunction::ExpandTypeFromArgs(
731 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000732 assert(LV.isSimple() &&
733 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000734
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000735 auto Exp = getTypeExpansion(Ty, getContext());
736 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
737 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
David Blaikie17ea2662015-04-04 21:07:17 +0000738 llvm::Value *EltAddr =
739 Builder.CreateConstGEP2_32(nullptr, LV.getAddress(), 0, i);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000740 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
741 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000742 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000743 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000744 llvm::Value *This = LV.getAddress();
745 for (const CXXBaseSpecifier *BS : RExp->Bases) {
746 // Perform a single step derived-to-base conversion.
747 llvm::Value *Base =
748 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
749 /*NullCheckValue=*/false, SourceLocation());
750 LValue SubLV = MakeAddrLValue(Base, BS->getType());
751
752 // Recurse onto bases.
753 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
754 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000755 for (auto FD : RExp->Fields) {
756 // FIXME: What are the right qualifiers here?
757 LValue SubLV = EmitLValueForField(LV, FD);
758 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000759 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000760 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
David Blaikie2e804282015-04-05 22:47:07 +0000761 llvm::Value *RealAddr =
762 Builder.CreateStructGEP(nullptr, LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000763 EmitStoreThroughLValue(RValue::get(*AI++),
764 MakeAddrLValue(RealAddr, CExp->EltTy));
David Blaikie2e804282015-04-05 22:47:07 +0000765 llvm::Value *ImagAddr =
766 Builder.CreateStructGEP(nullptr, LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000767 EmitStoreThroughLValue(RValue::get(*AI++),
768 MakeAddrLValue(ImagAddr, CExp->EltTy));
769 } else {
770 assert(isa<NoExpansion>(Exp.get()));
771 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000772 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000773}
774
775void CodeGenFunction::ExpandTypeToArgs(
776 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
777 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
778 auto Exp = getTypeExpansion(Ty, getContext());
779 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
780 llvm::Value *Addr = RV.getAggregateAddr();
781 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
David Blaikie17ea2662015-04-04 21:07:17 +0000782 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(nullptr, Addr, 0, i);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000783 RValue EltRV =
784 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
785 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
786 }
787 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000788 llvm::Value *This = RV.getAggregateAddr();
789 for (const CXXBaseSpecifier *BS : RExp->Bases) {
790 // Perform a single step derived-to-base conversion.
791 llvm::Value *Base =
792 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
793 /*NullCheckValue=*/false, SourceLocation());
794 RValue BaseRV = RValue::getAggregate(Base);
795
796 // Recurse onto bases.
797 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
798 IRCallArgPos);
799 }
800
801 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000802 for (auto FD : RExp->Fields) {
803 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
804 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
805 IRCallArgPos);
806 }
807 } else if (isa<ComplexExpansion>(Exp.get())) {
808 ComplexPairTy CV = RV.getComplexVal();
809 IRCallArgs[IRCallArgPos++] = CV.first;
810 IRCallArgs[IRCallArgPos++] = CV.second;
811 } else {
812 assert(isa<NoExpansion>(Exp.get()));
813 assert(RV.isScalar() &&
814 "Unexpected non-scalar rvalue during struct expansion.");
815
816 // Insert a bitcast as needed.
817 llvm::Value *V = RV.getScalarVal();
818 if (IRCallArgPos < IRFuncTy->getNumParams() &&
819 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
820 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
821
822 IRCallArgs[IRCallArgPos++] = V;
823 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000824}
825
Chris Lattner895c52b2010-06-27 06:04:18 +0000826/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000827/// accessing some number of bytes out of it, try to gep into the struct to get
828/// at its inner goodness. Dive as deep as possible without entering an element
829/// with an in-memory size smaller than DstSize.
830static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000831EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000833 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000834 // We can't dive into a zero-element struct.
835 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000836
Chris Lattner2192fe52011-07-18 04:24:23 +0000837 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000838
Chris Lattner1cd66982010-06-27 05:56:15 +0000839 // 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 +0000840 // first element is the same size as the whole struct, we can enter it. The
841 // comparison must be made on the store size and not the alloca size. Using
842 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000843 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000844 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000845 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000846 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000847 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000848
Chris Lattner1cd66982010-06-27 05:56:15 +0000849 // GEP into the first element.
David Blaikie17ea2662015-04-04 21:07:17 +0000850 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcSTy, SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000851
Chris Lattner1cd66982010-06-27 05:56:15 +0000852 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000853 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000854 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000855 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000856 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000857
858 return SrcPtr;
859}
860
Chris Lattner055097f2010-06-27 06:26:04 +0000861/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
862/// are either integers or pointers. This does a truncation of the value if it
863/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000864///
865/// This behaves as if the value were coerced through memory, so on big-endian
866/// targets the high bits are preserved in a truncation, while little-endian
867/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000868static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000869 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000870 CodeGenFunction &CGF) {
871 if (Val->getType() == Ty)
872 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000873
Chris Lattner055097f2010-06-27 06:26:04 +0000874 if (isa<llvm::PointerType>(Val->getType())) {
875 // If this is Pointer->Pointer avoid conversion to and from int.
876 if (isa<llvm::PointerType>(Ty))
877 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000878
Chris Lattner055097f2010-06-27 06:26:04 +0000879 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000880 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000881 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000882
Chris Lattner2192fe52011-07-18 04:24:23 +0000883 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000884 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000885 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000886
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000887 if (Val->getType() != DestIntTy) {
888 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
889 if (DL.isBigEndian()) {
890 // Preserve the high bits on big-endian targets.
891 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000892 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
893 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
894
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000895 if (SrcSize > DstSize) {
896 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
897 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
898 } else {
899 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
900 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
901 }
902 } else {
903 // Little-endian targets preserve the low bits. No shifts required.
904 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
905 }
906 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000907
Chris Lattner055097f2010-06-27 06:26:04 +0000908 if (isa<llvm::PointerType>(Ty))
909 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
910 return Val;
911}
912
Chris Lattner1cd66982010-06-27 05:56:15 +0000913
914
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000915/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
916/// a pointer to an object of type \arg Ty.
917///
918/// This safely handles the case when the src type is smaller than the
919/// destination type; in this situation the values of bits which not
920/// present in the src are undefined.
921static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000922 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000923 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000924 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000925 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000926
Chris Lattnerd200eda2010-06-28 22:51:39 +0000927 // If SrcTy and Ty are the same, just do a load.
928 if (SrcTy == Ty)
929 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000930
Micah Villmowdd31ca12012-10-08 16:25:52 +0000931 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000932
Chris Lattner2192fe52011-07-18 04:24:23 +0000933 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000934 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000935 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
936 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000937
Micah Villmowdd31ca12012-10-08 16:25:52 +0000938 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000939
Chris Lattner055097f2010-06-27 06:26:04 +0000940 // If the source and destination are integer or pointer types, just do an
941 // extension or truncation to the desired type.
942 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
943 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
944 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
945 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
946 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000947
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000948 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000949 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000950 // Generally SrcSize is never greater than DstSize, since this means we are
951 // losing bits. However, this can happen in cases where the structure has
952 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000953 //
Mike Stump18bb9282009-05-16 07:57:57 +0000954 // FIXME: Assert that we aren't truncating non-padding bits when have access
955 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000956 llvm::Value *Casted =
957 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000958 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
959 // FIXME: Use better alignment / avoid requiring aligned load.
960 Load->setAlignment(1);
961 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000962 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000963
Chris Lattner3fcc7902010-06-27 01:06:27 +0000964 // Otherwise do coercion through memory. This is stupid, but
965 // simple.
966 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000967 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
968 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
969 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000970 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000971 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
972 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
973 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000974 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000975}
976
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000977// Function to store a first-class aggregate into memory. We prefer to
978// store the elements rather than the aggregate to be more friendly to
979// fast-isel.
980// FIXME: Do we need to recurse here?
981static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
982 llvm::Value *DestPtr, bool DestIsVolatile,
983 bool LowAlignment) {
984 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000985 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000986 dyn_cast<llvm::StructType>(Val->getType())) {
987 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
David Blaikie17ea2662015-04-04 21:07:17 +0000988 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(STy, DestPtr, 0, i);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000989 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
990 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
991 DestIsVolatile);
992 if (LowAlignment)
993 SI->setAlignment(1);
994 }
995 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000996 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
997 if (LowAlignment)
998 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000999 }
1000}
1001
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001002/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1003/// where the source and destination may have different types.
1004///
1005/// This safely handles the case when the src type is larger than the
1006/// destination type; the upper bits of the src will be lost.
1007static void CreateCoercedStore(llvm::Value *Src,
1008 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +00001009 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001010 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001011 llvm::Type *SrcTy = Src->getType();
1012 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001013 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001014 if (SrcTy == DstTy) {
1015 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1016 return;
1017 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001018
Micah Villmowdd31ca12012-10-08 16:25:52 +00001019 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001020
Chris Lattner2192fe52011-07-18 04:24:23 +00001021 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +00001022 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1023 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1024 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001025
Chris Lattner055097f2010-06-27 06:26:04 +00001026 // If the source and destination are integer or pointer types, just do an
1027 // extension or truncation to the desired type.
1028 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1029 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1030 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1031 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1032 return;
1033 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001034
Micah Villmowdd31ca12012-10-08 16:25:52 +00001035 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001036
Daniel Dunbar313321e2009-02-03 05:31:23 +00001037 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001038 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001039 llvm::Value *Casted =
1040 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +00001041 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001042 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001043 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001044 // Otherwise do coercion through memory. This is stupid, but
1045 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001046
1047 // Generally SrcSize is never greater than DstSize, since this means we are
1048 // losing bits. However, this can happen in cases where the structure has
1049 // additional padding, for example due to a user specified alignment.
1050 //
1051 // FIXME: Assert that we aren't truncating non-padding bits when have access
1052 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001053 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1054 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001055 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1056 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1057 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001058 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001059 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1060 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1061 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001062 }
1063}
1064
Alexey Samsonov153004f2014-09-29 22:08:00 +00001065namespace {
1066
1067/// Encapsulates information about the way function arguments from
1068/// CGFunctionInfo should be passed to actual LLVM IR function.
1069class ClangToLLVMArgMapping {
1070 static const unsigned InvalidIndex = ~0U;
1071 unsigned InallocaArgNo;
1072 unsigned SRetArgNo;
1073 unsigned TotalIRArgs;
1074
1075 /// Arguments of LLVM IR function corresponding to single Clang argument.
1076 struct IRArgs {
1077 unsigned PaddingArgIndex;
1078 // Argument is expanded to IR arguments at positions
1079 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1080 unsigned FirstArgIndex;
1081 unsigned NumberOfArgs;
1082
1083 IRArgs()
1084 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1085 NumberOfArgs(0) {}
1086 };
1087
1088 SmallVector<IRArgs, 8> ArgInfo;
1089
1090public:
1091 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1092 bool OnlyRequiredArgs = false)
1093 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1094 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1095 construct(Context, FI, OnlyRequiredArgs);
1096 }
1097
1098 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1099 unsigned getInallocaArgNo() const {
1100 assert(hasInallocaArg());
1101 return InallocaArgNo;
1102 }
1103
1104 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1105 unsigned getSRetArgNo() const {
1106 assert(hasSRetArg());
1107 return SRetArgNo;
1108 }
1109
1110 unsigned totalIRArgs() const { return TotalIRArgs; }
1111
1112 bool hasPaddingArg(unsigned ArgNo) const {
1113 assert(ArgNo < ArgInfo.size());
1114 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1115 }
1116 unsigned getPaddingArgNo(unsigned ArgNo) const {
1117 assert(hasPaddingArg(ArgNo));
1118 return ArgInfo[ArgNo].PaddingArgIndex;
1119 }
1120
1121 /// Returns index of first IR argument corresponding to ArgNo, and their
1122 /// quantity.
1123 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1124 assert(ArgNo < ArgInfo.size());
1125 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1126 ArgInfo[ArgNo].NumberOfArgs);
1127 }
1128
1129private:
1130 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1131 bool OnlyRequiredArgs);
1132};
1133
1134void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1135 const CGFunctionInfo &FI,
1136 bool OnlyRequiredArgs) {
1137 unsigned IRArgNo = 0;
1138 bool SwapThisWithSRet = false;
1139 const ABIArgInfo &RetAI = FI.getReturnInfo();
1140
1141 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1142 SwapThisWithSRet = RetAI.isSRetAfterThis();
1143 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1144 }
1145
1146 unsigned ArgNo = 0;
1147 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1148 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1149 ++I, ++ArgNo) {
1150 assert(I != FI.arg_end());
1151 QualType ArgType = I->type;
1152 const ABIArgInfo &AI = I->info;
1153 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1154 auto &IRArgs = ArgInfo[ArgNo];
1155
1156 if (AI.getPaddingType())
1157 IRArgs.PaddingArgIndex = IRArgNo++;
1158
1159 switch (AI.getKind()) {
1160 case ABIArgInfo::Extend:
1161 case ABIArgInfo::Direct: {
1162 // FIXME: handle sseregparm someday...
1163 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1164 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1165 IRArgs.NumberOfArgs = STy->getNumElements();
1166 } else {
1167 IRArgs.NumberOfArgs = 1;
1168 }
1169 break;
1170 }
1171 case ABIArgInfo::Indirect:
1172 IRArgs.NumberOfArgs = 1;
1173 break;
1174 case ABIArgInfo::Ignore:
1175 case ABIArgInfo::InAlloca:
1176 // ignore and inalloca doesn't have matching LLVM parameters.
1177 IRArgs.NumberOfArgs = 0;
1178 break;
1179 case ABIArgInfo::Expand: {
1180 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1181 break;
1182 }
1183 }
1184
1185 if (IRArgs.NumberOfArgs > 0) {
1186 IRArgs.FirstArgIndex = IRArgNo;
1187 IRArgNo += IRArgs.NumberOfArgs;
1188 }
1189
1190 // Skip over the sret parameter when it comes second. We already handled it
1191 // above.
1192 if (IRArgNo == 1 && SwapThisWithSRet)
1193 IRArgNo++;
1194 }
1195 assert(ArgNo == ArgInfo.size());
1196
1197 if (FI.usesInAlloca())
1198 InallocaArgNo = IRArgNo++;
1199
1200 TotalIRArgs = IRArgNo;
1201}
1202} // namespace
1203
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001204/***/
1205
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001206bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001207 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001208}
1209
Tim Northovere77cc392014-03-29 13:28:05 +00001210bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1211 return ReturnTypeUsesSRet(FI) &&
1212 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1213}
1214
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001215bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1216 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1217 switch (BT->getKind()) {
1218 default:
1219 return false;
1220 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001221 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001222 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001223 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001224 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001225 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001226 }
1227 }
1228
1229 return false;
1230}
1231
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001232bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1233 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1234 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1235 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001236 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001237 }
1238 }
1239
1240 return false;
1241}
1242
Chris Lattnera5f58b02011-07-09 17:41:47 +00001243llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001244 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1245 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001246}
1247
Chris Lattnera5f58b02011-07-09 17:41:47 +00001248llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001249CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001250
David Blaikie82e95a32014-11-19 07:49:47 +00001251 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1252 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001253 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001254
Alexey Samsonov153004f2014-09-29 22:08:00 +00001255 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001256 const ABIArgInfo &retAI = FI.getReturnInfo();
1257 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001258 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001259 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001260
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001261 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001262 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001263 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001264 break;
1265
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001266 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001267 if (retAI.getInAllocaSRet()) {
1268 // sret things on win32 aren't void, they return the sret pointer.
1269 QualType ret = FI.getReturnType();
1270 llvm::Type *ty = ConvertType(ret);
1271 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1272 resultType = llvm::PointerType::get(ty, addressSpace);
1273 } else {
1274 resultType = llvm::Type::getVoidTy(getLLVMContext());
1275 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001276 break;
1277
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001278 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001279 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1280 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001281 break;
1282 }
1283
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001284 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001285 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001286 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Alexey Samsonov153004f2014-09-29 22:08:00 +00001289 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1290 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1291
1292 // Add type for sret argument.
1293 if (IRFunctionArgs.hasSRetArg()) {
1294 QualType Ret = FI.getReturnType();
1295 llvm::Type *Ty = ConvertType(Ret);
1296 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1297 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1298 llvm::PointerType::get(Ty, AddressSpace);
1299 }
1300
1301 // Add type for inalloca argument.
1302 if (IRFunctionArgs.hasInallocaArg()) {
1303 auto ArgStruct = FI.getArgStruct();
1304 assert(ArgStruct);
1305 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1306 }
1307
John McCallc818bbb2012-12-07 07:03:17 +00001308 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001309 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001310 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1311 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001312 for (; it != ie; ++it, ++ArgNo) {
1313 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Rafael Espindolafad28de2012-10-24 01:59:00 +00001315 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001316 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1317 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1318 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001319
Alexey Samsonov153004f2014-09-29 22:08:00 +00001320 unsigned FirstIRArg, NumIRArgs;
1321 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1322
1323 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001324 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001325 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001326 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001327 break;
1328
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001329 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001330 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001331 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001332 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001333 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001334 break;
1335 }
1336
1337 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001338 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001339 // Fast-isel and the optimizer generally like scalar values better than
1340 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001341 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001342 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001343 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1344 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001345 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001346 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001347 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001348 assert(NumIRArgs == 1);
1349 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001350 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001351 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Daniel Dunbard3674e62008-09-11 01:48:57 +00001354 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001355 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1356 getExpandedTypes(it->type, ArgTypesIter);
1357 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001358 break;
1359 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001360 }
1361
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001362 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1363 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001364
1365 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001366}
1367
Chris Lattner2192fe52011-07-18 04:24:23 +00001368llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001369 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001370 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001371
Chris Lattner8806e322011-07-10 00:18:59 +00001372 if (!isFuncTypeConvertible(FPT))
1373 return llvm::StructType::get(getLLVMContext());
1374
1375 const CGFunctionInfo *Info;
1376 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001377 Info =
1378 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001379 else
John McCalla729c622012-02-17 03:33:10 +00001380 Info = &arrangeCXXMethodDeclaration(MD);
1381 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001382}
1383
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001384void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001385 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001386 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001387 unsigned &CallingConv,
1388 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001389 llvm::AttrBuilder FuncAttrs;
1390 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001391 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001392
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001393 CallingConv = FI.getEffectiveCallingConvention();
1394
John McCallab26cfa2010-02-05 21:31:56 +00001395 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001396 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001397
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001398 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001399 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001400 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001401 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001402 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001403 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001404 if (TargetDecl->hasAttr<NoReturnAttr>())
1405 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001406 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1407 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001408
1409 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001410 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001411 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001412 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001413 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1414 // These attributes are not inherited by overloads.
1415 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1416 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001417 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001418 }
1419
Eric Christopherbf005ec2011-08-15 22:38:22 +00001420 // 'const' and 'pure' attribute functions are also nounwind.
1421 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001422 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1423 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001424 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001425 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1426 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001427 }
David Majnemer631a90b2015-02-04 07:23:21 +00001428 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001429 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001430 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1431 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001432
1433 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001434 }
1435
Paul Robinson08556952014-12-11 20:14:04 +00001436 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1437 if (!HasOptnone) {
1438 if (CodeGenOpts.OptimizeSize)
1439 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1440 if (CodeGenOpts.OptimizeSize == 2)
1441 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1442 }
1443
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001444 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001445 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001446 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001447 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001448 if (CodeGenOpts.EnableSegmentedStacks &&
1449 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001450 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001451
Bill Wendling2f81db62013-02-22 20:53:29 +00001452 if (AttrOnCallSite) {
1453 // Attributes that should go on the call site only.
1454 if (!CodeGenOpts.SimplifyLibCalls)
1455 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001456 } else {
1457 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001458 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001459 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001460 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001461 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001462 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001463 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001464 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001465 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001466 }
1467
Akira Hatanaka262a4c42015-06-09 19:04:36 +00001468 FuncAttrs.addAttribute("disable-tail-calls",
1469 llvm::toStringRef(CodeGenOpts.DisableTailCalls));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001470 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001471 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001472 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001473 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001474 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001475 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001476 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001477 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001478 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001479 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001480 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001481 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001482
Bill Wendlingd8f49502013-08-01 21:41:02 +00001483 if (!CodeGenOpts.StackRealignment)
1484 FuncAttrs.addAttribute("no-realign-stack");
Eric Christopher70c16652015-03-25 23:14:47 +00001485
1486 // Add target-cpu and target-features work if they differ from the defaults.
1487 std::string &CPU = getTarget().getTargetOpts().CPU;
Eric Christopherf37ab1c2015-04-27 23:11:34 +00001488 if (CPU != "")
1489 FuncAttrs.addAttribute("target-cpu", CPU);
Eric Christopher70c16652015-03-25 23:14:47 +00001490
Eric Christopherf37ab1c2015-04-27 23:11:34 +00001491 // TODO: Features gets us the features on the command line including
1492 // feature dependencies. For canonicalization purposes we might want to
1493 // avoid putting features in the target-features set if we know it'll be one
1494 // of the default features in the backend, e.g. corei7-avx and +avx or figure
1495 // out non-explicit dependencies.
1496 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
Eric Christopher70c16652015-03-25 23:14:47 +00001497 if (!Features.empty()) {
1498 std::stringstream S;
1499 std::copy(Features.begin(), Features.end(),
1500 std::ostream_iterator<std::string>(S, ","));
1501 // The drop_back gets rid of the trailing space.
1502 FuncAttrs.addAttribute("target-features",
1503 StringRef(S.str()).drop_back(1));
1504 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001505 }
1506
Alexey Samsonov153004f2014-09-29 22:08:00 +00001507 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001508
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001509 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001510 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001511 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001512 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001513 if (RetTy->hasSignedIntegerRepresentation())
1514 RetAttrs.addAttribute(llvm::Attribute::SExt);
1515 else if (RetTy->hasUnsignedIntegerRepresentation())
1516 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001517 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001518 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001519 if (RetAI.getInReg())
1520 RetAttrs.addAttribute(llvm::Attribute::InReg);
1521 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001522 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001523 break;
1524
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001525 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001526 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001527 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001528 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1529 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001530 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001531 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001532
Daniel Dunbard3674e62008-09-11 01:48:57 +00001533 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001534 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001535 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001536
Hal Finkela2347ba2014-07-18 15:52:10 +00001537 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1538 QualType PTy = RefTy->getPointeeType();
1539 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1540 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1541 .getQuantity());
1542 else if (getContext().getTargetAddressSpace(PTy) == 0)
1543 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1544 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001545
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001546 // Attach return attributes.
1547 if (RetAttrs.hasAttributes()) {
1548 PAL.push_back(llvm::AttributeSet::get(
1549 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1550 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001551
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001552 // Attach attributes to sret.
1553 if (IRFunctionArgs.hasSRetArg()) {
1554 llvm::AttrBuilder SRETAttrs;
1555 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1556 if (RetAI.getInReg())
1557 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1558 PAL.push_back(llvm::AttributeSet::get(
1559 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1560 }
1561
1562 // Attach attributes to inalloca argument.
1563 if (IRFunctionArgs.hasInallocaArg()) {
1564 llvm::AttrBuilder Attrs;
1565 Attrs.addAttribute(llvm::Attribute::InAlloca);
1566 PAL.push_back(llvm::AttributeSet::get(
1567 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1568 }
1569
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001570 unsigned ArgNo = 0;
1571 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1572 E = FI.arg_end();
1573 I != E; ++I, ++ArgNo) {
1574 QualType ParamType = I->type;
1575 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001576 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001577
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001578 // Add attribute for padding argument, if necessary.
1579 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001580 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001581 PAL.push_back(llvm::AttributeSet::get(
1582 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1583 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001584 }
1585
John McCall39ec71f2010-03-27 00:47:27 +00001586 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1587 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001588 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001589 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001590 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001591 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001592 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001593 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1594 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1595 Attrs.addAttribute(llvm::Attribute::SExt);
1596 else
1597 Attrs.addAttribute(llvm::Attribute::ZExt);
1598 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001599 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001600 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001601 if (ArgNo == 0 && FI.isChainCall())
1602 Attrs.addAttribute(llvm::Attribute::Nest);
1603 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001604 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001605 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001606
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001607 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001608 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001609 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001610
Anders Carlsson20759ad2009-09-16 15:53:40 +00001611 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001612 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001613
Bill Wendlinga7912f82012-10-10 07:36:56 +00001614 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1615
Daniel Dunbarc2304432009-03-18 19:51:01 +00001616 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001617 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1618 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001619 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001620
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001621 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001622 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001623 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001624
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001625 case ABIArgInfo::InAlloca:
1626 // inalloca disables readnone and readonly.
1627 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1628 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001629 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
Hal Finkela2347ba2014-07-18 15:52:10 +00001632 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1633 QualType PTy = RefTy->getPointeeType();
1634 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1635 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1636 .getQuantity());
1637 else if (getContext().getTargetAddressSpace(PTy) == 0)
1638 Attrs.addAttribute(llvm::Attribute::NonNull);
1639 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001640
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001641 if (Attrs.hasAttributes()) {
1642 unsigned FirstIRArg, NumIRArgs;
1643 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1644 for (unsigned i = 0; i < NumIRArgs; i++)
1645 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1646 FirstIRArg + i + 1, Attrs));
1647 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001648 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001649 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001650
Bill Wendlinga7912f82012-10-10 07:36:56 +00001651 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001652 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001653 AttributeSet::get(getLLVMContext(),
1654 llvm::AttributeSet::FunctionIndex,
1655 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001656}
1657
John McCalla738c252011-03-09 04:27:21 +00001658/// An argument came in as a promoted argument; demote it back to its
1659/// declared type.
1660static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1661 const VarDecl *var,
1662 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001663 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001664
1665 // This can happen with promotions that actually don't change the
1666 // underlying type, like the enum promotions.
1667 if (value->getType() == varType) return value;
1668
1669 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1670 && "unexpected promotion type");
1671
1672 if (isa<llvm::IntegerType>(varType))
1673 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1674
1675 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1676}
1677
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001678/// Returns the attribute (either parameter attribute, or function
1679/// attribute), which declares argument ArgNo to be non-null.
1680static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1681 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001682 // FIXME: __attribute__((nonnull)) can also be applied to:
1683 // - references to pointers, where the pointee is known to be
1684 // nonnull (apparently a Clang extension)
1685 // - transparent unions containing pointers
1686 // In the former case, LLVM IR cannot represent the constraint. In
1687 // the latter case, we have no guarantee that the transparent union
1688 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001689 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1690 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001691 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001692 if (PVD) {
1693 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1694 return ParmNNAttr;
1695 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001696 // Check function attributes.
1697 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001698 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001699 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001700 if (NNAttr->isNonNull(ArgNo))
1701 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001702 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001703 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001704}
1705
Daniel Dunbard931a872009-02-02 22:03:45 +00001706void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1707 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001708 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001709 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1710 // Naked functions don't have prologues.
1711 return;
1712
John McCallcaa19452009-07-28 01:00:58 +00001713 // If this is an implicit-return-zero function, go ahead and
1714 // initialize the return value. TODO: it might be nice to have
1715 // a more general mechanism for this that didn't require synthesized
1716 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001717 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001718 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001719 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001720 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001721 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001722 Builder.CreateStore(Zero, ReturnValue);
1723 }
1724 }
1725
Mike Stump18bb9282009-05-16 07:57:57 +00001726 // FIXME: We no longer need the types from FunctionArgList; lift up and
1727 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001728
Alexey Samsonov153004f2014-09-29 22:08:00 +00001729 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001730 // Flattened function arguments.
1731 SmallVector<llvm::Argument *, 16> FnArgs;
1732 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1733 for (auto &Arg : Fn->args()) {
1734 FnArgs.push_back(&Arg);
1735 }
1736 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001737
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001738 // If we're using inalloca, all the memory arguments are GEPs off of the last
1739 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001740 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001741 if (IRFunctionArgs.hasInallocaArg()) {
1742 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001743 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1744 }
1745
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001746 // Name the struct return parameter.
1747 if (IRFunctionArgs.hasSRetArg()) {
1748 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001749 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001750 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001751 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001752 }
Mike Stump11289f42009-09-09 15:08:12 +00001753
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001754 // Track if we received the parameter as a pointer (indirect, byval, or
1755 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1756 // into a local alloca for us.
1757 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001758 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001759 SmallVector<ValueAndIsPtr, 16> ArgVals;
1760 ArgVals.reserve(Args.size());
1761
Reid Kleckner739756c2013-12-04 19:23:12 +00001762 // Create a pointer value for every parameter declaration. This usually
1763 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1764 // any cleanups or do anything that might unwind. We do that separately, so
1765 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001766 assert(FI.arg_size() == Args.size() &&
1767 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001768 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001769 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001770 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001771 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001772 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001773 QualType Ty = info_it->type;
1774 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001775
John McCalla738c252011-03-09 04:27:21 +00001776 bool isPromoted =
1777 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1778
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001779 unsigned FirstIRArg, NumIRArgs;
1780 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001781
Daniel Dunbard3674e62008-09-11 01:48:57 +00001782 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001783 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001784 assert(NumIRArgs == 0);
David Blaikie1ed728c2015-04-05 22:45:47 +00001785 llvm::Value *V =
1786 Builder.CreateStructGEP(FI.getArgStruct(), ArgStruct,
1787 ArgI.getInAllocaFieldIndex(), Arg->getName());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001788 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001789 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001790 }
1791
Daniel Dunbar747865a2009-02-05 09:16:39 +00001792 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001793 assert(NumIRArgs == 1);
1794 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001795
John McCall47fb9502013-03-07 21:37:08 +00001796 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001797 // Aggregates and complex variables are accessed by reference. All we
1798 // need to do is realign the value, if requested
1799 if (ArgI.getIndirectRealign()) {
1800 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1801
1802 // Copy from the incoming argument pointer to the temporary with the
1803 // appropriate alignment.
1804 //
1805 // FIXME: We should have a common utility for generating an aggregate
1806 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001807 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001808 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001809 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1810 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1811 Builder.CreateMemCpy(Dst,
1812 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001813 llvm::ConstantInt::get(IntPtrTy,
1814 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001815 ArgI.getIndirectAlign(),
1816 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001817 V = AlignedTemp;
1818 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001819 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001820 } else {
1821 // Load scalar value from indirect argument.
David Majnemere1544562015-04-24 01:25:05 +00001822 V = EmitLoadOfScalar(V, false, ArgI.getIndirectAlign(), Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001823 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001824
1825 if (isPromoted)
1826 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001827 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001828 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001829 break;
1830 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001831
1832 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001833 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001834
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001835 // If we have the trivial case, handle it with no muss and fuss.
1836 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001837 ArgI.getCoerceToType() == ConvertType(Ty) &&
1838 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001839 assert(NumIRArgs == 1);
1840 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001841 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001842
Hal Finkel48d53e22014-07-19 01:41:07 +00001843 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001844 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1845 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001846 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1847 AI->getArgNo() + 1,
1848 llvm::Attribute::NonNull));
1849
Hal Finkel48d53e22014-07-19 01:41:07 +00001850 QualType OTy = PVD->getOriginalType();
1851 if (const auto *ArrTy =
1852 getContext().getAsConstantArrayType(OTy)) {
1853 // A C99 array parameter declaration with the static keyword also
1854 // indicates dereferenceability, and if the size is constant we can
1855 // use the dereferenceable attribute (which requires the size in
1856 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001857 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001858 QualType ETy = ArrTy->getElementType();
1859 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1860 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1861 ArrSize) {
1862 llvm::AttrBuilder Attrs;
1863 Attrs.addDereferenceableAttr(
1864 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1865 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1866 AI->getArgNo() + 1, Attrs));
1867 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1868 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1869 AI->getArgNo() + 1,
1870 llvm::Attribute::NonNull));
1871 }
1872 }
1873 } else if (const auto *ArrTy =
1874 getContext().getAsVariableArrayType(OTy)) {
1875 // For C99 VLAs with the static keyword, we don't know the size so
1876 // we can't use the dereferenceable attribute, but in addrspace(0)
1877 // we know that it must be nonnull.
1878 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1879 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1880 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1881 AI->getArgNo() + 1,
1882 llvm::Attribute::NonNull));
1883 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001884
1885 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1886 if (!AVAttr)
1887 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1888 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1889 if (AVAttr) {
1890 llvm::Value *AlignmentValue =
1891 EmitScalarExpr(AVAttr->getAlignment());
1892 llvm::ConstantInt *AlignmentCI =
1893 cast<llvm::ConstantInt>(AlignmentValue);
1894 unsigned Alignment =
1895 std::min((unsigned) AlignmentCI->getZExtValue(),
1896 +llvm::Value::MaximumAlignment);
1897
1898 llvm::AttrBuilder Attrs;
1899 Attrs.addAlignmentAttr(Alignment);
1900 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1901 AI->getArgNo() + 1, Attrs));
1902 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001903 }
1904
Bill Wendling507c3512012-10-16 05:23:44 +00001905 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001906 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1907 AI->getArgNo() + 1,
1908 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001909
Chris Lattner7369c142011-07-20 06:29:00 +00001910 // Ensure the argument is the correct type.
1911 if (V->getType() != ArgI.getCoerceToType())
1912 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1913
John McCalla738c252011-03-09 04:27:21 +00001914 if (isPromoted)
1915 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001916
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001917 if (const CXXMethodDecl *MD =
1918 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001919 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001920 V = CGM.getCXXABI().
1921 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001922 }
1923
Rafael Espindola8778c282012-11-29 16:09:03 +00001924 // Because of merging of function types from multiple decls it is
1925 // possible for the type of an argument to not match the corresponding
1926 // type in the function type. Since we are codegening the callee
1927 // in here, add a cast to the argument type.
1928 llvm::Type *LTy = ConvertType(Arg->getType());
1929 if (V->getType() != LTy)
1930 V = Builder.CreateBitCast(V, LTy);
1931
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001932 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001933 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001936 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001937
Chris Lattnerff941a62010-07-28 18:24:28 +00001938 // The alignment we need to use is the max of the requested alignment for
1939 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001940 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001941 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001942 AlignmentToUse = std::max(AlignmentToUse,
1943 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001944
Chris Lattnerff941a62010-07-28 18:24:28 +00001945 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001946 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001947 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001948
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001949 // If the value is offset in memory, apply the offset now.
1950 if (unsigned Offs = ArgI.getDirectOffset()) {
1951 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
David Blaikie5e259a82015-04-03 22:54:16 +00001952 Ptr = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001953 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001954 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1955 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001956
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001957 // Fast-isel and the optimizer generally like scalar values better than
1958 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001959 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001960 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1961 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001962 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001963 llvm::Type *DstTy =
1964 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001965 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001966
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001967 if (SrcSize <= DstSize) {
1968 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1969
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001970 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001971 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001972 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001973 AI->setName(Arg->getName() + ".coerce" + Twine(i));
David Blaikie17ea2662015-04-04 21:07:17 +00001974 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(STy, Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001975 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001976 }
1977 } else {
1978 llvm::AllocaInst *TempAlloca =
1979 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1980 TempAlloca->setAlignment(AlignmentToUse);
1981 llvm::Value *TempV = TempAlloca;
1982
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001983 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001984 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001985 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001986 AI->setName(Arg->getName() + ".coerce" + Twine(i));
David Blaikie17ea2662015-04-04 21:07:17 +00001987 llvm::Value *EltPtr =
1988 Builder.CreateConstGEP2_32(ArgI.getCoerceToType(), TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001989 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001990 }
1991
1992 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001993 }
1994 } else {
1995 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001996 assert(NumIRArgs == 1);
1997 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001998 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001999 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002000 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002001
2002
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002003 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002004 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002005 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002006 if (isPromoted)
2007 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002008 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
2009 } else {
2010 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002011 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002012 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002013 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002014
2015 case ABIArgInfo::Expand: {
2016 // If this structure was expanded into multiple arguments then
2017 // we need to create a temporary and reconstruct it from the
2018 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00002019 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00002020 CharUnits Align = getContext().getDeclAlign(Arg);
2021 Alloca->setAlignment(Align.getQuantity());
2022 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002023 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002024
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002025 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2026 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2027 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2028 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2029 auto AI = FnArgs[FirstIRArg + i];
2030 AI->setName(Arg->getName() + "." + Twine(i));
2031 }
2032 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002033 }
2034
2035 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002036 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002037 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002038 if (!hasScalarEvaluationKind(Ty)) {
2039 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
2040 } else {
2041 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2042 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
2043 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002044 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002045 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002046 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002047
Reid Kleckner739756c2013-12-04 19:23:12 +00002048 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2049 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002050 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2051 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002052 } else {
2053 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002054 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2055 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002056 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002057}
2058
John McCallffa2c1a2012-01-29 07:46:59 +00002059static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2060 while (insn->use_empty()) {
2061 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2062 if (!bitcast) return;
2063
2064 // This is "safe" because we would have used a ConstantExpr otherwise.
2065 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2066 bitcast->eraseFromParent();
2067 }
2068}
2069
John McCall31168b02011-06-15 23:02:42 +00002070/// Try to emit a fused autorelease of a return result.
2071static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2072 llvm::Value *result) {
2073 // We must be immediately followed the cast.
2074 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002075 if (BB->empty()) return nullptr;
2076 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002077
Chris Lattner2192fe52011-07-18 04:24:23 +00002078 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002079
2080 // result is in a BasicBlock and is therefore an Instruction.
2081 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2082
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002083 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002084
2085 // Look for:
2086 // %generator = bitcast %type1* %generator2 to %type2*
2087 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2088 // We would have emitted this as a constant if the operand weren't
2089 // an Instruction.
2090 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2091
2092 // Require the generator to be immediately followed by the cast.
2093 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002094 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002095
2096 insnsToKill.push_back(bitcast);
2097 }
2098
2099 // Look for:
2100 // %generator = call i8* @objc_retain(i8* %originalResult)
2101 // or
2102 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2103 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002104 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002105
2106 bool doRetainAutorelease;
2107
2108 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2109 doRetainAutorelease = true;
2110 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2111 .objc_retainAutoreleasedReturnValue) {
2112 doRetainAutorelease = false;
2113
John McCallcfa4e9b2012-09-07 23:30:50 +00002114 // If we emitted an assembly marker for this call (and the
2115 // ARCEntrypoints field should have been set if so), go looking
2116 // for that call. If we can't find it, we can't do this
2117 // optimization. But it should always be the immediately previous
2118 // instruction, unless we needed bitcasts around the call.
2119 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2120 llvm::Instruction *prev = call->getPrevNode();
2121 assert(prev);
2122 if (isa<llvm::BitCastInst>(prev)) {
2123 prev = prev->getPrevNode();
2124 assert(prev);
2125 }
2126 assert(isa<llvm::CallInst>(prev));
2127 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2128 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2129 insnsToKill.push_back(prev);
2130 }
John McCall31168b02011-06-15 23:02:42 +00002131 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002132 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002133 }
2134
2135 result = call->getArgOperand(0);
2136 insnsToKill.push_back(call);
2137
2138 // Keep killing bitcasts, for sanity. Note that we no longer care
2139 // about precise ordering as long as there's exactly one use.
2140 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2141 if (!bitcast->hasOneUse()) break;
2142 insnsToKill.push_back(bitcast);
2143 result = bitcast->getOperand(0);
2144 }
2145
2146 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002147 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002148 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2149 (*i)->eraseFromParent();
2150
2151 // Do the fused retain/autorelease if we were asked to.
2152 if (doRetainAutorelease)
2153 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2154
2155 // Cast back to the result type.
2156 return CGF.Builder.CreateBitCast(result, resultType);
2157}
2158
John McCallffa2c1a2012-01-29 07:46:59 +00002159/// If this is a +1 of the value of an immutable 'self', remove it.
2160static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2161 llvm::Value *result) {
2162 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002163 const ObjCMethodDecl *method =
2164 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002165 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002166 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002167 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002168
2169 // Look for a retain call.
2170 llvm::CallInst *retainCall =
2171 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2172 if (!retainCall ||
2173 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002174 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002175
2176 // Look for an ordinary load of 'self'.
2177 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2178 llvm::LoadInst *load =
2179 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2180 if (!load || load->isAtomic() || load->isVolatile() ||
2181 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002182 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002183
2184 // Okay! Burn it all down. This relies for correctness on the
2185 // assumption that the retain is emitted as part of the return and
2186 // that thereafter everything is used "linearly".
2187 llvm::Type *resultType = result->getType();
2188 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2189 assert(retainCall->use_empty());
2190 retainCall->eraseFromParent();
2191 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2192
2193 return CGF.Builder.CreateBitCast(load, resultType);
2194}
2195
John McCall31168b02011-06-15 23:02:42 +00002196/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002197///
2198/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002199static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2200 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002201 // If we're returning 'self', kill the initial retain. This is a
2202 // heuristic attempt to "encourage correctness" in the really unfortunate
2203 // case where we have a return of self during a dealloc and we desperately
2204 // need to avoid the possible autorelease.
2205 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2206 return self;
2207
John McCall31168b02011-06-15 23:02:42 +00002208 // At -O0, try to emit a fused retain/autorelease.
2209 if (CGF.shouldUseFusedARCCalls())
2210 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2211 return fused;
2212
2213 return CGF.EmitARCAutoreleaseReturnValue(result);
2214}
2215
John McCall6e1c0122012-01-29 02:35:02 +00002216/// Heuristically search for a dominating store to the return-value slot.
2217static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2218 // If there are multiple uses of the return-value slot, just check
2219 // for something immediately preceding the IP. Sometimes this can
2220 // happen with how we generate implicit-returns; it can also happen
2221 // with noreturn cleanups.
2222 if (!CGF.ReturnValue->hasOneUse()) {
2223 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002224 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002225 llvm::Instruction *I = &IP->back();
2226
2227 // Skip lifetime markers
2228 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2229 IE = IP->rend();
2230 II != IE; ++II) {
2231 if (llvm::IntrinsicInst *Intrinsic =
2232 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2233 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2234 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2235 ++II;
2236 if (isa<llvm::BitCastInst>(&*II)) {
2237 if (CastAddr == &*II) {
2238 continue;
2239 }
2240 }
2241 }
2242 }
2243 I = &*II;
2244 break;
2245 }
2246
2247 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(I);
Craig Topper8a13c412014-05-21 05:09:00 +00002248 if (!store) return nullptr;
2249 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002250 assert(!store->isAtomic() && !store->isVolatile()); // see below
2251 return store;
2252 }
2253
2254 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002255 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002256 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002257
2258 // These aren't actually possible for non-coerced returns, and we
2259 // only care about non-coerced returns on this code path.
2260 assert(!store->isAtomic() && !store->isVolatile());
2261
2262 // Now do a first-and-dirty dominance check: just walk up the
2263 // single-predecessors chain from the current insertion point.
2264 llvm::BasicBlock *StoreBB = store->getParent();
2265 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2266 while (IP != StoreBB) {
2267 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002268 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002269 }
2270
2271 // Okay, the store's basic block dominates the insertion point; we
2272 // can do our thing.
2273 return store;
2274}
2275
Adrian Prantl3be10542013-05-02 17:30:20 +00002276void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002277 bool EmitRetDbgLoc,
2278 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002279 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2280 // Naked functions don't have epilogues.
2281 Builder.CreateUnreachable();
2282 return;
2283 }
2284
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002285 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002286 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002287 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002288 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002289 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002290
Dan Gohman481e40c2010-07-20 20:13:52 +00002291 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002292 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002293 QualType RetTy = FI.getReturnType();
2294 const ABIArgInfo &RetAI = FI.getReturnInfo();
2295
2296 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002297 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002298 // Aggregrates get evaluated directly into the destination. Sometimes we
2299 // need to return the sret value in a register, though.
2300 assert(hasAggregateEvaluationKind(RetTy));
2301 if (RetAI.getInAllocaSRet()) {
2302 llvm::Function::arg_iterator EI = CurFn->arg_end();
2303 --EI;
2304 llvm::Value *ArgStruct = EI;
David Blaikie2e804282015-04-05 22:47:07 +00002305 llvm::Value *SRet = Builder.CreateStructGEP(
2306 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
Reid Klecknerfab1e892014-02-25 00:59:14 +00002307 RV = Builder.CreateLoad(SRet, "sret");
2308 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002309 break;
2310
Daniel Dunbar03816342010-08-21 02:24:36 +00002311 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002312 auto AI = CurFn->arg_begin();
2313 if (RetAI.isSRetAfterThis())
2314 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002315 switch (getEvaluationKind(RetTy)) {
2316 case TEK_Complex: {
2317 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002318 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2319 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002320 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002321 /*isInit*/ true);
2322 break;
2323 }
2324 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002325 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002326 break;
2327 case TEK_Scalar:
2328 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002329 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002330 /*isInit*/ true);
2331 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002332 }
2333 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002334 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002335
2336 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002337 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002338 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2339 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002340 // The internal return value temp always will have pointer-to-return-type
2341 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002342
John McCall6e1c0122012-01-29 02:35:02 +00002343 // If there is a dominating store to ReturnValue, we can elide
2344 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002345 if (llvm::StoreInst *SI =
2346 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002347 // Reuse the debug location from the store unless there is
2348 // cleanup code to be emitted between the store and return
2349 // instruction.
2350 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002351 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002352 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002353 RV = SI->getValueOperand();
2354 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002355
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002356 // If that was the only use of the return value, nuke it as well now.
2357 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2358 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002359 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002360 }
John McCall6e1c0122012-01-29 02:35:02 +00002361
2362 // Otherwise, we have to do a simple load.
2363 } else {
2364 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002365 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002366 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002367 llvm::Value *V = ReturnValue;
2368 // If the value is offset in memory, apply the offset now.
2369 if (unsigned Offs = RetAI.getDirectOffset()) {
2370 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
David Blaikie5e259a82015-04-03 22:54:16 +00002371 V = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002372 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002373 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2374 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002375
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002376 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002377 }
John McCall31168b02011-06-15 23:02:42 +00002378
2379 // In ARC, end functions that return a retainable type with a call
2380 // to objc_autoreleaseReturnValue.
2381 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002382 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002383 !FI.isReturnsRetained() &&
2384 RetTy->isObjCRetainableType());
2385 RV = emitAutoreleaseOfResult(*this, RV);
2386 }
2387
Chris Lattner726b3d02010-06-26 23:13:19 +00002388 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002389
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002390 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002391 break;
2392
2393 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002394 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002395 }
2396
Alexey Samsonovde443c52014-08-13 00:26:40 +00002397 llvm::Instruction *Ret;
2398 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002399 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002400 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2401 SanitizerScope SanScope(this);
2402 llvm::Value *Cond = Builder.CreateICmpNE(
2403 RV, llvm::Constant::getNullValue(RV->getType()));
2404 llvm::Constant *StaticData[] = {
2405 EmitCheckSourceLocation(EndLoc),
2406 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2407 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002408 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2409 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002410 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002411 }
2412 Ret = Builder.CreateRet(RV);
2413 } else {
2414 Ret = Builder.CreateRetVoid();
2415 }
2416
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002417 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002418 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002419}
2420
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002421static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2422 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2423 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2424}
2425
2426static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2427 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2428 // placeholders.
2429 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2430 llvm::Value *Placeholder =
2431 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2432 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2433 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2434 Ty.getQualifiers(),
2435 AggValueSlot::IsNotDestructed,
2436 AggValueSlot::DoesNotNeedGCBarriers,
2437 AggValueSlot::IsNotAliased);
2438}
2439
John McCall32ea9692011-03-11 20:59:21 +00002440void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002441 const VarDecl *param,
2442 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002443 // StartFunction converted the ABI-lowered parameter(s) into a
2444 // local alloca. We need to turn that into an r-value suitable
2445 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002446 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002447
John McCall32ea9692011-03-11 20:59:21 +00002448 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002449
John McCall23f66262010-05-26 22:34:26 +00002450 // For the most part, we just need to load the alloca, except:
2451 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002452 // 2) references to non-scalars are pointers directly to the aggregate.
2453 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002454 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002455 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002456 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002457
2458 // Locals which are references to scalars are represented
2459 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002460 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002461 }
2462
Reid Klecknerab2090d2014-07-26 01:34:32 +00002463 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2464 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002465
Nick Lewycky2d84e842013-10-02 02:29:49 +00002466 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002467}
2468
John McCall31168b02011-06-15 23:02:42 +00002469static bool isProvablyNull(llvm::Value *addr) {
2470 return isa<llvm::ConstantPointerNull>(addr);
2471}
2472
2473static bool isProvablyNonNull(llvm::Value *addr) {
2474 return isa<llvm::AllocaInst>(addr);
2475}
2476
2477/// Emit the actual writing-back of a writeback.
2478static void emitWriteback(CodeGenFunction &CGF,
2479 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002480 const LValue &srcLV = writeback.Source;
2481 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002482 assert(!isProvablyNull(srcAddr) &&
2483 "shouldn't have writeback for provably null argument");
2484
Craig Topper8a13c412014-05-21 05:09:00 +00002485 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002486
2487 // If the argument wasn't provably non-null, we need to null check
2488 // before doing the store.
2489 bool provablyNonNull = isProvablyNonNull(srcAddr);
2490 if (!provablyNonNull) {
2491 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2492 contBB = CGF.createBasicBlock("icr.done");
2493
2494 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2495 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2496 CGF.EmitBlock(writebackBB);
2497 }
2498
2499 // Load the value to writeback.
2500 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2501
2502 // Cast it back, in case we're writing an id to a Foo* or something.
2503 value = CGF.Builder.CreateBitCast(value,
2504 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2505 "icr.writeback-cast");
2506
2507 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002508
2509 // If we have a "to use" value, it's something we need to emit a use
2510 // of. This has to be carefully threaded in: if it's done after the
2511 // release it's potentially undefined behavior (and the optimizer
2512 // will ignore it), and if it happens before the retain then the
2513 // optimizer could move the release there.
2514 if (writeback.ToUse) {
2515 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2516
2517 // Retain the new value. No need to block-copy here: the block's
2518 // being passed up the stack.
2519 value = CGF.EmitARCRetainNonBlock(value);
2520
2521 // Emit the intrinsic use here.
2522 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2523
2524 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002525 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002526
2527 // Put the new value in place (primitively).
2528 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2529
2530 // Release the old value.
2531 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2532
2533 // Otherwise, we can just do a normal lvalue store.
2534 } else {
2535 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2536 }
John McCall31168b02011-06-15 23:02:42 +00002537
2538 // Jump to the continuation block.
2539 if (!provablyNonNull)
2540 CGF.EmitBlock(contBB);
2541}
2542
2543static void emitWritebacks(CodeGenFunction &CGF,
2544 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002545 for (const auto &I : args.writebacks())
2546 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002547}
2548
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002549static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2550 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002551 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002552 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2553 CallArgs.getCleanupsToDeactivate();
2554 // Iterate in reverse to increase the likelihood of popping the cleanup.
2555 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2556 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2557 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2558 I->IsActiveIP->eraseFromParent();
2559 }
2560}
2561
John McCalleff18842013-03-23 02:35:54 +00002562static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2563 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2564 if (uop->getOpcode() == UO_AddrOf)
2565 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002566 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002567}
2568
John McCall31168b02011-06-15 23:02:42 +00002569/// Emit an argument that's being passed call-by-writeback. That is,
2570/// we are passing the address of
2571static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2572 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002573 LValue srcLV;
2574
2575 // Make an optimistic effort to emit the address as an l-value.
2576 // This can fail if the the argument expression is more complicated.
2577 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2578 srcLV = CGF.EmitLValue(lvExpr);
2579
2580 // Otherwise, just emit it as a scalar.
2581 } else {
2582 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2583
2584 QualType srcAddrType =
2585 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2586 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2587 }
2588 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002589
2590 // The dest and src types don't necessarily match in LLVM terms
2591 // because of the crazy ObjC compatibility rules.
2592
Chris Lattner2192fe52011-07-18 04:24:23 +00002593 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002594 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2595
2596 // If the address is a constant null, just pass the appropriate null.
2597 if (isProvablyNull(srcAddr)) {
2598 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2599 CRE->getType());
2600 return;
2601 }
2602
John McCall31168b02011-06-15 23:02:42 +00002603 // Create the temporary.
2604 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2605 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002606 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2607 // and that cleanup will be conditional if we can't prove that the l-value
2608 // isn't null, so we need to register a dominating point so that the cleanups
2609 // system will make valid IR.
2610 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2611
John McCall31168b02011-06-15 23:02:42 +00002612 // Zero-initialize it if we're not doing a copy-initialization.
2613 bool shouldCopy = CRE->shouldCopy();
2614 if (!shouldCopy) {
2615 llvm::Value *null =
2616 llvm::ConstantPointerNull::get(
2617 cast<llvm::PointerType>(destType->getElementType()));
2618 CGF.Builder.CreateStore(null, temp);
2619 }
Craig Topper8a13c412014-05-21 05:09:00 +00002620
2621 llvm::BasicBlock *contBB = nullptr;
2622 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002623
2624 // If the address is *not* known to be non-null, we need to switch.
2625 llvm::Value *finalArgument;
2626
2627 bool provablyNonNull = isProvablyNonNull(srcAddr);
2628 if (provablyNonNull) {
2629 finalArgument = temp;
2630 } else {
2631 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2632
2633 finalArgument = CGF.Builder.CreateSelect(isNull,
2634 llvm::ConstantPointerNull::get(destType),
2635 temp, "icr.argument");
2636
2637 // If we need to copy, then the load has to be conditional, which
2638 // means we need control flow.
2639 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002640 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002641 contBB = CGF.createBasicBlock("icr.cont");
2642 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2643 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2644 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002645 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002646 }
2647 }
2648
Craig Topper8a13c412014-05-21 05:09:00 +00002649 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002650
John McCall31168b02011-06-15 23:02:42 +00002651 // Perform a copy if necessary.
2652 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002653 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002654 assert(srcRV.isScalar());
2655
2656 llvm::Value *src = srcRV.getScalarVal();
2657 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2658 "icr.cast");
2659
2660 // Use an ordinary store, not a store-to-lvalue.
2661 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002662
2663 // If optimization is enabled, and the value was held in a
2664 // __strong variable, we need to tell the optimizer that this
2665 // value has to stay alive until we're doing the store back.
2666 // This is because the temporary is effectively unretained,
2667 // and so otherwise we can violate the high-level semantics.
2668 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2669 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2670 valueToUse = src;
2671 }
John McCall31168b02011-06-15 23:02:42 +00002672 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002673
John McCall31168b02011-06-15 23:02:42 +00002674 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002675 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002676 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002677 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002678
2679 // Make a phi for the value to intrinsically use.
2680 if (valueToUse) {
2681 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2682 "icr.to-use");
2683 phiToUse->addIncoming(valueToUse, copyBB);
2684 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2685 originBB);
2686 valueToUse = phiToUse;
2687 }
2688
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002689 condEval.end(CGF);
2690 }
John McCall31168b02011-06-15 23:02:42 +00002691
John McCalleff18842013-03-23 02:35:54 +00002692 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002693 args.add(RValue::get(finalArgument), CRE->getType());
2694}
2695
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002696void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2697 assert(!StackBase && !StackCleanup.isValid());
2698
2699 // Save the stack.
2700 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00002701 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002702
2703 // Control gets really tied up in landing pads, so we have to spill the
2704 // stacksave to an alloca to avoid violating SSA form.
2705 // TODO: This is dead if we never emit the cleanup. We should create the
2706 // alloca and store lazily on the first cleanup emission.
2707 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2708 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2709 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2710 StackCleanup = CGF.EHStack.getInnermostEHScope();
2711 assert(StackCleanup.isValid());
2712}
2713
2714void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2715 if (StackBase) {
2716 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2717 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2718 // We could load StackBase from StackBaseMem, but in the non-exceptional
2719 // case we can skip it.
2720 CGF.Builder.CreateCall(F, StackBase);
2721 }
2722}
2723
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002724void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
2725 SourceLocation ArgLoc,
2726 const FunctionDecl *FD,
2727 unsigned ParmNum) {
2728 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002729 return;
2730 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2731 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2732 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2733 if (!NNAttr)
2734 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002735 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002736 assert(RV.isScalar());
2737 llvm::Value *V = RV.getScalarVal();
2738 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002739 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002740 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002741 EmitCheckSourceLocation(ArgLoc),
2742 EmitCheckSourceLocation(NNAttr->getLocation()),
2743 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002744 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002745 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002746 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002747}
2748
Reid Kleckner739756c2013-12-04 19:23:12 +00002749void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2750 ArrayRef<QualType> ArgTypes,
2751 CallExpr::const_arg_iterator ArgBeg,
2752 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002753 const FunctionDecl *CalleeDecl,
David Blaikie835afb22015-01-21 23:08:17 +00002754 unsigned ParamsToSkip) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002755 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2756 // because arguments are destroyed left to right in the callee.
2757 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002758 // Insert a stack save if we're going to need any inalloca args.
2759 bool HasInAllocaArgs = false;
2760 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2761 I != E && !HasInAllocaArgs; ++I)
2762 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2763 if (HasInAllocaArgs) {
2764 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2765 Args.allocateArgumentMemory(*this);
2766 }
2767
2768 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002769 size_t CallArgsStart = Args.size();
2770 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2771 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2772 EmitCallArg(Args, *Arg, ArgTypes[I]);
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002773 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002774 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002775 }
2776
2777 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2778 // IR function.
2779 std::reverse(Args.begin() + CallArgsStart, Args.end());
2780 return;
2781 }
2782
2783 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2784 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2785 assert(Arg != ArgEnd);
2786 EmitCallArg(Args, *Arg, ArgTypes[I]);
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002787 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002788 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002789 }
2790}
2791
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002792namespace {
2793
2794struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2795 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2796 : Addr(Addr), Ty(Ty) {}
2797
2798 llvm::Value *Addr;
2799 QualType Ty;
2800
Craig Topper4f12f102014-03-12 06:41:41 +00002801 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002802 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2803 assert(!Dtor->isTrivial());
2804 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2805 /*Delegating=*/false, Addr);
2806 }
2807};
2808
2809}
2810
David Blaikie38b25912015-02-09 19:13:51 +00002811struct DisableDebugLocationUpdates {
2812 CodeGenFunction &CGF;
2813 bool disabledDebugInfo;
2814 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2815 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2816 CGF.disableDebugInfo();
2817 }
2818 ~DisableDebugLocationUpdates() {
2819 if (disabledDebugInfo)
2820 CGF.enableDebugInfo();
2821 }
2822};
2823
John McCall32ea9692011-03-11 20:59:21 +00002824void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2825 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002826 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002827 if (const ObjCIndirectCopyRestoreExpr *CRE
2828 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002829 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002830 assert(getContext().hasSameType(E->getType(), type));
2831 return emitWritebackArg(*this, args, CRE);
2832 }
2833
John McCall0a76c0c2011-08-26 18:42:59 +00002834 assert(type->isReferenceType() == E->isGLValue() &&
2835 "reference binding to unmaterialized r-value!");
2836
John McCall17054bd62011-08-26 21:08:13 +00002837 if (E->isGLValue()) {
2838 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002839 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002842 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2843
2844 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2845 // However, we still have to push an EH-only cleanup in case we unwind before
2846 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002847 if (HasAggregateEvalKind &&
2848 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2849 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002850 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002851 AggValueSlot Slot;
2852 if (args.isUsingInAlloca())
2853 Slot = createPlaceholderSlot(*this, type);
2854 else
2855 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002856
2857 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2858 bool DestroyedInCallee =
2859 RD && RD->hasNonTrivialDestructor() &&
2860 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2861 if (DestroyedInCallee)
2862 Slot.setExternallyDestructed();
2863
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002864 EmitAggExpr(E, Slot);
2865 RValue RV = Slot.asRValue();
2866 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002867
Reid Klecknere39ee212014-05-03 00:33:28 +00002868 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002869 // Create a no-op GEP between the placeholder and the cleanup so we can
2870 // RAUW it successfully. It also serves as a marker of the first
2871 // instruction where the cleanup is active.
2872 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002873 // This unreachable is a temporary marker which will be removed later.
2874 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2875 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002876 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002877 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002878 }
2879
2880 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002881 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2882 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2883 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002884 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2885 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2886 } else {
2887 // We can't represent a misaligned lvalue in the CallArgList, so copy
2888 // to an aligned temporary now.
2889 llvm::Value *tmp = CreateMemTemp(type);
2890 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2891 L.getAlignment());
2892 args.add(RValue::getAggregate(tmp), type);
2893 }
Eli Friedmandf968192011-05-26 00:10:27 +00002894 return;
2895 }
2896
John McCall32ea9692011-03-11 20:59:21 +00002897 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002898}
2899
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002900QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2901 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2902 // implicitly widens null pointer constants that are arguments to varargs
2903 // functions to pointer-sized ints.
2904 if (!getTarget().getTriple().isOSWindows())
2905 return Arg->getType();
2906
2907 if (Arg->getType()->isIntegerType() &&
2908 getContext().getTypeSize(Arg->getType()) <
2909 getContext().getTargetInfo().getPointerWidth(0) &&
2910 Arg->isNullPointerConstant(getContext(),
2911 Expr::NPC_ValueDependentIsNotNull)) {
2912 return getContext().getIntPtrType();
2913 }
2914
2915 return Arg->getType();
2916}
2917
Dan Gohman515a60d2012-02-16 00:57:37 +00002918// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2919// optimizer it can aggressively ignore unwind edges.
2920void
2921CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2922 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2923 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2924 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2925 CGM.getNoObjCARCExceptionsMetadata());
2926}
2927
John McCall882987f2013-02-28 19:01:20 +00002928/// Emits a call to the given no-arguments nounwind runtime function.
2929llvm::CallInst *
2930CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2931 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002932 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002933}
2934
2935/// Emits a call to the given nounwind runtime function.
2936llvm::CallInst *
2937CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2938 ArrayRef<llvm::Value*> args,
2939 const llvm::Twine &name) {
2940 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2941 call->setDoesNotThrow();
2942 return call;
2943}
2944
2945/// Emits a simple call (never an invoke) to the given no-arguments
2946/// runtime function.
2947llvm::CallInst *
2948CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2949 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002950 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002951}
2952
2953/// Emits a simple call (never an invoke) to the given runtime
2954/// function.
2955llvm::CallInst *
2956CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2957 ArrayRef<llvm::Value*> args,
2958 const llvm::Twine &name) {
2959 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2960 call->setCallingConv(getRuntimeCC());
2961 return call;
2962}
2963
2964/// Emits a call or invoke to the given noreturn runtime function.
2965void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2966 ArrayRef<llvm::Value*> args) {
2967 if (getInvokeDest()) {
2968 llvm::InvokeInst *invoke =
2969 Builder.CreateInvoke(callee,
2970 getUnreachableBlock(),
2971 getInvokeDest(),
2972 args);
2973 invoke->setDoesNotReturn();
2974 invoke->setCallingConv(getRuntimeCC());
2975 } else {
2976 llvm::CallInst *call = Builder.CreateCall(callee, args);
2977 call->setDoesNotReturn();
2978 call->setCallingConv(getRuntimeCC());
2979 Builder.CreateUnreachable();
2980 }
2981}
2982
2983/// Emits a call or invoke instruction to the given nullary runtime
2984/// function.
2985llvm::CallSite
2986CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2987 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002988 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002989}
2990
2991/// Emits a call or invoke instruction to the given runtime function.
2992llvm::CallSite
2993CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2994 ArrayRef<llvm::Value*> args,
2995 const Twine &name) {
2996 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2997 callSite.setCallingConv(getRuntimeCC());
2998 return callSite;
2999}
3000
3001llvm::CallSite
3002CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
3003 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003004 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00003005}
3006
John McCallbd309292010-07-06 01:34:17 +00003007/// Emits a call or invoke instruction to the given function, depending
3008/// on the current state of the EH stack.
3009llvm::CallSite
3010CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003011 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003012 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003013 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003014
Dan Gohman515a60d2012-02-16 00:57:37 +00003015 llvm::Instruction *Inst;
3016 if (!InvokeDest)
3017 Inst = Builder.CreateCall(Callee, Args, Name);
3018 else {
3019 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
3020 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
3021 EmitBlock(ContBB);
3022 }
3023
3024 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3025 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003026 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003027 AddObjCARCExceptionMetadata(Inst);
3028
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003029 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003030}
3031
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003032/// \brief Store a non-aggregate value to an address to initialize it. For
3033/// initialization, a non-atomic store will be used.
3034static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3035 LValue Dst) {
3036 if (Src.isScalar())
3037 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3038 else
3039 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3040}
3041
3042void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3043 llvm::Value *New) {
3044 DeferredReplacements.push_back(std::make_pair(Old, New));
3045}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003046
Daniel Dunbard931a872009-02-02 22:03:45 +00003047RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003048 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003049 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003050 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00003051 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00003052 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003053 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003054
3055 // Handle struct-return functions by passing a pointer to the
3056 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003057 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003058 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003059
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003060 llvm::FunctionType *IRFuncTy =
3061 cast<llvm::FunctionType>(
3062 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003063
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003064 // If we're using inalloca, insert the allocation after the stack save.
3065 // FIXME: Do this earlier rather than hacking it in here!
David Blaikie1ed728c2015-04-05 22:45:47 +00003066 llvm::AllocaInst *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003067 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00003068 llvm::Instruction *IP = CallArgs.getStackBase();
3069 llvm::AllocaInst *AI;
3070 if (IP) {
3071 IP = IP->getNextNode();
3072 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3073 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003074 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003075 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003076 AI->setUsedWithInAlloca(true);
3077 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3078 ArgMemory = AI;
3079 }
3080
Alexey Samsonov153004f2014-09-29 22:08:00 +00003081 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003082 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3083
Chris Lattner4ca97c32009-06-13 00:26:38 +00003084 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003085 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00003086 llvm::Value *SRetPtr = nullptr;
Leny Kholodov6aab1112015-06-08 10:23:49 +00003087 size_t UnusedReturnSize = 0;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003088 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003089 SRetPtr = ReturnValue.getValue();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003090 if (!SRetPtr) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003091 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003092 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3093 uint64_t size =
3094 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
3095 if (EmitLifetimeStart(size, SRetPtr))
3096 UnusedReturnSize = size;
3097 }
3098 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003099 if (IRFunctionArgs.hasSRetArg()) {
3100 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003101 } else {
3102 llvm::Value *Addr =
David Blaikie2e804282015-04-05 22:47:07 +00003103 Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
3104 RetAI.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003105 Builder.CreateStore(SRetPtr, Addr);
3106 }
Anders Carlsson17490832009-12-24 20:40:36 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003109 assert(CallInfo.arg_size() == CallArgs.size() &&
3110 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003111 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003112 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003113 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003114 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003115 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003116 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003117
John McCall47fb9502013-03-07 21:37:08 +00003118 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003119
3120 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003121 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3122 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3123 llvm::UndefValue::get(ArgInfo.getPaddingType());
3124
3125 unsigned FirstIRArg, NumIRArgs;
3126 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003127
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003128 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003129 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003130 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003131 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3132 if (RV.isAggregate()) {
3133 // Replace the placeholder with the appropriate argument slot GEP.
3134 llvm::Instruction *Placeholder =
3135 cast<llvm::Instruction>(RV.getAggregateAddr());
3136 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3137 Builder.SetInsertPoint(Placeholder);
David Blaikie2e804282015-04-05 22:47:07 +00003138 llvm::Value *Addr =
3139 Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
3140 ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003141 Builder.restoreIP(IP);
3142 deferPlaceholderReplacement(Placeholder, Addr);
3143 } else {
3144 // Store the RValue into the argument struct.
3145 llvm::Value *Addr =
David Blaikie2e804282015-04-05 22:47:07 +00003146 Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
3147 ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003148 unsigned AS = Addr->getType()->getPointerAddressSpace();
3149 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3150 // There are some cases where a trivial bitcast is not avoidable. The
3151 // definition of a type later in a translation unit may change it's type
3152 // from {}* to (%struct.foo*)*.
3153 if (Addr->getType() != MemType)
3154 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003155 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3156 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3157 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003158 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003159 }
3160
Daniel Dunbar03816342010-08-21 02:24:36 +00003161 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003162 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003163 if (RV.isScalar() || RV.isComplex()) {
3164 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003165 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3166 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3167 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003168 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003169
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003170 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003171 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003172 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003173 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003174 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003175 // 1. If the argument is not byval, and we are required to copy the
3176 // source. (This case doesn't occur on any common architecture.)
3177 // 2. If the argument is byval, RV is not sufficiently aligned, and
3178 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003179 // 3. If the argument is byval, but RV is located in an address space
3180 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003181 llvm::Value *Addr = RV.getAggregateAddr();
3182 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003183 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003184 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003185 const unsigned ArgAddrSpace =
3186 (FirstIRArg < IRFuncTy->getNumParams()
3187 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3188 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003189 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003190 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Mehdi Aminib3d52092015-03-10 02:36:43 +00003191 llvm::getOrEnforceKnownAlignment(Addr, Align, *TD) < Align) ||
3192 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003193 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003194 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3195 if (Align > AI->getAlignment())
3196 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003197 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003198 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003199 } else {
3200 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003201 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003202 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003203 }
3204 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003205 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003206
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003207 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003208 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003209 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003210
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003211 case ABIArgInfo::Extend:
3212 case ABIArgInfo::Direct: {
3213 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003214 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3215 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003216 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003217 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003218 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003219 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003220 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003221 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003222
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003223 // We might have to widen integers, but we should never truncate.
3224 if (ArgInfo.getCoerceToType() != V->getType() &&
3225 V->getType()->isIntegerTy())
3226 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3227
Chris Lattner3ce86682011-07-12 04:53:39 +00003228 // If the argument doesn't match, perform a bitcast to coerce it. This
3229 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003230 if (FirstIRArg < IRFuncTy->getNumParams() &&
3231 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3232 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3233 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003234 break;
3235 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003236
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003237 // FIXME: Avoid the conversion through memory if possible.
3238 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003239 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003240 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003241 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003242 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003243 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003244 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003245
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003246 // If the value is offset in memory, apply the offset now.
3247 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3248 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
David Blaikie5e259a82015-04-03 22:54:16 +00003249 SrcPtr = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003250 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003251 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3252
3253 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003254
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003255 // Fast-isel and the optimizer generally like scalar values better than
3256 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003257 llvm::StructType *STy =
3258 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003259 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003260 llvm::Type *SrcTy =
3261 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3262 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3263 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3264
3265 // If the source type is smaller than the destination type of the
3266 // coerce-to logic, copy the source value into a temp alloca the size
3267 // of the destination type to allow loading all of it. The bits past
3268 // the source value are left undef.
3269 if (SrcSize < DstSize) {
3270 llvm::AllocaInst *TempAlloca
3271 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3272 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3273 SrcPtr = TempAlloca;
3274 } else {
3275 SrcPtr = Builder.CreateBitCast(SrcPtr,
3276 llvm::PointerType::getUnqual(STy));
3277 }
3278
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003279 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003280 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
David Blaikie17ea2662015-04-04 21:07:17 +00003281 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(STy, SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003282 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3283 // We don't know what we're loading from.
3284 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003285 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003286 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003287 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003288 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003289 assert(NumIRArgs == 1);
3290 IRCallArgs[FirstIRArg] =
3291 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003292 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003293
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003294 break;
3295 }
3296
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003297 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003298 unsigned IRArgPos = FirstIRArg;
3299 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3300 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003301 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003302 }
3303 }
Mike Stump11289f42009-09-09 15:08:12 +00003304
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003305 if (ArgMemory) {
3306 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003307 if (CallInfo.isVariadic()) {
3308 // When passing non-POD arguments by value to variadic functions, we will
3309 // end up with a variadic prototype and an inalloca call site. In such
3310 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3311 // the callee.
3312 unsigned CalleeAS =
3313 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3314 Callee = Builder.CreateBitCast(
3315 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3316 } else {
3317 llvm::Type *LastParamTy =
3318 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3319 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003320#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003321 // Assert that these structs have equivalent element types.
3322 llvm::StructType *FullTy = CallInfo.getArgStruct();
3323 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3324 cast<llvm::PointerType>(LastParamTy)->getElementType());
3325 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3326 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3327 DE = DeclaredTy->element_end(),
3328 FI = FullTy->element_begin();
3329 DI != DE; ++DI, ++FI)
3330 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003331#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003332 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3333 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003334 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003335 assert(IRFunctionArgs.hasInallocaArg());
3336 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003337 }
3338
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003339 if (!CallArgs.getCleanupsToDeactivate().empty())
3340 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3341
Chris Lattner4ca97c32009-06-13 00:26:38 +00003342 // If the callee is a bitcast of a function to a varargs pointer to function
3343 // type, check to see if we can remove the bitcast. This handles some cases
3344 // with unprototyped functions.
3345 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3346 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003347 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3348 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003349 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003350 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003351
Chris Lattner4ca97c32009-06-13 00:26:38 +00003352 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3353 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003354 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003355 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003356 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003357 bool ArgsMatch = true;
3358 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3359 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3360 ArgsMatch = false;
3361 break;
3362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattner4ca97c32009-06-13 00:26:38 +00003364 // Strip the cast if we can get away with it. This is a nice cleanup,
3365 // but also allows us to inline the function at -O0 if it is marked
3366 // always_inline.
3367 if (ArgsMatch)
3368 Callee = CalleeF;
3369 }
3370 }
Mike Stump11289f42009-09-09 15:08:12 +00003371
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003372 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3373 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3374 // Inalloca argument can have different type.
3375 if (IRFunctionArgs.hasInallocaArg() &&
3376 i == IRFunctionArgs.getInallocaArgNo())
3377 continue;
3378 if (i < IRFuncTy->getNumParams())
3379 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3380 }
3381
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003382 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003383 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003384 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3385 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003386 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003387 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003388
Craig Topper8a13c412014-05-21 05:09:00 +00003389 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003390 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00003391 llvm::Attribute::NoUnwind) ||
3392 currentFunctionUsesSEHTry())
John McCallbd309292010-07-06 01:34:17 +00003393 InvokeDest = getInvokeDest();
3394
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003395 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003396 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003397 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003398 } else {
3399 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003400 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003401 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003402 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003403 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003404 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003405
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003406 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3407 !CS.hasFnAttr(llvm::Attribute::NoInline))
3408 Attrs =
3409 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3410 llvm::Attribute::AlwaysInline);
3411
Reid Klecknera5930002015-02-11 21:40:48 +00003412 // Disable inlining inside SEH __try blocks.
Reid Kleckner11c033e2015-02-12 23:40:45 +00003413 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003414 Attrs =
3415 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3416 llvm::Attribute::NoInline);
3417
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003418 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003419 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003420
Dan Gohman515a60d2012-02-16 00:57:37 +00003421 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3422 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003423 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003424 AddObjCARCExceptionMetadata(CS.getInstruction());
3425
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003426 // If the call doesn't return, finish the basic block and clear the
3427 // insertion point; this allows the rest of IRgen to discard
3428 // unreachable code.
3429 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003430 if (UnusedReturnSize)
3431 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
3432 SRetPtr);
3433
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003434 Builder.CreateUnreachable();
3435 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003436
Mike Stump18bb9282009-05-16 07:57:57 +00003437 // FIXME: For now, emit a dummy basic block because expr emitters in
3438 // generally are not ready to handle emitting expressions at unreachable
3439 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003440 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003441
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003442 // Return a reasonable RValue.
3443 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003444 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003445
3446 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003447 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003448 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003449
John McCall31168b02011-06-15 23:02:42 +00003450 // Emit any writebacks immediately. Arguably this should happen
3451 // after any return-value munging.
3452 if (CallArgs.hasWritebacks())
3453 emitWritebacks(*this, CallArgs);
3454
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003455 // The stack cleanup for inalloca arguments has to run out of the normal
3456 // lexical order, so deactivate it and run it manually here.
3457 CallArgs.freeArgumentMemory(*this);
3458
Hal Finkelee90a222014-09-26 05:04:30 +00003459 RValue Ret = [&] {
3460 switch (RetAI.getKind()) {
3461 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003462 case ABIArgInfo::Indirect: {
3463 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3464 if (UnusedReturnSize)
3465 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
3466 SRetPtr);
3467 return ret;
3468 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003469
Hal Finkelee90a222014-09-26 05:04:30 +00003470 case ABIArgInfo::Ignore:
3471 // If we are ignoring an argument that had a result, make sure to
3472 // construct the appropriate return value for our caller.
3473 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003474
Hal Finkelee90a222014-09-26 05:04:30 +00003475 case ABIArgInfo::Extend:
3476 case ABIArgInfo::Direct: {
3477 llvm::Type *RetIRTy = ConvertType(RetTy);
3478 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3479 switch (getEvaluationKind(RetTy)) {
3480 case TEK_Complex: {
3481 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3482 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3483 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003484 }
Hal Finkelee90a222014-09-26 05:04:30 +00003485 case TEK_Aggregate: {
3486 llvm::Value *DestPtr = ReturnValue.getValue();
3487 bool DestIsVolatile = ReturnValue.isVolatile();
3488
3489 if (!DestPtr) {
3490 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3491 DestIsVolatile = false;
3492 }
3493 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3494 return RValue::getAggregate(DestPtr);
3495 }
3496 case TEK_Scalar: {
3497 // If the argument doesn't match, perform a bitcast to coerce it. This
3498 // can happen due to trivial type mismatches.
3499 llvm::Value *V = CI;
3500 if (V->getType() != RetIRTy)
3501 V = Builder.CreateBitCast(V, RetIRTy);
3502 return RValue::get(V);
3503 }
3504 }
3505 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003506 }
Hal Finkelee90a222014-09-26 05:04:30 +00003507
3508 llvm::Value *DestPtr = ReturnValue.getValue();
3509 bool DestIsVolatile = ReturnValue.isVolatile();
3510
3511 if (!DestPtr) {
3512 DestPtr = CreateMemTemp(RetTy, "coerce");
3513 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003514 }
Hal Finkelee90a222014-09-26 05:04:30 +00003515
3516 // If the value is offset in memory, apply the offset now.
3517 llvm::Value *StorePtr = DestPtr;
3518 if (unsigned Offs = RetAI.getDirectOffset()) {
3519 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
David Blaikie5e259a82015-04-03 22:54:16 +00003520 StorePtr =
3521 Builder.CreateConstGEP1_32(Builder.getInt8Ty(), StorePtr, Offs);
Hal Finkelee90a222014-09-26 05:04:30 +00003522 StorePtr = Builder.CreateBitCast(StorePtr,
3523 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003524 }
Hal Finkelee90a222014-09-26 05:04:30 +00003525 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3526
3527 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003528 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003529
Hal Finkelee90a222014-09-26 05:04:30 +00003530 case ABIArgInfo::Expand:
3531 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003532 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003533
Hal Finkelee90a222014-09-26 05:04:30 +00003534 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3535 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003536
Hal Finkelee90a222014-09-26 05:04:30 +00003537 if (Ret.isScalar() && TargetDecl) {
3538 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3539 llvm::Value *OffsetValue = nullptr;
3540 if (const auto *Offset = AA->getOffset())
3541 OffsetValue = EmitScalarExpr(Offset);
3542
3543 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3544 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3545 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3546 OffsetValue);
3547 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003548 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003549
Hal Finkelee90a222014-09-26 05:04:30 +00003550 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003551}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003552
3553/* VarArg handling */
3554
3555llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3556 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3557}