blob: 98056f5d6e92db059ce64d3895e1f8d28c9440f2 [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000029#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
Nick Lewyckyd9bce502016-09-20 15:49:58 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Attributes.h"
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000034#include "llvm/IR/CallingConv.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000035#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000036#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000038#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000039#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000040#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000041using namespace clang;
42using namespace CodeGen;
43
44/***/
45
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000046unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000047 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Erich Keane757d3172016-11-02 18:29:35 +000051 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000052 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000053 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
54 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000055 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000057 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000058 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000061 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000062 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000063 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000064 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000066 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000067 }
68}
69
John McCall8ee376f2010-02-24 07:14:12 +000070/// Derives the 'this' type for codegen purposes, i.e. ignoring method
71/// qualification.
72/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000073static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000076}
77
John McCall8ee376f2010-02-24 07:14:12 +000078/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000079static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80 return MD->getType()->getCanonicalTypeUnqualified()
81 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000082}
83
84/// Returns the "extra-canonicalized" return type, which discards
85/// qualifiers on the return type. Codegen doesn't care about them,
86/// and it makes ABI code a little easier to be able to assume that
87/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000088static CanQualType GetReturnType(QualType RetTy) {
89 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000090}
91
John McCall8dda7b22012-07-07 06:41:13 +000092/// Arrange the argument and result information for a value of the given
93/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000094const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000095CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000096 // When translating an unprototyped function type, always use a
97 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000098 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000099 /*instanceMethod=*/false,
100 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000101 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000102}
103
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000104/// Adds the formal parameters in FPT to the given prefix. If any parameter in
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000105/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
106static void appendParameterTypes(const CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000108 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
109 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000110 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000111 // Fill out paramInfos.
112 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
113 assert(paramInfos.size() <= prefix.size());
114 auto protoParamInfos = FPT->getExtParameterInfos();
115 paramInfos.reserve(prefix.size() + protoParamInfos.size());
116 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000117 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000118 }
119
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000120 // Fast path: unknown target.
121 if (FD == nullptr) {
122 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
123 return;
124 }
125
126 // In the vast majority cases, we'll have precisely FPT->getNumParams()
127 // parameters; the only thing that can change this is the presence of
128 // pass_object_size. So, we preallocate for the common case.
129 prefix.reserve(prefix.size() + FPT->getNumParams());
130
131 assert(FD->getNumParams() == FPT->getNumParams());
132 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
133 prefix.push_back(FPT->getParamType(I));
134 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
135 prefix.push_back(CGT.getContext().getSizeType());
136 }
137}
138
John McCall8dda7b22012-07-07 06:41:13 +0000139/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140/// type, on top of any implicit parameters already stored.
141static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000142arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000143 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000144 CanQual<FunctionProtoType> FTP,
145 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000146 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000147 RequiredArgs Required =
148 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000149 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000150 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000151 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000152
Peter Collingbournef7706832014-12-12 23:41:25 +0000153 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
154 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000155 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000156 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000157}
158
John McCalla729c622012-02-17 03:33:10 +0000159/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000160/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000161const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
163 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000164 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000165 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000166 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167}
168
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000169static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170 // Set the appropriate calling convention for the Function.
171 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000172 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000173
174 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000175 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000176
Erich Keane757d3172016-11-02 18:29:35 +0000177 if (D->hasAttr<RegCallAttr>())
178 return CC_X86RegCall;
179
Douglas Gregora941dca2010-05-18 16:57:00 +0000180 if (D->hasAttr<ThisCallAttr>())
181 return CC_X86ThisCall;
182
Reid Klecknerd7857f02014-10-24 17:42:17 +0000183 if (D->hasAttr<VectorCallAttr>())
184 return CC_X86VectorCall;
185
Dawn Perchik335e16b2010-09-03 01:29:35 +0000186 if (D->hasAttr<PascalAttr>())
187 return CC_X86Pascal;
188
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000189 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
190 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
191
Guy Benyeif0a014b2012-12-25 08:53:55 +0000192 if (D->hasAttr<IntelOclBiccAttr>())
193 return CC_IntelOclBicc;
194
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000195 if (D->hasAttr<MSABIAttr>())
196 return IsWindows ? CC_C : CC_X86_64Win64;
197
198 if (D->hasAttr<SysVABIAttr>())
199 return IsWindows ? CC_X86_64SysV : CC_C;
200
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000201 if (D->hasAttr<PreserveMostAttr>())
202 return CC_PreserveMost;
203
204 if (D->hasAttr<PreserveAllAttr>())
205 return CC_PreserveAll;
206
John McCallab26cfa2010-02-05 21:31:56 +0000207 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000208}
209
John McCalla729c622012-02-17 03:33:10 +0000210/// Arrange the argument and result information for a call to an
211/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000212/// (Zero value of RD means we don't have any meaningful "this" argument type,
213/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000214/// The member function must be an ordinary function, i.e. not a
215/// constructor or destructor.
216const CGFunctionInfo &
217CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000218 const FunctionProtoType *FTP,
219 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000220 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000221
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000223 if (RD)
224 argTypes.push_back(GetThisType(Context, RD));
225 else
226 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000227
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000228 return ::arrangeLLVMFunctionInfo(
229 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000230 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000231}
232
John McCalla729c622012-02-17 03:33:10 +0000233/// Arrange the argument and result information for a declaration or
234/// definition of the given C++ non-static member function. The
235/// member function must be an ordinary function, i.e. not a
236/// constructor or destructor.
237const CGFunctionInfo &
238CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000239 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000240 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
241
John McCalla729c622012-02-17 03:33:10 +0000242 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000243
John McCalla729c622012-02-17 03:33:10 +0000244 if (MD->isInstance()) {
245 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000246 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000247 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000248 }
249
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000250 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000251}
252
Richard Smith5179eb72016-06-28 19:03:57 +0000253bool CodeGenTypes::inheritingCtorHasParams(
254 const InheritedConstructor &Inherited, CXXCtorType Type) {
255 // Parameters are unnecessary if we're constructing a base class subobject
256 // and the inherited constructor lives in a virtual base.
257 return Type == Ctor_Complete ||
258 !Inherited.getShadowDecl()->constructsVirtualBase() ||
259 !Target.getCXXABI().hasConstructorVariants();
260 }
261
John McCalla729c622012-02-17 03:33:10 +0000262const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000263CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
264 StructorType Type) {
265
John McCalla729c622012-02-17 03:33:10 +0000266 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000267 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000269
Richard Smith5179eb72016-06-28 19:03:57 +0000270 bool PassParams = true;
271
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000272 GlobalDecl GD;
273 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
274 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000275
276 // A base class inheriting constructor doesn't get forwarded arguments
277 // needed to construct a virtual base (or base class thereof).
278 if (auto Inherited = CD->getInheritedConstructor())
279 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000280 } else {
281 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
282 GD = GlobalDecl(DD, toCXXDtorType(Type));
283 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000284
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000285 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000286
287 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000288 if (PassParams)
289 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000290
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000291 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000292
293 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000294 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
295 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000296
John McCall8dda7b22012-07-07 06:41:13 +0000297 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000298 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
299 ? argTypes.front()
300 : TheCXXABI.hasMostDerivedReturn(GD)
301 ? CGM.getContext().VoidPtrTy
302 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000303 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
304 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000305 paramInfos, required);
306}
307
308static SmallVector<CanQualType, 16>
309getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
310 SmallVector<CanQualType, 16> argTypes;
311 for (auto &arg : args)
312 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
313 return argTypes;
314}
315
316static SmallVector<CanQualType, 16>
317getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
318 SmallVector<CanQualType, 16> argTypes;
319 for (auto &arg : args)
320 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
321 return argTypes;
322}
323
324static void addExtParameterInfosForCall(
325 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
326 const FunctionProtoType *proto,
327 unsigned prefixArgs,
328 unsigned totalArgs) {
329 assert(proto->hasExtParameterInfos());
330 assert(paramInfos.size() <= prefixArgs);
331 assert(proto->getNumParams() + prefixArgs <= totalArgs);
332
333 // Add default infos for any prefix args that don't already have infos.
334 paramInfos.resize(prefixArgs);
335
336 // Add infos for the prototype.
337 auto protoInfos = proto->getExtParameterInfos();
338 paramInfos.append(protoInfos.begin(), protoInfos.end());
339
340 // Add default infos for the variadic arguments.
341 paramInfos.resize(totalArgs);
342}
343
344static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
345getExtParameterInfosForCall(const FunctionProtoType *proto,
346 unsigned prefixArgs, unsigned totalArgs) {
347 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
348 if (proto->hasExtParameterInfos()) {
349 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
350 }
351 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000352}
353
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000354/// Arrange a call to a C++ method, passing the given arguments.
355const CGFunctionInfo &
356CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
357 const CXXConstructorDecl *D,
358 CXXCtorType CtorKind,
359 unsigned ExtraArgs) {
360 // FIXME: Kill copy.
361 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000362 for (const auto &Arg : args)
363 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000364
365 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000366 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000367 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000368 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
369 ? ArgTypes.front()
370 : TheCXXABI.hasMostDerivedReturn(GD)
371 ? CGM.getContext().VoidPtrTy
372 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000373
374 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000375 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
376 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000377 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
378 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000379 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000380}
381
John McCalla729c622012-02-17 03:33:10 +0000382/// Arrange the argument and result information for the declaration or
383/// definition of the given function.
384const CGFunctionInfo &
385CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000386 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000387 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000388 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000389
John McCall2da83a32010-02-26 00:48:12 +0000390 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000391
John McCall2da83a32010-02-26 00:48:12 +0000392 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000393
394 // When declaring a function without a prototype, always use a
395 // non-variadic type.
George Burgess IV35cfca22017-01-06 19:10:48 +0000396 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000397 return arrangeLLVMFunctionInfo(
398 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000399 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000400 }
401
George Burgess IV35cfca22017-01-06 19:10:48 +0000402 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000403}
404
John McCalla729c622012-02-17 03:33:10 +0000405/// Arrange the argument and result information for the declaration or
406/// definition of an Objective-C method.
407const CGFunctionInfo &
408CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
409 // It happens that this is the same as a call with no optional
410 // arguments, except also using the formal 'self' type.
411 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
412}
413
414/// Arrange the argument and result information for the function type
415/// through which to perform a send to the given Objective-C method,
416/// using the given receiver type. The receiver type is not always
417/// the 'self' type of the method or even an Objective-C pointer type.
418/// This is *not* the right method for actually performing such a
419/// message send, due to the possibility of optional arguments.
420const CGFunctionInfo &
421CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
422 QualType receiverType) {
423 SmallVector<CanQualType, 16> argTys;
424 argTys.push_back(Context.getCanonicalParamType(receiverType));
425 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000426 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000427 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000428 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000429 }
John McCall31168b02011-06-15 23:02:42 +0000430
431 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000432 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
433 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000434
David Blaikiebbafb8a2012-03-11 07:00:24 +0000435 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000436 MD->hasAttr<NSReturnsRetainedAttr>())
437 einfo = einfo.withProducesResult(true);
438
John McCalla729c622012-02-17 03:33:10 +0000439 RequiredArgs required =
440 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
441
Peter Collingbournef7706832014-12-12 23:41:25 +0000442 return arrangeLLVMFunctionInfo(
443 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000444 /*chainCall=*/false, argTys, einfo, {}, required);
445}
446
447const CGFunctionInfo &
448CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
449 const CallArgList &args) {
450 auto argTypes = getArgTypesForCall(Context, args);
451 FunctionType::ExtInfo einfo;
452
453 return arrangeLLVMFunctionInfo(
454 GetReturnType(returnType), /*instanceMethod=*/false,
455 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000456}
457
John McCalla729c622012-02-17 03:33:10 +0000458const CGFunctionInfo &
459CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000460 // FIXME: Do we need to handle ObjCMethodDecl?
461 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000462
Anders Carlsson6710c532010-02-06 02:44:09 +0000463 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000464 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000465
466 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000467 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000468
John McCalla729c622012-02-17 03:33:10 +0000469 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000470}
471
Reid Klecknerc3473512014-08-29 21:43:29 +0000472/// Arrange a thunk that takes 'this' as the first parameter followed by
473/// varargs. Return a void pointer, regardless of the actual return type.
474/// The body of the thunk will end in a musttail call to a function of the
475/// correct type, and the caller will bitcast the function to the correct
476/// prototype.
477const CGFunctionInfo &
478CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
479 assert(MD->isVirtual() && "only virtual memptrs have thunks");
480 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
481 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000482 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
483 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000484 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000485}
486
David Majnemerdfa6d202015-03-11 18:36:39 +0000487const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000488CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
489 CXXCtorType CT) {
490 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
491
David Majnemerdfa6d202015-03-11 18:36:39 +0000492 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
493 SmallVector<CanQualType, 2> ArgTys;
494 const CXXRecordDecl *RD = CD->getParent();
495 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000496 if (CT == Ctor_CopyingClosure)
497 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000498 if (RD->getNumVBases() > 0)
499 ArgTys.push_back(Context.IntTy);
500 CallingConv CC = Context.getDefaultCallingConvention(
501 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
502 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
503 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000504 FunctionType::ExtInfo(CC), {},
505 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000506}
507
John McCallc818bbb2012-12-07 07:03:17 +0000508/// Arrange a call as unto a free function, except possibly with an
509/// additional number of formal parameters considered required.
510static const CGFunctionInfo &
511arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000512 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000513 const CallArgList &args,
514 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000515 unsigned numExtraRequiredArgs,
516 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000517 assert(args.size() >= numExtraRequiredArgs);
518
John McCallc56a8b32016-03-11 04:30:31 +0000519 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
520
John McCallc818bbb2012-12-07 07:03:17 +0000521 // In most cases, there are no optional arguments.
522 RequiredArgs required = RequiredArgs::All;
523
524 // If we have a variadic prototype, the required arguments are the
525 // extra prefix plus the arguments in the prototype.
526 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
527 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000528 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000529
John McCallc56a8b32016-03-11 04:30:31 +0000530 if (proto->hasExtParameterInfos())
531 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
532 args.size());
533
John McCallc818bbb2012-12-07 07:03:17 +0000534 // If we don't have a prototype at all, but we're supposed to
535 // explicitly use the variadic convention for unprototyped calls,
536 // treat all of the arguments as required but preserve the nominal
537 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000538 } else if (CGM.getTargetCodeGenInfo()
539 .isNoProtoCallVariadic(args,
540 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000541 required = RequiredArgs(args.size());
542 }
543
Peter Collingbournef7706832014-12-12 23:41:25 +0000544 // FIXME: Kill copy.
545 SmallVector<CanQualType, 16> argTypes;
546 for (const auto &arg : args)
547 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
548 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
549 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000550 argTypes, fnType->getExtInfo(), paramInfos,
551 required);
John McCallc818bbb2012-12-07 07:03:17 +0000552}
553
John McCalla729c622012-02-17 03:33:10 +0000554/// Figure out the rules for calling a function with the given formal
555/// type using the given arguments. The arguments are necessary
556/// because the function might be unprototyped, in which case it's
557/// target-dependent in crazy ways.
558const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000559CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000560 const FunctionType *fnType,
561 bool chainCall) {
562 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
563 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000564}
John McCalla729c622012-02-17 03:33:10 +0000565
John McCallc56a8b32016-03-11 04:30:31 +0000566/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000567/// extra implicit argument.
568const CGFunctionInfo &
569CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
570 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000571 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
572 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000573}
574
575const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000576CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
577 const FunctionArgList &params) {
578 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
579 auto argTypes = getArgTypesForDeclaration(Context, params);
580
George Burgess IV419996c2016-06-16 23:06:04 +0000581 return arrangeLLVMFunctionInfo(
582 GetReturnType(proto->getReturnType()),
583 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
584 proto->getExtInfo(), paramInfos,
585 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000586}
587
588const CGFunctionInfo &
589CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
590 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000591 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000592 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000593 for (const auto &Arg : args)
594 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000595 return arrangeLLVMFunctionInfo(
596 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000597 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
598 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000599}
600
John McCallc56a8b32016-03-11 04:30:31 +0000601const CGFunctionInfo &
602CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
603 const FunctionArgList &args) {
604 auto argTypes = getArgTypesForDeclaration(Context, args);
605
606 return arrangeLLVMFunctionInfo(
607 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
608 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
609}
610
611const CGFunctionInfo &
612CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
613 ArrayRef<CanQualType> argTypes) {
614 return arrangeLLVMFunctionInfo(
615 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
616 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
617}
618
John McCall8dda7b22012-07-07 06:41:13 +0000619/// Arrange a call to a C++ method, passing the given arguments.
620const CGFunctionInfo &
621CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000622 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000623 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000624 unsigned numRequiredArgs =
625 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
626 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
627 auto paramInfos =
628 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
629
John McCall8dda7b22012-07-07 06:41:13 +0000630 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000631 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000632
John McCallc56a8b32016-03-11 04:30:31 +0000633 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000634 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000635 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
636 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000637}
638
John McCalla729c622012-02-17 03:33:10 +0000639const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000640 return arrangeLLVMFunctionInfo(
641 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000642 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
643}
644
645const CGFunctionInfo &
646CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
647 const CallArgList &args) {
648 assert(signature.arg_size() <= args.size());
649 if (signature.arg_size() == args.size())
650 return signature;
651
652 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
653 auto sigParamInfos = signature.getExtParameterInfos();
654 if (!sigParamInfos.empty()) {
655 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
656 paramInfos.resize(args.size());
657 }
658
659 auto argTypes = getArgTypesForCall(Context, args);
660
661 assert(signature.getRequiredArgs().allowsOptionalArgs());
662 return arrangeLLVMFunctionInfo(signature.getReturnType(),
663 signature.isInstanceMethod(),
664 signature.isChainCall(),
665 argTypes,
666 signature.getExtInfo(),
667 paramInfos,
668 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000669}
670
John McCalla729c622012-02-17 03:33:10 +0000671/// Arrange the argument and result information for an abstract value
672/// of a given function type. This is the method which all of the
673/// above functions ultimately defer to.
674const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000675CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000676 bool instanceMethod,
677 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000678 ArrayRef<CanQualType> argTypes,
679 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000680 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000681 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000682 assert(std::all_of(argTypes.begin(), argTypes.end(),
683 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000684
Daniel Dunbare0be8292009-02-03 00:07:12 +0000685 // Lookup or create unique function info.
686 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000687 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
688 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000689
Craig Topper8a13c412014-05-21 05:09:00 +0000690 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000691 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000692 if (FI)
693 return *FI;
694
John McCallc56a8b32016-03-11 04:30:31 +0000695 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
696
John McCalla729c622012-02-17 03:33:10 +0000697 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000698 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000699 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000700 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000701
David Blaikie82e95a32014-11-19 07:49:47 +0000702 bool inserted = FunctionsBeingProcessed.insert(FI).second;
703 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000704 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000705
Daniel Dunbar313321e2009-02-03 05:31:23 +0000706 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000707 if (info.getCC() != CC_Swift) {
708 getABIInfo().computeInfo(*FI);
709 } else {
710 swiftcall::computeABIInfo(CGM, *FI);
711 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000712
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000713 // Loop over all of the computed argument and return value info. If any of
714 // them are direct or extend without a specified coerce type, specify the
715 // default now.
John McCalla729c622012-02-17 03:33:10 +0000716 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000717 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000718 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000719
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000720 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000721 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000722 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000723
John McCalla729c622012-02-17 03:33:10 +0000724 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
725 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000726
Daniel Dunbare0be8292009-02-03 00:07:12 +0000727 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000728}
729
John McCalla729c622012-02-17 03:33:10 +0000730CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000731 bool instanceMethod,
732 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000733 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000734 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000735 CanQualType resultType,
736 ArrayRef<CanQualType> argTypes,
737 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000738 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
739
740 void *buffer =
741 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
742 argTypes.size() + 1, paramInfos.size()));
743
John McCalla729c622012-02-17 03:33:10 +0000744 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
745 FI->CallingConvention = llvmCC;
746 FI->EffectiveCallingConvention = llvmCC;
747 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000748 FI->InstanceMethod = instanceMethod;
749 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000750 FI->NoReturn = info.getNoReturn();
751 FI->ReturnsRetained = info.getProducesResult();
752 FI->Required = required;
753 FI->HasRegParm = info.getHasRegParm();
754 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000755 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000756 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000757 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000758 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000759 FI->getArgsBuffer()[0].type = resultType;
760 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
761 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000762 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
763 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000764 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000765}
766
767/***/
768
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000769namespace {
770// ABIArgInfo::Expand implementation.
771
772// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
773struct TypeExpansion {
774 enum TypeExpansionKind {
775 // Elements of constant arrays are expanded recursively.
776 TEK_ConstantArray,
777 // Record fields are expanded recursively (but if record is a union, only
778 // the field with the largest size is expanded).
779 TEK_Record,
780 // For complex types, real and imaginary parts are expanded recursively.
781 TEK_Complex,
782 // All other types are not expandable.
783 TEK_None
784 };
785
786 const TypeExpansionKind Kind;
787
788 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000789 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000790};
791
792struct ConstantArrayExpansion : TypeExpansion {
793 QualType EltTy;
794 uint64_t NumElts;
795
796 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
797 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
798 static bool classof(const TypeExpansion *TE) {
799 return TE->Kind == TEK_ConstantArray;
800 }
801};
802
803struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000804 SmallVector<const CXXBaseSpecifier *, 1> Bases;
805
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000806 SmallVector<const FieldDecl *, 1> Fields;
807
Reid Klecknere9f6a712014-10-31 17:10:41 +0000808 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
809 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000810 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
811 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000812 static bool classof(const TypeExpansion *TE) {
813 return TE->Kind == TEK_Record;
814 }
815};
816
817struct ComplexExpansion : TypeExpansion {
818 QualType EltTy;
819
820 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
821 static bool classof(const TypeExpansion *TE) {
822 return TE->Kind == TEK_Complex;
823 }
824};
825
826struct NoExpansion : TypeExpansion {
827 NoExpansion() : TypeExpansion(TEK_None) {}
828 static bool classof(const TypeExpansion *TE) {
829 return TE->Kind == TEK_None;
830 }
831};
832} // namespace
833
834static std::unique_ptr<TypeExpansion>
835getTypeExpansion(QualType Ty, const ASTContext &Context) {
836 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
837 return llvm::make_unique<ConstantArrayExpansion>(
838 AT->getElementType(), AT->getSize().getZExtValue());
839 }
840 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000841 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000842 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000843 const RecordDecl *RD = RT->getDecl();
844 assert(!RD->hasFlexibleArrayMember() &&
845 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000846 if (RD->isUnion()) {
847 // Unions can be here only in degenerative cases - all the fields are same
848 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000849 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000850 CharUnits UnionSize = CharUnits::Zero();
851
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000852 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000853 // Skip zero length bitfields.
854 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
855 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000856 assert(!FD->isBitField() &&
857 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000858 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000859 if (UnionSize < FieldSize) {
860 UnionSize = FieldSize;
861 LargestFD = FD;
862 }
863 }
864 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000865 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000866 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000867 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
868 assert(!CXXRD->isDynamicClass() &&
869 "cannot expand vtable pointers in dynamic classes");
870 for (const CXXBaseSpecifier &BS : CXXRD->bases())
871 Bases.push_back(&BS);
872 }
873
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000874 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000875 // Skip zero length bitfields.
876 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
877 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000878 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000879 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000880 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000881 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000882 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000883 return llvm::make_unique<RecordExpansion>(std::move(Bases),
884 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000885 }
886 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
887 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
888 }
889 return llvm::make_unique<NoExpansion>();
890}
891
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000892static int getExpansionSize(QualType Ty, const ASTContext &Context) {
893 auto Exp = getTypeExpansion(Ty, Context);
894 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
895 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
896 }
897 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
898 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000899 for (auto BS : RExp->Bases)
900 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000901 for (auto FD : RExp->Fields)
902 Res += getExpansionSize(FD->getType(), Context);
903 return Res;
904 }
905 if (isa<ComplexExpansion>(Exp.get()))
906 return 2;
907 assert(isa<NoExpansion>(Exp.get()));
908 return 1;
909}
910
Alexey Samsonov153004f2014-09-29 22:08:00 +0000911void
912CodeGenTypes::getExpandedTypes(QualType Ty,
913 SmallVectorImpl<llvm::Type *>::iterator &TI) {
914 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000915 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
916 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000917 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000918 }
919 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000920 for (auto BS : RExp->Bases)
921 getExpandedTypes(BS->getType(), TI);
922 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000923 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000924 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
925 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000926 *TI++ = EltTy;
927 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000928 } else {
929 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000930 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000931 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000932}
933
John McCall7f416cc2015-09-08 08:05:57 +0000934static void forConstantArrayExpansion(CodeGenFunction &CGF,
935 ConstantArrayExpansion *CAE,
936 Address BaseAddr,
937 llvm::function_ref<void(Address)> Fn) {
938 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
939 CharUnits EltAlign =
940 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
941
942 for (int i = 0, n = CAE->NumElts; i < n; i++) {
943 llvm::Value *EltAddr =
944 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
945 Fn(Address(EltAddr, EltAlign));
946 }
947}
948
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000949void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000950 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000951 assert(LV.isSimple() &&
952 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000953
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000954 auto Exp = getTypeExpansion(Ty, getContext());
955 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000956 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
957 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000958 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
959 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000960 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000961 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000962 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000963 for (const CXXBaseSpecifier *BS : RExp->Bases) {
964 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000965 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000966 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
967 /*NullCheckValue=*/false, SourceLocation());
968 LValue SubLV = MakeAddrLValue(Base, BS->getType());
969
970 // Recurse onto bases.
971 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
972 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000973 for (auto FD : RExp->Fields) {
974 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000975 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000976 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000977 }
John McCall7f416cc2015-09-08 08:05:57 +0000978 } else if (isa<ComplexExpansion>(Exp.get())) {
979 auto realValue = *AI++;
980 auto imagValue = *AI++;
981 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000982 } else {
983 assert(isa<NoExpansion>(Exp.get()));
984 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000985 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000986}
987
988void CodeGenFunction::ExpandTypeToArgs(
989 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
990 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
991 auto Exp = getTypeExpansion(Ty, getContext());
992 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000993 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
994 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000995 RValue EltRV =
996 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
997 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000998 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000999 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001000 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001001 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1002 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001003 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001004 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1005 /*NullCheckValue=*/false, SourceLocation());
1006 RValue BaseRV = RValue::getAggregate(Base);
1007
1008 // Recurse onto bases.
1009 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1010 IRCallArgPos);
1011 }
1012
1013 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001014 for (auto FD : RExp->Fields) {
1015 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1016 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1017 IRCallArgPos);
1018 }
1019 } else if (isa<ComplexExpansion>(Exp.get())) {
1020 ComplexPairTy CV = RV.getComplexVal();
1021 IRCallArgs[IRCallArgPos++] = CV.first;
1022 IRCallArgs[IRCallArgPos++] = CV.second;
1023 } else {
1024 assert(isa<NoExpansion>(Exp.get()));
1025 assert(RV.isScalar() &&
1026 "Unexpected non-scalar rvalue during struct expansion.");
1027
1028 // Insert a bitcast as needed.
1029 llvm::Value *V = RV.getScalarVal();
1030 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1031 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1032 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1033
1034 IRCallArgs[IRCallArgPos++] = V;
1035 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001036}
1037
John McCall7f416cc2015-09-08 08:05:57 +00001038/// Create a temporary allocation for the purposes of coercion.
1039static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1040 CharUnits MinAlign) {
1041 // Don't use an alignment that's worse than what LLVM would prefer.
1042 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1043 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1044
1045 return CGF.CreateTempAlloca(Ty, Align);
1046}
1047
Chris Lattner895c52b2010-06-27 06:04:18 +00001048/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001049/// accessing some number of bytes out of it, try to gep into the struct to get
1050/// at its inner goodness. Dive as deep as possible without entering an element
1051/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001052static Address
1053EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001054 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001055 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001056 // We can't dive into a zero-element struct.
1057 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001058
Chris Lattner2192fe52011-07-18 04:24:23 +00001059 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001060
Chris Lattner1cd66982010-06-27 05:56:15 +00001061 // 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 +00001062 // first element is the same size as the whole struct, we can enter it. The
1063 // comparison must be made on the store size and not the alloca size. Using
1064 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001065 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001066 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001067 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001068 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001069 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Chris Lattner1cd66982010-06-27 05:56:15 +00001071 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001072 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001073
Chris Lattner1cd66982010-06-27 05:56:15 +00001074 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001075 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001076 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001077 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001078
1079 return SrcPtr;
1080}
1081
Chris Lattner055097f2010-06-27 06:26:04 +00001082/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1083/// are either integers or pointers. This does a truncation of the value if it
1084/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001085///
1086/// This behaves as if the value were coerced through memory, so on big-endian
1087/// targets the high bits are preserved in a truncation, while little-endian
1088/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001089static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001090 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001091 CodeGenFunction &CGF) {
1092 if (Val->getType() == Ty)
1093 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001094
Chris Lattner055097f2010-06-27 06:26:04 +00001095 if (isa<llvm::PointerType>(Val->getType())) {
1096 // If this is Pointer->Pointer avoid conversion to and from int.
1097 if (isa<llvm::PointerType>(Ty))
1098 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001099
Chris Lattner055097f2010-06-27 06:26:04 +00001100 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001101 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001102 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001103
Chris Lattner2192fe52011-07-18 04:24:23 +00001104 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001105 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001106 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001107
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001108 if (Val->getType() != DestIntTy) {
1109 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1110 if (DL.isBigEndian()) {
1111 // Preserve the high bits on big-endian targets.
1112 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001113 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1114 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1115
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001116 if (SrcSize > DstSize) {
1117 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1118 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1119 } else {
1120 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1121 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1122 }
1123 } else {
1124 // Little-endian targets preserve the low bits. No shifts required.
1125 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1126 }
1127 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001128
Chris Lattner055097f2010-06-27 06:26:04 +00001129 if (isa<llvm::PointerType>(Ty))
1130 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1131 return Val;
1132}
1133
Chris Lattner1cd66982010-06-27 05:56:15 +00001134
1135
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001136/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001137/// a pointer to an object of type \arg Ty, known to be aligned to
1138/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001139///
1140/// This safely handles the case when the src type is smaller than the
1141/// destination type; in this situation the values of bits which not
1142/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001143static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001144 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001145 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001146
Chris Lattnerd200eda2010-06-28 22:51:39 +00001147 // If SrcTy and Ty are the same, just do a load.
1148 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001149 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001150
Micah Villmowdd31ca12012-10-08 16:25:52 +00001151 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001152
Chris Lattner2192fe52011-07-18 04:24:23 +00001153 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001154 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1155 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001156 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001157
Micah Villmowdd31ca12012-10-08 16:25:52 +00001158 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001159
Chris Lattner055097f2010-06-27 06:26:04 +00001160 // If the source and destination are integer or pointer types, just do an
1161 // extension or truncation to the desired type.
1162 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1163 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001164 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001165 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1166 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001167
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001168 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001169 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001170 // Generally SrcSize is never greater than DstSize, since this means we are
1171 // losing bits. However, this can happen in cases where the structure has
1172 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001173 //
Mike Stump18bb9282009-05-16 07:57:57 +00001174 // FIXME: Assert that we aren't truncating non-padding bits when have access
1175 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001176 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1177 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001178 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001179
John McCall7f416cc2015-09-08 08:05:57 +00001180 // Otherwise do coercion through memory. This is stupid, but simple.
1181 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1182 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1183 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001184 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1185 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001186 false);
1187 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001188}
1189
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001190// Function to store a first-class aggregate into memory. We prefer to
1191// store the elements rather than the aggregate to be more friendly to
1192// fast-isel.
1193// FIXME: Do we need to recurse here?
1194static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001195 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001196 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001197 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001198 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001199 const llvm::StructLayout *Layout =
1200 CGF.CGM.getDataLayout().getStructLayout(STy);
1201
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001202 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001203 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1204 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001205 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001206 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001207 }
1208 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001209 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001210 }
1211}
1212
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001213/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001214/// where the source and destination may have different types. The
1215/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001216///
1217/// This safely handles the case when the src type is larger than the
1218/// destination type; the upper bits of the src will be lost.
1219static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001220 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001221 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001222 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001223 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001224 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001225 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001226 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001227 return;
1228 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001229
Micah Villmowdd31ca12012-10-08 16:25:52 +00001230 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001231
Chris Lattner2192fe52011-07-18 04:24:23 +00001232 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001233 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1234 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001235 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001236
Chris Lattner055097f2010-06-27 06:26:04 +00001237 // If the source and destination are integer or pointer types, just do an
1238 // extension or truncation to the desired type.
1239 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1240 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1241 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001242 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001243 return;
1244 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001245
Micah Villmowdd31ca12012-10-08 16:25:52 +00001246 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001247
Daniel Dunbar313321e2009-02-03 05:31:23 +00001248 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001249 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001250 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1251 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001252 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001253 // Otherwise do coercion through memory. This is stupid, but
1254 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001255
1256 // Generally SrcSize is never greater than DstSize, since this means we are
1257 // losing bits. However, this can happen in cases where the structure has
1258 // additional padding, for example due to a user specified alignment.
1259 //
1260 // FIXME: Assert that we aren't truncating non-padding bits when have access
1261 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001262 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1263 CGF.Builder.CreateStore(Src, Tmp);
1264 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1265 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001266 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1267 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001268 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001269 }
1270}
1271
John McCall7f416cc2015-09-08 08:05:57 +00001272static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1273 const ABIArgInfo &info) {
1274 if (unsigned offset = info.getDirectOffset()) {
1275 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1276 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1277 CharUnits::fromQuantity(offset));
1278 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1279 }
1280 return addr;
1281}
1282
Alexey Samsonov153004f2014-09-29 22:08:00 +00001283namespace {
1284
1285/// Encapsulates information about the way function arguments from
1286/// CGFunctionInfo should be passed to actual LLVM IR function.
1287class ClangToLLVMArgMapping {
1288 static const unsigned InvalidIndex = ~0U;
1289 unsigned InallocaArgNo;
1290 unsigned SRetArgNo;
1291 unsigned TotalIRArgs;
1292
1293 /// Arguments of LLVM IR function corresponding to single Clang argument.
1294 struct IRArgs {
1295 unsigned PaddingArgIndex;
1296 // Argument is expanded to IR arguments at positions
1297 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1298 unsigned FirstArgIndex;
1299 unsigned NumberOfArgs;
1300
1301 IRArgs()
1302 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1303 NumberOfArgs(0) {}
1304 };
1305
1306 SmallVector<IRArgs, 8> ArgInfo;
1307
1308public:
1309 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1310 bool OnlyRequiredArgs = false)
1311 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1312 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1313 construct(Context, FI, OnlyRequiredArgs);
1314 }
1315
1316 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1317 unsigned getInallocaArgNo() const {
1318 assert(hasInallocaArg());
1319 return InallocaArgNo;
1320 }
1321
1322 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1323 unsigned getSRetArgNo() const {
1324 assert(hasSRetArg());
1325 return SRetArgNo;
1326 }
1327
1328 unsigned totalIRArgs() const { return TotalIRArgs; }
1329
1330 bool hasPaddingArg(unsigned ArgNo) const {
1331 assert(ArgNo < ArgInfo.size());
1332 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1333 }
1334 unsigned getPaddingArgNo(unsigned ArgNo) const {
1335 assert(hasPaddingArg(ArgNo));
1336 return ArgInfo[ArgNo].PaddingArgIndex;
1337 }
1338
1339 /// Returns index of first IR argument corresponding to ArgNo, and their
1340 /// quantity.
1341 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1342 assert(ArgNo < ArgInfo.size());
1343 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1344 ArgInfo[ArgNo].NumberOfArgs);
1345 }
1346
1347private:
1348 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1349 bool OnlyRequiredArgs);
1350};
1351
1352void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1353 const CGFunctionInfo &FI,
1354 bool OnlyRequiredArgs) {
1355 unsigned IRArgNo = 0;
1356 bool SwapThisWithSRet = false;
1357 const ABIArgInfo &RetAI = FI.getReturnInfo();
1358
1359 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1360 SwapThisWithSRet = RetAI.isSRetAfterThis();
1361 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1362 }
1363
1364 unsigned ArgNo = 0;
1365 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1366 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1367 ++I, ++ArgNo) {
1368 assert(I != FI.arg_end());
1369 QualType ArgType = I->type;
1370 const ABIArgInfo &AI = I->info;
1371 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1372 auto &IRArgs = ArgInfo[ArgNo];
1373
1374 if (AI.getPaddingType())
1375 IRArgs.PaddingArgIndex = IRArgNo++;
1376
1377 switch (AI.getKind()) {
1378 case ABIArgInfo::Extend:
1379 case ABIArgInfo::Direct: {
1380 // FIXME: handle sseregparm someday...
1381 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1382 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1383 IRArgs.NumberOfArgs = STy->getNumElements();
1384 } else {
1385 IRArgs.NumberOfArgs = 1;
1386 }
1387 break;
1388 }
1389 case ABIArgInfo::Indirect:
1390 IRArgs.NumberOfArgs = 1;
1391 break;
1392 case ABIArgInfo::Ignore:
1393 case ABIArgInfo::InAlloca:
1394 // ignore and inalloca doesn't have matching LLVM parameters.
1395 IRArgs.NumberOfArgs = 0;
1396 break;
John McCallf26e73d2016-03-11 04:30:43 +00001397 case ABIArgInfo::CoerceAndExpand:
1398 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1399 break;
1400 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001401 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1402 break;
1403 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001404
1405 if (IRArgs.NumberOfArgs > 0) {
1406 IRArgs.FirstArgIndex = IRArgNo;
1407 IRArgNo += IRArgs.NumberOfArgs;
1408 }
1409
1410 // Skip over the sret parameter when it comes second. We already handled it
1411 // above.
1412 if (IRArgNo == 1 && SwapThisWithSRet)
1413 IRArgNo++;
1414 }
1415 assert(ArgNo == ArgInfo.size());
1416
1417 if (FI.usesInAlloca())
1418 InallocaArgNo = IRArgNo++;
1419
1420 TotalIRArgs = IRArgNo;
1421}
1422} // namespace
1423
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001424/***/
1425
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001426bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001427 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001428}
1429
Tim Northovere77cc392014-03-29 13:28:05 +00001430bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1431 return ReturnTypeUsesSRet(FI) &&
1432 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1433}
1434
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001435bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1436 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1437 switch (BT->getKind()) {
1438 default:
1439 return false;
1440 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001441 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001442 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001443 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001444 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001445 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001446 }
1447 }
1448
1449 return false;
1450}
1451
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001452bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1453 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1454 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1455 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001456 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001457 }
1458 }
1459
1460 return false;
1461}
1462
Chris Lattnera5f58b02011-07-09 17:41:47 +00001463llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001464 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1465 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001466}
1467
Chris Lattnera5f58b02011-07-09 17:41:47 +00001468llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001469CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001470
David Blaikie82e95a32014-11-19 07:49:47 +00001471 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1472 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001473 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001474
Alexey Samsonov153004f2014-09-29 22:08:00 +00001475 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001476 const ABIArgInfo &retAI = FI.getReturnInfo();
1477 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001478 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001479 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001480
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001481 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001482 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001483 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001484 break;
1485
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001486 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001487 if (retAI.getInAllocaSRet()) {
1488 // sret things on win32 aren't void, they return the sret pointer.
1489 QualType ret = FI.getReturnType();
1490 llvm::Type *ty = ConvertType(ret);
1491 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1492 resultType = llvm::PointerType::get(ty, addressSpace);
1493 } else {
1494 resultType = llvm::Type::getVoidTy(getLLVMContext());
1495 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001496 break;
1497
John McCall7f416cc2015-09-08 08:05:57 +00001498 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001499 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001500 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001501 break;
John McCallf26e73d2016-03-11 04:30:43 +00001502
1503 case ABIArgInfo::CoerceAndExpand:
1504 resultType = retAI.getUnpaddedCoerceAndExpandType();
1505 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001506 }
Mike Stump11289f42009-09-09 15:08:12 +00001507
Alexey Samsonov153004f2014-09-29 22:08:00 +00001508 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1509 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1510
1511 // Add type for sret argument.
1512 if (IRFunctionArgs.hasSRetArg()) {
1513 QualType Ret = FI.getReturnType();
1514 llvm::Type *Ty = ConvertType(Ret);
1515 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1516 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1517 llvm::PointerType::get(Ty, AddressSpace);
1518 }
1519
1520 // Add type for inalloca argument.
1521 if (IRFunctionArgs.hasInallocaArg()) {
1522 auto ArgStruct = FI.getArgStruct();
1523 assert(ArgStruct);
1524 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1525 }
1526
John McCallc818bbb2012-12-07 07:03:17 +00001527 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001528 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001529 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1530 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001531 for (; it != ie; ++it, ++ArgNo) {
1532 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Rafael Espindolafad28de2012-10-24 01:59:00 +00001534 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001535 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1536 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1537 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001538
Alexey Samsonov153004f2014-09-29 22:08:00 +00001539 unsigned FirstIRArg, NumIRArgs;
1540 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1541
1542 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001543 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001544 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001545 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001546 break;
1547
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001548 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001549 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001550 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001551 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001552 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001553 break;
1554 }
1555
1556 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001557 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001558 // Fast-isel and the optimizer generally like scalar values better than
1559 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001560 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001561 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001562 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1563 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001564 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001565 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001566 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001567 assert(NumIRArgs == 1);
1568 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001569 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001570 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
John McCallf26e73d2016-03-11 04:30:43 +00001573 case ABIArgInfo::CoerceAndExpand: {
1574 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1575 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1576 *ArgTypesIter++ = EltTy;
1577 }
1578 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1579 break;
1580 }
1581
Daniel Dunbard3674e62008-09-11 01:48:57 +00001582 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001583 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1584 getExpandedTypes(it->type, ArgTypesIter);
1585 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001586 break;
1587 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001588 }
1589
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001590 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1591 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001592
1593 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001594}
1595
Chris Lattner2192fe52011-07-18 04:24:23 +00001596llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001597 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001598 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001599
Chris Lattner8806e322011-07-10 00:18:59 +00001600 if (!isFuncTypeConvertible(FPT))
1601 return llvm::StructType::get(getLLVMContext());
1602
1603 const CGFunctionInfo *Info;
1604 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001605 Info =
1606 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001607 else
John McCalla729c622012-02-17 03:33:10 +00001608 Info = &arrangeCXXMethodDeclaration(MD);
1609 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001610}
1611
Samuel Antao798f11c2015-11-23 22:04:44 +00001612static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1613 llvm::AttrBuilder &FuncAttrs,
1614 const FunctionProtoType *FPT) {
1615 if (!FPT)
1616 return;
1617
1618 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1619 FPT->isNothrow(Ctx))
1620 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1621}
1622
Justin Lebarb080b632017-01-25 21:29:48 +00001623void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1624 bool AttrOnCallSite,
1625 llvm::AttrBuilder &FuncAttrs) {
1626 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1627 if (!HasOptnone) {
1628 if (CodeGenOpts.OptimizeSize)
1629 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1630 if (CodeGenOpts.OptimizeSize == 2)
1631 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1632 }
1633
1634 if (CodeGenOpts.DisableRedZone)
1635 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1636 if (CodeGenOpts.NoImplicitFloat)
1637 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1638
1639 if (AttrOnCallSite) {
1640 // Attributes that should go on the call site only.
1641 if (!CodeGenOpts.SimplifyLibCalls ||
1642 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1643 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1644 if (!CodeGenOpts.TrapFuncName.empty())
1645 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1646 } else {
1647 // Attributes that should go on the function, but not the call site.
1648 if (!CodeGenOpts.DisableFPElim) {
1649 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1650 } else if (CodeGenOpts.OmitLeafFramePointer) {
1651 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1652 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1653 } else {
1654 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1655 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1656 }
1657
1658 FuncAttrs.addAttribute("less-precise-fpmad",
1659 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1660
1661 if (!CodeGenOpts.FPDenormalMode.empty())
1662 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1663
1664 FuncAttrs.addAttribute("no-trapping-math",
1665 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1666
1667 // TODO: Are these all needed?
1668 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1669 FuncAttrs.addAttribute("no-infs-fp-math",
1670 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1671 FuncAttrs.addAttribute("no-nans-fp-math",
1672 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1673 FuncAttrs.addAttribute("unsafe-fp-math",
1674 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1675 FuncAttrs.addAttribute("use-soft-float",
1676 llvm::toStringRef(CodeGenOpts.SoftFloat));
1677 FuncAttrs.addAttribute("stack-protector-buffer-size",
1678 llvm::utostr(CodeGenOpts.SSPBufferSize));
1679 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1680 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1681 FuncAttrs.addAttribute(
1682 "correctly-rounded-divide-sqrt-fp-math",
1683 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1684
1685 // TODO: Reciprocal estimate codegen options should apply to instructions?
1686 std::vector<std::string> &Recips = getTarget().getTargetOpts().Reciprocals;
1687 if (!Recips.empty())
1688 FuncAttrs.addAttribute("reciprocal-estimates",
1689 llvm::join(Recips.begin(), Recips.end(), ","));
1690
1691 if (CodeGenOpts.StackRealignment)
1692 FuncAttrs.addAttribute("stackrealign");
1693 if (CodeGenOpts.Backchain)
1694 FuncAttrs.addAttribute("backchain");
1695 }
1696
1697 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1698 // Conservatively, mark all functions and calls in CUDA as convergent
1699 // (meaning, they may call an intrinsically convergent op, such as
1700 // __syncthreads(), and so can't have certain optimizations applied around
1701 // them). LLVM will remove this attribute where it safely can.
1702 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1703
1704 // Exceptions aren't supported in CUDA device code.
1705 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1706
1707 // Respect -fcuda-flush-denormals-to-zero.
1708 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1709 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1710 }
1711}
1712
1713void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1714 llvm::AttrBuilder FuncAttrs;
1715 ConstructDefaultFnAttrList(F.getName(),
1716 F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1717 /* AttrOnCallsite = */ false, FuncAttrs);
1718 llvm::AttributeSet AS = llvm::AttributeSet::get(
1719 getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1720 F.addAttributes(llvm::AttributeSet::FunctionIndex, AS);
1721}
1722
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001723void CodeGenModule::ConstructAttributeList(
1724 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1725 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001726 llvm::AttrBuilder FuncAttrs;
1727 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001728
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001729 CallingConv = FI.getEffectiveCallingConvention();
John McCallab26cfa2010-02-05 21:31:56 +00001730 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001731 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001732
Samuel Antao798f11c2015-11-23 22:04:44 +00001733 // If we have information about the function prototype, we can learn
1734 // attributes form there.
1735 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1736 CalleeInfo.getCalleeFunctionProtoType());
1737
1738 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1739
Justin Lebarb080b632017-01-25 21:29:48 +00001740 bool HasOptnone = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001741 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001742 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001743 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001744 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001745 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001746 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001747 if (TargetDecl->hasAttr<NoReturnAttr>())
1748 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001749 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1750 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Yaxun Liu7d07ae72016-11-01 18:45:32 +00001751 if (TargetDecl->hasAttr<ConvergentAttr>())
1752 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Richard Smithdebc59d2013-01-30 05:45:05 +00001753
1754 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001755 AddAttributesFromFunctionProtoType(
1756 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001757 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1758 // These attributes are not inherited by overloads.
1759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1760 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001761 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001762 }
1763
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001764 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001765 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001766 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1767 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001768 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001769 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1770 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001771 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1772 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1773 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001774 }
David Majnemer631a90b2015-02-04 07:23:21 +00001775 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001776 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001777 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1778 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001779
1780 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
George Burgess IVe3763372016-12-22 02:50:20 +00001781 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1782 Optional<unsigned> NumElemsParam;
1783 // alloc_size args are base-1, 0 means not present.
1784 if (unsigned N = AllocSize->getNumElemsParam())
1785 NumElemsParam = N - 1;
1786 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam() - 1,
1787 NumElemsParam);
1788 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001789 }
1790
Justin Lebarb080b632017-01-25 21:29:48 +00001791 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
Paul Robinson08556952014-12-11 20:14:04 +00001792
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001793 if (CodeGenOpts.EnableSegmentedStacks &&
1794 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001795 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001796
Justin Lebarb080b632017-01-25 21:29:48 +00001797 if (!AttrOnCallSite) {
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001798 bool DisableTailCalls =
Justin Lebarb080b632017-01-25 21:29:48 +00001799 CodeGenOpts.DisableTailCalls ||
1800 (TargetDecl && (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1801 TargetDecl->hasAttr<AnyX86InterruptAttr>()));
1802 FuncAttrs.addAttribute("disable-tail-calls",
1803 llvm::toStringRef(DisableTailCalls));
Eric Christopher70c16652015-03-25 23:14:47 +00001804
Eric Christopher11acf732015-06-12 01:35:52 +00001805 // Add target-cpu and target-features attributes to functions. If
1806 // we have a decl for the function and it has a target attribute then
1807 // parse that and add it to the feature set.
1808 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001809 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001810 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001811 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001812 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001813
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001814 // Produce the canonical string for this set of features.
1815 std::vector<std::string> Features;
1816 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1817 ie = FeatureMap.end();
1818 it != ie; ++it)
1819 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001820
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001821 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001822 // While we populated the feature map above, we still need to
1823 // get and parse the target attribute so we can get the cpu for
1824 // the function.
1825 const auto *TD = FD->getAttr<TargetAttr>();
1826 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1827 if (ParsedAttr.second != "")
1828 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001829 if (TargetCPU != "")
1830 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1831 if (!Features.empty()) {
1832 std::sort(Features.begin(), Features.end());
1833 FuncAttrs.addAttribute(
1834 "target-features",
1835 llvm::join(Features.begin(), Features.end(), ","));
1836 }
1837 } else {
1838 // Otherwise just add the existing target cpu and target features to the
1839 // function.
1840 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1841 if (TargetCPU != "")
1842 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1843 if (!Features.empty()) {
1844 std::sort(Features.begin(), Features.end());
1845 FuncAttrs.addAttribute(
1846 "target-features",
1847 llvm::join(Features.begin(), Features.end(), ","));
1848 }
Eric Christopher70c16652015-03-25 23:14:47 +00001849 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001850 }
1851
Alexey Samsonov153004f2014-09-29 22:08:00 +00001852 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001853
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001854 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001855 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001856 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001857 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001858 if (RetTy->hasSignedIntegerRepresentation())
1859 RetAttrs.addAttribute(llvm::Attribute::SExt);
1860 else if (RetTy->hasUnsignedIntegerRepresentation())
1861 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001862 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001863 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001864 if (RetAI.getInReg())
1865 RetAttrs.addAttribute(llvm::Attribute::InReg);
1866 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001867 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001868 break;
1869
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001870 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001871 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001872 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001873 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1874 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001875 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001876 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001877
John McCallf26e73d2016-03-11 04:30:43 +00001878 case ABIArgInfo::CoerceAndExpand:
1879 break;
1880
Daniel Dunbard3674e62008-09-11 01:48:57 +00001881 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001882 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001883 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001884
Hal Finkela2347ba2014-07-18 15:52:10 +00001885 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1886 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001887 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001888 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1889 .getQuantity());
1890 else if (getContext().getTargetAddressSpace(PTy) == 0)
1891 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1892 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001893
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001894 // Attach return attributes.
1895 if (RetAttrs.hasAttributes()) {
1896 PAL.push_back(llvm::AttributeSet::get(
1897 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1898 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001899
John McCall12f23522016-04-04 18:33:08 +00001900 bool hasUsedSRet = false;
1901
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001902 // Attach attributes to sret.
1903 if (IRFunctionArgs.hasSRetArg()) {
1904 llvm::AttrBuilder SRETAttrs;
1905 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001906 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001907 if (RetAI.getInReg())
1908 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1909 PAL.push_back(llvm::AttributeSet::get(
1910 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1911 }
1912
1913 // Attach attributes to inalloca argument.
1914 if (IRFunctionArgs.hasInallocaArg()) {
1915 llvm::AttrBuilder Attrs;
1916 Attrs.addAttribute(llvm::Attribute::InAlloca);
1917 PAL.push_back(llvm::AttributeSet::get(
1918 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1919 }
1920
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001921 unsigned ArgNo = 0;
1922 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1923 E = FI.arg_end();
1924 I != E; ++I, ++ArgNo) {
1925 QualType ParamType = I->type;
1926 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001927 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001928
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001929 // Add attribute for padding argument, if necessary.
1930 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001931 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001932 PAL.push_back(llvm::AttributeSet::get(
1933 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1934 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001935 }
1936
John McCall39ec71f2010-03-27 00:47:27 +00001937 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1938 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001939 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001940 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001941 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001942 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001943 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001944 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1945 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1946 Attrs.addAttribute(llvm::Attribute::SExt);
1947 else
1948 Attrs.addAttribute(llvm::Attribute::ZExt);
1949 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001950 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001951 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001952 if (ArgNo == 0 && FI.isChainCall())
1953 Attrs.addAttribute(llvm::Attribute::Nest);
1954 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001955 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001956 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001957
James Y Knight71608572015-08-21 18:19:06 +00001958 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001959 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001960 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001961
Anders Carlsson20759ad2009-09-16 15:53:40 +00001962 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001963 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001964
John McCall7f416cc2015-09-08 08:05:57 +00001965 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001966
1967 // In a byval argument, it is important that the required
1968 // alignment of the type is honored, as LLVM might be creating a
1969 // *new* stack object, and needs to know what alignment to give
1970 // it. (Sometimes it can deduce a sensible alignment on its own,
1971 // but not if clang decides it must emit a packed struct, or the
1972 // user specifies increased alignment requirements.)
1973 //
1974 // This is different from indirect *not* byval, where the object
1975 // exists already, and the align attribute is purely
1976 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001977 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001978
John McCall7f416cc2015-09-08 08:05:57 +00001979 // For now, only add this when we have a byval argument.
1980 // TODO: be less lazy about updating test cases.
1981 if (AI.getIndirectByVal())
1982 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001983
Daniel Dunbarc2304432009-03-18 19:51:01 +00001984 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001985 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1986 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001987 break;
James Y Knight71608572015-08-21 18:19:06 +00001988 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001989 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001990 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001991 case ABIArgInfo::CoerceAndExpand:
1992 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001993
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001994 case ABIArgInfo::InAlloca:
1995 // inalloca disables readnone and readonly.
1996 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1997 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001998 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Hal Finkela2347ba2014-07-18 15:52:10 +00002001 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2002 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00002003 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00002004 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2005 .getQuantity());
2006 else if (getContext().getTargetAddressSpace(PTy) == 0)
2007 Attrs.addAttribute(llvm::Attribute::NonNull);
2008 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00002009
John McCall12f23522016-04-04 18:33:08 +00002010 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2011 case ParameterABI::Ordinary:
2012 break;
2013
2014 case ParameterABI::SwiftIndirectResult: {
2015 // Add 'sret' if we haven't already used it for something, but
2016 // only if the result is void.
2017 if (!hasUsedSRet && RetTy->isVoidType()) {
2018 Attrs.addAttribute(llvm::Attribute::StructRet);
2019 hasUsedSRet = true;
2020 }
2021
2022 // Add 'noalias' in either case.
2023 Attrs.addAttribute(llvm::Attribute::NoAlias);
2024
2025 // Add 'dereferenceable' and 'alignment'.
2026 auto PTy = ParamType->getPointeeType();
2027 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2028 auto info = getContext().getTypeInfoInChars(PTy);
2029 Attrs.addDereferenceableAttr(info.first.getQuantity());
2030 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2031 info.second.getQuantity()));
2032 }
2033 break;
2034 }
2035
2036 case ParameterABI::SwiftErrorResult:
2037 Attrs.addAttribute(llvm::Attribute::SwiftError);
2038 break;
2039
2040 case ParameterABI::SwiftContext:
2041 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2042 break;
2043 }
2044
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002045 if (Attrs.hasAttributes()) {
2046 unsigned FirstIRArg, NumIRArgs;
2047 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2048 for (unsigned i = 0; i < NumIRArgs; i++)
2049 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
2050 FirstIRArg + i + 1, Attrs));
2051 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002052 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002053 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002054
Bill Wendlinga7912f82012-10-10 07:36:56 +00002055 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002056 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002057 AttributeSet::get(getLLVMContext(),
2058 llvm::AttributeSet::FunctionIndex,
2059 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002060}
2061
John McCalla738c252011-03-09 04:27:21 +00002062/// An argument came in as a promoted argument; demote it back to its
2063/// declared type.
2064static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2065 const VarDecl *var,
2066 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002067 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002068
2069 // This can happen with promotions that actually don't change the
2070 // underlying type, like the enum promotions.
2071 if (value->getType() == varType) return value;
2072
2073 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2074 && "unexpected promotion type");
2075
2076 if (isa<llvm::IntegerType>(varType))
2077 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2078
2079 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2080}
2081
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002082/// Returns the attribute (either parameter attribute, or function
2083/// attribute), which declares argument ArgNo to be non-null.
2084static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2085 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002086 // FIXME: __attribute__((nonnull)) can also be applied to:
2087 // - references to pointers, where the pointee is known to be
2088 // nonnull (apparently a Clang extension)
2089 // - transparent unions containing pointers
2090 // In the former case, LLVM IR cannot represent the constraint. In
2091 // the latter case, we have no guarantee that the transparent union
2092 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002093 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2094 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002095 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002096 if (PVD) {
2097 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2098 return ParmNNAttr;
2099 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002100 // Check function attributes.
2101 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002102 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002103 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002104 if (NNAttr->isNonNull(ArgNo))
2105 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002106 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002107 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002108}
2109
John McCall12f23522016-04-04 18:33:08 +00002110namespace {
2111 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2112 Address Temp;
2113 Address Arg;
2114 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2115 void Emit(CodeGenFunction &CGF, Flags flags) override {
2116 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2117 CGF.Builder.CreateStore(errorValue, Arg);
2118 }
2119 };
2120}
2121
Daniel Dunbard931a872009-02-02 22:03:45 +00002122void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2123 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002124 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002125 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2126 // Naked functions don't have prologues.
2127 return;
2128
John McCallcaa19452009-07-28 01:00:58 +00002129 // If this is an implicit-return-zero function, go ahead and
2130 // initialize the return value. TODO: it might be nice to have
2131 // a more general mechanism for this that didn't require synthesized
2132 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002133 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002134 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002135 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002136 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002137 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002138 Builder.CreateStore(Zero, ReturnValue);
2139 }
2140 }
2141
Mike Stump18bb9282009-05-16 07:57:57 +00002142 // FIXME: We no longer need the types from FunctionArgList; lift up and
2143 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002144
Alexey Samsonov153004f2014-09-29 22:08:00 +00002145 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002146 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002147 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002148 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2149 for (auto &Arg : Fn->args()) {
2150 FnArgs.push_back(&Arg);
2151 }
2152 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002153
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002154 // If we're using inalloca, all the memory arguments are GEPs off of the last
2155 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002156 Address ArgStruct = Address::invalid();
2157 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002158 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002159 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2160 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2161 FI.getArgStructAlignment());
2162
2163 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002164 }
2165
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002166 // Name the struct return parameter.
2167 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002168 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002169 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002170 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002171 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002174 // Track if we received the parameter as a pointer (indirect, byval, or
2175 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2176 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002177 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002178 ArgVals.reserve(Args.size());
2179
Reid Kleckner739756c2013-12-04 19:23:12 +00002180 // Create a pointer value for every parameter declaration. This usually
2181 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2182 // any cleanups or do anything that might unwind. We do that separately, so
2183 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002184 assert(FI.arg_size() == Args.size() &&
2185 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002186 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002187 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002188 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002189 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002190 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002191 QualType Ty = info_it->type;
2192 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002193
John McCalla738c252011-03-09 04:27:21 +00002194 bool isPromoted =
2195 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2196
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002197 unsigned FirstIRArg, NumIRArgs;
2198 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002199
Daniel Dunbard3674e62008-09-11 01:48:57 +00002200 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002201 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002202 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002203 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2204 CharUnits FieldOffset =
2205 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2206 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2207 Arg->getName());
2208 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002209 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002210 }
2211
Daniel Dunbar747865a2009-02-05 09:16:39 +00002212 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002213 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002214 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002215
John McCall47fb9502013-03-07 21:37:08 +00002216 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002217 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002218 // need to do is realign the value, if requested.
2219 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002220 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002221 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002222
2223 // Copy from the incoming argument pointer to the temporary with the
2224 // appropriate alignment.
2225 //
2226 // FIXME: We should have a common utility for generating an aggregate
2227 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002228 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002229 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2230 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2231 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2232 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002233 V = AlignedTemp;
2234 }
John McCall7f416cc2015-09-08 08:05:57 +00002235 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002236 } else {
2237 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002238 llvm::Value *V =
2239 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002240
2241 if (isPromoted)
2242 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002243 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002244 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002245 break;
2246 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002247
2248 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002249 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002250
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002251 // If we have the trivial case, handle it with no muss and fuss.
2252 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002253 ArgI.getCoerceToType() == ConvertType(Ty) &&
2254 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002255 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002256 llvm::Value *V = FnArgs[FirstIRArg];
2257 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002258
Hal Finkel48d53e22014-07-19 01:41:07 +00002259 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002260 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2261 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002262 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2263 AI->getArgNo() + 1,
2264 llvm::Attribute::NonNull));
2265
Hal Finkel48d53e22014-07-19 01:41:07 +00002266 QualType OTy = PVD->getOriginalType();
2267 if (const auto *ArrTy =
2268 getContext().getAsConstantArrayType(OTy)) {
2269 // A C99 array parameter declaration with the static keyword also
2270 // indicates dereferenceability, and if the size is constant we can
2271 // use the dereferenceable attribute (which requires the size in
2272 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002273 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002274 QualType ETy = ArrTy->getElementType();
2275 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2276 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2277 ArrSize) {
2278 llvm::AttrBuilder Attrs;
2279 Attrs.addDereferenceableAttr(
2280 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2281 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2282 AI->getArgNo() + 1, Attrs));
2283 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2284 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2285 AI->getArgNo() + 1,
2286 llvm::Attribute::NonNull));
2287 }
2288 }
2289 } else if (const auto *ArrTy =
2290 getContext().getAsVariableArrayType(OTy)) {
2291 // For C99 VLAs with the static keyword, we don't know the size so
2292 // we can't use the dereferenceable attribute, but in addrspace(0)
2293 // we know that it must be nonnull.
2294 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2295 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2296 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2297 AI->getArgNo() + 1,
2298 llvm::Attribute::NonNull));
2299 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002300
2301 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2302 if (!AVAttr)
2303 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2304 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2305 if (AVAttr) {
2306 llvm::Value *AlignmentValue =
2307 EmitScalarExpr(AVAttr->getAlignment());
2308 llvm::ConstantInt *AlignmentCI =
2309 cast<llvm::ConstantInt>(AlignmentValue);
2310 unsigned Alignment =
2311 std::min((unsigned) AlignmentCI->getZExtValue(),
2312 +llvm::Value::MaximumAlignment);
2313
2314 llvm::AttrBuilder Attrs;
2315 Attrs.addAlignmentAttr(Alignment);
2316 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2317 AI->getArgNo() + 1, Attrs));
2318 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002319 }
2320
Bill Wendling507c3512012-10-16 05:23:44 +00002321 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002322 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2323 AI->getArgNo() + 1,
2324 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002325
John McCall12f23522016-04-04 18:33:08 +00002326 // LLVM expects swifterror parameters to be used in very restricted
2327 // ways. Copy the value into a less-restricted temporary.
2328 if (FI.getExtParameterInfo(ArgNo).getABI()
2329 == ParameterABI::SwiftErrorResult) {
2330 QualType pointeeTy = Ty->getPointeeType();
2331 assert(pointeeTy->isPointerType());
2332 Address temp =
2333 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2334 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2335 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2336 Builder.CreateStore(incomingErrorValue, temp);
2337 V = temp.getPointer();
2338
2339 // Push a cleanup to copy the value back at the end of the function.
2340 // The convention does not guarantee that the value will be written
2341 // back if the function exits with an unwind exception.
2342 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2343 }
2344
Chris Lattner7369c142011-07-20 06:29:00 +00002345 // Ensure the argument is the correct type.
2346 if (V->getType() != ArgI.getCoerceToType())
2347 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2348
John McCalla738c252011-03-09 04:27:21 +00002349 if (isPromoted)
2350 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002351
2352 // Because of merging of function types from multiple decls it is
2353 // possible for the type of an argument to not match the corresponding
2354 // type in the function type. Since we are codegening the callee
2355 // in here, add a cast to the argument type.
2356 llvm::Type *LTy = ConvertType(Arg->getType());
2357 if (V->getType() != LTy)
2358 V = Builder.CreateBitCast(V, LTy);
2359
John McCall7f416cc2015-09-08 08:05:57 +00002360 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002361 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002362 }
Mike Stump11289f42009-09-09 15:08:12 +00002363
John McCall7f416cc2015-09-08 08:05:57 +00002364 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2365 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002366
John McCall7f416cc2015-09-08 08:05:57 +00002367 // Pointer to store into.
2368 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002369
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002370 // Fast-isel and the optimizer generally like scalar values better than
2371 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002372 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002373 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2374 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002375 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002376 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002377 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002378 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002379
John McCall7f416cc2015-09-08 08:05:57 +00002380 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002381 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002382 AddrToStoreInto =
2383 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002384 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002385 AddrToStoreInto =
2386 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002387 }
John McCall7f416cc2015-09-08 08:05:57 +00002388
2389 assert(STy->getNumElements() == NumIRArgs);
2390 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2391 auto AI = FnArgs[FirstIRArg + i];
2392 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2393 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2394 Address EltPtr =
2395 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2396 Builder.CreateStore(AI, EltPtr);
2397 }
2398
2399 if (SrcSize > DstSize) {
2400 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2401 }
2402
Chris Lattner15ec3612010-06-29 00:06:42 +00002403 } else {
2404 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002405 assert(NumIRArgs == 1);
2406 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002407 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002408 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002409 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002410
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002411 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002412 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002413 llvm::Value *V =
2414 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002415 if (isPromoted)
2416 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002417 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002418 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002419 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002420 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002421 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002422 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002423
John McCallf26e73d2016-03-11 04:30:43 +00002424 case ABIArgInfo::CoerceAndExpand: {
2425 // Reconstruct into a temporary.
2426 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2427 ArgVals.push_back(ParamValue::forIndirect(alloca));
2428
2429 auto coercionType = ArgI.getCoerceAndExpandType();
2430 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2431 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2432
2433 unsigned argIndex = FirstIRArg;
2434 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2435 llvm::Type *eltType = coercionType->getElementType(i);
2436 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2437 continue;
2438
2439 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2440 auto elt = FnArgs[argIndex++];
2441 Builder.CreateStore(elt, eltAddr);
2442 }
2443 assert(argIndex == FirstIRArg + NumIRArgs);
2444 break;
2445 }
2446
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002447 case ABIArgInfo::Expand: {
2448 // If this structure was expanded into multiple arguments then
2449 // we need to create a temporary and reconstruct it from the
2450 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002451 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2452 LValue LV = MakeAddrLValue(Alloca, Ty);
2453 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002454
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002455 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2456 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2457 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2458 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2459 auto AI = FnArgs[FirstIRArg + i];
2460 AI->setName(Arg->getName() + "." + Twine(i));
2461 }
2462 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002463 }
2464
2465 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002466 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002467 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002468 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002469 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002470 } else {
2471 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002472 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002473 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002474 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002475 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002476 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002477
Reid Kleckner739756c2013-12-04 19:23:12 +00002478 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2479 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002480 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002481 } else {
2482 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002483 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002484 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002485}
2486
John McCallffa2c1a2012-01-29 07:46:59 +00002487static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2488 while (insn->use_empty()) {
2489 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2490 if (!bitcast) return;
2491
2492 // This is "safe" because we would have used a ConstantExpr otherwise.
2493 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2494 bitcast->eraseFromParent();
2495 }
2496}
2497
John McCall31168b02011-06-15 23:02:42 +00002498/// Try to emit a fused autorelease of a return result.
2499static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2500 llvm::Value *result) {
2501 // We must be immediately followed the cast.
2502 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002503 if (BB->empty()) return nullptr;
2504 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002505
Chris Lattner2192fe52011-07-18 04:24:23 +00002506 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002507
2508 // result is in a BasicBlock and is therefore an Instruction.
2509 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2510
Justin Bogner882f8612016-08-18 21:46:54 +00002511 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002512
2513 // Look for:
2514 // %generator = bitcast %type1* %generator2 to %type2*
2515 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2516 // We would have emitted this as a constant if the operand weren't
2517 // an Instruction.
2518 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2519
2520 // Require the generator to be immediately followed by the cast.
2521 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002522 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002523
Justin Bogner882f8612016-08-18 21:46:54 +00002524 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002525 }
2526
2527 // Look for:
2528 // %generator = call i8* @objc_retain(i8* %originalResult)
2529 // or
2530 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2531 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002532 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002533
2534 bool doRetainAutorelease;
2535
John McCallb04ecb72015-10-21 18:06:43 +00002536 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002537 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002538 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002539 .objc_retainAutoreleasedReturnValue) {
2540 doRetainAutorelease = false;
2541
John McCallcfa4e9b2012-09-07 23:30:50 +00002542 // If we emitted an assembly marker for this call (and the
2543 // ARCEntrypoints field should have been set if so), go looking
2544 // for that call. If we can't find it, we can't do this
2545 // optimization. But it should always be the immediately previous
2546 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002547 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002548 llvm::Instruction *prev = call->getPrevNode();
2549 assert(prev);
2550 if (isa<llvm::BitCastInst>(prev)) {
2551 prev = prev->getPrevNode();
2552 assert(prev);
2553 }
2554 assert(isa<llvm::CallInst>(prev));
2555 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002556 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002557 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002558 }
John McCall31168b02011-06-15 23:02:42 +00002559 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002560 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002561 }
2562
2563 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002564 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002565
2566 // Keep killing bitcasts, for sanity. Note that we no longer care
2567 // about precise ordering as long as there's exactly one use.
2568 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2569 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002570 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002571 result = bitcast->getOperand(0);
2572 }
2573
2574 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002575 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002576 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002577
2578 // Do the fused retain/autorelease if we were asked to.
2579 if (doRetainAutorelease)
2580 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2581
2582 // Cast back to the result type.
2583 return CGF.Builder.CreateBitCast(result, resultType);
2584}
2585
John McCallffa2c1a2012-01-29 07:46:59 +00002586/// If this is a +1 of the value of an immutable 'self', remove it.
2587static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2588 llvm::Value *result) {
2589 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002590 const ObjCMethodDecl *method =
2591 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002592 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002593 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002594 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002595
2596 // Look for a retain call.
2597 llvm::CallInst *retainCall =
2598 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2599 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002600 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002601 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002602
2603 // Look for an ordinary load of 'self'.
2604 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2605 llvm::LoadInst *load =
2606 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2607 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002608 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002609 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002610
2611 // Okay! Burn it all down. This relies for correctness on the
2612 // assumption that the retain is emitted as part of the return and
2613 // that thereafter everything is used "linearly".
2614 llvm::Type *resultType = result->getType();
2615 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2616 assert(retainCall->use_empty());
2617 retainCall->eraseFromParent();
2618 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2619
2620 return CGF.Builder.CreateBitCast(load, resultType);
2621}
2622
John McCall31168b02011-06-15 23:02:42 +00002623/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002624///
2625/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002626static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2627 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002628 // If we're returning 'self', kill the initial retain. This is a
2629 // heuristic attempt to "encourage correctness" in the really unfortunate
2630 // case where we have a return of self during a dealloc and we desperately
2631 // need to avoid the possible autorelease.
2632 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2633 return self;
2634
John McCall31168b02011-06-15 23:02:42 +00002635 // At -O0, try to emit a fused retain/autorelease.
2636 if (CGF.shouldUseFusedARCCalls())
2637 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2638 return fused;
2639
2640 return CGF.EmitARCAutoreleaseReturnValue(result);
2641}
2642
John McCall6e1c0122012-01-29 02:35:02 +00002643/// Heuristically search for a dominating store to the return-value slot.
2644static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002645 // Check if a User is a store which pointerOperand is the ReturnValue.
2646 // We are looking for stores to the ReturnValue, not for stores of the
2647 // ReturnValue to some other location.
2648 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2649 auto *SI = dyn_cast<llvm::StoreInst>(U);
2650 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2651 return nullptr;
2652 // These aren't actually possible for non-coerced returns, and we
2653 // only care about non-coerced returns on this code path.
2654 assert(!SI->isAtomic() && !SI->isVolatile());
2655 return SI;
2656 };
John McCall6e1c0122012-01-29 02:35:02 +00002657 // If there are multiple uses of the return-value slot, just check
2658 // for something immediately preceding the IP. Sometimes this can
2659 // happen with how we generate implicit-returns; it can also happen
2660 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002661 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002662 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002663 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002664 llvm::Instruction *I = &IP->back();
2665
2666 // Skip lifetime markers
2667 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2668 IE = IP->rend();
2669 II != IE; ++II) {
2670 if (llvm::IntrinsicInst *Intrinsic =
2671 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2672 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2673 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2674 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002675 if (II == IE)
2676 break;
2677 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2678 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002679 }
2680 }
2681 I = &*II;
2682 break;
2683 }
2684
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002685 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002686 }
2687
2688 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002689 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002690 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002691
John McCall6e1c0122012-01-29 02:35:02 +00002692 // Now do a first-and-dirty dominance check: just walk up the
2693 // single-predecessors chain from the current insertion point.
2694 llvm::BasicBlock *StoreBB = store->getParent();
2695 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2696 while (IP != StoreBB) {
2697 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002698 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002699 }
2700
2701 // Okay, the store's basic block dominates the insertion point; we
2702 // can do our thing.
2703 return store;
2704}
2705
Adrian Prantl3be10542013-05-02 17:30:20 +00002706void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002707 bool EmitRetDbgLoc,
2708 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002709 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2710 // Naked functions don't have epilogues.
2711 Builder.CreateUnreachable();
2712 return;
2713 }
2714
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002715 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002716 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002717 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002718 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002719 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002720
Dan Gohman481e40c2010-07-20 20:13:52 +00002721 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002722 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002723 QualType RetTy = FI.getReturnType();
2724 const ABIArgInfo &RetAI = FI.getReturnInfo();
2725
2726 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002727 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002728 // Aggregrates get evaluated directly into the destination. Sometimes we
2729 // need to return the sret value in a register, though.
2730 assert(hasAggregateEvaluationKind(RetTy));
2731 if (RetAI.getInAllocaSRet()) {
2732 llvm::Function::arg_iterator EI = CurFn->arg_end();
2733 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002734 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002735 llvm::Value *SRet = Builder.CreateStructGEP(
2736 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002737 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002738 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002739 break;
2740
Daniel Dunbar03816342010-08-21 02:24:36 +00002741 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002742 auto AI = CurFn->arg_begin();
2743 if (RetAI.isSRetAfterThis())
2744 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002745 switch (getEvaluationKind(RetTy)) {
2746 case TEK_Complex: {
2747 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002748 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002749 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002750 /*isInit*/ true);
2751 break;
2752 }
2753 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002754 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002755 break;
2756 case TEK_Scalar:
2757 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002758 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002759 /*isInit*/ true);
2760 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002761 }
2762 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002763 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002764
2765 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002766 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002767 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2768 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002769 // The internal return value temp always will have pointer-to-return-type
2770 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002771
John McCall6e1c0122012-01-29 02:35:02 +00002772 // If there is a dominating store to ReturnValue, we can elide
2773 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002774 if (llvm::StoreInst *SI =
2775 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002776 // Reuse the debug location from the store unless there is
2777 // cleanup code to be emitted between the store and return
2778 // instruction.
2779 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002780 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002781 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002782 RV = SI->getValueOperand();
2783 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002784
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002785 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002786 auto returnValueInst = ReturnValue.getPointer();
2787 if (returnValueInst->use_empty()) {
2788 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2789 alloca->eraseFromParent();
2790 ReturnValue = Address::invalid();
2791 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002792 }
John McCall6e1c0122012-01-29 02:35:02 +00002793
2794 // Otherwise, we have to do a simple load.
2795 } else {
2796 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002797 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002798 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002799 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002800 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002801
John McCall7f416cc2015-09-08 08:05:57 +00002802 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002803 }
John McCall31168b02011-06-15 23:02:42 +00002804
2805 // In ARC, end functions that return a retainable type with a call
2806 // to objc_autoreleaseReturnValue.
2807 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002808#ifndef NDEBUG
2809 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2810 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2811 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2812 // CurCodeDecl or BlockInfo.
2813 QualType RT;
2814
2815 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2816 RT = FD->getReturnType();
2817 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2818 RT = MD->getReturnType();
2819 else if (isa<BlockDecl>(CurCodeDecl))
2820 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2821 else
2822 llvm_unreachable("Unexpected function/method type");
2823
David Blaikiebbafb8a2012-03-11 07:00:24 +00002824 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002825 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002826 RT->isObjCRetainableType());
2827#endif
John McCall31168b02011-06-15 23:02:42 +00002828 RV = emitAutoreleaseOfResult(*this, RV);
2829 }
2830
Chris Lattner726b3d02010-06-26 23:13:19 +00002831 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002832
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002833 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002834 break;
2835
John McCallf26e73d2016-03-11 04:30:43 +00002836 case ABIArgInfo::CoerceAndExpand: {
2837 auto coercionType = RetAI.getCoerceAndExpandType();
2838 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2839
2840 // Load all of the coerced elements out into results.
2841 llvm::SmallVector<llvm::Value*, 4> results;
2842 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2843 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2844 auto coercedEltType = coercionType->getElementType(i);
2845 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2846 continue;
2847
2848 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2849 auto elt = Builder.CreateLoad(eltAddr);
2850 results.push_back(elt);
2851 }
2852
2853 // If we have one result, it's the single direct result type.
2854 if (results.size() == 1) {
2855 RV = results[0];
2856
2857 // Otherwise, we need to make a first-class aggregate.
2858 } else {
2859 // Construct a return type that lacks padding elements.
2860 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2861
2862 RV = llvm::UndefValue::get(returnType);
2863 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2864 RV = Builder.CreateInsertValue(RV, results[i], i);
2865 }
2866 }
2867 break;
2868 }
2869
Chris Lattner726b3d02010-06-26 23:13:19 +00002870 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002871 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002872 }
2873
Alexey Samsonovde443c52014-08-13 00:26:40 +00002874 llvm::Instruction *Ret;
2875 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002876 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2877 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002878 SanitizerScope SanScope(this);
2879 llvm::Value *Cond = Builder.CreateICmpNE(
2880 RV, llvm::Constant::getNullValue(RV->getType()));
2881 llvm::Constant *StaticData[] = {
2882 EmitCheckSourceLocation(EndLoc),
2883 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2884 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002885 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002886 SanitizerHandler::NonnullReturn, StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002887 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002888 }
2889 Ret = Builder.CreateRet(RV);
2890 } else {
2891 Ret = Builder.CreateRetVoid();
2892 }
2893
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002894 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002895 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002896}
2897
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002898static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2899 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2900 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2901}
2902
John McCall7f416cc2015-09-08 08:05:57 +00002903static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2904 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002905 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2906 // placeholders.
2907 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002908 llvm::Type *IRPtrTy = IRTy->getPointerTo();
2909 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00002910
2911 // FIXME: When we generate this IR in one pass, we shouldn't need
2912 // this win32-specific alignment hack.
2913 CharUnits Align = CharUnits::fromQuantity(4);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002914 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002915
2916 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002917 Ty.getQualifiers(),
2918 AggValueSlot::IsNotDestructed,
2919 AggValueSlot::DoesNotNeedGCBarriers,
2920 AggValueSlot::IsNotAliased);
2921}
2922
John McCall32ea9692011-03-11 20:59:21 +00002923void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002924 const VarDecl *param,
2925 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002926 // StartFunction converted the ABI-lowered parameter(s) into a
2927 // local alloca. We need to turn that into an r-value suitable
2928 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002929 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002930
John McCall32ea9692011-03-11 20:59:21 +00002931 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002932
Reid Klecknerab2090d2014-07-26 01:34:32 +00002933 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2934 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002935
John McCall811b2912016-11-18 01:08:24 +00002936 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
2937 // but the argument needs to be the original pointer.
2938 if (type->isReferenceType()) {
2939 args.add(RValue::get(Builder.CreateLoad(local)), type);
2940
2941 // In ARC, move out of consumed arguments so that the release cleanup
2942 // entered by StartFunction doesn't cause an over-release. This isn't
2943 // optimal -O0 code generation, but it should get cleaned up when
2944 // optimization is enabled. This also assumes that delegate calls are
2945 // performed exactly once for a set of arguments, but that should be safe.
2946 } else if (getLangOpts().ObjCAutoRefCount &&
2947 param->hasAttr<NSConsumedAttr>() &&
2948 type->isObjCRetainableType()) {
2949 llvm::Value *ptr = Builder.CreateLoad(local);
2950 auto null =
2951 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
2952 Builder.CreateStore(null, local);
2953 args.add(RValue::get(ptr), type);
2954
Richard Smithd62d4982016-06-14 01:13:21 +00002955 // For the most part, we just need to load the alloca, except that
2956 // aggregate r-values are actually pointers to temporaries.
John McCall811b2912016-11-18 01:08:24 +00002957 } else {
Richard Smithd62d4982016-06-14 01:13:21 +00002958 args.add(convertTempToRValue(local, type, loc), type);
John McCall811b2912016-11-18 01:08:24 +00002959 }
John McCall23f66262010-05-26 22:34:26 +00002960}
2961
John McCall31168b02011-06-15 23:02:42 +00002962static bool isProvablyNull(llvm::Value *addr) {
2963 return isa<llvm::ConstantPointerNull>(addr);
2964}
2965
John McCall31168b02011-06-15 23:02:42 +00002966/// Emit the actual writing-back of a writeback.
2967static void emitWriteback(CodeGenFunction &CGF,
2968 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002969 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002970 Address srcAddr = srcLV.getAddress();
2971 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002972 "shouldn't have writeback for provably null argument");
2973
Craig Topper8a13c412014-05-21 05:09:00 +00002974 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002975
2976 // If the argument wasn't provably non-null, we need to null check
2977 // before doing the store.
Nick Lewyckyd9bce502016-09-20 15:49:58 +00002978 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002979 if (!provablyNonNull) {
2980 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2981 contBB = CGF.createBasicBlock("icr.done");
2982
John McCall7f416cc2015-09-08 08:05:57 +00002983 llvm::Value *isNull =
2984 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002985 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2986 CGF.EmitBlock(writebackBB);
2987 }
2988
2989 // Load the value to writeback.
2990 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2991
2992 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002993 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2994 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002995
2996 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002997
2998 // If we have a "to use" value, it's something we need to emit a use
2999 // of. This has to be carefully threaded in: if it's done after the
3000 // release it's potentially undefined behavior (and the optimizer
3001 // will ignore it), and if it happens before the retain then the
3002 // optimizer could move the release there.
3003 if (writeback.ToUse) {
3004 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3005
3006 // Retain the new value. No need to block-copy here: the block's
3007 // being passed up the stack.
3008 value = CGF.EmitARCRetainNonBlock(value);
3009
3010 // Emit the intrinsic use here.
3011 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3012
3013 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00003014 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00003015
3016 // Put the new value in place (primitively).
3017 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3018
3019 // Release the old value.
3020 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3021
3022 // Otherwise, we can just do a normal lvalue store.
3023 } else {
3024 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3025 }
John McCall31168b02011-06-15 23:02:42 +00003026
3027 // Jump to the continuation block.
3028 if (!provablyNonNull)
3029 CGF.EmitBlock(contBB);
3030}
3031
3032static void emitWritebacks(CodeGenFunction &CGF,
3033 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00003034 for (const auto &I : args.writebacks())
3035 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00003036}
3037
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003038static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3039 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003040 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003041 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3042 CallArgs.getCleanupsToDeactivate();
3043 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00003044 for (const auto &I : llvm::reverse(Cleanups)) {
3045 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3046 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003047 }
3048}
3049
John McCalleff18842013-03-23 02:35:54 +00003050static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3051 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3052 if (uop->getOpcode() == UO_AddrOf)
3053 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003054 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003055}
3056
John McCall31168b02011-06-15 23:02:42 +00003057/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003058/// we are passing the address of an __autoreleased temporary; it
3059/// might be copy-initialized with the current value of the given
3060/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003061static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3062 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003063 LValue srcLV;
3064
3065 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003066 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003067 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3068 srcLV = CGF.EmitLValue(lvExpr);
3069
3070 // Otherwise, just emit it as a scalar.
3071 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003072 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003073
3074 QualType srcAddrType =
3075 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003076 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003077 }
John McCall7f416cc2015-09-08 08:05:57 +00003078 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003079
3080 // The dest and src types don't necessarily match in LLVM terms
3081 // because of the crazy ObjC compatibility rules.
3082
Chris Lattner2192fe52011-07-18 04:24:23 +00003083 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003084 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3085
3086 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003087 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003088 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3089 CRE->getType());
3090 return;
3091 }
3092
John McCall31168b02011-06-15 23:02:42 +00003093 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003094 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3095 CGF.getPointerAlign(),
3096 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003097 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3098 // and that cleanup will be conditional if we can't prove that the l-value
3099 // isn't null, so we need to register a dominating point so that the cleanups
3100 // system will make valid IR.
3101 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3102
John McCall31168b02011-06-15 23:02:42 +00003103 // Zero-initialize it if we're not doing a copy-initialization.
3104 bool shouldCopy = CRE->shouldCopy();
3105 if (!shouldCopy) {
3106 llvm::Value *null =
3107 llvm::ConstantPointerNull::get(
3108 cast<llvm::PointerType>(destType->getElementType()));
3109 CGF.Builder.CreateStore(null, temp);
3110 }
Craig Topper8a13c412014-05-21 05:09:00 +00003111
3112 llvm::BasicBlock *contBB = nullptr;
3113 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003114
3115 // If the address is *not* known to be non-null, we need to switch.
3116 llvm::Value *finalArgument;
3117
Nick Lewyckyd9bce502016-09-20 15:49:58 +00003118 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003119 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003120 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003121 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003122 llvm::Value *isNull =
3123 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003124
3125 finalArgument = CGF.Builder.CreateSelect(isNull,
3126 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003127 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003128
3129 // If we need to copy, then the load has to be conditional, which
3130 // means we need control flow.
3131 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003132 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003133 contBB = CGF.createBasicBlock("icr.cont");
3134 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3135 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3136 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003137 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003138 }
3139 }
3140
Craig Topper8a13c412014-05-21 05:09:00 +00003141 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003142
John McCall31168b02011-06-15 23:02:42 +00003143 // Perform a copy if necessary.
3144 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003145 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003146 assert(srcRV.isScalar());
3147
3148 llvm::Value *src = srcRV.getScalarVal();
3149 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3150 "icr.cast");
3151
3152 // Use an ordinary store, not a store-to-lvalue.
3153 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003154
3155 // If optimization is enabled, and the value was held in a
3156 // __strong variable, we need to tell the optimizer that this
3157 // value has to stay alive until we're doing the store back.
3158 // This is because the temporary is effectively unretained,
3159 // and so otherwise we can violate the high-level semantics.
3160 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3161 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3162 valueToUse = src;
3163 }
John McCall31168b02011-06-15 23:02:42 +00003164 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003165
John McCall31168b02011-06-15 23:02:42 +00003166 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003167 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003168 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003169 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003170
3171 // Make a phi for the value to intrinsically use.
3172 if (valueToUse) {
3173 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3174 "icr.to-use");
3175 phiToUse->addIncoming(valueToUse, copyBB);
3176 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3177 originBB);
3178 valueToUse = phiToUse;
3179 }
3180
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003181 condEval.end(CGF);
3182 }
John McCall31168b02011-06-15 23:02:42 +00003183
John McCalleff18842013-03-23 02:35:54 +00003184 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003185 args.add(RValue::get(finalArgument), CRE->getType());
3186}
3187
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003188void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003189 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003190
3191 // Save the stack.
3192 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003193 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003194}
3195
Nico Weber8cdb3f92015-08-25 18:43:32 +00003196void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3197 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003198 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003199 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003200 CGF.Builder.CreateCall(F, StackBase);
3201 }
3202}
3203
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003204void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3205 SourceLocation ArgLoc,
3206 const FunctionDecl *FD,
3207 unsigned ParmNum) {
3208 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003209 return;
3210 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3211 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3212 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3213 if (!NNAttr)
3214 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003215 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003216 assert(RV.isScalar());
3217 llvm::Value *V = RV.getScalarVal();
3218 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003219 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003220 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003221 EmitCheckSourceLocation(ArgLoc),
3222 EmitCheckSourceLocation(NNAttr->getLocation()),
3223 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003224 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003225 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003226 SanitizerHandler::NonnullArg, StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003227}
3228
David Blaikief05779e2015-07-21 18:37:18 +00003229void CodeGenFunction::EmitCallArgs(
3230 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3231 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Richard Smith762672a2016-09-28 19:09:10 +00003232 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip,
Richard Smitha560ccf2016-09-29 21:30:12 +00003233 EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003234 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003235
3236 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3237 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3238 return;
3239 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3240 if (PS == nullptr)
3241 return;
3242
3243 const auto &Context = getContext();
3244 auto SizeTy = Context.getSizeType();
3245 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3246 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3247 Args.add(RValue::get(V), SizeTy);
3248 };
3249
Reid Kleckner739756c2013-12-04 19:23:12 +00003250 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003251 // because arguments are destroyed left to right in the callee. As a special
3252 // case, there are certain language constructs that require left-to-right
3253 // evaluation, and in those cases we consider the evaluation order requirement
3254 // to trump the "destruction order is reverse construction order" guarantee.
3255 bool LeftToRight =
3256 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3257 ? Order == EvaluationOrder::ForceLeftToRight
3258 : Order != EvaluationOrder::ForceRightToLeft;
3259
3260 // Insert a stack save if we're going to need any inalloca args.
3261 bool HasInAllocaArgs = false;
3262 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003263 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3264 I != E && !HasInAllocaArgs; ++I)
3265 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3266 if (HasInAllocaArgs) {
3267 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3268 Args.allocateArgumentMemory(*this);
3269 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003270 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003271
Richard Smitha560ccf2016-09-29 21:30:12 +00003272 // Evaluate each argument in the appropriate order.
3273 size_t CallArgsStart = Args.size();
3274 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3275 unsigned Idx = LeftToRight ? I : E - I - 1;
3276 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3277 if (!LeftToRight) MaybeEmitImplicitObjectSize(Idx, *Arg);
3278 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
3279 EmitNonNullArgCheck(Args.back().RV, ArgTypes[Idx], (*Arg)->getExprLoc(),
3280 CalleeDecl, ParamsToSkip + Idx);
3281 if (LeftToRight) MaybeEmitImplicitObjectSize(Idx, *Arg);
3282 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003283
Richard Smitha560ccf2016-09-29 21:30:12 +00003284 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003285 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3286 // IR function.
3287 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003288 }
3289}
3290
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003291namespace {
3292
David Blaikie7e70d682015-08-18 22:40:54 +00003293struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003294 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003295 : Addr(Addr), Ty(Ty) {}
3296
John McCall7f416cc2015-09-08 08:05:57 +00003297 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003298 QualType Ty;
3299
Craig Topper4f12f102014-03-12 06:41:41 +00003300 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003301 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3302 assert(!Dtor->isTrivial());
3303 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3304 /*Delegating=*/false, Addr);
3305 }
3306};
3307
David Blaikie38b25912015-02-09 19:13:51 +00003308struct DisableDebugLocationUpdates {
3309 CodeGenFunction &CGF;
3310 bool disabledDebugInfo;
3311 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3312 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3313 CGF.disableDebugInfo();
3314 }
3315 ~DisableDebugLocationUpdates() {
3316 if (disabledDebugInfo)
3317 CGF.enableDebugInfo();
3318 }
3319};
3320
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003321} // end anonymous namespace
3322
John McCall32ea9692011-03-11 20:59:21 +00003323void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3324 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003325 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003326 if (const ObjCIndirectCopyRestoreExpr *CRE
3327 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003328 assert(getLangOpts().ObjCAutoRefCount);
Vedant Kumar30914f32016-10-03 15:29:22 +00003329 assert(getContext().hasSameUnqualifiedType(E->getType(), type));
John McCall31168b02011-06-15 23:02:42 +00003330 return emitWritebackArg(*this, args, CRE);
3331 }
3332
John McCall0a76c0c2011-08-26 18:42:59 +00003333 assert(type->isReferenceType() == E->isGLValue() &&
3334 "reference binding to unmaterialized r-value!");
3335
John McCall17054bd62011-08-26 21:08:13 +00003336 if (E->isGLValue()) {
3337 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003338 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003339 }
Mike Stump11289f42009-09-09 15:08:12 +00003340
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003341 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3342
3343 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3344 // However, we still have to push an EH-only cleanup in case we unwind before
3345 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003346 if (HasAggregateEvalKind &&
3347 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3348 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003349 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003350 AggValueSlot Slot;
3351 if (args.isUsingInAlloca())
3352 Slot = createPlaceholderSlot(*this, type);
3353 else
3354 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003355
3356 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3357 bool DestroyedInCallee =
3358 RD && RD->hasNonTrivialDestructor() &&
3359 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3360 if (DestroyedInCallee)
3361 Slot.setExternallyDestructed();
3362
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003363 EmitAggExpr(E, Slot);
3364 RValue RV = Slot.asRValue();
3365 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003366
Reid Klecknere39ee212014-05-03 00:33:28 +00003367 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003368 // Create a no-op GEP between the placeholder and the cleanup so we can
3369 // RAUW it successfully. It also serves as a marker of the first
3370 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003371 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3372 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003373 // This unreachable is a temporary marker which will be removed later.
3374 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3375 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003376 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003377 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003378 }
3379
3380 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003381 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3382 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3383 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003384 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3385 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3386 } else {
3387 // We can't represent a misaligned lvalue in the CallArgList, so copy
3388 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003389 Address tmp = CreateMemTemp(type);
3390 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003391 args.add(RValue::getAggregate(tmp), type);
3392 }
Eli Friedmandf968192011-05-26 00:10:27 +00003393 return;
3394 }
3395
John McCall32ea9692011-03-11 20:59:21 +00003396 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003397}
3398
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003399QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3400 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3401 // implicitly widens null pointer constants that are arguments to varargs
3402 // functions to pointer-sized ints.
3403 if (!getTarget().getTriple().isOSWindows())
3404 return Arg->getType();
3405
3406 if (Arg->getType()->isIntegerType() &&
3407 getContext().getTypeSize(Arg->getType()) <
3408 getContext().getTargetInfo().getPointerWidth(0) &&
3409 Arg->isNullPointerConstant(getContext(),
3410 Expr::NPC_ValueDependentIsNotNull)) {
3411 return getContext().getIntPtrType();
3412 }
3413
3414 return Arg->getType();
3415}
3416
Dan Gohman515a60d2012-02-16 00:57:37 +00003417// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3418// optimizer it can aggressively ignore unwind edges.
3419void
3420CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3421 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3422 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3423 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3424 CGM.getNoObjCARCExceptionsMetadata());
3425}
3426
John McCall882987f2013-02-28 19:01:20 +00003427/// Emits a call to the given no-arguments nounwind runtime function.
3428llvm::CallInst *
3429CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3430 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003431 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003432}
3433
3434/// Emits a call to the given nounwind runtime function.
3435llvm::CallInst *
3436CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3437 ArrayRef<llvm::Value*> args,
3438 const llvm::Twine &name) {
3439 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3440 call->setDoesNotThrow();
3441 return call;
3442}
3443
3444/// Emits a simple call (never an invoke) to the given no-arguments
3445/// runtime function.
3446llvm::CallInst *
3447CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3448 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003449 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003450}
3451
David Majnemer0b17d442015-12-15 21:27:59 +00003452// Calls which may throw must have operand bundles indicating which funclet
3453// they are nested within.
3454static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003455getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003456 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003457 // There is no need for a funclet operand bundle if we aren't inside a
3458 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003459 if (!CurrentFuncletPad)
3460 return;
3461
3462 // Skip intrinsics which cannot throw.
3463 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3464 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3465 return;
3466
3467 BundleList.emplace_back("funclet", CurrentFuncletPad);
3468}
3469
David Majnemer971d31b2016-02-24 17:02:45 +00003470/// Emits a simple call (never an invoke) to the given runtime function.
3471llvm::CallInst *
3472CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3473 ArrayRef<llvm::Value*> args,
3474 const llvm::Twine &name) {
3475 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3476 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3477
3478 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3479 call->setCallingConv(getRuntimeCC());
3480 return call;
3481}
3482
John McCall882987f2013-02-28 19:01:20 +00003483/// Emits a call or invoke to the given noreturn runtime function.
3484void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3485 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003486 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3487 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3488
John McCall882987f2013-02-28 19:01:20 +00003489 if (getInvokeDest()) {
3490 llvm::InvokeInst *invoke =
3491 Builder.CreateInvoke(callee,
3492 getUnreachableBlock(),
3493 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003494 args,
3495 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003496 invoke->setDoesNotReturn();
3497 invoke->setCallingConv(getRuntimeCC());
3498 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003499 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003500 call->setDoesNotReturn();
3501 call->setCallingConv(getRuntimeCC());
3502 Builder.CreateUnreachable();
3503 }
3504}
3505
Sanjay Patel846b63b2016-01-18 22:15:33 +00003506/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003507llvm::CallSite
3508CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3509 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003510 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003511}
3512
3513/// Emits a call or invoke instruction to the given runtime function.
3514llvm::CallSite
3515CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3516 ArrayRef<llvm::Value*> args,
3517 const Twine &name) {
3518 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3519 callSite.setCallingConv(getRuntimeCC());
3520 return callSite;
3521}
3522
John McCallbd309292010-07-06 01:34:17 +00003523/// Emits a call or invoke instruction to the given function, depending
3524/// on the current state of the EH stack.
3525llvm::CallSite
3526CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003527 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003528 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003529 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003530 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3531 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003532
Dan Gohman515a60d2012-02-16 00:57:37 +00003533 llvm::Instruction *Inst;
3534 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003535 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003536 else {
3537 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003538 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3539 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003540 EmitBlock(ContBB);
3541 }
3542
3543 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3544 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003545 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003546 AddObjCARCExceptionMetadata(Inst);
3547
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003548 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003549}
3550
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003551/// \brief Store a non-aggregate value to an address to initialize it. For
3552/// initialization, a non-atomic store will be used.
3553static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3554 LValue Dst) {
3555 if (Src.isScalar())
3556 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3557 else
3558 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3559}
3560
3561void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3562 llvm::Value *New) {
3563 DeferredReplacements.push_back(std::make_pair(Old, New));
3564}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003565
Daniel Dunbard931a872009-02-02 22:03:45 +00003566RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003567 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003568 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003569 const CallArgList &CallArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00003570 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003571 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003572
John McCallb92ab1a2016-10-26 23:46:34 +00003573 assert(Callee.isOrdinary());
3574
Daniel Dunbar613855c2008-09-09 23:27:19 +00003575 // Handle struct-return functions by passing a pointer to the
3576 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003577 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003578 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003579
John McCallb92ab1a2016-10-26 23:46:34 +00003580 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3581
3582 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003583
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003584 // If we're using inalloca, insert the allocation after the stack save.
3585 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003586 Address ArgMemory = Address::invalid();
3587 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003588 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003589 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003590 llvm::Instruction *IP = CallArgs.getStackBase();
3591 llvm::AllocaInst *AI;
3592 if (IP) {
3593 IP = IP->getNextNode();
3594 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3595 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003596 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003597 }
John McCall7f416cc2015-09-08 08:05:57 +00003598 auto Align = CallInfo.getArgStructAlignment();
3599 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003600 AI->setUsedWithInAlloca(true);
3601 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003602 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003603 }
3604
John McCall7f416cc2015-09-08 08:05:57 +00003605 // Helper function to drill into the inalloca allocation.
3606 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3607 auto FieldOffset =
3608 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3609 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3610 };
3611
Alexey Samsonov153004f2014-09-29 22:08:00 +00003612 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003613 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3614
Chris Lattner4ca97c32009-06-13 00:26:38 +00003615 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003616 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003617 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003618 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003619 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003620 if (!ReturnValue.isNull()) {
3621 SRetPtr = ReturnValue.getValue();
3622 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003623 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003624 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3625 uint64_t size =
3626 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003627 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003628 UnusedReturnSize = size;
3629 }
3630 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003631 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003632 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003633 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003634 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3635 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003636 }
Anders Carlsson17490832009-12-24 20:40:36 +00003637 }
Mike Stump11289f42009-09-09 15:08:12 +00003638
John McCall12f23522016-04-04 18:33:08 +00003639 Address swiftErrorTemp = Address::invalid();
3640 Address swiftErrorArg = Address::invalid();
3641
John McCallb92ab1a2016-10-26 23:46:34 +00003642 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003643 assert(CallInfo.arg_size() == CallArgs.size() &&
3644 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003645 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003646 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003647 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003648 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003649 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003650 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003651
Rafael Espindolafad28de2012-10-24 01:59:00 +00003652 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003653 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3654 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3655 llvm::UndefValue::get(ArgInfo.getPaddingType());
3656
3657 unsigned FirstIRArg, NumIRArgs;
3658 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003659
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003660 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003661 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003662 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003663 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3664 if (RV.isAggregate()) {
3665 // Replace the placeholder with the appropriate argument slot GEP.
3666 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003667 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003668 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3669 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003670 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003671 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003672 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003673 } else {
3674 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003675 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3676 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003677 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3678 // There are some cases where a trivial bitcast is not avoidable. The
3679 // definition of a type later in a translation unit may change it's type
3680 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003681 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003682 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003683 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003684 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3685 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003686 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003687 }
3688
Daniel Dunbar03816342010-08-21 02:24:36 +00003689 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003690 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003691 if (RV.isScalar() || RV.isComplex()) {
3692 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003693 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3694 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003695
John McCall7f416cc2015-09-08 08:05:57 +00003696 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003697 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003698 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003699 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003700 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003701 // 1. If the argument is not byval, and we are required to copy the
3702 // source. (This case doesn't occur on any common architecture.)
3703 // 2. If the argument is byval, RV is not sufficiently aligned, and
3704 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003705 // 3. If the argument is byval, but RV is located in an address space
3706 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003707 Address Addr = RV.getAggregateAddress();
3708 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003709 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003710 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003711 const unsigned ArgAddrSpace =
3712 (FirstIRArg < IRFuncTy->getNumParams()
3713 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3714 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003715 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003716 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3717 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3718 Align.getQuantity(), *TD)
3719 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003720 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003721 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003722 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3723 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003724 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003725 } else {
3726 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003727 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003728 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003729 }
3730 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003731 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003732
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003733 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003734 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003735 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003736
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003737 case ABIArgInfo::Extend:
3738 case ABIArgInfo::Direct: {
3739 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003740 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3741 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003742 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003743 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003744 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003745 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003746 else
John McCall7f416cc2015-09-08 08:05:57 +00003747 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003748
John McCall12f23522016-04-04 18:33:08 +00003749 // Implement swifterror by copying into a new swifterror argument.
3750 // We'll write back in the normal path out of the call.
3751 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3752 == ParameterABI::SwiftErrorResult) {
3753 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3754
3755 QualType pointeeTy = I->Ty->getPointeeType();
3756 swiftErrorArg =
3757 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3758
3759 swiftErrorTemp =
3760 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3761 V = swiftErrorTemp.getPointer();
3762 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3763
3764 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3765 Builder.CreateStore(errorValue, swiftErrorTemp);
3766 }
3767
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003768 // We might have to widen integers, but we should never truncate.
3769 if (ArgInfo.getCoerceToType() != V->getType() &&
3770 V->getType()->isIntegerTy())
3771 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3772
Chris Lattner3ce86682011-07-12 04:53:39 +00003773 // If the argument doesn't match, perform a bitcast to coerce it. This
3774 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003775 if (FirstIRArg < IRFuncTy->getNumParams() &&
3776 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3777 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003778
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003779 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003780 break;
3781 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003782
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003783 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003784 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003785 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003786 Src = CreateMemTemp(I->Ty, "coerce");
3787 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003788 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003789 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003790 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003791 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003792
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003793 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003794 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003795
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003796 // Fast-isel and the optimizer generally like scalar values better than
3797 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003798 llvm::StructType *STy =
3799 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003800 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003801 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003802 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3803 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3804
3805 // If the source type is smaller than the destination type of the
3806 // coerce-to logic, copy the source value into a temp alloca the size
3807 // of the destination type to allow loading all of it. The bits past
3808 // the source value are left undef.
3809 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003810 Address TempAlloca
3811 = CreateTempAlloca(STy, Src.getAlignment(),
3812 Src.getName() + ".coerce");
3813 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3814 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003815 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003816 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003817 }
3818
John McCall7f416cc2015-09-08 08:05:57 +00003819 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003820 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003821 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003822 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3823 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3824 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003825 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003826 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003827 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003828 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003829 assert(NumIRArgs == 1);
3830 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003831 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003832 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003833
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003834 break;
3835 }
3836
John McCallf26e73d2016-03-11 04:30:43 +00003837 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003838 auto coercionType = ArgInfo.getCoerceAndExpandType();
3839 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3840
John McCall12f23522016-04-04 18:33:08 +00003841 llvm::Value *tempSize = nullptr;
3842 Address addr = Address::invalid();
3843 if (RV.isAggregate()) {
3844 addr = RV.getAggregateAddress();
3845 } else {
3846 assert(RV.isScalar()); // complex should always just be direct
3847
3848 llvm::Type *scalarType = RV.getScalarVal()->getType();
3849 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3850 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3851
3852 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3853
3854 // Materialize to a temporary.
3855 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3856 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3857 scalarAlign)));
3858 EmitLifetimeStart(scalarSize, addr.getPointer());
3859
3860 Builder.CreateStore(RV.getScalarVal(), addr);
3861 }
3862
John McCallf26e73d2016-03-11 04:30:43 +00003863 addr = Builder.CreateElementBitCast(addr, coercionType);
3864
3865 unsigned IRArgPos = FirstIRArg;
3866 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3867 llvm::Type *eltType = coercionType->getElementType(i);
3868 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3869 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3870 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3871 IRCallArgs[IRArgPos++] = elt;
3872 }
3873 assert(IRArgPos == FirstIRArg + NumIRArgs);
3874
John McCall12f23522016-04-04 18:33:08 +00003875 if (tempSize) {
3876 EmitLifetimeEnd(tempSize, addr.getPointer());
3877 }
3878
John McCallf26e73d2016-03-11 04:30:43 +00003879 break;
3880 }
3881
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003882 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003883 unsigned IRArgPos = FirstIRArg;
3884 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3885 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003886 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003887 }
3888 }
Mike Stump11289f42009-09-09 15:08:12 +00003889
John McCallb92ab1a2016-10-26 23:46:34 +00003890 llvm::Value *CalleePtr = Callee.getFunctionPointer();
3891
3892 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00003893 if (ArgMemory.isValid()) {
3894 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003895 if (CallInfo.isVariadic()) {
3896 // When passing non-POD arguments by value to variadic functions, we will
3897 // end up with a variadic prototype and an inalloca call site. In such
3898 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3899 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00003900 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
3901 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
3902 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
Reid Klecknerafba553e2014-07-08 02:24:27 +00003903 } else {
3904 llvm::Type *LastParamTy =
3905 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3906 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003907#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003908 // Assert that these structs have equivalent element types.
3909 llvm::StructType *FullTy = CallInfo.getArgStruct();
3910 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3911 cast<llvm::PointerType>(LastParamTy)->getElementType());
3912 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3913 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3914 DE = DeclaredTy->element_end(),
3915 FI = FullTy->element_begin();
3916 DI != DE; ++DI, ++FI)
3917 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003918#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003919 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3920 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003921 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003922 assert(IRFunctionArgs.hasInallocaArg());
3923 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003924 }
3925
John McCallb92ab1a2016-10-26 23:46:34 +00003926 // 2. Prepare the function pointer.
3927
3928 // If the callee is a bitcast of a non-variadic function to have a
3929 // variadic function pointer type, check to see if we can remove the
3930 // bitcast. This comes up with unprototyped functions.
3931 //
3932 // This makes the IR nicer, but more importantly it ensures that we
3933 // can inline the function at -O0 if it is marked always_inline.
3934 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
3935 llvm::FunctionType *CalleeFT =
3936 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
3937 if (!CalleeFT->isVarArg())
3938 return Ptr;
3939
3940 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
3941 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
3942 return Ptr;
3943
3944 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
3945 if (!OrigFn)
3946 return Ptr;
3947
3948 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
3949
3950 // If the original type is variadic, or if any of the component types
3951 // disagree, we cannot remove the cast.
3952 if (OrigFT->isVarArg() ||
3953 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
3954 OrigFT->getReturnType() != CalleeFT->getReturnType())
3955 return Ptr;
3956
3957 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
3958 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
3959 return Ptr;
3960
3961 return OrigFn;
3962 };
3963 CalleePtr = simplifyVariadicCallee(CalleePtr);
3964
3965 // 3. Perform the actual call.
3966
3967 // Deactivate any cleanups that we're supposed to do immediately before
3968 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003969 if (!CallArgs.getCleanupsToDeactivate().empty())
3970 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3971
John McCallb92ab1a2016-10-26 23:46:34 +00003972 // Assert that the arguments we computed match up. The IR verifier
3973 // will catch this, but this is a common enough source of problems
3974 // during IRGen changes that it's way better for debugging to catch
3975 // it ourselves here.
3976#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003977 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3978 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3979 // Inalloca argument can have different type.
3980 if (IRFunctionArgs.hasInallocaArg() &&
3981 i == IRFunctionArgs.getInallocaArgNo())
3982 continue;
3983 if (i < IRFuncTy->getNumParams())
3984 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3985 }
John McCallb92ab1a2016-10-26 23:46:34 +00003986#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003987
John McCallb92ab1a2016-10-26 23:46:34 +00003988 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003989 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003990 CodeGen::AttributeListType AttributeList;
John McCallb92ab1a2016-10-26 23:46:34 +00003991 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
3992 Callee.getAbstractInfo(),
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003993 AttributeList, CallingConv,
3994 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003995 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003996 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003997
John McCallb92ab1a2016-10-26 23:46:34 +00003998 // Apply some call-site-specific attributes.
3999 // TODO: work this into building the attribute set.
4000
4001 // Apply always_inline to all calls within flatten functions.
4002 // FIXME: should this really take priority over __try, below?
4003 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4004 !(Callee.getAbstractInfo().getCalleeDecl() &&
4005 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4006 Attrs =
4007 Attrs.addAttribute(getLLVMContext(),
4008 llvm::AttributeSet::FunctionIndex,
4009 llvm::Attribute::AlwaysInline);
4010 }
4011
4012 // Disable inlining inside SEH __try blocks.
4013 if (isSEHTryScope()) {
4014 Attrs =
4015 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
4016 llvm::Attribute::NoInline);
4017 }
4018
4019 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004020 bool CannotThrow;
4021 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00004022 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00004023 CannotThrow = false;
4024 } else if (isCleanupPadScope() &&
4025 EHPersonality::get(*this).isMSVCXXPersonality()) {
4026 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00004027 // exception is thrown during a cleanup outside of a try/catch.
4028 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004029 CannotThrow = true;
4030 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00004031 // Otherwise, nounwind call sites will never throw.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004032 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
4033 llvm::Attribute::NoUnwind);
4034 }
4035 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00004036
David Majnemer0b17d442015-12-15 21:27:59 +00004037 SmallVector<llvm::OperandBundleDef, 1> BundleList;
John McCallb92ab1a2016-10-26 23:46:34 +00004038 getBundlesForFunclet(CalleePtr, CurrentFuncletPad, BundleList);
David Majnemer0b17d442015-12-15 21:27:59 +00004039
John McCallb92ab1a2016-10-26 23:46:34 +00004040 // Emit the actual call/invoke instruction.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004041 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00004042 if (!InvokeDest) {
John McCallb92ab1a2016-10-26 23:46:34 +00004043 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004044 } else {
4045 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
John McCallb92ab1a2016-10-26 23:46:34 +00004046 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004047 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004048 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004049 }
John McCallb92ab1a2016-10-26 23:46:34 +00004050 llvm::Instruction *CI = CS.getInstruction();
Chris Lattnere70a0072010-06-29 16:40:28 +00004051 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004052 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004053
John McCallb92ab1a2016-10-26 23:46:34 +00004054 // Apply the attributes and calling convention.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004055 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004056 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004057
John McCallb92ab1a2016-10-26 23:46:34 +00004058 // Apply various metadata.
4059
4060 if (!CI->getType()->isVoidTy())
4061 CI->setName("call");
4062
Adam Nemet1e217bc2016-03-28 22:18:53 +00004063 // Insert instrumentation or attach profile metadata at indirect call sites.
4064 // For more details, see the comment before the definition of
4065 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004066 if (!CS.getCalledFunction())
4067 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004068 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004069
Dan Gohman515a60d2012-02-16 00:57:37 +00004070 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4071 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004072 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004073 AddObjCARCExceptionMetadata(CI);
4074
4075 // Suppress tail calls if requested.
4076 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4077 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4078 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4079 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4080 }
4081
4082 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004083
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004084 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004085 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004086 // unreachable code.
4087 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00004088 if (UnusedReturnSize)
4089 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00004090 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00004091
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004092 Builder.CreateUnreachable();
4093 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004094
Mike Stump18bb9282009-05-16 07:57:57 +00004095 // FIXME: For now, emit a dummy basic block because expr emitters in
4096 // generally are not ready to handle emitting expressions at unreachable
4097 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004098 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004099
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004100 // Return a reasonable RValue.
4101 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004102 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004103
John McCall12f23522016-04-04 18:33:08 +00004104 // Perform the swifterror writeback.
4105 if (swiftErrorTemp.isValid()) {
4106 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4107 Builder.CreateStore(errorResult, swiftErrorArg);
4108 }
4109
John McCallb92ab1a2016-10-26 23:46:34 +00004110 // Emit any call-associated writebacks immediately. Arguably this
4111 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004112 if (CallArgs.hasWritebacks())
4113 emitWritebacks(*this, CallArgs);
4114
Nico Weber8cdb3f92015-08-25 18:43:32 +00004115 // The stack cleanup for inalloca arguments has to run out of the normal
4116 // lexical order, so deactivate it and run it manually here.
4117 CallArgs.freeArgumentMemory(*this);
4118
John McCallb92ab1a2016-10-26 23:46:34 +00004119 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004120 RValue Ret = [&] {
4121 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004122 case ABIArgInfo::CoerceAndExpand: {
4123 auto coercionType = RetAI.getCoerceAndExpandType();
4124 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4125
4126 Address addr = SRetPtr;
4127 addr = Builder.CreateElementBitCast(addr, coercionType);
4128
John McCall12f23522016-04-04 18:33:08 +00004129 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4130 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4131
John McCallf26e73d2016-03-11 04:30:43 +00004132 unsigned unpaddedIndex = 0;
4133 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4134 llvm::Type *eltType = coercionType->getElementType(i);
4135 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4136 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004137 llvm::Value *elt = CI;
4138 if (requiresExtract)
4139 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4140 else
4141 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004142 Builder.CreateStore(elt, eltAddr);
4143 }
John McCall12f23522016-04-04 18:33:08 +00004144 // FALLTHROUGH
4145 }
4146
4147 case ABIArgInfo::InAlloca:
4148 case ABIArgInfo::Indirect: {
4149 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4150 if (UnusedReturnSize)
4151 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4152 SRetPtr.getPointer());
4153 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004154 }
4155
Hal Finkelee90a222014-09-26 05:04:30 +00004156 case ABIArgInfo::Ignore:
4157 // If we are ignoring an argument that had a result, make sure to
4158 // construct the appropriate return value for our caller.
4159 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004160
Hal Finkelee90a222014-09-26 05:04:30 +00004161 case ABIArgInfo::Extend:
4162 case ABIArgInfo::Direct: {
4163 llvm::Type *RetIRTy = ConvertType(RetTy);
4164 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4165 switch (getEvaluationKind(RetTy)) {
4166 case TEK_Complex: {
4167 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4168 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4169 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004170 }
Hal Finkelee90a222014-09-26 05:04:30 +00004171 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004172 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004173 bool DestIsVolatile = ReturnValue.isVolatile();
4174
John McCall7f416cc2015-09-08 08:05:57 +00004175 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004176 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4177 DestIsVolatile = false;
4178 }
John McCall7f416cc2015-09-08 08:05:57 +00004179 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004180 return RValue::getAggregate(DestPtr);
4181 }
4182 case TEK_Scalar: {
4183 // If the argument doesn't match, perform a bitcast to coerce it. This
4184 // can happen due to trivial type mismatches.
4185 llvm::Value *V = CI;
4186 if (V->getType() != RetIRTy)
4187 V = Builder.CreateBitCast(V, RetIRTy);
4188 return RValue::get(V);
4189 }
4190 }
4191 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004192 }
Hal Finkelee90a222014-09-26 05:04:30 +00004193
John McCall7f416cc2015-09-08 08:05:57 +00004194 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004195 bool DestIsVolatile = ReturnValue.isVolatile();
4196
John McCall7f416cc2015-09-08 08:05:57 +00004197 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004198 DestPtr = CreateMemTemp(RetTy, "coerce");
4199 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004200 }
Hal Finkelee90a222014-09-26 05:04:30 +00004201
4202 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004203 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4204 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004205
4206 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004207 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004208
Hal Finkelee90a222014-09-26 05:04:30 +00004209 case ABIArgInfo::Expand:
4210 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004211 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004212
Hal Finkelee90a222014-09-26 05:04:30 +00004213 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4214 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004215
John McCallb92ab1a2016-10-26 23:46:34 +00004216 // Emit the assume_aligned check on the return value.
4217 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
Hal Finkelee90a222014-09-26 05:04:30 +00004218 if (Ret.isScalar() && TargetDecl) {
4219 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4220 llvm::Value *OffsetValue = nullptr;
4221 if (const auto *Offset = AA->getOffset())
4222 OffsetValue = EmitScalarExpr(Offset);
4223
4224 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4225 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4226 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4227 OffsetValue);
4228 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004229 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004230
Hal Finkelee90a222014-09-26 05:04:30 +00004231 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004232}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004233
4234/* VarArg handling */
4235
Charles Davisc7d5c942015-09-17 20:55:33 +00004236Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4237 VAListAddr = VE->isMicrosoftABI()
4238 ? EmitMSVAListRef(VE->getSubExpr())
4239 : EmitVAListRef(VE->getSubExpr());
4240 QualType Ty = VE->getType();
4241 if (VE->isMicrosoftABI())
4242 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004243 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004244}