blob: ffa28c17694d86fce994b9f29bb85e4ab5b736d3 [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"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
53 case CC_X86VectorCall: return llvm::CallingConv::C;
John McCallab26cfa2010-02-05 21:31:56 +000054 }
55}
56
John McCall8ee376f2010-02-24 07:14:12 +000057/// Derives the 'this' type for codegen purposes, i.e. ignoring method
58/// qualification.
59/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000060static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
61 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
62 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000063}
64
John McCall8ee376f2010-02-24 07:14:12 +000065/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000066static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
67 return MD->getType()->getCanonicalTypeUnqualified()
68 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000069}
70
71/// Returns the "extra-canonicalized" return type, which discards
72/// qualifiers on the return type. Codegen doesn't care about them,
73/// and it makes ABI code a little easier to be able to assume that
74/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000075static CanQualType GetReturnType(QualType RetTy) {
76 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000077}
78
John McCall8dda7b22012-07-07 06:41:13 +000079/// Arrange the argument and result information for a value of the given
80/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000081const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000082CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000083 // When translating an unprototyped function type, always use a
84 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000085 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000086 false, None, FTNP->getExtInfo(),
87 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000088}
89
John McCall8dda7b22012-07-07 06:41:13 +000090/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000091/// type, on top of any implicit parameters already stored.
92static const CGFunctionInfo &
93arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
94 SmallVectorImpl<CanQualType> &prefix,
95 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000096 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000097 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000098 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
99 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +0000100 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +0000101 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000102 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000103}
104
John McCalla729c622012-02-17 03:33:10 +0000105/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000106/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000107const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000108CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000109 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000110 return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000111}
112
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000113static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000114 // Set the appropriate calling convention for the Function.
115 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000116 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117
118 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000119 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000120
Douglas Gregora941dca2010-05-18 16:57:00 +0000121 if (D->hasAttr<ThisCallAttr>())
122 return CC_X86ThisCall;
123
Reid Klecknerd7857f02014-10-24 17:42:17 +0000124 if (D->hasAttr<VectorCallAttr>())
125 return CC_X86VectorCall;
126
Dawn Perchik335e16b2010-09-03 01:29:35 +0000127 if (D->hasAttr<PascalAttr>())
128 return CC_X86Pascal;
129
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000130 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
131 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
132
Derek Schuffa2020962012-10-16 22:30:41 +0000133 if (D->hasAttr<PnaclCallAttr>())
134 return CC_PnaclCall;
135
Guy Benyeif0a014b2012-12-25 08:53:55 +0000136 if (D->hasAttr<IntelOclBiccAttr>())
137 return CC_IntelOclBicc;
138
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000139 if (D->hasAttr<MSABIAttr>())
140 return IsWindows ? CC_C : CC_X86_64Win64;
141
142 if (D->hasAttr<SysVABIAttr>())
143 return IsWindows ? CC_X86_64SysV : CC_C;
144
John McCallab26cfa2010-02-05 21:31:56 +0000145 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000146}
147
John McCalla729c622012-02-17 03:33:10 +0000148/// Arrange the argument and result information for a call to an
149/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000150/// (Zero value of RD means we don't have any meaningful "this" argument type,
151/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000152/// The member function must be an ordinary function, i.e. not a
153/// constructor or destructor.
154const CGFunctionInfo &
155CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
156 const FunctionProtoType *FTP) {
157 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000158
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000159 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000160 if (RD)
161 argTypes.push_back(GetThisType(Context, RD));
162 else
163 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000164
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000165 return ::arrangeLLVMFunctionInfo(
166 *this, true, argTypes,
167 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000168}
169
John McCalla729c622012-02-17 03:33:10 +0000170/// Arrange the argument and result information for a declaration or
171/// definition of the given C++ non-static member function. The
172/// member function must be an ordinary function, i.e. not a
173/// constructor or destructor.
174const CGFunctionInfo &
175CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000176 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000177 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
178
John McCalla729c622012-02-17 03:33:10 +0000179 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000180
John McCalla729c622012-02-17 03:33:10 +0000181 if (MD->isInstance()) {
182 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000183 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000184 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000185 }
186
John McCall8dda7b22012-07-07 06:41:13 +0000187 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000188}
189
John McCalla729c622012-02-17 03:33:10 +0000190const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000191CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
192 StructorType Type) {
193
John McCalla729c622012-02-17 03:33:10 +0000194 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000195 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000196
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000197 GlobalDecl GD;
198 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
199 GD = GlobalDecl(CD, toCXXCtorType(Type));
200 } else {
201 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
202 GD = GlobalDecl(DD, toCXXDtorType(Type));
203 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000204
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000205 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000206
207 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000208 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
209 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000210
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000212
213 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000214 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000215
John McCall8dda7b22012-07-07 06:41:13 +0000216 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000217 CanQualType resultType =
218 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Reid Kleckner4982b822014-01-31 22:54:50 +0000219 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000220}
221
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000222/// Arrange a call to a C++ method, passing the given arguments.
223const CGFunctionInfo &
224CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
225 const CXXConstructorDecl *D,
226 CXXCtorType CtorKind,
227 unsigned ExtraArgs) {
228 // FIXME: Kill copy.
229 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000230 for (const auto &Arg : args)
231 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000232
233 CanQual<FunctionProtoType> FPT = GetFormalType(D);
234 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
235 GlobalDecl GD(D, CtorKind);
236 CanQualType ResultType =
237 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
238
239 FunctionType::ExtInfo Info = FPT->getExtInfo();
240 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
241}
242
John McCalla729c622012-02-17 03:33:10 +0000243/// Arrange the argument and result information for the declaration or
244/// definition of the given function.
245const CGFunctionInfo &
246CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000247 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000248 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000249 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000250
John McCall2da83a32010-02-26 00:48:12 +0000251 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000252
John McCall2da83a32010-02-26 00:48:12 +0000253 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000254
255 // When declaring a function without a prototype, always use a
256 // non-variadic type.
257 if (isa<FunctionNoProtoType>(FTy)) {
258 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000259 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000260 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000261 }
262
John McCall2da83a32010-02-26 00:48:12 +0000263 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000264 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000265}
266
John McCalla729c622012-02-17 03:33:10 +0000267/// Arrange the argument and result information for the declaration or
268/// definition of an Objective-C method.
269const CGFunctionInfo &
270CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
271 // It happens that this is the same as a call with no optional
272 // arguments, except also using the formal 'self' type.
273 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
274}
275
276/// Arrange the argument and result information for the function type
277/// through which to perform a send to the given Objective-C method,
278/// using the given receiver type. The receiver type is not always
279/// the 'self' type of the method or even an Objective-C pointer type.
280/// This is *not* the right method for actually performing such a
281/// message send, due to the possibility of optional arguments.
282const CGFunctionInfo &
283CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
284 QualType receiverType) {
285 SmallVector<CanQualType, 16> argTys;
286 argTys.push_back(Context.getCanonicalParamType(receiverType));
287 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000288 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000289 for (const auto *I : MD->params()) {
290 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000291 }
John McCall31168b02011-06-15 23:02:42 +0000292
293 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000294 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
295 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000296
David Blaikiebbafb8a2012-03-11 07:00:24 +0000297 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000298 MD->hasAttr<NSReturnsRetainedAttr>())
299 einfo = einfo.withProducesResult(true);
300
John McCalla729c622012-02-17 03:33:10 +0000301 RequiredArgs required =
302 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
303
Reid Kleckner4982b822014-01-31 22:54:50 +0000304 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
305 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000306}
307
John McCalla729c622012-02-17 03:33:10 +0000308const CGFunctionInfo &
309CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000310 // FIXME: Do we need to handle ObjCMethodDecl?
311 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000312
Anders Carlsson6710c532010-02-06 02:44:09 +0000313 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000314 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000315
316 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000317 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000318
John McCalla729c622012-02-17 03:33:10 +0000319 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000320}
321
Reid Klecknerc3473512014-08-29 21:43:29 +0000322/// Arrange a thunk that takes 'this' as the first parameter followed by
323/// varargs. Return a void pointer, regardless of the actual return type.
324/// The body of the thunk will end in a musttail call to a function of the
325/// correct type, and the caller will bitcast the function to the correct
326/// prototype.
327const CGFunctionInfo &
328CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
329 assert(MD->isVirtual() && "only virtual memptrs have thunks");
330 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
331 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
332 return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
333 FTP->getExtInfo(), RequiredArgs(1));
334}
335
John McCallc818bbb2012-12-07 07:03:17 +0000336/// Arrange a call as unto a free function, except possibly with an
337/// additional number of formal parameters considered required.
338static const CGFunctionInfo &
339arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000340 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000341 const CallArgList &args,
342 const FunctionType *fnType,
343 unsigned numExtraRequiredArgs) {
344 assert(args.size() >= numExtraRequiredArgs);
345
346 // In most cases, there are no optional arguments.
347 RequiredArgs required = RequiredArgs::All;
348
349 // If we have a variadic prototype, the required arguments are the
350 // extra prefix plus the arguments in the prototype.
351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
352 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000353 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000354
355 // If we don't have a prototype at all, but we're supposed to
356 // explicitly use the variadic convention for unprototyped calls,
357 // treat all of the arguments as required but preserve the nominal
358 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000359 } else if (CGM.getTargetCodeGenInfo()
360 .isNoProtoCallVariadic(args,
361 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000362 required = RequiredArgs(args.size());
363 }
364
Alp Toker314cc812014-01-25 16:55:45 +0000365 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000366 fnType->getExtInfo(), required);
367}
368
John McCalla729c622012-02-17 03:33:10 +0000369/// Figure out the rules for calling a function with the given formal
370/// type using the given arguments. The arguments are necessary
371/// because the function might be unprototyped, in which case it's
372/// target-dependent in crazy ways.
373const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000374CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
375 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000376 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000377}
John McCalla729c622012-02-17 03:33:10 +0000378
John McCallc818bbb2012-12-07 07:03:17 +0000379/// A block function call is essentially a free-function call with an
380/// extra implicit argument.
381const CGFunctionInfo &
382CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
383 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000384 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000385}
386
387const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000388CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
389 const CallArgList &args,
390 FunctionType::ExtInfo info,
391 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000392 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000393 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000394 for (const auto &Arg : args)
395 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000396 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
397 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000398}
399
400/// Arrange a call to a C++ method, passing the given arguments.
401const CGFunctionInfo &
402CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
403 const FunctionProtoType *FPT,
404 RequiredArgs required) {
405 // FIXME: Kill copy.
406 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000407 for (const auto &Arg : args)
408 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000409
410 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000411 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
412 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000413}
414
Reid Kleckner4982b822014-01-31 22:54:50 +0000415const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
416 QualType resultType, const FunctionArgList &args,
417 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000418 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000419 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000420 for (auto Arg : args)
421 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000422
423 RequiredArgs required =
424 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000425 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000426 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000427}
428
John McCalla729c622012-02-17 03:33:10 +0000429const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000430 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000431 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000432}
433
John McCalla729c622012-02-17 03:33:10 +0000434/// Arrange the argument and result information for an abstract value
435/// of a given function type. This is the method which all of the
436/// above functions ultimately defer to.
437const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000438CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000439 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000440 ArrayRef<CanQualType> argTypes,
441 FunctionType::ExtInfo info,
442 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000443#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000444 for (ArrayRef<CanQualType>::const_iterator
445 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000446 assert(I->isCanonicalAsParam());
447#endif
448
John McCalla729c622012-02-17 03:33:10 +0000449 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000450
Daniel Dunbare0be8292009-02-03 00:07:12 +0000451 // Lookup or create unique function info.
452 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000453 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
454 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000455
Craig Topper8a13c412014-05-21 05:09:00 +0000456 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000457 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000458 if (FI)
459 return *FI;
460
John McCalla729c622012-02-17 03:33:10 +0000461 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000462 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
463 required);
John McCalla729c622012-02-17 03:33:10 +0000464 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000465
John McCalla729c622012-02-17 03:33:10 +0000466 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
467 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000468
Daniel Dunbar313321e2009-02-03 05:31:23 +0000469 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000470 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000471
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000472 // Loop over all of the computed argument and return value info. If any of
473 // them are direct or extend without a specified coerce type, specify the
474 // default now.
John McCalla729c622012-02-17 03:33:10 +0000475 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000476 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000477 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000478
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000479 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000480 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000481 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000482
John McCalla729c622012-02-17 03:33:10 +0000483 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
484 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000485
Daniel Dunbare0be8292009-02-03 00:07:12 +0000486 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000487}
488
John McCalla729c622012-02-17 03:33:10 +0000489CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000490 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000491 const FunctionType::ExtInfo &info,
492 CanQualType resultType,
493 ArrayRef<CanQualType> argTypes,
494 RequiredArgs required) {
495 void *buffer = operator new(sizeof(CGFunctionInfo) +
496 sizeof(ArgInfo) * (argTypes.size() + 1));
497 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
498 FI->CallingConvention = llvmCC;
499 FI->EffectiveCallingConvention = llvmCC;
500 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000501 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000502 FI->NoReturn = info.getNoReturn();
503 FI->ReturnsRetained = info.getProducesResult();
504 FI->Required = required;
505 FI->HasRegParm = info.getHasRegParm();
506 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000507 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000508 FI->NumArgs = argTypes.size();
509 FI->getArgsBuffer()[0].type = resultType;
510 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
511 FI->getArgsBuffer()[i + 1].type = argTypes[i];
512 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000513}
514
515/***/
516
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000517namespace {
518// ABIArgInfo::Expand implementation.
519
520// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
521struct TypeExpansion {
522 enum TypeExpansionKind {
523 // Elements of constant arrays are expanded recursively.
524 TEK_ConstantArray,
525 // Record fields are expanded recursively (but if record is a union, only
526 // the field with the largest size is expanded).
527 TEK_Record,
528 // For complex types, real and imaginary parts are expanded recursively.
529 TEK_Complex,
530 // All other types are not expandable.
531 TEK_None
532 };
533
534 const TypeExpansionKind Kind;
535
536 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
537 virtual ~TypeExpansion() {}
538};
539
540struct ConstantArrayExpansion : TypeExpansion {
541 QualType EltTy;
542 uint64_t NumElts;
543
544 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
545 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
546 static bool classof(const TypeExpansion *TE) {
547 return TE->Kind == TEK_ConstantArray;
548 }
549};
550
551struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000552 SmallVector<const CXXBaseSpecifier *, 1> Bases;
553
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000554 SmallVector<const FieldDecl *, 1> Fields;
555
Reid Klecknere9f6a712014-10-31 17:10:41 +0000556 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
557 SmallVector<const FieldDecl *, 1> &&Fields)
558 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000559 static bool classof(const TypeExpansion *TE) {
560 return TE->Kind == TEK_Record;
561 }
562};
563
564struct ComplexExpansion : TypeExpansion {
565 QualType EltTy;
566
567 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
568 static bool classof(const TypeExpansion *TE) {
569 return TE->Kind == TEK_Complex;
570 }
571};
572
573struct NoExpansion : TypeExpansion {
574 NoExpansion() : TypeExpansion(TEK_None) {}
575 static bool classof(const TypeExpansion *TE) {
576 return TE->Kind == TEK_None;
577 }
578};
579} // namespace
580
581static std::unique_ptr<TypeExpansion>
582getTypeExpansion(QualType Ty, const ASTContext &Context) {
583 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
584 return llvm::make_unique<ConstantArrayExpansion>(
585 AT->getElementType(), AT->getSize().getZExtValue());
586 }
587 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000588 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000589 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000590 const RecordDecl *RD = RT->getDecl();
591 assert(!RD->hasFlexibleArrayMember() &&
592 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000593 if (RD->isUnion()) {
594 // Unions can be here only in degenerative cases - all the fields are same
595 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000596 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000597 CharUnits UnionSize = CharUnits::Zero();
598
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000599 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000600 assert(!FD->isBitField() &&
601 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000602 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000603 if (UnionSize < FieldSize) {
604 UnionSize = FieldSize;
605 LargestFD = FD;
606 }
607 }
608 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000609 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000610 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000611 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
612 assert(!CXXRD->isDynamicClass() &&
613 "cannot expand vtable pointers in dynamic classes");
614 for (const CXXBaseSpecifier &BS : CXXRD->bases())
615 Bases.push_back(&BS);
616 }
617
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000618 for (const auto *FD : RD->fields()) {
619 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000620 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000621 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000622 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000623 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000624 return llvm::make_unique<RecordExpansion>(std::move(Bases),
625 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000626 }
627 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
628 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
629 }
630 return llvm::make_unique<NoExpansion>();
631}
632
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000633static int getExpansionSize(QualType Ty, const ASTContext &Context) {
634 auto Exp = getTypeExpansion(Ty, Context);
635 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
636 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
637 }
638 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
639 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000640 for (auto BS : RExp->Bases)
641 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000642 for (auto FD : RExp->Fields)
643 Res += getExpansionSize(FD->getType(), Context);
644 return Res;
645 }
646 if (isa<ComplexExpansion>(Exp.get()))
647 return 2;
648 assert(isa<NoExpansion>(Exp.get()));
649 return 1;
650}
651
Alexey Samsonov153004f2014-09-29 22:08:00 +0000652void
653CodeGenTypes::getExpandedTypes(QualType Ty,
654 SmallVectorImpl<llvm::Type *>::iterator &TI) {
655 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000656 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
657 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000658 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000659 }
660 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000661 for (auto BS : RExp->Bases)
662 getExpandedTypes(BS->getType(), TI);
663 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000664 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000665 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
666 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000667 *TI++ = EltTy;
668 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000669 } else {
670 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000671 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000672 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000673}
674
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000675void CodeGenFunction::ExpandTypeFromArgs(
676 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000677 assert(LV.isSimple() &&
678 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000679
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000680 auto Exp = getTypeExpansion(Ty, getContext());
681 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
682 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
683 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
684 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
685 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000686 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000687 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000688 llvm::Value *This = LV.getAddress();
689 for (const CXXBaseSpecifier *BS : RExp->Bases) {
690 // Perform a single step derived-to-base conversion.
691 llvm::Value *Base =
692 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
693 /*NullCheckValue=*/false, SourceLocation());
694 LValue SubLV = MakeAddrLValue(Base, BS->getType());
695
696 // Recurse onto bases.
697 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
698 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000699 for (auto FD : RExp->Fields) {
700 // FIXME: What are the right qualifiers here?
701 LValue SubLV = EmitLValueForField(LV, FD);
702 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000703 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000704 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000705 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000706 EmitStoreThroughLValue(RValue::get(*AI++),
707 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000708 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000709 EmitStoreThroughLValue(RValue::get(*AI++),
710 MakeAddrLValue(ImagAddr, CExp->EltTy));
711 } else {
712 assert(isa<NoExpansion>(Exp.get()));
713 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000714 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000715}
716
717void CodeGenFunction::ExpandTypeToArgs(
718 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
719 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
720 auto Exp = getTypeExpansion(Ty, getContext());
721 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
722 llvm::Value *Addr = RV.getAggregateAddr();
723 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
724 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
725 RValue EltRV =
726 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
727 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
728 }
729 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000730 llvm::Value *This = RV.getAggregateAddr();
731 for (const CXXBaseSpecifier *BS : RExp->Bases) {
732 // Perform a single step derived-to-base conversion.
733 llvm::Value *Base =
734 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
735 /*NullCheckValue=*/false, SourceLocation());
736 RValue BaseRV = RValue::getAggregate(Base);
737
738 // Recurse onto bases.
739 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
740 IRCallArgPos);
741 }
742
743 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000744 for (auto FD : RExp->Fields) {
745 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
746 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
747 IRCallArgPos);
748 }
749 } else if (isa<ComplexExpansion>(Exp.get())) {
750 ComplexPairTy CV = RV.getComplexVal();
751 IRCallArgs[IRCallArgPos++] = CV.first;
752 IRCallArgs[IRCallArgPos++] = CV.second;
753 } else {
754 assert(isa<NoExpansion>(Exp.get()));
755 assert(RV.isScalar() &&
756 "Unexpected non-scalar rvalue during struct expansion.");
757
758 // Insert a bitcast as needed.
759 llvm::Value *V = RV.getScalarVal();
760 if (IRCallArgPos < IRFuncTy->getNumParams() &&
761 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
762 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
763
764 IRCallArgs[IRCallArgPos++] = V;
765 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000766}
767
Chris Lattner895c52b2010-06-27 06:04:18 +0000768/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000769/// accessing some number of bytes out of it, try to gep into the struct to get
770/// at its inner goodness. Dive as deep as possible without entering an element
771/// with an in-memory size smaller than DstSize.
772static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000773EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000774 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000775 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000776 // We can't dive into a zero-element struct.
777 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000778
Chris Lattner2192fe52011-07-18 04:24:23 +0000779 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000780
Chris Lattner1cd66982010-06-27 05:56:15 +0000781 // 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 +0000782 // first element is the same size as the whole struct, we can enter it. The
783 // comparison must be made on the store size and not the alloca size. Using
784 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000785 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000786 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000787 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000788 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000789 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000790
Chris Lattner1cd66982010-06-27 05:56:15 +0000791 // GEP into the first element.
792 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000793
Chris Lattner1cd66982010-06-27 05:56:15 +0000794 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000795 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000796 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000797 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000798 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000799
800 return SrcPtr;
801}
802
Chris Lattner055097f2010-06-27 06:26:04 +0000803/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
804/// are either integers or pointers. This does a truncation of the value if it
805/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000806///
807/// This behaves as if the value were coerced through memory, so on big-endian
808/// targets the high bits are preserved in a truncation, while little-endian
809/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000810static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000811 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000812 CodeGenFunction &CGF) {
813 if (Val->getType() == Ty)
814 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000815
Chris Lattner055097f2010-06-27 06:26:04 +0000816 if (isa<llvm::PointerType>(Val->getType())) {
817 // If this is Pointer->Pointer avoid conversion to and from int.
818 if (isa<llvm::PointerType>(Ty))
819 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000820
Chris Lattner055097f2010-06-27 06:26:04 +0000821 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000822 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000823 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000824
Chris Lattner2192fe52011-07-18 04:24:23 +0000825 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000826 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000827 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000828
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000829 if (Val->getType() != DestIntTy) {
830 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
831 if (DL.isBigEndian()) {
832 // Preserve the high bits on big-endian targets.
833 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000834 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
835 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
836
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000837 if (SrcSize > DstSize) {
838 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
839 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
840 } else {
841 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
842 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
843 }
844 } else {
845 // Little-endian targets preserve the low bits. No shifts required.
846 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
847 }
848 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000849
Chris Lattner055097f2010-06-27 06:26:04 +0000850 if (isa<llvm::PointerType>(Ty))
851 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
852 return Val;
853}
854
Chris Lattner1cd66982010-06-27 05:56:15 +0000855
856
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000857/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
858/// a pointer to an object of type \arg Ty.
859///
860/// This safely handles the case when the src type is smaller than the
861/// destination type; in this situation the values of bits which not
862/// present in the src are undefined.
863static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000864 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000865 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000866 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000867 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000868
Chris Lattnerd200eda2010-06-28 22:51:39 +0000869 // If SrcTy and Ty are the same, just do a load.
870 if (SrcTy == Ty)
871 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000872
Micah Villmowdd31ca12012-10-08 16:25:52 +0000873 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000874
Chris Lattner2192fe52011-07-18 04:24:23 +0000875 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000876 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000877 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
878 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000879
Micah Villmowdd31ca12012-10-08 16:25:52 +0000880 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000881
Chris Lattner055097f2010-06-27 06:26:04 +0000882 // If the source and destination are integer or pointer types, just do an
883 // extension or truncation to the desired type.
884 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
885 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
886 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
887 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
888 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000889
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000890 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000891 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000892 // Generally SrcSize is never greater than DstSize, since this means we are
893 // losing bits. However, this can happen in cases where the structure has
894 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000895 //
Mike Stump18bb9282009-05-16 07:57:57 +0000896 // FIXME: Assert that we aren't truncating non-padding bits when have access
897 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000898 llvm::Value *Casted =
899 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000900 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
901 // FIXME: Use better alignment / avoid requiring aligned load.
902 Load->setAlignment(1);
903 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000904 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000905
Chris Lattner3fcc7902010-06-27 01:06:27 +0000906 // Otherwise do coercion through memory. This is stupid, but
907 // simple.
908 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000909 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
910 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
911 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000912 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000913 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
914 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
915 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000916 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000917}
918
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000919// Function to store a first-class aggregate into memory. We prefer to
920// store the elements rather than the aggregate to be more friendly to
921// fast-isel.
922// FIXME: Do we need to recurse here?
923static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
924 llvm::Value *DestPtr, bool DestIsVolatile,
925 bool LowAlignment) {
926 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000927 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000928 dyn_cast<llvm::StructType>(Val->getType())) {
929 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
930 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
931 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
932 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
933 DestIsVolatile);
934 if (LowAlignment)
935 SI->setAlignment(1);
936 }
937 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000938 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
939 if (LowAlignment)
940 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000941 }
942}
943
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000944/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
945/// where the source and destination may have different types.
946///
947/// This safely handles the case when the src type is larger than the
948/// destination type; the upper bits of the src will be lost.
949static void CreateCoercedStore(llvm::Value *Src,
950 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000951 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000952 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000953 llvm::Type *SrcTy = Src->getType();
954 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000955 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000956 if (SrcTy == DstTy) {
957 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
958 return;
959 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000960
Micah Villmowdd31ca12012-10-08 16:25:52 +0000961 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000962
Chris Lattner2192fe52011-07-18 04:24:23 +0000963 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000964 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
965 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
966 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000967
Chris Lattner055097f2010-06-27 06:26:04 +0000968 // If the source and destination are integer or pointer types, just do an
969 // extension or truncation to the desired type.
970 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
971 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
972 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
973 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
974 return;
975 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000976
Micah Villmowdd31ca12012-10-08 16:25:52 +0000977 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000978
Daniel Dunbar313321e2009-02-03 05:31:23 +0000979 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000980 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000981 llvm::Value *Casted =
982 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000983 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000984 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000985 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000986 // Otherwise do coercion through memory. This is stupid, but
987 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000988
989 // Generally SrcSize is never greater than DstSize, since this means we are
990 // losing bits. However, this can happen in cases where the structure has
991 // additional padding, for example due to a user specified alignment.
992 //
993 // FIXME: Assert that we aren't truncating non-padding bits when have access
994 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000995 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
996 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000997 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
998 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
999 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001000 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001001 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1002 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1003 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001004 }
1005}
1006
Alexey Samsonov153004f2014-09-29 22:08:00 +00001007namespace {
1008
1009/// Encapsulates information about the way function arguments from
1010/// CGFunctionInfo should be passed to actual LLVM IR function.
1011class ClangToLLVMArgMapping {
1012 static const unsigned InvalidIndex = ~0U;
1013 unsigned InallocaArgNo;
1014 unsigned SRetArgNo;
1015 unsigned TotalIRArgs;
1016
1017 /// Arguments of LLVM IR function corresponding to single Clang argument.
1018 struct IRArgs {
1019 unsigned PaddingArgIndex;
1020 // Argument is expanded to IR arguments at positions
1021 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1022 unsigned FirstArgIndex;
1023 unsigned NumberOfArgs;
1024
1025 IRArgs()
1026 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1027 NumberOfArgs(0) {}
1028 };
1029
1030 SmallVector<IRArgs, 8> ArgInfo;
1031
1032public:
1033 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1034 bool OnlyRequiredArgs = false)
1035 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1036 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1037 construct(Context, FI, OnlyRequiredArgs);
1038 }
1039
1040 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1041 unsigned getInallocaArgNo() const {
1042 assert(hasInallocaArg());
1043 return InallocaArgNo;
1044 }
1045
1046 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1047 unsigned getSRetArgNo() const {
1048 assert(hasSRetArg());
1049 return SRetArgNo;
1050 }
1051
1052 unsigned totalIRArgs() const { return TotalIRArgs; }
1053
1054 bool hasPaddingArg(unsigned ArgNo) const {
1055 assert(ArgNo < ArgInfo.size());
1056 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1057 }
1058 unsigned getPaddingArgNo(unsigned ArgNo) const {
1059 assert(hasPaddingArg(ArgNo));
1060 return ArgInfo[ArgNo].PaddingArgIndex;
1061 }
1062
1063 /// Returns index of first IR argument corresponding to ArgNo, and their
1064 /// quantity.
1065 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1066 assert(ArgNo < ArgInfo.size());
1067 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1068 ArgInfo[ArgNo].NumberOfArgs);
1069 }
1070
1071private:
1072 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1073 bool OnlyRequiredArgs);
1074};
1075
1076void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1077 const CGFunctionInfo &FI,
1078 bool OnlyRequiredArgs) {
1079 unsigned IRArgNo = 0;
1080 bool SwapThisWithSRet = false;
1081 const ABIArgInfo &RetAI = FI.getReturnInfo();
1082
1083 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1084 SwapThisWithSRet = RetAI.isSRetAfterThis();
1085 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1086 }
1087
1088 unsigned ArgNo = 0;
1089 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1090 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1091 ++I, ++ArgNo) {
1092 assert(I != FI.arg_end());
1093 QualType ArgType = I->type;
1094 const ABIArgInfo &AI = I->info;
1095 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1096 auto &IRArgs = ArgInfo[ArgNo];
1097
1098 if (AI.getPaddingType())
1099 IRArgs.PaddingArgIndex = IRArgNo++;
1100
1101 switch (AI.getKind()) {
1102 case ABIArgInfo::Extend:
1103 case ABIArgInfo::Direct: {
1104 // FIXME: handle sseregparm someday...
1105 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1106 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1107 IRArgs.NumberOfArgs = STy->getNumElements();
1108 } else {
1109 IRArgs.NumberOfArgs = 1;
1110 }
1111 break;
1112 }
1113 case ABIArgInfo::Indirect:
1114 IRArgs.NumberOfArgs = 1;
1115 break;
1116 case ABIArgInfo::Ignore:
1117 case ABIArgInfo::InAlloca:
1118 // ignore and inalloca doesn't have matching LLVM parameters.
1119 IRArgs.NumberOfArgs = 0;
1120 break;
1121 case ABIArgInfo::Expand: {
1122 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1123 break;
1124 }
1125 }
1126
1127 if (IRArgs.NumberOfArgs > 0) {
1128 IRArgs.FirstArgIndex = IRArgNo;
1129 IRArgNo += IRArgs.NumberOfArgs;
1130 }
1131
1132 // Skip over the sret parameter when it comes second. We already handled it
1133 // above.
1134 if (IRArgNo == 1 && SwapThisWithSRet)
1135 IRArgNo++;
1136 }
1137 assert(ArgNo == ArgInfo.size());
1138
1139 if (FI.usesInAlloca())
1140 InallocaArgNo = IRArgNo++;
1141
1142 TotalIRArgs = IRArgNo;
1143}
1144} // namespace
1145
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001146/***/
1147
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001148bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001149 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001150}
1151
Tim Northovere77cc392014-03-29 13:28:05 +00001152bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1153 return ReturnTypeUsesSRet(FI) &&
1154 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1155}
1156
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001157bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1158 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1159 switch (BT->getKind()) {
1160 default:
1161 return false;
1162 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001163 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001164 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001165 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001166 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001167 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001168 }
1169 }
1170
1171 return false;
1172}
1173
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001174bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1175 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1176 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1177 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001178 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001179 }
1180 }
1181
1182 return false;
1183}
1184
Chris Lattnera5f58b02011-07-09 17:41:47 +00001185llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001186 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1187 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001188}
1189
Chris Lattnera5f58b02011-07-09 17:41:47 +00001190llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001191CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001192
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001193 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
1194 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001195
Alexey Samsonov153004f2014-09-29 22:08:00 +00001196 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001197 const ABIArgInfo &retAI = FI.getReturnInfo();
1198 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001199 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001200 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001201
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001202 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001203 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001204 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001205 break;
1206
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001207 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001208 if (retAI.getInAllocaSRet()) {
1209 // sret things on win32 aren't void, they return the sret pointer.
1210 QualType ret = FI.getReturnType();
1211 llvm::Type *ty = ConvertType(ret);
1212 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1213 resultType = llvm::PointerType::get(ty, addressSpace);
1214 } else {
1215 resultType = llvm::Type::getVoidTy(getLLVMContext());
1216 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001217 break;
1218
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001219 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001220 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1221 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001222 break;
1223 }
1224
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001225 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001226 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001227 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001228 }
Mike Stump11289f42009-09-09 15:08:12 +00001229
Alexey Samsonov153004f2014-09-29 22:08:00 +00001230 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1231 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1232
1233 // Add type for sret argument.
1234 if (IRFunctionArgs.hasSRetArg()) {
1235 QualType Ret = FI.getReturnType();
1236 llvm::Type *Ty = ConvertType(Ret);
1237 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1238 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1239 llvm::PointerType::get(Ty, AddressSpace);
1240 }
1241
1242 // Add type for inalloca argument.
1243 if (IRFunctionArgs.hasInallocaArg()) {
1244 auto ArgStruct = FI.getArgStruct();
1245 assert(ArgStruct);
1246 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1247 }
1248
John McCallc818bbb2012-12-07 07:03:17 +00001249 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001250 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001251 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1252 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001253 for (; it != ie; ++it, ++ArgNo) {
1254 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Rafael Espindolafad28de2012-10-24 01:59:00 +00001256 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001257 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1258 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1259 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001260
Alexey Samsonov153004f2014-09-29 22:08:00 +00001261 unsigned FirstIRArg, NumIRArgs;
1262 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1263
1264 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001265 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001266 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001267 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001268 break;
1269
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001270 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001271 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001272 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001273 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001274 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001275 break;
1276 }
1277
1278 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001279 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001280 // Fast-isel and the optimizer generally like scalar values better than
1281 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001282 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001283 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001284 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1285 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001286 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001287 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001288 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001289 assert(NumIRArgs == 1);
1290 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001291 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001292 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Daniel Dunbard3674e62008-09-11 01:48:57 +00001295 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001296 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1297 getExpandedTypes(it->type, ArgTypesIter);
1298 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001299 break;
1300 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001301 }
1302
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001303 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1304 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001305
1306 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001307}
1308
Chris Lattner2192fe52011-07-18 04:24:23 +00001309llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001310 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001311 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001312
Chris Lattner8806e322011-07-10 00:18:59 +00001313 if (!isFuncTypeConvertible(FPT))
1314 return llvm::StructType::get(getLLVMContext());
1315
1316 const CGFunctionInfo *Info;
1317 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001318 Info =
1319 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001320 else
John McCalla729c622012-02-17 03:33:10 +00001321 Info = &arrangeCXXMethodDeclaration(MD);
1322 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001323}
1324
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001325void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001326 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001327 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001328 unsigned &CallingConv,
1329 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001330 llvm::AttrBuilder FuncAttrs;
1331 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001332
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001333 CallingConv = FI.getEffectiveCallingConvention();
1334
John McCallab26cfa2010-02-05 21:31:56 +00001335 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001336 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001337
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001338 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001339 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001340 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001341 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001342 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001343 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001344 if (TargetDecl->hasAttr<NoReturnAttr>())
1345 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001346 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1347 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001348
1349 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001350 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001351 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001352 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001353 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1354 // These attributes are not inherited by overloads.
1355 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1356 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001357 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001358 }
1359
Eric Christopherbf005ec2011-08-15 22:38:22 +00001360 // 'const' and 'pure' attribute functions are also nounwind.
1361 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001362 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1363 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001364 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001365 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1366 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001367 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001368 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001369 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001370 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1371 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001372 }
1373
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001374 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001375 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001376 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001377 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001378 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001379 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001380 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001381 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001382 if (CodeGenOpts.EnableSegmentedStacks &&
1383 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001384 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001385
Bill Wendling2f81db62013-02-22 20:53:29 +00001386 if (AttrOnCallSite) {
1387 // Attributes that should go on the call site only.
1388 if (!CodeGenOpts.SimplifyLibCalls)
1389 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001390 } else {
1391 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001392 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001393 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001394 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001395 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001396 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001397 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001398 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001399 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001400 }
1401
Bill Wendlingdabafea2013-03-13 22:24:33 +00001402 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001403 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001404 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001405 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001406 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001407 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001408 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001409 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001410 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001411 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001412 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001413 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001414
Bill Wendlingd8f49502013-08-01 21:41:02 +00001415 if (!CodeGenOpts.StackRealignment)
1416 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001417 }
1418
Alexey Samsonov153004f2014-09-29 22:08:00 +00001419 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001420
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001421 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001422 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001423 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001424 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001425 if (RetTy->hasSignedIntegerRepresentation())
1426 RetAttrs.addAttribute(llvm::Attribute::SExt);
1427 else if (RetTy->hasUnsignedIntegerRepresentation())
1428 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001429 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001430 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001431 if (RetAI.getInReg())
1432 RetAttrs.addAttribute(llvm::Attribute::InReg);
1433 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001434 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001435 break;
1436
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001437 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001438 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001439 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001440 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1441 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001442 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001443 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001444
Daniel Dunbard3674e62008-09-11 01:48:57 +00001445 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001446 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001447 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001448
Hal Finkela2347ba2014-07-18 15:52:10 +00001449 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1450 QualType PTy = RefTy->getPointeeType();
1451 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1452 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1453 .getQuantity());
1454 else if (getContext().getTargetAddressSpace(PTy) == 0)
1455 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1456 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001457
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001458 // Attach return attributes.
1459 if (RetAttrs.hasAttributes()) {
1460 PAL.push_back(llvm::AttributeSet::get(
1461 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1462 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001463
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001464 // Attach attributes to sret.
1465 if (IRFunctionArgs.hasSRetArg()) {
1466 llvm::AttrBuilder SRETAttrs;
1467 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1468 if (RetAI.getInReg())
1469 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1470 PAL.push_back(llvm::AttributeSet::get(
1471 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1472 }
1473
1474 // Attach attributes to inalloca argument.
1475 if (IRFunctionArgs.hasInallocaArg()) {
1476 llvm::AttrBuilder Attrs;
1477 Attrs.addAttribute(llvm::Attribute::InAlloca);
1478 PAL.push_back(llvm::AttributeSet::get(
1479 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1480 }
1481
1482
1483 unsigned ArgNo = 0;
1484 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1485 E = FI.arg_end();
1486 I != E; ++I, ++ArgNo) {
1487 QualType ParamType = I->type;
1488 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001489 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001490
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001491 // Add attribute for padding argument, if necessary.
1492 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001493 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001494 PAL.push_back(llvm::AttributeSet::get(
1495 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1496 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001497 }
1498
John McCall39ec71f2010-03-27 00:47:27 +00001499 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1500 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001501 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001502 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001503 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001504 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001505 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001506 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001507 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001508 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001509 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001510 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001511 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001512 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001513
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001514 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001515 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001516 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001517
Anders Carlsson20759ad2009-09-16 15:53:40 +00001518 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001519 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001520
Bill Wendlinga7912f82012-10-10 07:36:56 +00001521 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1522
Daniel Dunbarc2304432009-03-18 19:51:01 +00001523 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001524 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1525 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001526 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001527
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001528 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001529 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001530 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001531
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001532 case ABIArgInfo::InAlloca:
1533 // inalloca disables readnone and readonly.
1534 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1535 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001536 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Hal Finkela2347ba2014-07-18 15:52:10 +00001539 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1540 QualType PTy = RefTy->getPointeeType();
1541 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1542 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1543 .getQuantity());
1544 else if (getContext().getTargetAddressSpace(PTy) == 0)
1545 Attrs.addAttribute(llvm::Attribute::NonNull);
1546 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001547
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001548 if (Attrs.hasAttributes()) {
1549 unsigned FirstIRArg, NumIRArgs;
1550 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1551 for (unsigned i = 0; i < NumIRArgs; i++)
1552 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1553 FirstIRArg + i + 1, Attrs));
1554 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001555 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001556 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001557
Bill Wendlinga7912f82012-10-10 07:36:56 +00001558 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001559 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001560 AttributeSet::get(getLLVMContext(),
1561 llvm::AttributeSet::FunctionIndex,
1562 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001563}
1564
John McCalla738c252011-03-09 04:27:21 +00001565/// An argument came in as a promoted argument; demote it back to its
1566/// declared type.
1567static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1568 const VarDecl *var,
1569 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001570 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001571
1572 // This can happen with promotions that actually don't change the
1573 // underlying type, like the enum promotions.
1574 if (value->getType() == varType) return value;
1575
1576 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1577 && "unexpected promotion type");
1578
1579 if (isa<llvm::IntegerType>(varType))
1580 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1581
1582 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1583}
1584
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001585/// Returns the attribute (either parameter attribute, or function
1586/// attribute), which declares argument ArgNo to be non-null.
1587static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1588 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001589 // FIXME: __attribute__((nonnull)) can also be applied to:
1590 // - references to pointers, where the pointee is known to be
1591 // nonnull (apparently a Clang extension)
1592 // - transparent unions containing pointers
1593 // In the former case, LLVM IR cannot represent the constraint. In
1594 // the latter case, we have no guarantee that the transparent union
1595 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001596 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1597 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001598 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001599 if (PVD) {
1600 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1601 return ParmNNAttr;
1602 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001603 // Check function attributes.
1604 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001605 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001606 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001607 if (NNAttr->isNonNull(ArgNo))
1608 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001609 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001610 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001611}
1612
Daniel Dunbard931a872009-02-02 22:03:45 +00001613void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1614 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001615 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001616 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1617 // Naked functions don't have prologues.
1618 return;
1619
John McCallcaa19452009-07-28 01:00:58 +00001620 // If this is an implicit-return-zero function, go ahead and
1621 // initialize the return value. TODO: it might be nice to have
1622 // a more general mechanism for this that didn't require synthesized
1623 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001624 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001625 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001626 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001627 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001628 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001629 Builder.CreateStore(Zero, ReturnValue);
1630 }
1631 }
1632
Mike Stump18bb9282009-05-16 07:57:57 +00001633 // FIXME: We no longer need the types from FunctionArgList; lift up and
1634 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001635
Alexey Samsonov153004f2014-09-29 22:08:00 +00001636 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001637 // Flattened function arguments.
1638 SmallVector<llvm::Argument *, 16> FnArgs;
1639 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1640 for (auto &Arg : Fn->args()) {
1641 FnArgs.push_back(&Arg);
1642 }
1643 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001644
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001645 // If we're using inalloca, all the memory arguments are GEPs off of the last
1646 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001647 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001648 if (IRFunctionArgs.hasInallocaArg()) {
1649 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001650 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1651 }
1652
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001653 // Name the struct return parameter.
1654 if (IRFunctionArgs.hasSRetArg()) {
1655 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001656 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001657 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001658 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001661 // Track if we received the parameter as a pointer (indirect, byval, or
1662 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1663 // into a local alloca for us.
1664 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001665 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001666 SmallVector<ValueAndIsPtr, 16> ArgVals;
1667 ArgVals.reserve(Args.size());
1668
Reid Kleckner739756c2013-12-04 19:23:12 +00001669 // Create a pointer value for every parameter declaration. This usually
1670 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1671 // any cleanups or do anything that might unwind. We do that separately, so
1672 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001673 assert(FI.arg_size() == Args.size() &&
1674 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001675 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001676 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001677 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001678 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001679 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001680 QualType Ty = info_it->type;
1681 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001682
John McCalla738c252011-03-09 04:27:21 +00001683 bool isPromoted =
1684 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1685
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001686 unsigned FirstIRArg, NumIRArgs;
1687 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001688
Daniel Dunbard3674e62008-09-11 01:48:57 +00001689 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001690 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001691 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001692 llvm::Value *V = Builder.CreateStructGEP(
1693 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1694 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001695 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001696 }
1697
Daniel Dunbar747865a2009-02-05 09:16:39 +00001698 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001699 assert(NumIRArgs == 1);
1700 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001701
John McCall47fb9502013-03-07 21:37:08 +00001702 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001703 // Aggregates and complex variables are accessed by reference. All we
1704 // need to do is realign the value, if requested
1705 if (ArgI.getIndirectRealign()) {
1706 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1707
1708 // Copy from the incoming argument pointer to the temporary with the
1709 // appropriate alignment.
1710 //
1711 // FIXME: We should have a common utility for generating an aggregate
1712 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001713 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001714 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001715 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1716 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1717 Builder.CreateMemCpy(Dst,
1718 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001719 llvm::ConstantInt::get(IntPtrTy,
1720 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001721 ArgI.getIndirectAlign(),
1722 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001723 V = AlignedTemp;
1724 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001725 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001726 } else {
1727 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001728 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001729 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1730 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001731
1732 if (isPromoted)
1733 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001734 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001735 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001736 break;
1737 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001738
1739 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001740 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001741
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001742 // If we have the trivial case, handle it with no muss and fuss.
1743 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001744 ArgI.getCoerceToType() == ConvertType(Ty) &&
1745 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001746 assert(NumIRArgs == 1);
1747 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001748 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001749
Hal Finkel48d53e22014-07-19 01:41:07 +00001750 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001751 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1752 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001753 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1754 AI->getArgNo() + 1,
1755 llvm::Attribute::NonNull));
1756
Hal Finkel48d53e22014-07-19 01:41:07 +00001757 QualType OTy = PVD->getOriginalType();
1758 if (const auto *ArrTy =
1759 getContext().getAsConstantArrayType(OTy)) {
1760 // A C99 array parameter declaration with the static keyword also
1761 // indicates dereferenceability, and if the size is constant we can
1762 // use the dereferenceable attribute (which requires the size in
1763 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001764 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001765 QualType ETy = ArrTy->getElementType();
1766 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1767 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1768 ArrSize) {
1769 llvm::AttrBuilder Attrs;
1770 Attrs.addDereferenceableAttr(
1771 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1772 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1773 AI->getArgNo() + 1, Attrs));
1774 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1775 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1776 AI->getArgNo() + 1,
1777 llvm::Attribute::NonNull));
1778 }
1779 }
1780 } else if (const auto *ArrTy =
1781 getContext().getAsVariableArrayType(OTy)) {
1782 // For C99 VLAs with the static keyword, we don't know the size so
1783 // we can't use the dereferenceable attribute, but in addrspace(0)
1784 // we know that it must be nonnull.
1785 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1786 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1787 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1788 AI->getArgNo() + 1,
1789 llvm::Attribute::NonNull));
1790 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001791
1792 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1793 if (!AVAttr)
1794 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1795 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1796 if (AVAttr) {
1797 llvm::Value *AlignmentValue =
1798 EmitScalarExpr(AVAttr->getAlignment());
1799 llvm::ConstantInt *AlignmentCI =
1800 cast<llvm::ConstantInt>(AlignmentValue);
1801 unsigned Alignment =
1802 std::min((unsigned) AlignmentCI->getZExtValue(),
1803 +llvm::Value::MaximumAlignment);
1804
1805 llvm::AttrBuilder Attrs;
1806 Attrs.addAlignmentAttr(Alignment);
1807 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1808 AI->getArgNo() + 1, Attrs));
1809 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001810 }
1811
Bill Wendling507c3512012-10-16 05:23:44 +00001812 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001813 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1814 AI->getArgNo() + 1,
1815 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001816
Chris Lattner7369c142011-07-20 06:29:00 +00001817 // Ensure the argument is the correct type.
1818 if (V->getType() != ArgI.getCoerceToType())
1819 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1820
John McCalla738c252011-03-09 04:27:21 +00001821 if (isPromoted)
1822 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001823
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001824 if (const CXXMethodDecl *MD =
1825 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001826 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001827 V = CGM.getCXXABI().
1828 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001829 }
1830
Rafael Espindola8778c282012-11-29 16:09:03 +00001831 // Because of merging of function types from multiple decls it is
1832 // possible for the type of an argument to not match the corresponding
1833 // type in the function type. Since we are codegening the callee
1834 // in here, add a cast to the argument type.
1835 llvm::Type *LTy = ConvertType(Arg->getType());
1836 if (V->getType() != LTy)
1837 V = Builder.CreateBitCast(V, LTy);
1838
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001839 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001840 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001843 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001844
Chris Lattnerff941a62010-07-28 18:24:28 +00001845 // The alignment we need to use is the max of the requested alignment for
1846 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001847 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001848 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001849 AlignmentToUse = std::max(AlignmentToUse,
1850 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001851
Chris Lattnerff941a62010-07-28 18:24:28 +00001852 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001853 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001854 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001855
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001856 // If the value is offset in memory, apply the offset now.
1857 if (unsigned Offs = ArgI.getDirectOffset()) {
1858 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1859 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001860 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001861 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1862 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001863
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001864 // Fast-isel and the optimizer generally like scalar values better than
1865 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001866 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001867 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1868 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001869 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001870 llvm::Type *DstTy =
1871 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001872 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001873
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001874 if (SrcSize <= DstSize) {
1875 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1876
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001877 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001878 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001879 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001880 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1881 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001882 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001883 }
1884 } else {
1885 llvm::AllocaInst *TempAlloca =
1886 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1887 TempAlloca->setAlignment(AlignmentToUse);
1888 llvm::Value *TempV = TempAlloca;
1889
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001890 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001891 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001892 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001893 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1894 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001895 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001896 }
1897
1898 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001899 }
1900 } else {
1901 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001902 assert(NumIRArgs == 1);
1903 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001904 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001905 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001906 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001907
1908
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001909 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001910 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001911 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001912 if (isPromoted)
1913 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001914 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1915 } else {
1916 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001917 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001918 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001919 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001920
1921 case ABIArgInfo::Expand: {
1922 // If this structure was expanded into multiple arguments then
1923 // we need to create a temporary and reconstruct it from the
1924 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001925 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001926 CharUnits Align = getContext().getDeclAlign(Arg);
1927 Alloca->setAlignment(Align.getQuantity());
1928 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001929 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001930
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001931 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1932 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1933 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1934 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1935 auto AI = FnArgs[FirstIRArg + i];
1936 AI->setName(Arg->getName() + "." + Twine(i));
1937 }
1938 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001939 }
1940
1941 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001942 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001943 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001944 if (!hasScalarEvaluationKind(Ty)) {
1945 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1946 } else {
1947 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1948 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1949 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001950 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001951 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001952 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001953
Reid Kleckner739756c2013-12-04 19:23:12 +00001954 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1955 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001956 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1957 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001958 } else {
1959 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001960 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1961 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001962 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001963}
1964
John McCallffa2c1a2012-01-29 07:46:59 +00001965static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1966 while (insn->use_empty()) {
1967 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1968 if (!bitcast) return;
1969
1970 // This is "safe" because we would have used a ConstantExpr otherwise.
1971 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1972 bitcast->eraseFromParent();
1973 }
1974}
1975
John McCall31168b02011-06-15 23:02:42 +00001976/// Try to emit a fused autorelease of a return result.
1977static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1978 llvm::Value *result) {
1979 // We must be immediately followed the cast.
1980 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001981 if (BB->empty()) return nullptr;
1982 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001983
Chris Lattner2192fe52011-07-18 04:24:23 +00001984 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001985
1986 // result is in a BasicBlock and is therefore an Instruction.
1987 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1988
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001989 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001990
1991 // Look for:
1992 // %generator = bitcast %type1* %generator2 to %type2*
1993 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1994 // We would have emitted this as a constant if the operand weren't
1995 // an Instruction.
1996 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1997
1998 // Require the generator to be immediately followed by the cast.
1999 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002000 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002001
2002 insnsToKill.push_back(bitcast);
2003 }
2004
2005 // Look for:
2006 // %generator = call i8* @objc_retain(i8* %originalResult)
2007 // or
2008 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2009 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002010 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002011
2012 bool doRetainAutorelease;
2013
2014 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2015 doRetainAutorelease = true;
2016 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2017 .objc_retainAutoreleasedReturnValue) {
2018 doRetainAutorelease = false;
2019
John McCallcfa4e9b2012-09-07 23:30:50 +00002020 // If we emitted an assembly marker for this call (and the
2021 // ARCEntrypoints field should have been set if so), go looking
2022 // for that call. If we can't find it, we can't do this
2023 // optimization. But it should always be the immediately previous
2024 // instruction, unless we needed bitcasts around the call.
2025 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2026 llvm::Instruction *prev = call->getPrevNode();
2027 assert(prev);
2028 if (isa<llvm::BitCastInst>(prev)) {
2029 prev = prev->getPrevNode();
2030 assert(prev);
2031 }
2032 assert(isa<llvm::CallInst>(prev));
2033 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2034 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2035 insnsToKill.push_back(prev);
2036 }
John McCall31168b02011-06-15 23:02:42 +00002037 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002038 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002039 }
2040
2041 result = call->getArgOperand(0);
2042 insnsToKill.push_back(call);
2043
2044 // Keep killing bitcasts, for sanity. Note that we no longer care
2045 // about precise ordering as long as there's exactly one use.
2046 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2047 if (!bitcast->hasOneUse()) break;
2048 insnsToKill.push_back(bitcast);
2049 result = bitcast->getOperand(0);
2050 }
2051
2052 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002053 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002054 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2055 (*i)->eraseFromParent();
2056
2057 // Do the fused retain/autorelease if we were asked to.
2058 if (doRetainAutorelease)
2059 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2060
2061 // Cast back to the result type.
2062 return CGF.Builder.CreateBitCast(result, resultType);
2063}
2064
John McCallffa2c1a2012-01-29 07:46:59 +00002065/// If this is a +1 of the value of an immutable 'self', remove it.
2066static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2067 llvm::Value *result) {
2068 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002069 const ObjCMethodDecl *method =
2070 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002071 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002072 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002073 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002074
2075 // Look for a retain call.
2076 llvm::CallInst *retainCall =
2077 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2078 if (!retainCall ||
2079 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002080 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002081
2082 // Look for an ordinary load of 'self'.
2083 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2084 llvm::LoadInst *load =
2085 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2086 if (!load || load->isAtomic() || load->isVolatile() ||
2087 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002088 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002089
2090 // Okay! Burn it all down. This relies for correctness on the
2091 // assumption that the retain is emitted as part of the return and
2092 // that thereafter everything is used "linearly".
2093 llvm::Type *resultType = result->getType();
2094 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2095 assert(retainCall->use_empty());
2096 retainCall->eraseFromParent();
2097 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2098
2099 return CGF.Builder.CreateBitCast(load, resultType);
2100}
2101
John McCall31168b02011-06-15 23:02:42 +00002102/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002103///
2104/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002105static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2106 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002107 // If we're returning 'self', kill the initial retain. This is a
2108 // heuristic attempt to "encourage correctness" in the really unfortunate
2109 // case where we have a return of self during a dealloc and we desperately
2110 // need to avoid the possible autorelease.
2111 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2112 return self;
2113
John McCall31168b02011-06-15 23:02:42 +00002114 // At -O0, try to emit a fused retain/autorelease.
2115 if (CGF.shouldUseFusedARCCalls())
2116 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2117 return fused;
2118
2119 return CGF.EmitARCAutoreleaseReturnValue(result);
2120}
2121
John McCall6e1c0122012-01-29 02:35:02 +00002122/// Heuristically search for a dominating store to the return-value slot.
2123static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2124 // If there are multiple uses of the return-value slot, just check
2125 // for something immediately preceding the IP. Sometimes this can
2126 // happen with how we generate implicit-returns; it can also happen
2127 // with noreturn cleanups.
2128 if (!CGF.ReturnValue->hasOneUse()) {
2129 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002130 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002131 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002132 if (!store) return nullptr;
2133 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002134 assert(!store->isAtomic() && !store->isVolatile()); // see below
2135 return store;
2136 }
2137
2138 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002139 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002140 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002141
2142 // These aren't actually possible for non-coerced returns, and we
2143 // only care about non-coerced returns on this code path.
2144 assert(!store->isAtomic() && !store->isVolatile());
2145
2146 // Now do a first-and-dirty dominance check: just walk up the
2147 // single-predecessors chain from the current insertion point.
2148 llvm::BasicBlock *StoreBB = store->getParent();
2149 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2150 while (IP != StoreBB) {
2151 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002152 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002153 }
2154
2155 // Okay, the store's basic block dominates the insertion point; we
2156 // can do our thing.
2157 return store;
2158}
2159
Adrian Prantl3be10542013-05-02 17:30:20 +00002160void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002161 bool EmitRetDbgLoc,
2162 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002163 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2164 // Naked functions don't have epilogues.
2165 Builder.CreateUnreachable();
2166 return;
2167 }
2168
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002169 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002170 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002171 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002172 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002173 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002174
Dan Gohman481e40c2010-07-20 20:13:52 +00002175 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002176 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002177 QualType RetTy = FI.getReturnType();
2178 const ABIArgInfo &RetAI = FI.getReturnInfo();
2179
2180 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002181 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002182 // Aggregrates get evaluated directly into the destination. Sometimes we
2183 // need to return the sret value in a register, though.
2184 assert(hasAggregateEvaluationKind(RetTy));
2185 if (RetAI.getInAllocaSRet()) {
2186 llvm::Function::arg_iterator EI = CurFn->arg_end();
2187 --EI;
2188 llvm::Value *ArgStruct = EI;
2189 llvm::Value *SRet =
2190 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2191 RV = Builder.CreateLoad(SRet, "sret");
2192 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002193 break;
2194
Daniel Dunbar03816342010-08-21 02:24:36 +00002195 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002196 auto AI = CurFn->arg_begin();
2197 if (RetAI.isSRetAfterThis())
2198 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002199 switch (getEvaluationKind(RetTy)) {
2200 case TEK_Complex: {
2201 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002202 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2203 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002204 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002205 /*isInit*/ true);
2206 break;
2207 }
2208 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002209 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002210 break;
2211 case TEK_Scalar:
2212 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002213 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002214 /*isInit*/ true);
2215 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002216 }
2217 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002218 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002219
2220 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002221 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002222 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2223 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002224 // The internal return value temp always will have pointer-to-return-type
2225 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002226
John McCall6e1c0122012-01-29 02:35:02 +00002227 // If there is a dominating store to ReturnValue, we can elide
2228 // the load, zap the store, and usually zap the alloca.
2229 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002230 // Reuse the debug location from the store unless there is
2231 // cleanup code to be emitted between the store and return
2232 // instruction.
2233 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002234 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002235 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002236 RV = SI->getValueOperand();
2237 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002238
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002239 // If that was the only use of the return value, nuke it as well now.
2240 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2241 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002242 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002243 }
John McCall6e1c0122012-01-29 02:35:02 +00002244
2245 // Otherwise, we have to do a simple load.
2246 } else {
2247 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002248 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002249 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002250 llvm::Value *V = ReturnValue;
2251 // If the value is offset in memory, apply the offset now.
2252 if (unsigned Offs = RetAI.getDirectOffset()) {
2253 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2254 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002255 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002256 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2257 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002258
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002259 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002260 }
John McCall31168b02011-06-15 23:02:42 +00002261
2262 // In ARC, end functions that return a retainable type with a call
2263 // to objc_autoreleaseReturnValue.
2264 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002265 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002266 !FI.isReturnsRetained() &&
2267 RetTy->isObjCRetainableType());
2268 RV = emitAutoreleaseOfResult(*this, RV);
2269 }
2270
Chris Lattner726b3d02010-06-26 23:13:19 +00002271 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002272
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002273 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002274 break;
2275
2276 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002277 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002278 }
2279
Alexey Samsonovde443c52014-08-13 00:26:40 +00002280 llvm::Instruction *Ret;
2281 if (RV) {
Alexey Samsonov035462c2014-10-30 19:33:44 +00002282 if (SanOpts.ReturnsNonnullAttribute) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002283 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2284 SanitizerScope SanScope(this);
2285 llvm::Value *Cond = Builder.CreateICmpNE(
2286 RV, llvm::Constant::getNullValue(RV->getType()));
2287 llvm::Constant *StaticData[] = {
2288 EmitCheckSourceLocation(EndLoc),
2289 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2290 };
2291 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
2292 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002293 }
2294 Ret = Builder.CreateRet(RV);
2295 } else {
2296 Ret = Builder.CreateRetVoid();
2297 }
2298
Devang Patel65497582010-07-21 18:08:50 +00002299 if (!RetDbgLoc.isUnknown())
2300 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002301}
2302
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002303static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2304 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2305 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2306}
2307
2308static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2309 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2310 // placeholders.
2311 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2312 llvm::Value *Placeholder =
2313 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2314 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2315 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2316 Ty.getQualifiers(),
2317 AggValueSlot::IsNotDestructed,
2318 AggValueSlot::DoesNotNeedGCBarriers,
2319 AggValueSlot::IsNotAliased);
2320}
2321
John McCall32ea9692011-03-11 20:59:21 +00002322void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002323 const VarDecl *param,
2324 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002325 // StartFunction converted the ABI-lowered parameter(s) into a
2326 // local alloca. We need to turn that into an r-value suitable
2327 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002328 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002329
John McCall32ea9692011-03-11 20:59:21 +00002330 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002331
John McCall23f66262010-05-26 22:34:26 +00002332 // For the most part, we just need to load the alloca, except:
2333 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002334 // 2) references to non-scalars are pointers directly to the aggregate.
2335 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002336 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002337 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002338 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002339
2340 // Locals which are references to scalars are represented
2341 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002342 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002343 }
2344
Reid Klecknerab2090d2014-07-26 01:34:32 +00002345 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2346 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002347
Nick Lewycky2d84e842013-10-02 02:29:49 +00002348 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002349}
2350
John McCall31168b02011-06-15 23:02:42 +00002351static bool isProvablyNull(llvm::Value *addr) {
2352 return isa<llvm::ConstantPointerNull>(addr);
2353}
2354
2355static bool isProvablyNonNull(llvm::Value *addr) {
2356 return isa<llvm::AllocaInst>(addr);
2357}
2358
2359/// Emit the actual writing-back of a writeback.
2360static void emitWriteback(CodeGenFunction &CGF,
2361 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002362 const LValue &srcLV = writeback.Source;
2363 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002364 assert(!isProvablyNull(srcAddr) &&
2365 "shouldn't have writeback for provably null argument");
2366
Craig Topper8a13c412014-05-21 05:09:00 +00002367 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002368
2369 // If the argument wasn't provably non-null, we need to null check
2370 // before doing the store.
2371 bool provablyNonNull = isProvablyNonNull(srcAddr);
2372 if (!provablyNonNull) {
2373 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2374 contBB = CGF.createBasicBlock("icr.done");
2375
2376 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2377 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2378 CGF.EmitBlock(writebackBB);
2379 }
2380
2381 // Load the value to writeback.
2382 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2383
2384 // Cast it back, in case we're writing an id to a Foo* or something.
2385 value = CGF.Builder.CreateBitCast(value,
2386 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2387 "icr.writeback-cast");
2388
2389 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002390
2391 // If we have a "to use" value, it's something we need to emit a use
2392 // of. This has to be carefully threaded in: if it's done after the
2393 // release it's potentially undefined behavior (and the optimizer
2394 // will ignore it), and if it happens before the retain then the
2395 // optimizer could move the release there.
2396 if (writeback.ToUse) {
2397 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2398
2399 // Retain the new value. No need to block-copy here: the block's
2400 // being passed up the stack.
2401 value = CGF.EmitARCRetainNonBlock(value);
2402
2403 // Emit the intrinsic use here.
2404 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2405
2406 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002407 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002408
2409 // Put the new value in place (primitively).
2410 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2411
2412 // Release the old value.
2413 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2414
2415 // Otherwise, we can just do a normal lvalue store.
2416 } else {
2417 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2418 }
John McCall31168b02011-06-15 23:02:42 +00002419
2420 // Jump to the continuation block.
2421 if (!provablyNonNull)
2422 CGF.EmitBlock(contBB);
2423}
2424
2425static void emitWritebacks(CodeGenFunction &CGF,
2426 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002427 for (const auto &I : args.writebacks())
2428 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002429}
2430
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002431static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2432 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002433 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002434 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2435 CallArgs.getCleanupsToDeactivate();
2436 // Iterate in reverse to increase the likelihood of popping the cleanup.
2437 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2438 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2439 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2440 I->IsActiveIP->eraseFromParent();
2441 }
2442}
2443
John McCalleff18842013-03-23 02:35:54 +00002444static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2445 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2446 if (uop->getOpcode() == UO_AddrOf)
2447 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002448 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002449}
2450
John McCall31168b02011-06-15 23:02:42 +00002451/// Emit an argument that's being passed call-by-writeback. That is,
2452/// we are passing the address of
2453static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2454 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002455 LValue srcLV;
2456
2457 // Make an optimistic effort to emit the address as an l-value.
2458 // This can fail if the the argument expression is more complicated.
2459 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2460 srcLV = CGF.EmitLValue(lvExpr);
2461
2462 // Otherwise, just emit it as a scalar.
2463 } else {
2464 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2465
2466 QualType srcAddrType =
2467 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2468 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2469 }
2470 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002471
2472 // The dest and src types don't necessarily match in LLVM terms
2473 // because of the crazy ObjC compatibility rules.
2474
Chris Lattner2192fe52011-07-18 04:24:23 +00002475 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002476 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2477
2478 // If the address is a constant null, just pass the appropriate null.
2479 if (isProvablyNull(srcAddr)) {
2480 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2481 CRE->getType());
2482 return;
2483 }
2484
John McCall31168b02011-06-15 23:02:42 +00002485 // Create the temporary.
2486 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2487 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002488 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2489 // and that cleanup will be conditional if we can't prove that the l-value
2490 // isn't null, so we need to register a dominating point so that the cleanups
2491 // system will make valid IR.
2492 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2493
John McCall31168b02011-06-15 23:02:42 +00002494 // Zero-initialize it if we're not doing a copy-initialization.
2495 bool shouldCopy = CRE->shouldCopy();
2496 if (!shouldCopy) {
2497 llvm::Value *null =
2498 llvm::ConstantPointerNull::get(
2499 cast<llvm::PointerType>(destType->getElementType()));
2500 CGF.Builder.CreateStore(null, temp);
2501 }
Craig Topper8a13c412014-05-21 05:09:00 +00002502
2503 llvm::BasicBlock *contBB = nullptr;
2504 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002505
2506 // If the address is *not* known to be non-null, we need to switch.
2507 llvm::Value *finalArgument;
2508
2509 bool provablyNonNull = isProvablyNonNull(srcAddr);
2510 if (provablyNonNull) {
2511 finalArgument = temp;
2512 } else {
2513 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2514
2515 finalArgument = CGF.Builder.CreateSelect(isNull,
2516 llvm::ConstantPointerNull::get(destType),
2517 temp, "icr.argument");
2518
2519 // If we need to copy, then the load has to be conditional, which
2520 // means we need control flow.
2521 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002522 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002523 contBB = CGF.createBasicBlock("icr.cont");
2524 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2525 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2526 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002527 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002528 }
2529 }
2530
Craig Topper8a13c412014-05-21 05:09:00 +00002531 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002532
John McCall31168b02011-06-15 23:02:42 +00002533 // Perform a copy if necessary.
2534 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002535 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002536 assert(srcRV.isScalar());
2537
2538 llvm::Value *src = srcRV.getScalarVal();
2539 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2540 "icr.cast");
2541
2542 // Use an ordinary store, not a store-to-lvalue.
2543 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002544
2545 // If optimization is enabled, and the value was held in a
2546 // __strong variable, we need to tell the optimizer that this
2547 // value has to stay alive until we're doing the store back.
2548 // This is because the temporary is effectively unretained,
2549 // and so otherwise we can violate the high-level semantics.
2550 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2551 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2552 valueToUse = src;
2553 }
John McCall31168b02011-06-15 23:02:42 +00002554 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002555
John McCall31168b02011-06-15 23:02:42 +00002556 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002557 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002558 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002559 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002560
2561 // Make a phi for the value to intrinsically use.
2562 if (valueToUse) {
2563 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2564 "icr.to-use");
2565 phiToUse->addIncoming(valueToUse, copyBB);
2566 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2567 originBB);
2568 valueToUse = phiToUse;
2569 }
2570
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002571 condEval.end(CGF);
2572 }
John McCall31168b02011-06-15 23:02:42 +00002573
John McCalleff18842013-03-23 02:35:54 +00002574 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002575 args.add(RValue::get(finalArgument), CRE->getType());
2576}
2577
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002578void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2579 assert(!StackBase && !StackCleanup.isValid());
2580
2581 // Save the stack.
2582 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2583 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2584
2585 // Control gets really tied up in landing pads, so we have to spill the
2586 // stacksave to an alloca to avoid violating SSA form.
2587 // TODO: This is dead if we never emit the cleanup. We should create the
2588 // alloca and store lazily on the first cleanup emission.
2589 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2590 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2591 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2592 StackCleanup = CGF.EHStack.getInnermostEHScope();
2593 assert(StackCleanup.isValid());
2594}
2595
2596void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2597 if (StackBase) {
2598 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2599 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2600 // We could load StackBase from StackBaseMem, but in the non-exceptional
2601 // case we can skip it.
2602 CGF.Builder.CreateCall(F, StackBase);
2603 }
2604}
2605
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002606static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2607 QualType ArgType, SourceLocation ArgLoc,
2608 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonov035462c2014-10-30 19:33:44 +00002609 if (!CGF.SanOpts.NonnullAttribute || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002610 return;
2611 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2612 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2613 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2614 if (!NNAttr)
2615 return;
2616 CodeGenFunction::SanitizerScope SanScope(&CGF);
2617 assert(RV.isScalar());
2618 llvm::Value *V = RV.getScalarVal();
2619 llvm::Value *Cond =
2620 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2621 llvm::Constant *StaticData[] = {
2622 CGF.EmitCheckSourceLocation(ArgLoc),
2623 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2624 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2625 };
2626 CGF.EmitCheck(Cond, "nonnull_arg", StaticData, None,
2627 CodeGenFunction::CRK_Recoverable);
2628}
2629
Reid Kleckner739756c2013-12-04 19:23:12 +00002630void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2631 ArrayRef<QualType> ArgTypes,
2632 CallExpr::const_arg_iterator ArgBeg,
2633 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002634 const FunctionDecl *CalleeDecl,
2635 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002636 bool ForceColumnInfo) {
2637 CGDebugInfo *DI = getDebugInfo();
2638 SourceLocation CallLoc;
2639 if (DI) CallLoc = DI->getLocation();
2640
2641 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2642 // because arguments are destroyed left to right in the callee.
2643 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002644 // Insert a stack save if we're going to need any inalloca args.
2645 bool HasInAllocaArgs = false;
2646 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2647 I != E && !HasInAllocaArgs; ++I)
2648 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2649 if (HasInAllocaArgs) {
2650 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2651 Args.allocateArgumentMemory(*this);
2652 }
2653
2654 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002655 size_t CallArgsStart = Args.size();
2656 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2657 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2658 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002659 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2660 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002661 // Restore the debug location.
2662 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2663 }
2664
2665 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2666 // IR function.
2667 std::reverse(Args.begin() + CallArgsStart, Args.end());
2668 return;
2669 }
2670
2671 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2672 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2673 assert(Arg != ArgEnd);
2674 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002675 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2676 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002677 // Restore the debug location.
2678 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2679 }
2680}
2681
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002682namespace {
2683
2684struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2685 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2686 : Addr(Addr), Ty(Ty) {}
2687
2688 llvm::Value *Addr;
2689 QualType Ty;
2690
Craig Topper4f12f102014-03-12 06:41:41 +00002691 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002692 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2693 assert(!Dtor->isTrivial());
2694 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2695 /*Delegating=*/false, Addr);
2696 }
2697};
2698
2699}
2700
John McCall32ea9692011-03-11 20:59:21 +00002701void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2702 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002703 if (const ObjCIndirectCopyRestoreExpr *CRE
2704 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002705 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002706 assert(getContext().hasSameType(E->getType(), type));
2707 return emitWritebackArg(*this, args, CRE);
2708 }
2709
John McCall0a76c0c2011-08-26 18:42:59 +00002710 assert(type->isReferenceType() == E->isGLValue() &&
2711 "reference binding to unmaterialized r-value!");
2712
John McCall17054bd62011-08-26 21:08:13 +00002713 if (E->isGLValue()) {
2714 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002715 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002718 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2719
2720 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2721 // However, we still have to push an EH-only cleanup in case we unwind before
2722 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002723 if (HasAggregateEvalKind &&
2724 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2725 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002726 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002727 AggValueSlot Slot;
2728 if (args.isUsingInAlloca())
2729 Slot = createPlaceholderSlot(*this, type);
2730 else
2731 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002732
2733 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2734 bool DestroyedInCallee =
2735 RD && RD->hasNonTrivialDestructor() &&
2736 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2737 if (DestroyedInCallee)
2738 Slot.setExternallyDestructed();
2739
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002740 EmitAggExpr(E, Slot);
2741 RValue RV = Slot.asRValue();
2742 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002743
Reid Klecknere39ee212014-05-03 00:33:28 +00002744 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002745 // Create a no-op GEP between the placeholder and the cleanup so we can
2746 // RAUW it successfully. It also serves as a marker of the first
2747 // instruction where the cleanup is active.
2748 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002749 // This unreachable is a temporary marker which will be removed later.
2750 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2751 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002752 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002753 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002754 }
2755
2756 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002757 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2758 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2759 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002760 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2761 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2762 } else {
2763 // We can't represent a misaligned lvalue in the CallArgList, so copy
2764 // to an aligned temporary now.
2765 llvm::Value *tmp = CreateMemTemp(type);
2766 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2767 L.getAlignment());
2768 args.add(RValue::getAggregate(tmp), type);
2769 }
Eli Friedmandf968192011-05-26 00:10:27 +00002770 return;
2771 }
2772
John McCall32ea9692011-03-11 20:59:21 +00002773 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002774}
2775
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002776QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2777 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2778 // implicitly widens null pointer constants that are arguments to varargs
2779 // functions to pointer-sized ints.
2780 if (!getTarget().getTriple().isOSWindows())
2781 return Arg->getType();
2782
2783 if (Arg->getType()->isIntegerType() &&
2784 getContext().getTypeSize(Arg->getType()) <
2785 getContext().getTargetInfo().getPointerWidth(0) &&
2786 Arg->isNullPointerConstant(getContext(),
2787 Expr::NPC_ValueDependentIsNotNull)) {
2788 return getContext().getIntPtrType();
2789 }
2790
2791 return Arg->getType();
2792}
2793
Dan Gohman515a60d2012-02-16 00:57:37 +00002794// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2795// optimizer it can aggressively ignore unwind edges.
2796void
2797CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2798 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2799 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2800 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2801 CGM.getNoObjCARCExceptionsMetadata());
2802}
2803
John McCall882987f2013-02-28 19:01:20 +00002804/// Emits a call to the given no-arguments nounwind runtime function.
2805llvm::CallInst *
2806CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2807 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002808 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002809}
2810
2811/// Emits a call to the given nounwind runtime function.
2812llvm::CallInst *
2813CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2814 ArrayRef<llvm::Value*> args,
2815 const llvm::Twine &name) {
2816 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2817 call->setDoesNotThrow();
2818 return call;
2819}
2820
2821/// Emits a simple call (never an invoke) to the given no-arguments
2822/// runtime function.
2823llvm::CallInst *
2824CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2825 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002826 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002827}
2828
2829/// Emits a simple call (never an invoke) to the given runtime
2830/// function.
2831llvm::CallInst *
2832CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2833 ArrayRef<llvm::Value*> args,
2834 const llvm::Twine &name) {
2835 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2836 call->setCallingConv(getRuntimeCC());
2837 return call;
2838}
2839
2840/// Emits a call or invoke to the given noreturn runtime function.
2841void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2842 ArrayRef<llvm::Value*> args) {
2843 if (getInvokeDest()) {
2844 llvm::InvokeInst *invoke =
2845 Builder.CreateInvoke(callee,
2846 getUnreachableBlock(),
2847 getInvokeDest(),
2848 args);
2849 invoke->setDoesNotReturn();
2850 invoke->setCallingConv(getRuntimeCC());
2851 } else {
2852 llvm::CallInst *call = Builder.CreateCall(callee, args);
2853 call->setDoesNotReturn();
2854 call->setCallingConv(getRuntimeCC());
2855 Builder.CreateUnreachable();
2856 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002857 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002858}
2859
2860/// Emits a call or invoke instruction to the given nullary runtime
2861/// function.
2862llvm::CallSite
2863CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2864 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002865 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002866}
2867
2868/// Emits a call or invoke instruction to the given runtime function.
2869llvm::CallSite
2870CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2871 ArrayRef<llvm::Value*> args,
2872 const Twine &name) {
2873 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2874 callSite.setCallingConv(getRuntimeCC());
2875 return callSite;
2876}
2877
2878llvm::CallSite
2879CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2880 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002881 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002882}
2883
John McCallbd309292010-07-06 01:34:17 +00002884/// Emits a call or invoke instruction to the given function, depending
2885/// on the current state of the EH stack.
2886llvm::CallSite
2887CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002888 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002889 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002890 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002891
Dan Gohman515a60d2012-02-16 00:57:37 +00002892 llvm::Instruction *Inst;
2893 if (!InvokeDest)
2894 Inst = Builder.CreateCall(Callee, Args, Name);
2895 else {
2896 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2897 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2898 EmitBlock(ContBB);
2899 }
2900
2901 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2902 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002903 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002904 AddObjCARCExceptionMetadata(Inst);
2905
2906 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002907}
2908
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002909/// \brief Store a non-aggregate value to an address to initialize it. For
2910/// initialization, a non-atomic store will be used.
2911static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2912 LValue Dst) {
2913 if (Src.isScalar())
2914 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2915 else
2916 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2917}
2918
2919void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2920 llvm::Value *New) {
2921 DeferredReplacements.push_back(std::make_pair(Old, New));
2922}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002923
Daniel Dunbard931a872009-02-02 22:03:45 +00002924RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002925 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002926 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002927 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002928 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002929 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002930 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002931
2932 // Handle struct-return functions by passing a pointer to the
2933 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002934 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002935 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002936
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002937 llvm::FunctionType *IRFuncTy =
2938 cast<llvm::FunctionType>(
2939 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002940
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002941 // If we're using inalloca, insert the allocation after the stack save.
2942 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002943 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002944 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002945 llvm::Instruction *IP = CallArgs.getStackBase();
2946 llvm::AllocaInst *AI;
2947 if (IP) {
2948 IP = IP->getNextNode();
2949 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2950 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002951 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002952 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002953 AI->setUsedWithInAlloca(true);
2954 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2955 ArgMemory = AI;
2956 }
2957
Alexey Samsonov153004f2014-09-29 22:08:00 +00002958 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002959 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2960
Chris Lattner4ca97c32009-06-13 00:26:38 +00002961 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002962 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002963 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002964 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002965 SRetPtr = ReturnValue.getValue();
2966 if (!SRetPtr)
2967 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002968 if (IRFunctionArgs.hasSRetArg()) {
2969 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002970 } else {
2971 llvm::Value *Addr =
2972 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2973 Builder.CreateStore(SRetPtr, Addr);
2974 }
Anders Carlsson17490832009-12-24 20:40:36 +00002975 }
Mike Stump11289f42009-09-09 15:08:12 +00002976
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002977 assert(CallInfo.arg_size() == CallArgs.size() &&
2978 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002979 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002980 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002981 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002982 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002983 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002984 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002985
John McCall47fb9502013-03-07 21:37:08 +00002986 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002987
2988 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002989 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2990 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2991 llvm::UndefValue::get(ArgInfo.getPaddingType());
2992
2993 unsigned FirstIRArg, NumIRArgs;
2994 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002995
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002996 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002997 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002998 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002999 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3000 if (RV.isAggregate()) {
3001 // Replace the placeholder with the appropriate argument slot GEP.
3002 llvm::Instruction *Placeholder =
3003 cast<llvm::Instruction>(RV.getAggregateAddr());
3004 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3005 Builder.SetInsertPoint(Placeholder);
3006 llvm::Value *Addr = Builder.CreateStructGEP(
3007 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3008 Builder.restoreIP(IP);
3009 deferPlaceholderReplacement(Placeholder, Addr);
3010 } else {
3011 // Store the RValue into the argument struct.
3012 llvm::Value *Addr =
3013 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003014 unsigned AS = Addr->getType()->getPointerAddressSpace();
3015 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3016 // There are some cases where a trivial bitcast is not avoidable. The
3017 // definition of a type later in a translation unit may change it's type
3018 // from {}* to (%struct.foo*)*.
3019 if (Addr->getType() != MemType)
3020 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003021 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3022 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3023 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003024 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003025 }
3026
Daniel Dunbar03816342010-08-21 02:24:36 +00003027 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003028 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003029 if (RV.isScalar() || RV.isComplex()) {
3030 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003031 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3032 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3033 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003034 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003035
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003036 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003037 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003038 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003039 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003040 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003041 // 1. If the argument is not byval, and we are required to copy the
3042 // source. (This case doesn't occur on any common architecture.)
3043 // 2. If the argument is byval, RV is not sufficiently aligned, and
3044 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003045 // 3. If the argument is byval, but RV is located in an address space
3046 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003047 llvm::Value *Addr = RV.getAggregateAddr();
3048 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003049 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003050 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003051 const unsigned ArgAddrSpace =
3052 (FirstIRArg < IRFuncTy->getNumParams()
3053 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3054 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003055 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003056 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00003057 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3058 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003059 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003060 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3061 if (Align > AI->getAlignment())
3062 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003063 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003064 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003065 } else {
3066 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003067 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003068 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003069 }
3070 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003071 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003072
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003073 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003074 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003075 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003076
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003077 case ABIArgInfo::Extend:
3078 case ABIArgInfo::Direct: {
3079 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003080 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3081 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003082 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003083 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003084 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003085 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003086 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003087 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003088
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003089 // We might have to widen integers, but we should never truncate.
3090 if (ArgInfo.getCoerceToType() != V->getType() &&
3091 V->getType()->isIntegerTy())
3092 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3093
Chris Lattner3ce86682011-07-12 04:53:39 +00003094 // If the argument doesn't match, perform a bitcast to coerce it. This
3095 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003096 if (FirstIRArg < IRFuncTy->getNumParams() &&
3097 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3098 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3099 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003100 break;
3101 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003102
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003103 // FIXME: Avoid the conversion through memory if possible.
3104 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003105 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003106 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003107 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003108 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003109 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003110 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003111
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003112 // If the value is offset in memory, apply the offset now.
3113 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3114 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3115 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003116 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003117 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3118
3119 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003120
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003121 // Fast-isel and the optimizer generally like scalar values better than
3122 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003123 llvm::StructType *STy =
3124 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003125 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003126 llvm::Type *SrcTy =
3127 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3128 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3129 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3130
3131 // If the source type is smaller than the destination type of the
3132 // coerce-to logic, copy the source value into a temp alloca the size
3133 // of the destination type to allow loading all of it. The bits past
3134 // the source value are left undef.
3135 if (SrcSize < DstSize) {
3136 llvm::AllocaInst *TempAlloca
3137 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3138 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3139 SrcPtr = TempAlloca;
3140 } else {
3141 SrcPtr = Builder.CreateBitCast(SrcPtr,
3142 llvm::PointerType::getUnqual(STy));
3143 }
3144
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003145 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003146 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3147 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003148 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3149 // We don't know what we're loading from.
3150 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003151 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003152 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003153 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003154 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003155 assert(NumIRArgs == 1);
3156 IRCallArgs[FirstIRArg] =
3157 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003158 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003159
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003160 break;
3161 }
3162
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003163 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003164 unsigned IRArgPos = FirstIRArg;
3165 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3166 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003167 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003168 }
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003171 if (ArgMemory) {
3172 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003173 if (CallInfo.isVariadic()) {
3174 // When passing non-POD arguments by value to variadic functions, we will
3175 // end up with a variadic prototype and an inalloca call site. In such
3176 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3177 // the callee.
3178 unsigned CalleeAS =
3179 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3180 Callee = Builder.CreateBitCast(
3181 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3182 } else {
3183 llvm::Type *LastParamTy =
3184 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3185 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003186#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003187 // Assert that these structs have equivalent element types.
3188 llvm::StructType *FullTy = CallInfo.getArgStruct();
3189 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3190 cast<llvm::PointerType>(LastParamTy)->getElementType());
3191 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3192 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3193 DE = DeclaredTy->element_end(),
3194 FI = FullTy->element_begin();
3195 DI != DE; ++DI, ++FI)
3196 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003197#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003198 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3199 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003200 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003201 assert(IRFunctionArgs.hasInallocaArg());
3202 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003203 }
3204
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003205 if (!CallArgs.getCleanupsToDeactivate().empty())
3206 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3207
Chris Lattner4ca97c32009-06-13 00:26:38 +00003208 // If the callee is a bitcast of a function to a varargs pointer to function
3209 // type, check to see if we can remove the bitcast. This handles some cases
3210 // with unprototyped functions.
3211 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3212 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003213 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3214 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003215 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003216 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003217
Chris Lattner4ca97c32009-06-13 00:26:38 +00003218 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3219 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003220 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003221 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003222 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003223 bool ArgsMatch = true;
3224 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3225 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3226 ArgsMatch = false;
3227 break;
3228 }
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chris Lattner4ca97c32009-06-13 00:26:38 +00003230 // Strip the cast if we can get away with it. This is a nice cleanup,
3231 // but also allows us to inline the function at -O0 if it is marked
3232 // always_inline.
3233 if (ArgsMatch)
3234 Callee = CalleeF;
3235 }
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003238 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3239 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3240 // Inalloca argument can have different type.
3241 if (IRFunctionArgs.hasInallocaArg() &&
3242 i == IRFunctionArgs.getInallocaArgNo())
3243 continue;
3244 if (i < IRFuncTy->getNumParams())
3245 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3246 }
3247
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003248 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003249 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003250 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3251 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003252 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003253 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Craig Topper8a13c412014-05-21 05:09:00 +00003255 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003256 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3257 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003258 InvokeDest = getInvokeDest();
3259
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003260 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003261 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003262 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003263 } else {
3264 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003265 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003266 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003267 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003268 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003269 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003270
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003271 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3272 !CS.hasFnAttr(llvm::Attribute::NoInline))
3273 Attrs =
3274 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3275 llvm::Attribute::AlwaysInline);
3276
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003277 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003278 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003279
Dan Gohman515a60d2012-02-16 00:57:37 +00003280 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3281 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003282 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003283 AddObjCARCExceptionMetadata(CS.getInstruction());
3284
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003285 // If the call doesn't return, finish the basic block and clear the
3286 // insertion point; this allows the rest of IRgen to discard
3287 // unreachable code.
3288 if (CS.doesNotReturn()) {
3289 Builder.CreateUnreachable();
3290 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003291
Mike Stump18bb9282009-05-16 07:57:57 +00003292 // FIXME: For now, emit a dummy basic block because expr emitters in
3293 // generally are not ready to handle emitting expressions at unreachable
3294 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003295 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003296
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003297 // Return a reasonable RValue.
3298 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003299 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003300
3301 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003302 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003303 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003304
John McCall31168b02011-06-15 23:02:42 +00003305 // Emit any writebacks immediately. Arguably this should happen
3306 // after any return-value munging.
3307 if (CallArgs.hasWritebacks())
3308 emitWritebacks(*this, CallArgs);
3309
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003310 // The stack cleanup for inalloca arguments has to run out of the normal
3311 // lexical order, so deactivate it and run it manually here.
3312 CallArgs.freeArgumentMemory(*this);
3313
Hal Finkelee90a222014-09-26 05:04:30 +00003314 RValue Ret = [&] {
3315 switch (RetAI.getKind()) {
3316 case ABIArgInfo::InAlloca:
3317 case ABIArgInfo::Indirect:
3318 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003319
Hal Finkelee90a222014-09-26 05:04:30 +00003320 case ABIArgInfo::Ignore:
3321 // If we are ignoring an argument that had a result, make sure to
3322 // construct the appropriate return value for our caller.
3323 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003324
Hal Finkelee90a222014-09-26 05:04:30 +00003325 case ABIArgInfo::Extend:
3326 case ABIArgInfo::Direct: {
3327 llvm::Type *RetIRTy = ConvertType(RetTy);
3328 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3329 switch (getEvaluationKind(RetTy)) {
3330 case TEK_Complex: {
3331 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3332 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3333 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003334 }
Hal Finkelee90a222014-09-26 05:04:30 +00003335 case TEK_Aggregate: {
3336 llvm::Value *DestPtr = ReturnValue.getValue();
3337 bool DestIsVolatile = ReturnValue.isVolatile();
3338
3339 if (!DestPtr) {
3340 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3341 DestIsVolatile = false;
3342 }
3343 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3344 return RValue::getAggregate(DestPtr);
3345 }
3346 case TEK_Scalar: {
3347 // If the argument doesn't match, perform a bitcast to coerce it. This
3348 // can happen due to trivial type mismatches.
3349 llvm::Value *V = CI;
3350 if (V->getType() != RetIRTy)
3351 V = Builder.CreateBitCast(V, RetIRTy);
3352 return RValue::get(V);
3353 }
3354 }
3355 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003356 }
Hal Finkelee90a222014-09-26 05:04:30 +00003357
3358 llvm::Value *DestPtr = ReturnValue.getValue();
3359 bool DestIsVolatile = ReturnValue.isVolatile();
3360
3361 if (!DestPtr) {
3362 DestPtr = CreateMemTemp(RetTy, "coerce");
3363 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003364 }
Hal Finkelee90a222014-09-26 05:04:30 +00003365
3366 // If the value is offset in memory, apply the offset now.
3367 llvm::Value *StorePtr = DestPtr;
3368 if (unsigned Offs = RetAI.getDirectOffset()) {
3369 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3370 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3371 StorePtr = Builder.CreateBitCast(StorePtr,
3372 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003373 }
Hal Finkelee90a222014-09-26 05:04:30 +00003374 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3375
3376 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003377 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003378
Hal Finkelee90a222014-09-26 05:04:30 +00003379 case ABIArgInfo::Expand:
3380 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003381 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003382
Hal Finkelee90a222014-09-26 05:04:30 +00003383 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3384 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003385
Hal Finkelee90a222014-09-26 05:04:30 +00003386 if (Ret.isScalar() && TargetDecl) {
3387 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3388 llvm::Value *OffsetValue = nullptr;
3389 if (const auto *Offset = AA->getOffset())
3390 OffsetValue = EmitScalarExpr(Offset);
3391
3392 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3393 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3394 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3395 OffsetValue);
3396 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003397 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003398
Hal Finkelee90a222014-09-26 05:04:30 +00003399 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003400}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003401
3402/* VarArg handling */
3403
3404llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3405 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3406}