blob: 86aaad043611cdd3c364b0d1ff1cdd5d4095ebda [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;
Douglas Gregora941dca2010-05-18 16:57:00 +000051 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000052 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
53 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000054 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
55 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000056 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000057 // TODO: Add support for __pascal to LLVM.
58 case CC_X86Pascal: return llvm::CallingConv::C;
59 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000060 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000061 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000062 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000063 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
64 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000065 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000066 }
67}
68
John McCall8ee376f2010-02-24 07:14:12 +000069/// Derives the 'this' type for codegen purposes, i.e. ignoring method
70/// qualification.
71/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000072static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
73 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
74 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000075}
76
John McCall8ee376f2010-02-24 07:14:12 +000077/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000078static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
79 return MD->getType()->getCanonicalTypeUnqualified()
80 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000081}
82
83/// Returns the "extra-canonicalized" return type, which discards
84/// qualifiers on the return type. Codegen doesn't care about them,
85/// and it makes ABI code a little easier to be able to assume that
86/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000087static CanQualType GetReturnType(QualType RetTy) {
88 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000089}
90
John McCall8dda7b22012-07-07 06:41:13 +000091/// Arrange the argument and result information for a value of the given
92/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000093const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000094CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000095 // When translating an unprototyped function type, always use a
96 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000097 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000098 /*instanceMethod=*/false,
99 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000100 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000101}
102
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000103/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
104/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
105static void appendParameterTypes(const CodeGenTypes &CGT,
106 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000107 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
108 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000109 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000110 // Fill out paramInfos.
111 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
112 assert(paramInfos.size() <= prefix.size());
113 auto protoParamInfos = FPT->getExtParameterInfos();
114 paramInfos.reserve(prefix.size() + protoParamInfos.size());
115 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000116 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000117 }
118
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000119 // Fast path: unknown target.
120 if (FD == nullptr) {
121 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
122 return;
123 }
124
125 // In the vast majority cases, we'll have precisely FPT->getNumParams()
126 // parameters; the only thing that can change this is the presence of
127 // pass_object_size. So, we preallocate for the common case.
128 prefix.reserve(prefix.size() + FPT->getNumParams());
129
130 assert(FD->getNumParams() == FPT->getNumParams());
131 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
132 prefix.push_back(FPT->getParamType(I));
133 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
134 prefix.push_back(CGT.getContext().getSizeType());
135 }
136}
137
John McCall8dda7b22012-07-07 06:41:13 +0000138/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000139/// type, on top of any implicit parameters already stored.
140static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000141arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000142 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000143 CanQual<FunctionProtoType> FTP,
144 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000145 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000146 RequiredArgs Required =
147 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000148 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000149 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000150 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000151
Peter Collingbournef7706832014-12-12 23:41:25 +0000152 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
153 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000154 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000155 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000156}
157
John McCalla729c622012-02-17 03:33:10 +0000158/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000159/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000160const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000161CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
162 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000163 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000164 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000165 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000166}
167
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000168static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000169 // Set the appropriate calling convention for the Function.
170 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000171 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000172
173 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000174 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000175
Douglas Gregora941dca2010-05-18 16:57:00 +0000176 if (D->hasAttr<ThisCallAttr>())
177 return CC_X86ThisCall;
178
Reid Klecknerd7857f02014-10-24 17:42:17 +0000179 if (D->hasAttr<VectorCallAttr>())
180 return CC_X86VectorCall;
181
Dawn Perchik335e16b2010-09-03 01:29:35 +0000182 if (D->hasAttr<PascalAttr>())
183 return CC_X86Pascal;
184
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000185 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
186 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
187
Guy Benyeif0a014b2012-12-25 08:53:55 +0000188 if (D->hasAttr<IntelOclBiccAttr>())
189 return CC_IntelOclBicc;
190
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000191 if (D->hasAttr<MSABIAttr>())
192 return IsWindows ? CC_C : CC_X86_64Win64;
193
194 if (D->hasAttr<SysVABIAttr>())
195 return IsWindows ? CC_X86_64SysV : CC_C;
196
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000197 if (D->hasAttr<PreserveMostAttr>())
198 return CC_PreserveMost;
199
200 if (D->hasAttr<PreserveAllAttr>())
201 return CC_PreserveAll;
202
John McCallab26cfa2010-02-05 21:31:56 +0000203 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000204}
205
John McCalla729c622012-02-17 03:33:10 +0000206/// Arrange the argument and result information for a call to an
207/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000208/// (Zero value of RD means we don't have any meaningful "this" argument type,
209/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000210/// The member function must be an ordinary function, i.e. not a
211/// constructor or destructor.
212const CGFunctionInfo &
213CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000214 const FunctionProtoType *FTP,
215 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000216 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000217
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000218 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000219 if (RD)
220 argTypes.push_back(GetThisType(Context, RD));
221 else
222 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000223
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000224 return ::arrangeLLVMFunctionInfo(
225 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000226 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000227}
228
John McCalla729c622012-02-17 03:33:10 +0000229/// Arrange the argument and result information for a declaration or
230/// definition of the given C++ non-static member function. The
231/// member function must be an ordinary function, i.e. not a
232/// constructor or destructor.
233const CGFunctionInfo &
234CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000235 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000236 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
237
John McCalla729c622012-02-17 03:33:10 +0000238 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000239
John McCalla729c622012-02-17 03:33:10 +0000240 if (MD->isInstance()) {
241 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000242 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000243 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000244 }
245
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000246 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000247}
248
Richard Smith5179eb72016-06-28 19:03:57 +0000249bool CodeGenTypes::inheritingCtorHasParams(
250 const InheritedConstructor &Inherited, CXXCtorType Type) {
251 // Parameters are unnecessary if we're constructing a base class subobject
252 // and the inherited constructor lives in a virtual base.
253 return Type == Ctor_Complete ||
254 !Inherited.getShadowDecl()->constructsVirtualBase() ||
255 !Target.getCXXABI().hasConstructorVariants();
256 }
257
John McCalla729c622012-02-17 03:33:10 +0000258const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000259CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
260 StructorType Type) {
261
John McCalla729c622012-02-17 03:33:10 +0000262 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000263 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000264 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000265
Richard Smith5179eb72016-06-28 19:03:57 +0000266 bool PassParams = true;
267
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 GlobalDecl GD;
269 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
270 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000271
272 // A base class inheriting constructor doesn't get forwarded arguments
273 // needed to construct a virtual base (or base class thereof).
274 if (auto Inherited = CD->getInheritedConstructor())
275 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000276 } else {
277 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
278 GD = GlobalDecl(DD, toCXXDtorType(Type));
279 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000280
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000281 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000282
283 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000284 if (PassParams)
285 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000286
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000287 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000288
289 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000290 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
291 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000292
John McCall8dda7b22012-07-07 06:41:13 +0000293 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000294 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
295 ? argTypes.front()
296 : TheCXXABI.hasMostDerivedReturn(GD)
297 ? CGM.getContext().VoidPtrTy
298 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000299 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
300 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000301 paramInfos, required);
302}
303
304static SmallVector<CanQualType, 16>
305getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
306 SmallVector<CanQualType, 16> argTypes;
307 for (auto &arg : args)
308 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
309 return argTypes;
310}
311
312static SmallVector<CanQualType, 16>
313getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
314 SmallVector<CanQualType, 16> argTypes;
315 for (auto &arg : args)
316 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
317 return argTypes;
318}
319
320static void addExtParameterInfosForCall(
321 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
322 const FunctionProtoType *proto,
323 unsigned prefixArgs,
324 unsigned totalArgs) {
325 assert(proto->hasExtParameterInfos());
326 assert(paramInfos.size() <= prefixArgs);
327 assert(proto->getNumParams() + prefixArgs <= totalArgs);
328
329 // Add default infos for any prefix args that don't already have infos.
330 paramInfos.resize(prefixArgs);
331
332 // Add infos for the prototype.
333 auto protoInfos = proto->getExtParameterInfos();
334 paramInfos.append(protoInfos.begin(), protoInfos.end());
335
336 // Add default infos for the variadic arguments.
337 paramInfos.resize(totalArgs);
338}
339
340static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
341getExtParameterInfosForCall(const FunctionProtoType *proto,
342 unsigned prefixArgs, unsigned totalArgs) {
343 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
344 if (proto->hasExtParameterInfos()) {
345 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
346 }
347 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000348}
349
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000350/// Arrange a call to a C++ method, passing the given arguments.
351const CGFunctionInfo &
352CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
353 const CXXConstructorDecl *D,
354 CXXCtorType CtorKind,
355 unsigned ExtraArgs) {
356 // FIXME: Kill copy.
357 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000358 for (const auto &Arg : args)
359 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000360
361 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000362 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000363 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000364 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
365 ? ArgTypes.front()
366 : TheCXXABI.hasMostDerivedReturn(GD)
367 ? CGM.getContext().VoidPtrTy
368 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000369
370 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000371 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
372 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000373 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
374 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000375 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000376}
377
John McCalla729c622012-02-17 03:33:10 +0000378/// Arrange the argument and result information for the declaration or
379/// definition of the given function.
380const CGFunctionInfo &
381CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000382 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000383 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000384 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000385
John McCall2da83a32010-02-26 00:48:12 +0000386 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000387
John McCall2da83a32010-02-26 00:48:12 +0000388 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000389
390 // When declaring a function without a prototype, always use a
391 // non-variadic type.
392 if (isa<FunctionNoProtoType>(FTy)) {
393 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000394 return arrangeLLVMFunctionInfo(
395 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000396 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000397 }
398
John McCall2da83a32010-02-26 00:48:12 +0000399 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000400 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000401}
402
John McCalla729c622012-02-17 03:33:10 +0000403/// Arrange the argument and result information for the declaration or
404/// definition of an Objective-C method.
405const CGFunctionInfo &
406CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
407 // It happens that this is the same as a call with no optional
408 // arguments, except also using the formal 'self' type.
409 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
410}
411
412/// Arrange the argument and result information for the function type
413/// through which to perform a send to the given Objective-C method,
414/// using the given receiver type. The receiver type is not always
415/// the 'self' type of the method or even an Objective-C pointer type.
416/// This is *not* the right method for actually performing such a
417/// message send, due to the possibility of optional arguments.
418const CGFunctionInfo &
419CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
420 QualType receiverType) {
421 SmallVector<CanQualType, 16> argTys;
422 argTys.push_back(Context.getCanonicalParamType(receiverType));
423 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000424 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000425 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000426 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000427 }
John McCall31168b02011-06-15 23:02:42 +0000428
429 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000430 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
431 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000432
David Blaikiebbafb8a2012-03-11 07:00:24 +0000433 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000434 MD->hasAttr<NSReturnsRetainedAttr>())
435 einfo = einfo.withProducesResult(true);
436
John McCalla729c622012-02-17 03:33:10 +0000437 RequiredArgs required =
438 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
439
Peter Collingbournef7706832014-12-12 23:41:25 +0000440 return arrangeLLVMFunctionInfo(
441 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000442 /*chainCall=*/false, argTys, einfo, {}, required);
443}
444
445const CGFunctionInfo &
446CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
447 const CallArgList &args) {
448 auto argTypes = getArgTypesForCall(Context, args);
449 FunctionType::ExtInfo einfo;
450
451 return arrangeLLVMFunctionInfo(
452 GetReturnType(returnType), /*instanceMethod=*/false,
453 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000454}
455
John McCalla729c622012-02-17 03:33:10 +0000456const CGFunctionInfo &
457CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000458 // FIXME: Do we need to handle ObjCMethodDecl?
459 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000460
Anders Carlsson6710c532010-02-06 02:44:09 +0000461 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000462 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000463
464 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000465 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000466
John McCalla729c622012-02-17 03:33:10 +0000467 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000468}
469
Reid Klecknerc3473512014-08-29 21:43:29 +0000470/// Arrange a thunk that takes 'this' as the first parameter followed by
471/// varargs. Return a void pointer, regardless of the actual return type.
472/// The body of the thunk will end in a musttail call to a function of the
473/// correct type, and the caller will bitcast the function to the correct
474/// prototype.
475const CGFunctionInfo &
476CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
477 assert(MD->isVirtual() && "only virtual memptrs have thunks");
478 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
479 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000480 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
481 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000482 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000483}
484
David Majnemerdfa6d202015-03-11 18:36:39 +0000485const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000486CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
487 CXXCtorType CT) {
488 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
489
David Majnemerdfa6d202015-03-11 18:36:39 +0000490 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
491 SmallVector<CanQualType, 2> ArgTys;
492 const CXXRecordDecl *RD = CD->getParent();
493 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000494 if (CT == Ctor_CopyingClosure)
495 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000496 if (RD->getNumVBases() > 0)
497 ArgTys.push_back(Context.IntTy);
498 CallingConv CC = Context.getDefaultCallingConvention(
499 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
500 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
501 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000502 FunctionType::ExtInfo(CC), {},
503 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000504}
505
John McCallc818bbb2012-12-07 07:03:17 +0000506/// Arrange a call as unto a free function, except possibly with an
507/// additional number of formal parameters considered required.
508static const CGFunctionInfo &
509arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000510 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000511 const CallArgList &args,
512 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000513 unsigned numExtraRequiredArgs,
514 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000515 assert(args.size() >= numExtraRequiredArgs);
516
John McCallc56a8b32016-03-11 04:30:31 +0000517 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
518
John McCallc818bbb2012-12-07 07:03:17 +0000519 // In most cases, there are no optional arguments.
520 RequiredArgs required = RequiredArgs::All;
521
522 // If we have a variadic prototype, the required arguments are the
523 // extra prefix plus the arguments in the prototype.
524 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
525 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000526 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000527
John McCallc56a8b32016-03-11 04:30:31 +0000528 if (proto->hasExtParameterInfos())
529 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
530 args.size());
531
John McCallc818bbb2012-12-07 07:03:17 +0000532 // If we don't have a prototype at all, but we're supposed to
533 // explicitly use the variadic convention for unprototyped calls,
534 // treat all of the arguments as required but preserve the nominal
535 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000536 } else if (CGM.getTargetCodeGenInfo()
537 .isNoProtoCallVariadic(args,
538 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000539 required = RequiredArgs(args.size());
540 }
541
Peter Collingbournef7706832014-12-12 23:41:25 +0000542 // FIXME: Kill copy.
543 SmallVector<CanQualType, 16> argTypes;
544 for (const auto &arg : args)
545 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
546 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
547 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000548 argTypes, fnType->getExtInfo(), paramInfos,
549 required);
John McCallc818bbb2012-12-07 07:03:17 +0000550}
551
John McCalla729c622012-02-17 03:33:10 +0000552/// Figure out the rules for calling a function with the given formal
553/// type using the given arguments. The arguments are necessary
554/// because the function might be unprototyped, in which case it's
555/// target-dependent in crazy ways.
556const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000557CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000558 const FunctionType *fnType,
559 bool chainCall) {
560 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
561 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000562}
John McCalla729c622012-02-17 03:33:10 +0000563
John McCallc56a8b32016-03-11 04:30:31 +0000564/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000565/// extra implicit argument.
566const CGFunctionInfo &
567CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
568 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000569 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
570 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000571}
572
573const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000574CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
575 const FunctionArgList &params) {
576 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
577 auto argTypes = getArgTypesForDeclaration(Context, params);
578
George Burgess IV419996c2016-06-16 23:06:04 +0000579 return arrangeLLVMFunctionInfo(
580 GetReturnType(proto->getReturnType()),
581 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
582 proto->getExtInfo(), paramInfos,
583 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000584}
585
586const CGFunctionInfo &
587CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
588 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000589 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000590 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000591 for (const auto &Arg : args)
592 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000593 return arrangeLLVMFunctionInfo(
594 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000595 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
596 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000597}
598
John McCallc56a8b32016-03-11 04:30:31 +0000599const CGFunctionInfo &
600CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
601 const FunctionArgList &args) {
602 auto argTypes = getArgTypesForDeclaration(Context, args);
603
604 return arrangeLLVMFunctionInfo(
605 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
606 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
607}
608
609const CGFunctionInfo &
610CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
611 ArrayRef<CanQualType> argTypes) {
612 return arrangeLLVMFunctionInfo(
613 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
614 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
615}
616
John McCall8dda7b22012-07-07 06:41:13 +0000617/// Arrange a call to a C++ method, passing the given arguments.
618const CGFunctionInfo &
619CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000620 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000621 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000622 unsigned numRequiredArgs =
623 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
624 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
625 auto paramInfos =
626 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
627
John McCall8dda7b22012-07-07 06:41:13 +0000628 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000629 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000630
John McCallc56a8b32016-03-11 04:30:31 +0000631 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000632 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000633 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
634 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000635}
636
John McCalla729c622012-02-17 03:33:10 +0000637const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000638 return arrangeLLVMFunctionInfo(
639 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000640 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
641}
642
643const CGFunctionInfo &
644CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
645 const CallArgList &args) {
646 assert(signature.arg_size() <= args.size());
647 if (signature.arg_size() == args.size())
648 return signature;
649
650 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
651 auto sigParamInfos = signature.getExtParameterInfos();
652 if (!sigParamInfos.empty()) {
653 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
654 paramInfos.resize(args.size());
655 }
656
657 auto argTypes = getArgTypesForCall(Context, args);
658
659 assert(signature.getRequiredArgs().allowsOptionalArgs());
660 return arrangeLLVMFunctionInfo(signature.getReturnType(),
661 signature.isInstanceMethod(),
662 signature.isChainCall(),
663 argTypes,
664 signature.getExtInfo(),
665 paramInfos,
666 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000667}
668
John McCalla729c622012-02-17 03:33:10 +0000669/// Arrange the argument and result information for an abstract value
670/// of a given function type. This is the method which all of the
671/// above functions ultimately defer to.
672const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000673CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000674 bool instanceMethod,
675 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000676 ArrayRef<CanQualType> argTypes,
677 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000678 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000679 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000680 assert(std::all_of(argTypes.begin(), argTypes.end(),
681 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000682
Daniel Dunbare0be8292009-02-03 00:07:12 +0000683 // Lookup or create unique function info.
684 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000685 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
686 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000687
Craig Topper8a13c412014-05-21 05:09:00 +0000688 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000689 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000690 if (FI)
691 return *FI;
692
John McCallc56a8b32016-03-11 04:30:31 +0000693 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
694
John McCalla729c622012-02-17 03:33:10 +0000695 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000696 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000697 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000698 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000699
David Blaikie82e95a32014-11-19 07:49:47 +0000700 bool inserted = FunctionsBeingProcessed.insert(FI).second;
701 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000702 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000703
Daniel Dunbar313321e2009-02-03 05:31:23 +0000704 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000705 if (info.getCC() != CC_Swift) {
706 getABIInfo().computeInfo(*FI);
707 } else {
708 swiftcall::computeABIInfo(CGM, *FI);
709 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000710
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000711 // Loop over all of the computed argument and return value info. If any of
712 // them are direct or extend without a specified coerce type, specify the
713 // default now.
John McCalla729c622012-02-17 03:33:10 +0000714 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000715 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000716 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000717
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000718 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000719 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000720 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000721
John McCalla729c622012-02-17 03:33:10 +0000722 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
723 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000724
Daniel Dunbare0be8292009-02-03 00:07:12 +0000725 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000726}
727
John McCalla729c622012-02-17 03:33:10 +0000728CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000729 bool instanceMethod,
730 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000731 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000732 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000733 CanQualType resultType,
734 ArrayRef<CanQualType> argTypes,
735 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000736 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
737
738 void *buffer =
739 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
740 argTypes.size() + 1, paramInfos.size()));
741
John McCalla729c622012-02-17 03:33:10 +0000742 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
743 FI->CallingConvention = llvmCC;
744 FI->EffectiveCallingConvention = llvmCC;
745 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000746 FI->InstanceMethod = instanceMethod;
747 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000748 FI->NoReturn = info.getNoReturn();
749 FI->ReturnsRetained = info.getProducesResult();
750 FI->Required = required;
751 FI->HasRegParm = info.getHasRegParm();
752 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000753 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000754 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000755 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000756 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000757 FI->getArgsBuffer()[0].type = resultType;
758 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
759 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000760 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
761 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000762 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000763}
764
765/***/
766
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000767namespace {
768// ABIArgInfo::Expand implementation.
769
770// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
771struct TypeExpansion {
772 enum TypeExpansionKind {
773 // Elements of constant arrays are expanded recursively.
774 TEK_ConstantArray,
775 // Record fields are expanded recursively (but if record is a union, only
776 // the field with the largest size is expanded).
777 TEK_Record,
778 // For complex types, real and imaginary parts are expanded recursively.
779 TEK_Complex,
780 // All other types are not expandable.
781 TEK_None
782 };
783
784 const TypeExpansionKind Kind;
785
786 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000787 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000788};
789
790struct ConstantArrayExpansion : TypeExpansion {
791 QualType EltTy;
792 uint64_t NumElts;
793
794 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
795 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
796 static bool classof(const TypeExpansion *TE) {
797 return TE->Kind == TEK_ConstantArray;
798 }
799};
800
801struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000802 SmallVector<const CXXBaseSpecifier *, 1> Bases;
803
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000804 SmallVector<const FieldDecl *, 1> Fields;
805
Reid Klecknere9f6a712014-10-31 17:10:41 +0000806 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
807 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000808 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
809 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000810 static bool classof(const TypeExpansion *TE) {
811 return TE->Kind == TEK_Record;
812 }
813};
814
815struct ComplexExpansion : TypeExpansion {
816 QualType EltTy;
817
818 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
819 static bool classof(const TypeExpansion *TE) {
820 return TE->Kind == TEK_Complex;
821 }
822};
823
824struct NoExpansion : TypeExpansion {
825 NoExpansion() : TypeExpansion(TEK_None) {}
826 static bool classof(const TypeExpansion *TE) {
827 return TE->Kind == TEK_None;
828 }
829};
830} // namespace
831
832static std::unique_ptr<TypeExpansion>
833getTypeExpansion(QualType Ty, const ASTContext &Context) {
834 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
835 return llvm::make_unique<ConstantArrayExpansion>(
836 AT->getElementType(), AT->getSize().getZExtValue());
837 }
838 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000839 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000840 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000841 const RecordDecl *RD = RT->getDecl();
842 assert(!RD->hasFlexibleArrayMember() &&
843 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000844 if (RD->isUnion()) {
845 // Unions can be here only in degenerative cases - all the fields are same
846 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000847 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000848 CharUnits UnionSize = CharUnits::Zero();
849
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000850 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000851 // Skip zero length bitfields.
852 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
853 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000854 assert(!FD->isBitField() &&
855 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000856 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000857 if (UnionSize < FieldSize) {
858 UnionSize = FieldSize;
859 LargestFD = FD;
860 }
861 }
862 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000863 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000864 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000865 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
866 assert(!CXXRD->isDynamicClass() &&
867 "cannot expand vtable pointers in dynamic classes");
868 for (const CXXBaseSpecifier &BS : CXXRD->bases())
869 Bases.push_back(&BS);
870 }
871
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000872 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000873 // Skip zero length bitfields.
874 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
875 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000876 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000877 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000878 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000879 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000880 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000881 return llvm::make_unique<RecordExpansion>(std::move(Bases),
882 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000883 }
884 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
885 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
886 }
887 return llvm::make_unique<NoExpansion>();
888}
889
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000890static int getExpansionSize(QualType Ty, const ASTContext &Context) {
891 auto Exp = getTypeExpansion(Ty, Context);
892 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
893 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
894 }
895 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
896 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000897 for (auto BS : RExp->Bases)
898 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000899 for (auto FD : RExp->Fields)
900 Res += getExpansionSize(FD->getType(), Context);
901 return Res;
902 }
903 if (isa<ComplexExpansion>(Exp.get()))
904 return 2;
905 assert(isa<NoExpansion>(Exp.get()));
906 return 1;
907}
908
Alexey Samsonov153004f2014-09-29 22:08:00 +0000909void
910CodeGenTypes::getExpandedTypes(QualType Ty,
911 SmallVectorImpl<llvm::Type *>::iterator &TI) {
912 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000913 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
914 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000915 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000916 }
917 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000918 for (auto BS : RExp->Bases)
919 getExpandedTypes(BS->getType(), TI);
920 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000921 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000922 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
923 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000924 *TI++ = EltTy;
925 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000926 } else {
927 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000928 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000929 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000930}
931
John McCall7f416cc2015-09-08 08:05:57 +0000932static void forConstantArrayExpansion(CodeGenFunction &CGF,
933 ConstantArrayExpansion *CAE,
934 Address BaseAddr,
935 llvm::function_ref<void(Address)> Fn) {
936 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
937 CharUnits EltAlign =
938 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
939
940 for (int i = 0, n = CAE->NumElts; i < n; i++) {
941 llvm::Value *EltAddr =
942 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
943 Fn(Address(EltAddr, EltAlign));
944 }
945}
946
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000947void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000948 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000949 assert(LV.isSimple() &&
950 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000951
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000952 auto Exp = getTypeExpansion(Ty, getContext());
953 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000954 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
955 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000956 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
957 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000958 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000959 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000960 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000961 for (const CXXBaseSpecifier *BS : RExp->Bases) {
962 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000963 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000964 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
965 /*NullCheckValue=*/false, SourceLocation());
966 LValue SubLV = MakeAddrLValue(Base, BS->getType());
967
968 // Recurse onto bases.
969 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
970 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000971 for (auto FD : RExp->Fields) {
972 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000973 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000974 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000975 }
John McCall7f416cc2015-09-08 08:05:57 +0000976 } else if (isa<ComplexExpansion>(Exp.get())) {
977 auto realValue = *AI++;
978 auto imagValue = *AI++;
979 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000980 } else {
981 assert(isa<NoExpansion>(Exp.get()));
982 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000983 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000984}
985
986void CodeGenFunction::ExpandTypeToArgs(
987 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
988 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
989 auto Exp = getTypeExpansion(Ty, getContext());
990 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000991 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
992 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000993 RValue EltRV =
994 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
995 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000996 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000997 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000998 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000999 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1000 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001001 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001002 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1003 /*NullCheckValue=*/false, SourceLocation());
1004 RValue BaseRV = RValue::getAggregate(Base);
1005
1006 // Recurse onto bases.
1007 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1008 IRCallArgPos);
1009 }
1010
1011 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001012 for (auto FD : RExp->Fields) {
1013 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1014 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1015 IRCallArgPos);
1016 }
1017 } else if (isa<ComplexExpansion>(Exp.get())) {
1018 ComplexPairTy CV = RV.getComplexVal();
1019 IRCallArgs[IRCallArgPos++] = CV.first;
1020 IRCallArgs[IRCallArgPos++] = CV.second;
1021 } else {
1022 assert(isa<NoExpansion>(Exp.get()));
1023 assert(RV.isScalar() &&
1024 "Unexpected non-scalar rvalue during struct expansion.");
1025
1026 // Insert a bitcast as needed.
1027 llvm::Value *V = RV.getScalarVal();
1028 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1029 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1030 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1031
1032 IRCallArgs[IRCallArgPos++] = V;
1033 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001034}
1035
John McCall7f416cc2015-09-08 08:05:57 +00001036/// Create a temporary allocation for the purposes of coercion.
1037static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1038 CharUnits MinAlign) {
1039 // Don't use an alignment that's worse than what LLVM would prefer.
1040 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1041 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1042
1043 return CGF.CreateTempAlloca(Ty, Align);
1044}
1045
Chris Lattner895c52b2010-06-27 06:04:18 +00001046/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001047/// accessing some number of bytes out of it, try to gep into the struct to get
1048/// at its inner goodness. Dive as deep as possible without entering an element
1049/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001050static Address
1051EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001052 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001053 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001054 // We can't dive into a zero-element struct.
1055 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001056
Chris Lattner2192fe52011-07-18 04:24:23 +00001057 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001058
Chris Lattner1cd66982010-06-27 05:56:15 +00001059 // 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 +00001060 // first element is the same size as the whole struct, we can enter it. The
1061 // comparison must be made on the store size and not the alloca size. Using
1062 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001063 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001064 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001065 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001066 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001067 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001068
Chris Lattner1cd66982010-06-27 05:56:15 +00001069 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001070 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001071
Chris Lattner1cd66982010-06-27 05:56:15 +00001072 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001073 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001074 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001075 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001076
1077 return SrcPtr;
1078}
1079
Chris Lattner055097f2010-06-27 06:26:04 +00001080/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1081/// are either integers or pointers. This does a truncation of the value if it
1082/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001083///
1084/// This behaves as if the value were coerced through memory, so on big-endian
1085/// targets the high bits are preserved in a truncation, while little-endian
1086/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001087static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001088 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001089 CodeGenFunction &CGF) {
1090 if (Val->getType() == Ty)
1091 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001092
Chris Lattner055097f2010-06-27 06:26:04 +00001093 if (isa<llvm::PointerType>(Val->getType())) {
1094 // If this is Pointer->Pointer avoid conversion to and from int.
1095 if (isa<llvm::PointerType>(Ty))
1096 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001097
Chris Lattner055097f2010-06-27 06:26:04 +00001098 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001099 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001100 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001101
Chris Lattner2192fe52011-07-18 04:24:23 +00001102 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001103 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001104 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001105
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001106 if (Val->getType() != DestIntTy) {
1107 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1108 if (DL.isBigEndian()) {
1109 // Preserve the high bits on big-endian targets.
1110 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001111 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1112 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1113
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001114 if (SrcSize > DstSize) {
1115 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1116 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1117 } else {
1118 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1119 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1120 }
1121 } else {
1122 // Little-endian targets preserve the low bits. No shifts required.
1123 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1124 }
1125 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001126
Chris Lattner055097f2010-06-27 06:26:04 +00001127 if (isa<llvm::PointerType>(Ty))
1128 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1129 return Val;
1130}
1131
Chris Lattner1cd66982010-06-27 05:56:15 +00001132
1133
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001134/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001135/// a pointer to an object of type \arg Ty, known to be aligned to
1136/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001137///
1138/// This safely handles the case when the src type is smaller than the
1139/// destination type; in this situation the values of bits which not
1140/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001141static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001142 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001143 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001144
Chris Lattnerd200eda2010-06-28 22:51:39 +00001145 // If SrcTy and Ty are the same, just do a load.
1146 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001147 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001148
Micah Villmowdd31ca12012-10-08 16:25:52 +00001149 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001150
Chris Lattner2192fe52011-07-18 04:24:23 +00001151 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001152 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1153 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001154 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001155
Micah Villmowdd31ca12012-10-08 16:25:52 +00001156 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001157
Chris Lattner055097f2010-06-27 06:26:04 +00001158 // If the source and destination are integer or pointer types, just do an
1159 // extension or truncation to the desired type.
1160 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1161 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001162 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001163 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1164 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001165
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001166 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001167 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001168 // Generally SrcSize is never greater than DstSize, since this means we are
1169 // losing bits. However, this can happen in cases where the structure has
1170 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001171 //
Mike Stump18bb9282009-05-16 07:57:57 +00001172 // FIXME: Assert that we aren't truncating non-padding bits when have access
1173 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001174 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1175 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001176 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001177
John McCall7f416cc2015-09-08 08:05:57 +00001178 // Otherwise do coercion through memory. This is stupid, but simple.
1179 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1180 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1181 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001182 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1183 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001184 false);
1185 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001186}
1187
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001188// Function to store a first-class aggregate into memory. We prefer to
1189// store the elements rather than the aggregate to be more friendly to
1190// fast-isel.
1191// FIXME: Do we need to recurse here?
1192static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001193 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001194 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001195 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001196 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001197 const llvm::StructLayout *Layout =
1198 CGF.CGM.getDataLayout().getStructLayout(STy);
1199
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001200 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001201 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1202 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001203 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001204 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001205 }
1206 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001207 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001208 }
1209}
1210
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001211/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001212/// where the source and destination may have different types. The
1213/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001214///
1215/// This safely handles the case when the src type is larger than the
1216/// destination type; the upper bits of the src will be lost.
1217static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001218 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001219 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001220 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001221 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001222 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001223 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001224 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001225 return;
1226 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001227
Micah Villmowdd31ca12012-10-08 16:25:52 +00001228 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001229
Chris Lattner2192fe52011-07-18 04:24:23 +00001230 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001231 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1232 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001233 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001234
Chris Lattner055097f2010-06-27 06:26:04 +00001235 // If the source and destination are integer or pointer types, just do an
1236 // extension or truncation to the desired type.
1237 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1238 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1239 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001240 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001241 return;
1242 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001243
Micah Villmowdd31ca12012-10-08 16:25:52 +00001244 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001245
Daniel Dunbar313321e2009-02-03 05:31:23 +00001246 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001247 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001248 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1249 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001250 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001251 // Otherwise do coercion through memory. This is stupid, but
1252 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001253
1254 // Generally SrcSize is never greater than DstSize, since this means we are
1255 // losing bits. However, this can happen in cases where the structure has
1256 // additional padding, for example due to a user specified alignment.
1257 //
1258 // FIXME: Assert that we aren't truncating non-padding bits when have access
1259 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001260 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1261 CGF.Builder.CreateStore(Src, Tmp);
1262 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1263 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001264 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1265 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001266 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001267 }
1268}
1269
John McCall7f416cc2015-09-08 08:05:57 +00001270static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1271 const ABIArgInfo &info) {
1272 if (unsigned offset = info.getDirectOffset()) {
1273 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1274 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1275 CharUnits::fromQuantity(offset));
1276 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1277 }
1278 return addr;
1279}
1280
Alexey Samsonov153004f2014-09-29 22:08:00 +00001281namespace {
1282
1283/// Encapsulates information about the way function arguments from
1284/// CGFunctionInfo should be passed to actual LLVM IR function.
1285class ClangToLLVMArgMapping {
1286 static const unsigned InvalidIndex = ~0U;
1287 unsigned InallocaArgNo;
1288 unsigned SRetArgNo;
1289 unsigned TotalIRArgs;
1290
1291 /// Arguments of LLVM IR function corresponding to single Clang argument.
1292 struct IRArgs {
1293 unsigned PaddingArgIndex;
1294 // Argument is expanded to IR arguments at positions
1295 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1296 unsigned FirstArgIndex;
1297 unsigned NumberOfArgs;
1298
1299 IRArgs()
1300 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1301 NumberOfArgs(0) {}
1302 };
1303
1304 SmallVector<IRArgs, 8> ArgInfo;
1305
1306public:
1307 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1308 bool OnlyRequiredArgs = false)
1309 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1310 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1311 construct(Context, FI, OnlyRequiredArgs);
1312 }
1313
1314 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1315 unsigned getInallocaArgNo() const {
1316 assert(hasInallocaArg());
1317 return InallocaArgNo;
1318 }
1319
1320 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1321 unsigned getSRetArgNo() const {
1322 assert(hasSRetArg());
1323 return SRetArgNo;
1324 }
1325
1326 unsigned totalIRArgs() const { return TotalIRArgs; }
1327
1328 bool hasPaddingArg(unsigned ArgNo) const {
1329 assert(ArgNo < ArgInfo.size());
1330 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1331 }
1332 unsigned getPaddingArgNo(unsigned ArgNo) const {
1333 assert(hasPaddingArg(ArgNo));
1334 return ArgInfo[ArgNo].PaddingArgIndex;
1335 }
1336
1337 /// Returns index of first IR argument corresponding to ArgNo, and their
1338 /// quantity.
1339 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1340 assert(ArgNo < ArgInfo.size());
1341 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1342 ArgInfo[ArgNo].NumberOfArgs);
1343 }
1344
1345private:
1346 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1347 bool OnlyRequiredArgs);
1348};
1349
1350void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1351 const CGFunctionInfo &FI,
1352 bool OnlyRequiredArgs) {
1353 unsigned IRArgNo = 0;
1354 bool SwapThisWithSRet = false;
1355 const ABIArgInfo &RetAI = FI.getReturnInfo();
1356
1357 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1358 SwapThisWithSRet = RetAI.isSRetAfterThis();
1359 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1360 }
1361
1362 unsigned ArgNo = 0;
1363 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1364 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1365 ++I, ++ArgNo) {
1366 assert(I != FI.arg_end());
1367 QualType ArgType = I->type;
1368 const ABIArgInfo &AI = I->info;
1369 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1370 auto &IRArgs = ArgInfo[ArgNo];
1371
1372 if (AI.getPaddingType())
1373 IRArgs.PaddingArgIndex = IRArgNo++;
1374
1375 switch (AI.getKind()) {
1376 case ABIArgInfo::Extend:
1377 case ABIArgInfo::Direct: {
1378 // FIXME: handle sseregparm someday...
1379 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1380 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1381 IRArgs.NumberOfArgs = STy->getNumElements();
1382 } else {
1383 IRArgs.NumberOfArgs = 1;
1384 }
1385 break;
1386 }
1387 case ABIArgInfo::Indirect:
1388 IRArgs.NumberOfArgs = 1;
1389 break;
1390 case ABIArgInfo::Ignore:
1391 case ABIArgInfo::InAlloca:
1392 // ignore and inalloca doesn't have matching LLVM parameters.
1393 IRArgs.NumberOfArgs = 0;
1394 break;
John McCallf26e73d2016-03-11 04:30:43 +00001395 case ABIArgInfo::CoerceAndExpand:
1396 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1397 break;
1398 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001399 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1400 break;
1401 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001402
1403 if (IRArgs.NumberOfArgs > 0) {
1404 IRArgs.FirstArgIndex = IRArgNo;
1405 IRArgNo += IRArgs.NumberOfArgs;
1406 }
1407
1408 // Skip over the sret parameter when it comes second. We already handled it
1409 // above.
1410 if (IRArgNo == 1 && SwapThisWithSRet)
1411 IRArgNo++;
1412 }
1413 assert(ArgNo == ArgInfo.size());
1414
1415 if (FI.usesInAlloca())
1416 InallocaArgNo = IRArgNo++;
1417
1418 TotalIRArgs = IRArgNo;
1419}
1420} // namespace
1421
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001422/***/
1423
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001424bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001425 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001426}
1427
Tim Northovere77cc392014-03-29 13:28:05 +00001428bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1429 return ReturnTypeUsesSRet(FI) &&
1430 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1431}
1432
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001433bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1434 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1435 switch (BT->getKind()) {
1436 default:
1437 return false;
1438 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001439 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001440 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001441 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001442 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001443 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001444 }
1445 }
1446
1447 return false;
1448}
1449
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001450bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1451 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1452 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1453 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001454 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001455 }
1456 }
1457
1458 return false;
1459}
1460
Chris Lattnera5f58b02011-07-09 17:41:47 +00001461llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001462 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1463 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001464}
1465
Chris Lattnera5f58b02011-07-09 17:41:47 +00001466llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001467CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001468
David Blaikie82e95a32014-11-19 07:49:47 +00001469 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1470 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001471 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001472
Alexey Samsonov153004f2014-09-29 22:08:00 +00001473 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001474 const ABIArgInfo &retAI = FI.getReturnInfo();
1475 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001476 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001477 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001478
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001479 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001480 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001481 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001482 break;
1483
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001484 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001485 if (retAI.getInAllocaSRet()) {
1486 // sret things on win32 aren't void, they return the sret pointer.
1487 QualType ret = FI.getReturnType();
1488 llvm::Type *ty = ConvertType(ret);
1489 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1490 resultType = llvm::PointerType::get(ty, addressSpace);
1491 } else {
1492 resultType = llvm::Type::getVoidTy(getLLVMContext());
1493 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001494 break;
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001497 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001498 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001499 break;
John McCallf26e73d2016-03-11 04:30:43 +00001500
1501 case ABIArgInfo::CoerceAndExpand:
1502 resultType = retAI.getUnpaddedCoerceAndExpandType();
1503 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Alexey Samsonov153004f2014-09-29 22:08:00 +00001506 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1507 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1508
1509 // Add type for sret argument.
1510 if (IRFunctionArgs.hasSRetArg()) {
1511 QualType Ret = FI.getReturnType();
1512 llvm::Type *Ty = ConvertType(Ret);
1513 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1514 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1515 llvm::PointerType::get(Ty, AddressSpace);
1516 }
1517
1518 // Add type for inalloca argument.
1519 if (IRFunctionArgs.hasInallocaArg()) {
1520 auto ArgStruct = FI.getArgStruct();
1521 assert(ArgStruct);
1522 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1523 }
1524
John McCallc818bbb2012-12-07 07:03:17 +00001525 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001526 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001527 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1528 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001529 for (; it != ie; ++it, ++ArgNo) {
1530 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Rafael Espindolafad28de2012-10-24 01:59:00 +00001532 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001533 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1534 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1535 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001536
Alexey Samsonov153004f2014-09-29 22:08:00 +00001537 unsigned FirstIRArg, NumIRArgs;
1538 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1539
1540 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001541 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001542 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001543 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001544 break;
1545
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001546 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001547 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001548 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001549 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001550 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001551 break;
1552 }
1553
1554 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001555 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001556 // Fast-isel and the optimizer generally like scalar values better than
1557 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001558 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001559 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001560 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1561 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001562 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001563 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001564 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001565 assert(NumIRArgs == 1);
1566 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001567 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001568 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
John McCallf26e73d2016-03-11 04:30:43 +00001571 case ABIArgInfo::CoerceAndExpand: {
1572 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1573 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1574 *ArgTypesIter++ = EltTy;
1575 }
1576 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1577 break;
1578 }
1579
Daniel Dunbard3674e62008-09-11 01:48:57 +00001580 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001581 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1582 getExpandedTypes(it->type, ArgTypesIter);
1583 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001584 break;
1585 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001586 }
1587
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001588 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1589 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001590
1591 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001592}
1593
Chris Lattner2192fe52011-07-18 04:24:23 +00001594llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001595 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001596 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001597
Chris Lattner8806e322011-07-10 00:18:59 +00001598 if (!isFuncTypeConvertible(FPT))
1599 return llvm::StructType::get(getLLVMContext());
1600
1601 const CGFunctionInfo *Info;
1602 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001603 Info =
1604 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001605 else
John McCalla729c622012-02-17 03:33:10 +00001606 Info = &arrangeCXXMethodDeclaration(MD);
1607 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001608}
1609
Samuel Antao798f11c2015-11-23 22:04:44 +00001610static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1611 llvm::AttrBuilder &FuncAttrs,
1612 const FunctionProtoType *FPT) {
1613 if (!FPT)
1614 return;
1615
1616 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1617 FPT->isNothrow(Ctx))
1618 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1619}
1620
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001621void CodeGenModule::ConstructAttributeList(
1622 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1623 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001624 llvm::AttrBuilder FuncAttrs;
1625 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001626 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001627
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001628 CallingConv = FI.getEffectiveCallingConvention();
1629
John McCallab26cfa2010-02-05 21:31:56 +00001630 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001631 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001632
Samuel Antao798f11c2015-11-23 22:04:44 +00001633 // If we have information about the function prototype, we can learn
1634 // attributes form there.
1635 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1636 CalleeInfo.getCalleeFunctionProtoType());
1637
1638 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1639
Amjad Aboudfaea5602016-03-07 14:22:46 +00001640 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001641 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001642 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001643 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001644 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001645 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001646 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001647 if (TargetDecl->hasAttr<NoReturnAttr>())
1648 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001649 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1650 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001651
1652 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001653 AddAttributesFromFunctionProtoType(
1654 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001655 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1656 // These attributes are not inherited by overloads.
1657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1658 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001659 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001660 }
1661
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001662 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001663 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001664 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1665 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001666 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001667 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1668 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001669 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1670 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1671 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001672 }
David Majnemer631a90b2015-02-04 07:23:21 +00001673 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001674 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001675 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1676 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001677
Amjad Aboudfaea5602016-03-07 14:22:46 +00001678 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001679 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001680 }
1681
Paul Robinson08556952014-12-11 20:14:04 +00001682 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1683 if (!HasOptnone) {
1684 if (CodeGenOpts.OptimizeSize)
1685 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1686 if (CodeGenOpts.OptimizeSize == 2)
1687 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1688 }
1689
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001690 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001691 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001692 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001693 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001694 if (CodeGenOpts.EnableSegmentedStacks &&
1695 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001696 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001697
Bill Wendling2f81db62013-02-22 20:53:29 +00001698 if (AttrOnCallSite) {
1699 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001700 if (!CodeGenOpts.SimplifyLibCalls ||
1701 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001702 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001703 if (!CodeGenOpts.TrapFuncName.empty())
1704 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001705 } else {
1706 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001707 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001708 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001709 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001710 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001711 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001712 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001713 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001714 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001715 }
1716
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001717 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001718 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001719 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001720 FuncAttrs.addAttribute(
1721 "disable-tail-calls",
1722 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001723
Bill Wendlingdabafea2013-03-13 22:24:33 +00001724 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001725 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001726
1727 if (!CodeGenOpts.FPDenormalMode.empty())
1728 FuncAttrs.addAttribute("denormal-fp-math",
1729 CodeGenOpts.FPDenormalMode);
1730
1731 FuncAttrs.addAttribute("no-trapping-math",
1732 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
Sanjay Patel0bb72c12016-10-04 20:44:05 +00001733
1734 // TODO: Are these all needed?
1735 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
Bill Wendlingdabafea2013-03-13 22:24:33 +00001736 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001737 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001738 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001739 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001740 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001741 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001742 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001743 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001744 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001745 llvm::utostr(CodeGenOpts.SSPBufferSize));
Yaxun Liu79c99fb2016-07-08 20:28:29 +00001746 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1747 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
Yaxun Liuffb60902016-08-09 20:10:18 +00001748 FuncAttrs.addAttribute(
1749 "correctly-rounded-divide-sqrt-fp-math",
1750 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001751
Sanjay Patel0bb72c12016-10-04 20:44:05 +00001752 // TODO: Reciprocal estimate codegen options should apply to instructions?
1753 std::vector<std::string> &Recips = getTarget().getTargetOpts().Reciprocals;
1754 if (!Recips.empty())
1755 FuncAttrs.addAttribute("reciprocal-estimates",
1756 llvm::join(Recips.begin(), Recips.end(), ","));
1757
Akira Hatanakaaecca042015-09-11 18:55:09 +00001758 if (CodeGenOpts.StackRealignment)
1759 FuncAttrs.addAttribute("stackrealign");
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001760 if (CodeGenOpts.Backchain)
1761 FuncAttrs.addAttribute("backchain");
Eric Christopher70c16652015-03-25 23:14:47 +00001762
Eric Christopher11acf732015-06-12 01:35:52 +00001763 // Add target-cpu and target-features attributes to functions. If
1764 // we have a decl for the function and it has a target attribute then
1765 // parse that and add it to the feature set.
1766 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001767 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001768 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001769 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001770 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001771
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001772 // Produce the canonical string for this set of features.
1773 std::vector<std::string> Features;
1774 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1775 ie = FeatureMap.end();
1776 it != ie; ++it)
1777 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001778
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001779 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001780 // While we populated the feature map above, we still need to
1781 // get and parse the target attribute so we can get the cpu for
1782 // the function.
1783 const auto *TD = FD->getAttr<TargetAttr>();
1784 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1785 if (ParsedAttr.second != "")
1786 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001787 if (TargetCPU != "")
1788 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1789 if (!Features.empty()) {
1790 std::sort(Features.begin(), Features.end());
1791 FuncAttrs.addAttribute(
1792 "target-features",
1793 llvm::join(Features.begin(), Features.end(), ","));
1794 }
1795 } else {
1796 // Otherwise just add the existing target cpu and target features to the
1797 // function.
1798 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1799 if (TargetCPU != "")
1800 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1801 if (!Features.empty()) {
1802 std::sort(Features.begin(), Features.end());
1803 FuncAttrs.addAttribute(
1804 "target-features",
1805 llvm::join(Features.begin(), Features.end(), ","));
1806 }
Eric Christopher70c16652015-03-25 23:14:47 +00001807 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001808 }
1809
Justin Lebarddd97fa2016-02-24 21:55:11 +00001810 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1811 // Conservatively, mark all functions and calls in CUDA as convergent
1812 // (meaning, they may call an intrinsically convergent op, such as
1813 // __syncthreads(), and so can't have certain optimizations applied around
1814 // them). LLVM will remove this attribute where it safely can.
1815 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Justin Lebard3a44f62016-04-05 18:26:20 +00001816
Justin Lebar3e6449b2016-10-04 23:41:49 +00001817 // Exceptions aren't supported in CUDA device code.
1818 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1819
Justin Lebard3a44f62016-04-05 18:26:20 +00001820 // Respect -fcuda-flush-denormals-to-zero.
1821 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1822 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
Justin Lebarddd97fa2016-02-24 21:55:11 +00001823 }
1824
Alexey Samsonov153004f2014-09-29 22:08:00 +00001825 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001826
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001827 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001828 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001829 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001830 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001831 if (RetTy->hasSignedIntegerRepresentation())
1832 RetAttrs.addAttribute(llvm::Attribute::SExt);
1833 else if (RetTy->hasUnsignedIntegerRepresentation())
1834 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001835 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001836 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001837 if (RetAI.getInReg())
1838 RetAttrs.addAttribute(llvm::Attribute::InReg);
1839 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001840 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001841 break;
1842
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001843 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001844 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001845 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001846 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1847 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001848 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001849 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001850
John McCallf26e73d2016-03-11 04:30:43 +00001851 case ABIArgInfo::CoerceAndExpand:
1852 break;
1853
Daniel Dunbard3674e62008-09-11 01:48:57 +00001854 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001855 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001856 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001857
Hal Finkela2347ba2014-07-18 15:52:10 +00001858 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1859 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001860 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001861 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1862 .getQuantity());
1863 else if (getContext().getTargetAddressSpace(PTy) == 0)
1864 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1865 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001866
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001867 // Attach return attributes.
1868 if (RetAttrs.hasAttributes()) {
1869 PAL.push_back(llvm::AttributeSet::get(
1870 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1871 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001872
John McCall12f23522016-04-04 18:33:08 +00001873 bool hasUsedSRet = false;
1874
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001875 // Attach attributes to sret.
1876 if (IRFunctionArgs.hasSRetArg()) {
1877 llvm::AttrBuilder SRETAttrs;
1878 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001879 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001880 if (RetAI.getInReg())
1881 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1882 PAL.push_back(llvm::AttributeSet::get(
1883 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1884 }
1885
1886 // Attach attributes to inalloca argument.
1887 if (IRFunctionArgs.hasInallocaArg()) {
1888 llvm::AttrBuilder Attrs;
1889 Attrs.addAttribute(llvm::Attribute::InAlloca);
1890 PAL.push_back(llvm::AttributeSet::get(
1891 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1892 }
1893
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001894 unsigned ArgNo = 0;
1895 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1896 E = FI.arg_end();
1897 I != E; ++I, ++ArgNo) {
1898 QualType ParamType = I->type;
1899 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001900 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001901
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001902 // Add attribute for padding argument, if necessary.
1903 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001904 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001905 PAL.push_back(llvm::AttributeSet::get(
1906 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1907 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001908 }
1909
John McCall39ec71f2010-03-27 00:47:27 +00001910 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1911 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001912 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001913 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001914 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001915 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001916 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001917 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1918 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1919 Attrs.addAttribute(llvm::Attribute::SExt);
1920 else
1921 Attrs.addAttribute(llvm::Attribute::ZExt);
1922 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001923 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001924 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001925 if (ArgNo == 0 && FI.isChainCall())
1926 Attrs.addAttribute(llvm::Attribute::Nest);
1927 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001928 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001929 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001930
James Y Knight71608572015-08-21 18:19:06 +00001931 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001932 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001933 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001934
Anders Carlsson20759ad2009-09-16 15:53:40 +00001935 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001936 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001937
John McCall7f416cc2015-09-08 08:05:57 +00001938 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001939
1940 // In a byval argument, it is important that the required
1941 // alignment of the type is honored, as LLVM might be creating a
1942 // *new* stack object, and needs to know what alignment to give
1943 // it. (Sometimes it can deduce a sensible alignment on its own,
1944 // but not if clang decides it must emit a packed struct, or the
1945 // user specifies increased alignment requirements.)
1946 //
1947 // This is different from indirect *not* byval, where the object
1948 // exists already, and the align attribute is purely
1949 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001950 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001951
John McCall7f416cc2015-09-08 08:05:57 +00001952 // For now, only add this when we have a byval argument.
1953 // TODO: be less lazy about updating test cases.
1954 if (AI.getIndirectByVal())
1955 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001956
Daniel Dunbarc2304432009-03-18 19:51:01 +00001957 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001958 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1959 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001960 break;
James Y Knight71608572015-08-21 18:19:06 +00001961 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001962 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001963 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001964 case ABIArgInfo::CoerceAndExpand:
1965 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001966
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001967 case ABIArgInfo::InAlloca:
1968 // inalloca disables readnone and readonly.
1969 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1970 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001971 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Hal Finkela2347ba2014-07-18 15:52:10 +00001974 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1975 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001976 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001977 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1978 .getQuantity());
1979 else if (getContext().getTargetAddressSpace(PTy) == 0)
1980 Attrs.addAttribute(llvm::Attribute::NonNull);
1981 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001982
John McCall12f23522016-04-04 18:33:08 +00001983 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
1984 case ParameterABI::Ordinary:
1985 break;
1986
1987 case ParameterABI::SwiftIndirectResult: {
1988 // Add 'sret' if we haven't already used it for something, but
1989 // only if the result is void.
1990 if (!hasUsedSRet && RetTy->isVoidType()) {
1991 Attrs.addAttribute(llvm::Attribute::StructRet);
1992 hasUsedSRet = true;
1993 }
1994
1995 // Add 'noalias' in either case.
1996 Attrs.addAttribute(llvm::Attribute::NoAlias);
1997
1998 // Add 'dereferenceable' and 'alignment'.
1999 auto PTy = ParamType->getPointeeType();
2000 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2001 auto info = getContext().getTypeInfoInChars(PTy);
2002 Attrs.addDereferenceableAttr(info.first.getQuantity());
2003 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2004 info.second.getQuantity()));
2005 }
2006 break;
2007 }
2008
2009 case ParameterABI::SwiftErrorResult:
2010 Attrs.addAttribute(llvm::Attribute::SwiftError);
2011 break;
2012
2013 case ParameterABI::SwiftContext:
2014 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2015 break;
2016 }
2017
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002018 if (Attrs.hasAttributes()) {
2019 unsigned FirstIRArg, NumIRArgs;
2020 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2021 for (unsigned i = 0; i < NumIRArgs; i++)
2022 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
2023 FirstIRArg + i + 1, Attrs));
2024 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002025 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002026 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002027
Bill Wendlinga7912f82012-10-10 07:36:56 +00002028 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002029 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002030 AttributeSet::get(getLLVMContext(),
2031 llvm::AttributeSet::FunctionIndex,
2032 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002033}
2034
John McCalla738c252011-03-09 04:27:21 +00002035/// An argument came in as a promoted argument; demote it back to its
2036/// declared type.
2037static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2038 const VarDecl *var,
2039 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002040 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002041
2042 // This can happen with promotions that actually don't change the
2043 // underlying type, like the enum promotions.
2044 if (value->getType() == varType) return value;
2045
2046 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2047 && "unexpected promotion type");
2048
2049 if (isa<llvm::IntegerType>(varType))
2050 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2051
2052 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2053}
2054
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002055/// Returns the attribute (either parameter attribute, or function
2056/// attribute), which declares argument ArgNo to be non-null.
2057static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2058 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002059 // FIXME: __attribute__((nonnull)) can also be applied to:
2060 // - references to pointers, where the pointee is known to be
2061 // nonnull (apparently a Clang extension)
2062 // - transparent unions containing pointers
2063 // In the former case, LLVM IR cannot represent the constraint. In
2064 // the latter case, we have no guarantee that the transparent union
2065 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002066 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2067 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002068 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002069 if (PVD) {
2070 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2071 return ParmNNAttr;
2072 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002073 // Check function attributes.
2074 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002075 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002076 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002077 if (NNAttr->isNonNull(ArgNo))
2078 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002079 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002080 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002081}
2082
John McCall12f23522016-04-04 18:33:08 +00002083namespace {
2084 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2085 Address Temp;
2086 Address Arg;
2087 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2088 void Emit(CodeGenFunction &CGF, Flags flags) override {
2089 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2090 CGF.Builder.CreateStore(errorValue, Arg);
2091 }
2092 };
2093}
2094
Daniel Dunbard931a872009-02-02 22:03:45 +00002095void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2096 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002097 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002098 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2099 // Naked functions don't have prologues.
2100 return;
2101
John McCallcaa19452009-07-28 01:00:58 +00002102 // If this is an implicit-return-zero function, go ahead and
2103 // initialize the return value. TODO: it might be nice to have
2104 // a more general mechanism for this that didn't require synthesized
2105 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002106 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002107 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002108 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002109 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002110 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002111 Builder.CreateStore(Zero, ReturnValue);
2112 }
2113 }
2114
Mike Stump18bb9282009-05-16 07:57:57 +00002115 // FIXME: We no longer need the types from FunctionArgList; lift up and
2116 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002117
Alexey Samsonov153004f2014-09-29 22:08:00 +00002118 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002119 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002120 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002121 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2122 for (auto &Arg : Fn->args()) {
2123 FnArgs.push_back(&Arg);
2124 }
2125 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002126
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002127 // If we're using inalloca, all the memory arguments are GEPs off of the last
2128 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002129 Address ArgStruct = Address::invalid();
2130 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002131 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002132 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2133 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2134 FI.getArgStructAlignment());
2135
2136 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002137 }
2138
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002139 // Name the struct return parameter.
2140 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002141 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002142 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002143 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002144 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002147 // Track if we received the parameter as a pointer (indirect, byval, or
2148 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2149 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002150 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002151 ArgVals.reserve(Args.size());
2152
Reid Kleckner739756c2013-12-04 19:23:12 +00002153 // Create a pointer value for every parameter declaration. This usually
2154 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2155 // any cleanups or do anything that might unwind. We do that separately, so
2156 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002157 assert(FI.arg_size() == Args.size() &&
2158 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002159 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002160 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002161 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002162 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002163 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002164 QualType Ty = info_it->type;
2165 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002166
John McCalla738c252011-03-09 04:27:21 +00002167 bool isPromoted =
2168 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2169
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002170 unsigned FirstIRArg, NumIRArgs;
2171 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002172
Daniel Dunbard3674e62008-09-11 01:48:57 +00002173 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002174 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002175 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002176 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2177 CharUnits FieldOffset =
2178 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2179 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2180 Arg->getName());
2181 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002182 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002183 }
2184
Daniel Dunbar747865a2009-02-05 09:16:39 +00002185 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002186 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002187 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002188
John McCall47fb9502013-03-07 21:37:08 +00002189 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002190 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002191 // need to do is realign the value, if requested.
2192 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002193 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002194 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002195
2196 // Copy from the incoming argument pointer to the temporary with the
2197 // appropriate alignment.
2198 //
2199 // FIXME: We should have a common utility for generating an aggregate
2200 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002201 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002202 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2203 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2204 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2205 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002206 V = AlignedTemp;
2207 }
John McCall7f416cc2015-09-08 08:05:57 +00002208 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002209 } else {
2210 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002211 llvm::Value *V =
2212 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002213
2214 if (isPromoted)
2215 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002216 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002217 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002218 break;
2219 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002220
2221 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002222 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002223
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002224 // If we have the trivial case, handle it with no muss and fuss.
2225 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002226 ArgI.getCoerceToType() == ConvertType(Ty) &&
2227 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002228 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002229 llvm::Value *V = FnArgs[FirstIRArg];
2230 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002231
Hal Finkel48d53e22014-07-19 01:41:07 +00002232 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002233 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2234 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002235 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2236 AI->getArgNo() + 1,
2237 llvm::Attribute::NonNull));
2238
Hal Finkel48d53e22014-07-19 01:41:07 +00002239 QualType OTy = PVD->getOriginalType();
2240 if (const auto *ArrTy =
2241 getContext().getAsConstantArrayType(OTy)) {
2242 // A C99 array parameter declaration with the static keyword also
2243 // indicates dereferenceability, and if the size is constant we can
2244 // use the dereferenceable attribute (which requires the size in
2245 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002246 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002247 QualType ETy = ArrTy->getElementType();
2248 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2249 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2250 ArrSize) {
2251 llvm::AttrBuilder Attrs;
2252 Attrs.addDereferenceableAttr(
2253 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2254 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2255 AI->getArgNo() + 1, Attrs));
2256 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2257 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2258 AI->getArgNo() + 1,
2259 llvm::Attribute::NonNull));
2260 }
2261 }
2262 } else if (const auto *ArrTy =
2263 getContext().getAsVariableArrayType(OTy)) {
2264 // For C99 VLAs with the static keyword, we don't know the size so
2265 // we can't use the dereferenceable attribute, but in addrspace(0)
2266 // we know that it must be nonnull.
2267 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2268 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2269 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2270 AI->getArgNo() + 1,
2271 llvm::Attribute::NonNull));
2272 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002273
2274 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2275 if (!AVAttr)
2276 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2277 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2278 if (AVAttr) {
2279 llvm::Value *AlignmentValue =
2280 EmitScalarExpr(AVAttr->getAlignment());
2281 llvm::ConstantInt *AlignmentCI =
2282 cast<llvm::ConstantInt>(AlignmentValue);
2283 unsigned Alignment =
2284 std::min((unsigned) AlignmentCI->getZExtValue(),
2285 +llvm::Value::MaximumAlignment);
2286
2287 llvm::AttrBuilder Attrs;
2288 Attrs.addAlignmentAttr(Alignment);
2289 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2290 AI->getArgNo() + 1, Attrs));
2291 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002292 }
2293
Bill Wendling507c3512012-10-16 05:23:44 +00002294 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002295 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2296 AI->getArgNo() + 1,
2297 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002298
John McCall12f23522016-04-04 18:33:08 +00002299 // LLVM expects swifterror parameters to be used in very restricted
2300 // ways. Copy the value into a less-restricted temporary.
2301 if (FI.getExtParameterInfo(ArgNo).getABI()
2302 == ParameterABI::SwiftErrorResult) {
2303 QualType pointeeTy = Ty->getPointeeType();
2304 assert(pointeeTy->isPointerType());
2305 Address temp =
2306 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2307 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2308 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2309 Builder.CreateStore(incomingErrorValue, temp);
2310 V = temp.getPointer();
2311
2312 // Push a cleanup to copy the value back at the end of the function.
2313 // The convention does not guarantee that the value will be written
2314 // back if the function exits with an unwind exception.
2315 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2316 }
2317
Chris Lattner7369c142011-07-20 06:29:00 +00002318 // Ensure the argument is the correct type.
2319 if (V->getType() != ArgI.getCoerceToType())
2320 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2321
John McCalla738c252011-03-09 04:27:21 +00002322 if (isPromoted)
2323 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002324
2325 // Because of merging of function types from multiple decls it is
2326 // possible for the type of an argument to not match the corresponding
2327 // type in the function type. Since we are codegening the callee
2328 // in here, add a cast to the argument type.
2329 llvm::Type *LTy = ConvertType(Arg->getType());
2330 if (V->getType() != LTy)
2331 V = Builder.CreateBitCast(V, LTy);
2332
John McCall7f416cc2015-09-08 08:05:57 +00002333 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002334 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002335 }
Mike Stump11289f42009-09-09 15:08:12 +00002336
John McCall7f416cc2015-09-08 08:05:57 +00002337 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2338 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002339
John McCall7f416cc2015-09-08 08:05:57 +00002340 // Pointer to store into.
2341 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002342
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002343 // Fast-isel and the optimizer generally like scalar values better than
2344 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002345 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002346 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2347 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002348 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002349 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002350 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002351 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002352
John McCall7f416cc2015-09-08 08:05:57 +00002353 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002354 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002355 AddrToStoreInto =
2356 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002357 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002358 AddrToStoreInto =
2359 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002360 }
John McCall7f416cc2015-09-08 08:05:57 +00002361
2362 assert(STy->getNumElements() == NumIRArgs);
2363 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2364 auto AI = FnArgs[FirstIRArg + i];
2365 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2366 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2367 Address EltPtr =
2368 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2369 Builder.CreateStore(AI, EltPtr);
2370 }
2371
2372 if (SrcSize > DstSize) {
2373 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2374 }
2375
Chris Lattner15ec3612010-06-29 00:06:42 +00002376 } else {
2377 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002378 assert(NumIRArgs == 1);
2379 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002380 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002381 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002382 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002383
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002384 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002385 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002386 llvm::Value *V =
2387 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002388 if (isPromoted)
2389 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002390 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002391 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002392 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002393 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002394 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002395 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002396
John McCallf26e73d2016-03-11 04:30:43 +00002397 case ABIArgInfo::CoerceAndExpand: {
2398 // Reconstruct into a temporary.
2399 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2400 ArgVals.push_back(ParamValue::forIndirect(alloca));
2401
2402 auto coercionType = ArgI.getCoerceAndExpandType();
2403 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2404 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2405
2406 unsigned argIndex = FirstIRArg;
2407 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2408 llvm::Type *eltType = coercionType->getElementType(i);
2409 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2410 continue;
2411
2412 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2413 auto elt = FnArgs[argIndex++];
2414 Builder.CreateStore(elt, eltAddr);
2415 }
2416 assert(argIndex == FirstIRArg + NumIRArgs);
2417 break;
2418 }
2419
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002420 case ABIArgInfo::Expand: {
2421 // If this structure was expanded into multiple arguments then
2422 // we need to create a temporary and reconstruct it from the
2423 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002424 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2425 LValue LV = MakeAddrLValue(Alloca, Ty);
2426 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002427
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002428 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2429 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2430 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2431 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2432 auto AI = FnArgs[FirstIRArg + i];
2433 AI->setName(Arg->getName() + "." + Twine(i));
2434 }
2435 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002436 }
2437
2438 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002439 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002440 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002441 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002442 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002443 } else {
2444 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002445 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002446 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002447 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002448 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002449 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002450
Reid Kleckner739756c2013-12-04 19:23:12 +00002451 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2452 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002453 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002454 } else {
2455 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002456 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002457 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002458}
2459
John McCallffa2c1a2012-01-29 07:46:59 +00002460static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2461 while (insn->use_empty()) {
2462 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2463 if (!bitcast) return;
2464
2465 // This is "safe" because we would have used a ConstantExpr otherwise.
2466 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2467 bitcast->eraseFromParent();
2468 }
2469}
2470
John McCall31168b02011-06-15 23:02:42 +00002471/// Try to emit a fused autorelease of a return result.
2472static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2473 llvm::Value *result) {
2474 // We must be immediately followed the cast.
2475 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002476 if (BB->empty()) return nullptr;
2477 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002478
Chris Lattner2192fe52011-07-18 04:24:23 +00002479 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002480
2481 // result is in a BasicBlock and is therefore an Instruction.
2482 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2483
Justin Bogner882f8612016-08-18 21:46:54 +00002484 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002485
2486 // Look for:
2487 // %generator = bitcast %type1* %generator2 to %type2*
2488 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2489 // We would have emitted this as a constant if the operand weren't
2490 // an Instruction.
2491 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2492
2493 // Require the generator to be immediately followed by the cast.
2494 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002495 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002496
Justin Bogner882f8612016-08-18 21:46:54 +00002497 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002498 }
2499
2500 // Look for:
2501 // %generator = call i8* @objc_retain(i8* %originalResult)
2502 // or
2503 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2504 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002505 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002506
2507 bool doRetainAutorelease;
2508
John McCallb04ecb72015-10-21 18:06:43 +00002509 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002510 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002511 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002512 .objc_retainAutoreleasedReturnValue) {
2513 doRetainAutorelease = false;
2514
John McCallcfa4e9b2012-09-07 23:30:50 +00002515 // If we emitted an assembly marker for this call (and the
2516 // ARCEntrypoints field should have been set if so), go looking
2517 // for that call. If we can't find it, we can't do this
2518 // optimization. But it should always be the immediately previous
2519 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002520 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002521 llvm::Instruction *prev = call->getPrevNode();
2522 assert(prev);
2523 if (isa<llvm::BitCastInst>(prev)) {
2524 prev = prev->getPrevNode();
2525 assert(prev);
2526 }
2527 assert(isa<llvm::CallInst>(prev));
2528 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002529 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002530 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002531 }
John McCall31168b02011-06-15 23:02:42 +00002532 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002533 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002534 }
2535
2536 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002537 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002538
2539 // Keep killing bitcasts, for sanity. Note that we no longer care
2540 // about precise ordering as long as there's exactly one use.
2541 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2542 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002543 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002544 result = bitcast->getOperand(0);
2545 }
2546
2547 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002548 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002549 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002550
2551 // Do the fused retain/autorelease if we were asked to.
2552 if (doRetainAutorelease)
2553 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2554
2555 // Cast back to the result type.
2556 return CGF.Builder.CreateBitCast(result, resultType);
2557}
2558
John McCallffa2c1a2012-01-29 07:46:59 +00002559/// If this is a +1 of the value of an immutable 'self', remove it.
2560static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2561 llvm::Value *result) {
2562 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002563 const ObjCMethodDecl *method =
2564 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002565 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002566 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002567 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002568
2569 // Look for a retain call.
2570 llvm::CallInst *retainCall =
2571 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2572 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002573 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002574 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002575
2576 // Look for an ordinary load of 'self'.
2577 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2578 llvm::LoadInst *load =
2579 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2580 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002581 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002582 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002583
2584 // Okay! Burn it all down. This relies for correctness on the
2585 // assumption that the retain is emitted as part of the return and
2586 // that thereafter everything is used "linearly".
2587 llvm::Type *resultType = result->getType();
2588 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2589 assert(retainCall->use_empty());
2590 retainCall->eraseFromParent();
2591 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2592
2593 return CGF.Builder.CreateBitCast(load, resultType);
2594}
2595
John McCall31168b02011-06-15 23:02:42 +00002596/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002597///
2598/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002599static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2600 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002601 // If we're returning 'self', kill the initial retain. This is a
2602 // heuristic attempt to "encourage correctness" in the really unfortunate
2603 // case where we have a return of self during a dealloc and we desperately
2604 // need to avoid the possible autorelease.
2605 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2606 return self;
2607
John McCall31168b02011-06-15 23:02:42 +00002608 // At -O0, try to emit a fused retain/autorelease.
2609 if (CGF.shouldUseFusedARCCalls())
2610 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2611 return fused;
2612
2613 return CGF.EmitARCAutoreleaseReturnValue(result);
2614}
2615
John McCall6e1c0122012-01-29 02:35:02 +00002616/// Heuristically search for a dominating store to the return-value slot.
2617static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002618 // Check if a User is a store which pointerOperand is the ReturnValue.
2619 // We are looking for stores to the ReturnValue, not for stores of the
2620 // ReturnValue to some other location.
2621 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2622 auto *SI = dyn_cast<llvm::StoreInst>(U);
2623 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2624 return nullptr;
2625 // These aren't actually possible for non-coerced returns, and we
2626 // only care about non-coerced returns on this code path.
2627 assert(!SI->isAtomic() && !SI->isVolatile());
2628 return SI;
2629 };
John McCall6e1c0122012-01-29 02:35:02 +00002630 // If there are multiple uses of the return-value slot, just check
2631 // for something immediately preceding the IP. Sometimes this can
2632 // happen with how we generate implicit-returns; it can also happen
2633 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002634 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002635 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002636 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002637 llvm::Instruction *I = &IP->back();
2638
2639 // Skip lifetime markers
2640 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2641 IE = IP->rend();
2642 II != IE; ++II) {
2643 if (llvm::IntrinsicInst *Intrinsic =
2644 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2645 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2646 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2647 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002648 if (II == IE)
2649 break;
2650 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2651 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002652 }
2653 }
2654 I = &*II;
2655 break;
2656 }
2657
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002658 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002659 }
2660
2661 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002662 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002663 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002664
John McCall6e1c0122012-01-29 02:35:02 +00002665 // Now do a first-and-dirty dominance check: just walk up the
2666 // single-predecessors chain from the current insertion point.
2667 llvm::BasicBlock *StoreBB = store->getParent();
2668 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2669 while (IP != StoreBB) {
2670 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002671 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002672 }
2673
2674 // Okay, the store's basic block dominates the insertion point; we
2675 // can do our thing.
2676 return store;
2677}
2678
Adrian Prantl3be10542013-05-02 17:30:20 +00002679void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002680 bool EmitRetDbgLoc,
2681 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002682 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2683 // Naked functions don't have epilogues.
2684 Builder.CreateUnreachable();
2685 return;
2686 }
2687
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002688 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002689 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002690 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002691 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002692 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002693
Dan Gohman481e40c2010-07-20 20:13:52 +00002694 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002695 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002696 QualType RetTy = FI.getReturnType();
2697 const ABIArgInfo &RetAI = FI.getReturnInfo();
2698
2699 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002700 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002701 // Aggregrates get evaluated directly into the destination. Sometimes we
2702 // need to return the sret value in a register, though.
2703 assert(hasAggregateEvaluationKind(RetTy));
2704 if (RetAI.getInAllocaSRet()) {
2705 llvm::Function::arg_iterator EI = CurFn->arg_end();
2706 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002707 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002708 llvm::Value *SRet = Builder.CreateStructGEP(
2709 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002710 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002711 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002712 break;
2713
Daniel Dunbar03816342010-08-21 02:24:36 +00002714 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002715 auto AI = CurFn->arg_begin();
2716 if (RetAI.isSRetAfterThis())
2717 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002718 switch (getEvaluationKind(RetTy)) {
2719 case TEK_Complex: {
2720 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002721 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002722 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002723 /*isInit*/ true);
2724 break;
2725 }
2726 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002727 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002728 break;
2729 case TEK_Scalar:
2730 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002731 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002732 /*isInit*/ true);
2733 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002734 }
2735 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002736 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002737
2738 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002739 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002740 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2741 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002742 // The internal return value temp always will have pointer-to-return-type
2743 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002744
John McCall6e1c0122012-01-29 02:35:02 +00002745 // If there is a dominating store to ReturnValue, we can elide
2746 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002747 if (llvm::StoreInst *SI =
2748 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002749 // Reuse the debug location from the store unless there is
2750 // cleanup code to be emitted between the store and return
2751 // instruction.
2752 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002753 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002754 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002755 RV = SI->getValueOperand();
2756 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002757
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002758 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002759 auto returnValueInst = ReturnValue.getPointer();
2760 if (returnValueInst->use_empty()) {
2761 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2762 alloca->eraseFromParent();
2763 ReturnValue = Address::invalid();
2764 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002765 }
John McCall6e1c0122012-01-29 02:35:02 +00002766
2767 // Otherwise, we have to do a simple load.
2768 } else {
2769 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002770 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002771 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002772 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002773 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002774
John McCall7f416cc2015-09-08 08:05:57 +00002775 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002776 }
John McCall31168b02011-06-15 23:02:42 +00002777
2778 // In ARC, end functions that return a retainable type with a call
2779 // to objc_autoreleaseReturnValue.
2780 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002781#ifndef NDEBUG
2782 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2783 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2784 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2785 // CurCodeDecl or BlockInfo.
2786 QualType RT;
2787
2788 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2789 RT = FD->getReturnType();
2790 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2791 RT = MD->getReturnType();
2792 else if (isa<BlockDecl>(CurCodeDecl))
2793 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2794 else
2795 llvm_unreachable("Unexpected function/method type");
2796
David Blaikiebbafb8a2012-03-11 07:00:24 +00002797 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002798 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002799 RT->isObjCRetainableType());
2800#endif
John McCall31168b02011-06-15 23:02:42 +00002801 RV = emitAutoreleaseOfResult(*this, RV);
2802 }
2803
Chris Lattner726b3d02010-06-26 23:13:19 +00002804 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002805
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002806 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002807 break;
2808
John McCallf26e73d2016-03-11 04:30:43 +00002809 case ABIArgInfo::CoerceAndExpand: {
2810 auto coercionType = RetAI.getCoerceAndExpandType();
2811 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2812
2813 // Load all of the coerced elements out into results.
2814 llvm::SmallVector<llvm::Value*, 4> results;
2815 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2816 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2817 auto coercedEltType = coercionType->getElementType(i);
2818 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2819 continue;
2820
2821 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2822 auto elt = Builder.CreateLoad(eltAddr);
2823 results.push_back(elt);
2824 }
2825
2826 // If we have one result, it's the single direct result type.
2827 if (results.size() == 1) {
2828 RV = results[0];
2829
2830 // Otherwise, we need to make a first-class aggregate.
2831 } else {
2832 // Construct a return type that lacks padding elements.
2833 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2834
2835 RV = llvm::UndefValue::get(returnType);
2836 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2837 RV = Builder.CreateInsertValue(RV, results[i], i);
2838 }
2839 }
2840 break;
2841 }
2842
Chris Lattner726b3d02010-06-26 23:13:19 +00002843 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002844 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002845 }
2846
Alexey Samsonovde443c52014-08-13 00:26:40 +00002847 llvm::Instruction *Ret;
2848 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002849 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2850 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002851 SanitizerScope SanScope(this);
2852 llvm::Value *Cond = Builder.CreateICmpNE(
2853 RV, llvm::Constant::getNullValue(RV->getType()));
2854 llvm::Constant *StaticData[] = {
2855 EmitCheckSourceLocation(EndLoc),
2856 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2857 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002858 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2859 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002860 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002861 }
2862 Ret = Builder.CreateRet(RV);
2863 } else {
2864 Ret = Builder.CreateRetVoid();
2865 }
2866
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002867 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002868 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002869}
2870
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002871static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2872 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2873 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2874}
2875
John McCall7f416cc2015-09-08 08:05:57 +00002876static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2877 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002878 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2879 // placeholders.
2880 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2881 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002882 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2883 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2884
2885 // FIXME: When we generate this IR in one pass, we shouldn't need
2886 // this win32-specific alignment hack.
2887 CharUnits Align = CharUnits::fromQuantity(4);
2888
2889 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002890 Ty.getQualifiers(),
2891 AggValueSlot::IsNotDestructed,
2892 AggValueSlot::DoesNotNeedGCBarriers,
2893 AggValueSlot::IsNotAliased);
2894}
2895
John McCall32ea9692011-03-11 20:59:21 +00002896void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002897 const VarDecl *param,
2898 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002899 // StartFunction converted the ABI-lowered parameter(s) into a
2900 // local alloca. We need to turn that into an r-value suitable
2901 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002902 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002903
John McCall32ea9692011-03-11 20:59:21 +00002904 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002905
Reid Klecknerab2090d2014-07-26 01:34:32 +00002906 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2907 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002908
Richard Smithd62d4982016-06-14 01:13:21 +00002909 // For the most part, we just need to load the alloca, except that
2910 // aggregate r-values are actually pointers to temporaries.
2911 if (type->isReferenceType())
2912 args.add(RValue::get(Builder.CreateLoad(local)), type);
2913 else
2914 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002915}
2916
John McCall31168b02011-06-15 23:02:42 +00002917static bool isProvablyNull(llvm::Value *addr) {
2918 return isa<llvm::ConstantPointerNull>(addr);
2919}
2920
John McCall31168b02011-06-15 23:02:42 +00002921/// Emit the actual writing-back of a writeback.
2922static void emitWriteback(CodeGenFunction &CGF,
2923 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002924 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002925 Address srcAddr = srcLV.getAddress();
2926 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002927 "shouldn't have writeback for provably null argument");
2928
Craig Topper8a13c412014-05-21 05:09:00 +00002929 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002930
2931 // If the argument wasn't provably non-null, we need to null check
2932 // before doing the store.
Nick Lewyckyd9bce502016-09-20 15:49:58 +00002933 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002934 if (!provablyNonNull) {
2935 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2936 contBB = CGF.createBasicBlock("icr.done");
2937
John McCall7f416cc2015-09-08 08:05:57 +00002938 llvm::Value *isNull =
2939 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002940 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2941 CGF.EmitBlock(writebackBB);
2942 }
2943
2944 // Load the value to writeback.
2945 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2946
2947 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002948 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2949 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002950
2951 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002952
2953 // If we have a "to use" value, it's something we need to emit a use
2954 // of. This has to be carefully threaded in: if it's done after the
2955 // release it's potentially undefined behavior (and the optimizer
2956 // will ignore it), and if it happens before the retain then the
2957 // optimizer could move the release there.
2958 if (writeback.ToUse) {
2959 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2960
2961 // Retain the new value. No need to block-copy here: the block's
2962 // being passed up the stack.
2963 value = CGF.EmitARCRetainNonBlock(value);
2964
2965 // Emit the intrinsic use here.
2966 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2967
2968 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002969 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002970
2971 // Put the new value in place (primitively).
2972 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2973
2974 // Release the old value.
2975 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2976
2977 // Otherwise, we can just do a normal lvalue store.
2978 } else {
2979 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2980 }
John McCall31168b02011-06-15 23:02:42 +00002981
2982 // Jump to the continuation block.
2983 if (!provablyNonNull)
2984 CGF.EmitBlock(contBB);
2985}
2986
2987static void emitWritebacks(CodeGenFunction &CGF,
2988 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002989 for (const auto &I : args.writebacks())
2990 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002991}
2992
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002993static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2994 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002995 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002996 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2997 CallArgs.getCleanupsToDeactivate();
2998 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002999 for (const auto &I : llvm::reverse(Cleanups)) {
3000 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3001 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003002 }
3003}
3004
John McCalleff18842013-03-23 02:35:54 +00003005static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3006 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3007 if (uop->getOpcode() == UO_AddrOf)
3008 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003009 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003010}
3011
John McCall31168b02011-06-15 23:02:42 +00003012/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003013/// we are passing the address of an __autoreleased temporary; it
3014/// might be copy-initialized with the current value of the given
3015/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003016static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3017 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003018 LValue srcLV;
3019
3020 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003021 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003022 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3023 srcLV = CGF.EmitLValue(lvExpr);
3024
3025 // Otherwise, just emit it as a scalar.
3026 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003027 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003028
3029 QualType srcAddrType =
3030 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003031 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003032 }
John McCall7f416cc2015-09-08 08:05:57 +00003033 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003034
3035 // The dest and src types don't necessarily match in LLVM terms
3036 // because of the crazy ObjC compatibility rules.
3037
Chris Lattner2192fe52011-07-18 04:24:23 +00003038 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003039 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3040
3041 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003042 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003043 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3044 CRE->getType());
3045 return;
3046 }
3047
John McCall31168b02011-06-15 23:02:42 +00003048 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003049 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3050 CGF.getPointerAlign(),
3051 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003052 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3053 // and that cleanup will be conditional if we can't prove that the l-value
3054 // isn't null, so we need to register a dominating point so that the cleanups
3055 // system will make valid IR.
3056 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3057
John McCall31168b02011-06-15 23:02:42 +00003058 // Zero-initialize it if we're not doing a copy-initialization.
3059 bool shouldCopy = CRE->shouldCopy();
3060 if (!shouldCopy) {
3061 llvm::Value *null =
3062 llvm::ConstantPointerNull::get(
3063 cast<llvm::PointerType>(destType->getElementType()));
3064 CGF.Builder.CreateStore(null, temp);
3065 }
Craig Topper8a13c412014-05-21 05:09:00 +00003066
3067 llvm::BasicBlock *contBB = nullptr;
3068 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003069
3070 // If the address is *not* known to be non-null, we need to switch.
3071 llvm::Value *finalArgument;
3072
Nick Lewyckyd9bce502016-09-20 15:49:58 +00003073 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003074 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003075 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003076 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003077 llvm::Value *isNull =
3078 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003079
3080 finalArgument = CGF.Builder.CreateSelect(isNull,
3081 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003082 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003083
3084 // If we need to copy, then the load has to be conditional, which
3085 // means we need control flow.
3086 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003087 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003088 contBB = CGF.createBasicBlock("icr.cont");
3089 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3090 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3091 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003092 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003093 }
3094 }
3095
Craig Topper8a13c412014-05-21 05:09:00 +00003096 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003097
John McCall31168b02011-06-15 23:02:42 +00003098 // Perform a copy if necessary.
3099 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003100 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003101 assert(srcRV.isScalar());
3102
3103 llvm::Value *src = srcRV.getScalarVal();
3104 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3105 "icr.cast");
3106
3107 // Use an ordinary store, not a store-to-lvalue.
3108 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003109
3110 // If optimization is enabled, and the value was held in a
3111 // __strong variable, we need to tell the optimizer that this
3112 // value has to stay alive until we're doing the store back.
3113 // This is because the temporary is effectively unretained,
3114 // and so otherwise we can violate the high-level semantics.
3115 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3116 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3117 valueToUse = src;
3118 }
John McCall31168b02011-06-15 23:02:42 +00003119 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003120
John McCall31168b02011-06-15 23:02:42 +00003121 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003122 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003123 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003124 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003125
3126 // Make a phi for the value to intrinsically use.
3127 if (valueToUse) {
3128 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3129 "icr.to-use");
3130 phiToUse->addIncoming(valueToUse, copyBB);
3131 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3132 originBB);
3133 valueToUse = phiToUse;
3134 }
3135
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003136 condEval.end(CGF);
3137 }
John McCall31168b02011-06-15 23:02:42 +00003138
John McCalleff18842013-03-23 02:35:54 +00003139 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003140 args.add(RValue::get(finalArgument), CRE->getType());
3141}
3142
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003143void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003144 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003145
3146 // Save the stack.
3147 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003148 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003149}
3150
Nico Weber8cdb3f92015-08-25 18:43:32 +00003151void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3152 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003153 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003154 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003155 CGF.Builder.CreateCall(F, StackBase);
3156 }
3157}
3158
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003159void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3160 SourceLocation ArgLoc,
3161 const FunctionDecl *FD,
3162 unsigned ParmNum) {
3163 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003164 return;
3165 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3166 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3167 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3168 if (!NNAttr)
3169 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003170 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003171 assert(RV.isScalar());
3172 llvm::Value *V = RV.getScalarVal();
3173 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003174 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003175 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003176 EmitCheckSourceLocation(ArgLoc),
3177 EmitCheckSourceLocation(NNAttr->getLocation()),
3178 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003179 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003180 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003181 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003182}
3183
David Blaikief05779e2015-07-21 18:37:18 +00003184void CodeGenFunction::EmitCallArgs(
3185 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3186 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Richard Smith762672a2016-09-28 19:09:10 +00003187 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip,
Richard Smitha560ccf2016-09-29 21:30:12 +00003188 EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003189 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003190
3191 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3192 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3193 return;
3194 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3195 if (PS == nullptr)
3196 return;
3197
3198 const auto &Context = getContext();
3199 auto SizeTy = Context.getSizeType();
3200 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3201 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3202 Args.add(RValue::get(V), SizeTy);
3203 };
3204
Reid Kleckner739756c2013-12-04 19:23:12 +00003205 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003206 // because arguments are destroyed left to right in the callee. As a special
3207 // case, there are certain language constructs that require left-to-right
3208 // evaluation, and in those cases we consider the evaluation order requirement
3209 // to trump the "destruction order is reverse construction order" guarantee.
3210 bool LeftToRight =
3211 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3212 ? Order == EvaluationOrder::ForceLeftToRight
3213 : Order != EvaluationOrder::ForceRightToLeft;
3214
3215 // Insert a stack save if we're going to need any inalloca args.
3216 bool HasInAllocaArgs = false;
3217 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003218 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3219 I != E && !HasInAllocaArgs; ++I)
3220 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3221 if (HasInAllocaArgs) {
3222 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3223 Args.allocateArgumentMemory(*this);
3224 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003225 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003226
Richard Smitha560ccf2016-09-29 21:30:12 +00003227 // Evaluate each argument in the appropriate order.
3228 size_t CallArgsStart = Args.size();
3229 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3230 unsigned Idx = LeftToRight ? I : E - I - 1;
3231 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3232 if (!LeftToRight) MaybeEmitImplicitObjectSize(Idx, *Arg);
3233 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
3234 EmitNonNullArgCheck(Args.back().RV, ArgTypes[Idx], (*Arg)->getExprLoc(),
3235 CalleeDecl, ParamsToSkip + Idx);
3236 if (LeftToRight) MaybeEmitImplicitObjectSize(Idx, *Arg);
3237 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003238
Richard Smitha560ccf2016-09-29 21:30:12 +00003239 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003240 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3241 // IR function.
3242 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003243 }
3244}
3245
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003246namespace {
3247
David Blaikie7e70d682015-08-18 22:40:54 +00003248struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003249 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003250 : Addr(Addr), Ty(Ty) {}
3251
John McCall7f416cc2015-09-08 08:05:57 +00003252 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003253 QualType Ty;
3254
Craig Topper4f12f102014-03-12 06:41:41 +00003255 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003256 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3257 assert(!Dtor->isTrivial());
3258 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3259 /*Delegating=*/false, Addr);
3260 }
3261};
3262
David Blaikie38b25912015-02-09 19:13:51 +00003263struct DisableDebugLocationUpdates {
3264 CodeGenFunction &CGF;
3265 bool disabledDebugInfo;
3266 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3267 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3268 CGF.disableDebugInfo();
3269 }
3270 ~DisableDebugLocationUpdates() {
3271 if (disabledDebugInfo)
3272 CGF.enableDebugInfo();
3273 }
3274};
3275
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003276} // end anonymous namespace
3277
John McCall32ea9692011-03-11 20:59:21 +00003278void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3279 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003280 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003281 if (const ObjCIndirectCopyRestoreExpr *CRE
3282 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003283 assert(getLangOpts().ObjCAutoRefCount);
Vedant Kumar30914f32016-10-03 15:29:22 +00003284 assert(getContext().hasSameUnqualifiedType(E->getType(), type));
John McCall31168b02011-06-15 23:02:42 +00003285 return emitWritebackArg(*this, args, CRE);
3286 }
3287
John McCall0a76c0c2011-08-26 18:42:59 +00003288 assert(type->isReferenceType() == E->isGLValue() &&
3289 "reference binding to unmaterialized r-value!");
3290
John McCall17054bd62011-08-26 21:08:13 +00003291 if (E->isGLValue()) {
3292 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003293 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003296 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3297
3298 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3299 // However, we still have to push an EH-only cleanup in case we unwind before
3300 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003301 if (HasAggregateEvalKind &&
3302 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3303 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003304 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003305 AggValueSlot Slot;
3306 if (args.isUsingInAlloca())
3307 Slot = createPlaceholderSlot(*this, type);
3308 else
3309 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003310
3311 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3312 bool DestroyedInCallee =
3313 RD && RD->hasNonTrivialDestructor() &&
3314 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3315 if (DestroyedInCallee)
3316 Slot.setExternallyDestructed();
3317
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003318 EmitAggExpr(E, Slot);
3319 RValue RV = Slot.asRValue();
3320 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003321
Reid Klecknere39ee212014-05-03 00:33:28 +00003322 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003323 // Create a no-op GEP between the placeholder and the cleanup so we can
3324 // RAUW it successfully. It also serves as a marker of the first
3325 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003326 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3327 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003328 // This unreachable is a temporary marker which will be removed later.
3329 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3330 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003331 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003332 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003333 }
3334
3335 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003336 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3337 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3338 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003339 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3340 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3341 } else {
3342 // We can't represent a misaligned lvalue in the CallArgList, so copy
3343 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003344 Address tmp = CreateMemTemp(type);
3345 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003346 args.add(RValue::getAggregate(tmp), type);
3347 }
Eli Friedmandf968192011-05-26 00:10:27 +00003348 return;
3349 }
3350
John McCall32ea9692011-03-11 20:59:21 +00003351 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003352}
3353
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003354QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3355 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3356 // implicitly widens null pointer constants that are arguments to varargs
3357 // functions to pointer-sized ints.
3358 if (!getTarget().getTriple().isOSWindows())
3359 return Arg->getType();
3360
3361 if (Arg->getType()->isIntegerType() &&
3362 getContext().getTypeSize(Arg->getType()) <
3363 getContext().getTargetInfo().getPointerWidth(0) &&
3364 Arg->isNullPointerConstant(getContext(),
3365 Expr::NPC_ValueDependentIsNotNull)) {
3366 return getContext().getIntPtrType();
3367 }
3368
3369 return Arg->getType();
3370}
3371
Dan Gohman515a60d2012-02-16 00:57:37 +00003372// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3373// optimizer it can aggressively ignore unwind edges.
3374void
3375CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3376 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3377 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3378 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3379 CGM.getNoObjCARCExceptionsMetadata());
3380}
3381
John McCall882987f2013-02-28 19:01:20 +00003382/// Emits a call to the given no-arguments nounwind runtime function.
3383llvm::CallInst *
3384CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3385 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003386 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003387}
3388
3389/// Emits a call to the given nounwind runtime function.
3390llvm::CallInst *
3391CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3392 ArrayRef<llvm::Value*> args,
3393 const llvm::Twine &name) {
3394 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3395 call->setDoesNotThrow();
3396 return call;
3397}
3398
3399/// Emits a simple call (never an invoke) to the given no-arguments
3400/// runtime function.
3401llvm::CallInst *
3402CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3403 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003404 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003405}
3406
David Majnemer0b17d442015-12-15 21:27:59 +00003407// Calls which may throw must have operand bundles indicating which funclet
3408// they are nested within.
3409static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003410getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003411 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003412 // There is no need for a funclet operand bundle if we aren't inside a
3413 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003414 if (!CurrentFuncletPad)
3415 return;
3416
3417 // Skip intrinsics which cannot throw.
3418 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3419 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3420 return;
3421
3422 BundleList.emplace_back("funclet", CurrentFuncletPad);
3423}
3424
David Majnemer971d31b2016-02-24 17:02:45 +00003425/// Emits a simple call (never an invoke) to the given runtime function.
3426llvm::CallInst *
3427CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3428 ArrayRef<llvm::Value*> args,
3429 const llvm::Twine &name) {
3430 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3431 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3432
3433 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3434 call->setCallingConv(getRuntimeCC());
3435 return call;
3436}
3437
John McCall882987f2013-02-28 19:01:20 +00003438/// Emits a call or invoke to the given noreturn runtime function.
3439void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3440 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003441 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3442 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3443
John McCall882987f2013-02-28 19:01:20 +00003444 if (getInvokeDest()) {
3445 llvm::InvokeInst *invoke =
3446 Builder.CreateInvoke(callee,
3447 getUnreachableBlock(),
3448 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003449 args,
3450 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003451 invoke->setDoesNotReturn();
3452 invoke->setCallingConv(getRuntimeCC());
3453 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003454 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003455 call->setDoesNotReturn();
3456 call->setCallingConv(getRuntimeCC());
3457 Builder.CreateUnreachable();
3458 }
3459}
3460
Sanjay Patel846b63b2016-01-18 22:15:33 +00003461/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003462llvm::CallSite
3463CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3464 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003465 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003466}
3467
3468/// Emits a call or invoke instruction to the given runtime function.
3469llvm::CallSite
3470CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3471 ArrayRef<llvm::Value*> args,
3472 const Twine &name) {
3473 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3474 callSite.setCallingConv(getRuntimeCC());
3475 return callSite;
3476}
3477
John McCallbd309292010-07-06 01:34:17 +00003478/// Emits a call or invoke instruction to the given function, depending
3479/// on the current state of the EH stack.
3480llvm::CallSite
3481CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003482 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003483 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003484 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003485 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3486 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003487
Dan Gohman515a60d2012-02-16 00:57:37 +00003488 llvm::Instruction *Inst;
3489 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003490 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003491 else {
3492 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003493 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3494 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003495 EmitBlock(ContBB);
3496 }
3497
3498 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3499 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003500 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003501 AddObjCARCExceptionMetadata(Inst);
3502
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003503 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003504}
3505
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003506/// \brief Store a non-aggregate value to an address to initialize it. For
3507/// initialization, a non-atomic store will be used.
3508static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3509 LValue Dst) {
3510 if (Src.isScalar())
3511 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3512 else
3513 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3514}
3515
3516void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3517 llvm::Value *New) {
3518 DeferredReplacements.push_back(std::make_pair(Old, New));
3519}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003520
Daniel Dunbard931a872009-02-02 22:03:45 +00003521RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003522 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003523 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003524 const CallArgList &CallArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00003525 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003526 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003527
John McCallb92ab1a2016-10-26 23:46:34 +00003528 assert(Callee.isOrdinary());
3529
Daniel Dunbar613855c2008-09-09 23:27:19 +00003530 // Handle struct-return functions by passing a pointer to the
3531 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003532 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003533 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003534
John McCallb92ab1a2016-10-26 23:46:34 +00003535 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3536
3537 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003538
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003539 // If we're using inalloca, insert the allocation after the stack save.
3540 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003541 Address ArgMemory = Address::invalid();
3542 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003543 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003544 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003545 llvm::Instruction *IP = CallArgs.getStackBase();
3546 llvm::AllocaInst *AI;
3547 if (IP) {
3548 IP = IP->getNextNode();
3549 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3550 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003551 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003552 }
John McCall7f416cc2015-09-08 08:05:57 +00003553 auto Align = CallInfo.getArgStructAlignment();
3554 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003555 AI->setUsedWithInAlloca(true);
3556 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003557 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003558 }
3559
John McCall7f416cc2015-09-08 08:05:57 +00003560 // Helper function to drill into the inalloca allocation.
3561 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3562 auto FieldOffset =
3563 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3564 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3565 };
3566
Alexey Samsonov153004f2014-09-29 22:08:00 +00003567 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003568 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3569
Chris Lattner4ca97c32009-06-13 00:26:38 +00003570 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003571 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003572 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003573 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003574 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003575 if (!ReturnValue.isNull()) {
3576 SRetPtr = ReturnValue.getValue();
3577 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003578 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003579 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3580 uint64_t size =
3581 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003582 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003583 UnusedReturnSize = size;
3584 }
3585 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003586 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003587 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003588 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003589 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3590 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003591 }
Anders Carlsson17490832009-12-24 20:40:36 +00003592 }
Mike Stump11289f42009-09-09 15:08:12 +00003593
John McCall12f23522016-04-04 18:33:08 +00003594 Address swiftErrorTemp = Address::invalid();
3595 Address swiftErrorArg = Address::invalid();
3596
John McCallb92ab1a2016-10-26 23:46:34 +00003597 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003598 assert(CallInfo.arg_size() == CallArgs.size() &&
3599 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003600 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003601 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003602 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003603 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003604 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003605 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003606
Rafael Espindolafad28de2012-10-24 01:59:00 +00003607 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003608 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3609 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3610 llvm::UndefValue::get(ArgInfo.getPaddingType());
3611
3612 unsigned FirstIRArg, NumIRArgs;
3613 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003614
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003615 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003616 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003617 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003618 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3619 if (RV.isAggregate()) {
3620 // Replace the placeholder with the appropriate argument slot GEP.
3621 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003622 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003623 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3624 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003625 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003626 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003627 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003628 } else {
3629 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003630 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3631 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003632 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3633 // There are some cases where a trivial bitcast is not avoidable. The
3634 // definition of a type later in a translation unit may change it's type
3635 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003636 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003637 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003638 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003639 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3640 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003641 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003642 }
3643
Daniel Dunbar03816342010-08-21 02:24:36 +00003644 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003645 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003646 if (RV.isScalar() || RV.isComplex()) {
3647 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003648 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3649 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003650
John McCall7f416cc2015-09-08 08:05:57 +00003651 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003652 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003653 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003654 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003655 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003656 // 1. If the argument is not byval, and we are required to copy the
3657 // source. (This case doesn't occur on any common architecture.)
3658 // 2. If the argument is byval, RV is not sufficiently aligned, and
3659 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003660 // 3. If the argument is byval, but RV is located in an address space
3661 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003662 Address Addr = RV.getAggregateAddress();
3663 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003664 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003665 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003666 const unsigned ArgAddrSpace =
3667 (FirstIRArg < IRFuncTy->getNumParams()
3668 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3669 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003670 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003671 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3672 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3673 Align.getQuantity(), *TD)
3674 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003675 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003676 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003677 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3678 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003679 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003680 } else {
3681 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003682 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003683 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003684 }
3685 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003686 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003687
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003688 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003689 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003690 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003691
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003692 case ABIArgInfo::Extend:
3693 case ABIArgInfo::Direct: {
3694 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003695 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3696 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003697 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003698 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003699 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003700 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003701 else
John McCall7f416cc2015-09-08 08:05:57 +00003702 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003703
John McCall12f23522016-04-04 18:33:08 +00003704 // Implement swifterror by copying into a new swifterror argument.
3705 // We'll write back in the normal path out of the call.
3706 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3707 == ParameterABI::SwiftErrorResult) {
3708 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3709
3710 QualType pointeeTy = I->Ty->getPointeeType();
3711 swiftErrorArg =
3712 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3713
3714 swiftErrorTemp =
3715 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3716 V = swiftErrorTemp.getPointer();
3717 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3718
3719 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3720 Builder.CreateStore(errorValue, swiftErrorTemp);
3721 }
3722
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003723 // We might have to widen integers, but we should never truncate.
3724 if (ArgInfo.getCoerceToType() != V->getType() &&
3725 V->getType()->isIntegerTy())
3726 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3727
Chris Lattner3ce86682011-07-12 04:53:39 +00003728 // If the argument doesn't match, perform a bitcast to coerce it. This
3729 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003730 if (FirstIRArg < IRFuncTy->getNumParams() &&
3731 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3732 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003733
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003734 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003735 break;
3736 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003737
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003738 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003739 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003740 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003741 Src = CreateMemTemp(I->Ty, "coerce");
3742 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003743 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003744 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003745 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003746 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003747
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003748 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003749 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003750
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003751 // Fast-isel and the optimizer generally like scalar values better than
3752 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003753 llvm::StructType *STy =
3754 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003755 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003756 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003757 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3758 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3759
3760 // If the source type is smaller than the destination type of the
3761 // coerce-to logic, copy the source value into a temp alloca the size
3762 // of the destination type to allow loading all of it. The bits past
3763 // the source value are left undef.
3764 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003765 Address TempAlloca
3766 = CreateTempAlloca(STy, Src.getAlignment(),
3767 Src.getName() + ".coerce");
3768 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3769 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003770 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003771 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003772 }
3773
John McCall7f416cc2015-09-08 08:05:57 +00003774 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003775 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003776 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003777 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3778 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3779 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003780 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003781 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003782 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003783 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003784 assert(NumIRArgs == 1);
3785 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003786 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003787 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003788
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003789 break;
3790 }
3791
John McCallf26e73d2016-03-11 04:30:43 +00003792 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003793 auto coercionType = ArgInfo.getCoerceAndExpandType();
3794 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3795
John McCall12f23522016-04-04 18:33:08 +00003796 llvm::Value *tempSize = nullptr;
3797 Address addr = Address::invalid();
3798 if (RV.isAggregate()) {
3799 addr = RV.getAggregateAddress();
3800 } else {
3801 assert(RV.isScalar()); // complex should always just be direct
3802
3803 llvm::Type *scalarType = RV.getScalarVal()->getType();
3804 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3805 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3806
3807 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3808
3809 // Materialize to a temporary.
3810 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3811 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3812 scalarAlign)));
3813 EmitLifetimeStart(scalarSize, addr.getPointer());
3814
3815 Builder.CreateStore(RV.getScalarVal(), addr);
3816 }
3817
John McCallf26e73d2016-03-11 04:30:43 +00003818 addr = Builder.CreateElementBitCast(addr, coercionType);
3819
3820 unsigned IRArgPos = FirstIRArg;
3821 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3822 llvm::Type *eltType = coercionType->getElementType(i);
3823 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3824 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3825 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3826 IRCallArgs[IRArgPos++] = elt;
3827 }
3828 assert(IRArgPos == FirstIRArg + NumIRArgs);
3829
John McCall12f23522016-04-04 18:33:08 +00003830 if (tempSize) {
3831 EmitLifetimeEnd(tempSize, addr.getPointer());
3832 }
3833
John McCallf26e73d2016-03-11 04:30:43 +00003834 break;
3835 }
3836
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003837 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003838 unsigned IRArgPos = FirstIRArg;
3839 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3840 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003841 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003842 }
3843 }
Mike Stump11289f42009-09-09 15:08:12 +00003844
John McCallb92ab1a2016-10-26 23:46:34 +00003845 llvm::Value *CalleePtr = Callee.getFunctionPointer();
3846
3847 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00003848 if (ArgMemory.isValid()) {
3849 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003850 if (CallInfo.isVariadic()) {
3851 // When passing non-POD arguments by value to variadic functions, we will
3852 // end up with a variadic prototype and an inalloca call site. In such
3853 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3854 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00003855 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
3856 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
3857 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
Reid Klecknerafba553e2014-07-08 02:24:27 +00003858 } else {
3859 llvm::Type *LastParamTy =
3860 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3861 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003862#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003863 // Assert that these structs have equivalent element types.
3864 llvm::StructType *FullTy = CallInfo.getArgStruct();
3865 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3866 cast<llvm::PointerType>(LastParamTy)->getElementType());
3867 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3868 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3869 DE = DeclaredTy->element_end(),
3870 FI = FullTy->element_begin();
3871 DI != DE; ++DI, ++FI)
3872 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003873#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003874 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3875 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003876 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003877 assert(IRFunctionArgs.hasInallocaArg());
3878 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003879 }
3880
John McCallb92ab1a2016-10-26 23:46:34 +00003881 // 2. Prepare the function pointer.
3882
3883 // If the callee is a bitcast of a non-variadic function to have a
3884 // variadic function pointer type, check to see if we can remove the
3885 // bitcast. This comes up with unprototyped functions.
3886 //
3887 // This makes the IR nicer, but more importantly it ensures that we
3888 // can inline the function at -O0 if it is marked always_inline.
3889 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
3890 llvm::FunctionType *CalleeFT =
3891 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
3892 if (!CalleeFT->isVarArg())
3893 return Ptr;
3894
3895 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
3896 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
3897 return Ptr;
3898
3899 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
3900 if (!OrigFn)
3901 return Ptr;
3902
3903 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
3904
3905 // If the original type is variadic, or if any of the component types
3906 // disagree, we cannot remove the cast.
3907 if (OrigFT->isVarArg() ||
3908 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
3909 OrigFT->getReturnType() != CalleeFT->getReturnType())
3910 return Ptr;
3911
3912 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
3913 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
3914 return Ptr;
3915
3916 return OrigFn;
3917 };
3918 CalleePtr = simplifyVariadicCallee(CalleePtr);
3919
3920 // 3. Perform the actual call.
3921
3922 // Deactivate any cleanups that we're supposed to do immediately before
3923 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003924 if (!CallArgs.getCleanupsToDeactivate().empty())
3925 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3926
John McCallb92ab1a2016-10-26 23:46:34 +00003927 // Assert that the arguments we computed match up. The IR verifier
3928 // will catch this, but this is a common enough source of problems
3929 // during IRGen changes that it's way better for debugging to catch
3930 // it ourselves here.
3931#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003932 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3933 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3934 // Inalloca argument can have different type.
3935 if (IRFunctionArgs.hasInallocaArg() &&
3936 i == IRFunctionArgs.getInallocaArgNo())
3937 continue;
3938 if (i < IRFuncTy->getNumParams())
3939 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3940 }
John McCallb92ab1a2016-10-26 23:46:34 +00003941#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003942
John McCallb92ab1a2016-10-26 23:46:34 +00003943 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003944 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003945 CodeGen::AttributeListType AttributeList;
John McCallb92ab1a2016-10-26 23:46:34 +00003946 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
3947 Callee.getAbstractInfo(),
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003948 AttributeList, CallingConv,
3949 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003950 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003951 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003952
John McCallb92ab1a2016-10-26 23:46:34 +00003953 // Apply some call-site-specific attributes.
3954 // TODO: work this into building the attribute set.
3955
3956 // Apply always_inline to all calls within flatten functions.
3957 // FIXME: should this really take priority over __try, below?
3958 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3959 !(Callee.getAbstractInfo().getCalleeDecl() &&
3960 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
3961 Attrs =
3962 Attrs.addAttribute(getLLVMContext(),
3963 llvm::AttributeSet::FunctionIndex,
3964 llvm::Attribute::AlwaysInline);
3965 }
3966
3967 // Disable inlining inside SEH __try blocks.
3968 if (isSEHTryScope()) {
3969 Attrs =
3970 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3971 llvm::Attribute::NoInline);
3972 }
3973
3974 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00003975 bool CannotThrow;
3976 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00003977 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00003978 CannotThrow = false;
3979 } else if (isCleanupPadScope() &&
3980 EHPersonality::get(*this).isMSVCXXPersonality()) {
3981 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00003982 // exception is thrown during a cleanup outside of a try/catch.
3983 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00003984 CannotThrow = true;
3985 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00003986 // Otherwise, nounwind call sites will never throw.
David Majnemer4e52d6f2015-12-12 05:39:21 +00003987 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3988 llvm::Attribute::NoUnwind);
3989 }
3990 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003991
David Majnemer0b17d442015-12-15 21:27:59 +00003992 SmallVector<llvm::OperandBundleDef, 1> BundleList;
John McCallb92ab1a2016-10-26 23:46:34 +00003993 getBundlesForFunclet(CalleePtr, CurrentFuncletPad, BundleList);
David Majnemer0b17d442015-12-15 21:27:59 +00003994
John McCallb92ab1a2016-10-26 23:46:34 +00003995 // Emit the actual call/invoke instruction.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003996 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003997 if (!InvokeDest) {
John McCallb92ab1a2016-10-26 23:46:34 +00003998 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003999 } else {
4000 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
John McCallb92ab1a2016-10-26 23:46:34 +00004001 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004002 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004003 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004004 }
John McCallb92ab1a2016-10-26 23:46:34 +00004005 llvm::Instruction *CI = CS.getInstruction();
Chris Lattnere70a0072010-06-29 16:40:28 +00004006 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004007 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004008
John McCallb92ab1a2016-10-26 23:46:34 +00004009 // Apply the attributes and calling convention.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004010 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004011 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004012
John McCallb92ab1a2016-10-26 23:46:34 +00004013 // Apply various metadata.
4014
4015 if (!CI->getType()->isVoidTy())
4016 CI->setName("call");
4017
Adam Nemet1e217bc2016-03-28 22:18:53 +00004018 // Insert instrumentation or attach profile metadata at indirect call sites.
4019 // For more details, see the comment before the definition of
4020 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004021 if (!CS.getCalledFunction())
4022 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004023 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004024
Dan Gohman515a60d2012-02-16 00:57:37 +00004025 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4026 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004027 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004028 AddObjCARCExceptionMetadata(CI);
4029
4030 // Suppress tail calls if requested.
4031 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4032 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4033 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4034 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4035 }
4036
4037 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004038
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004039 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004040 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004041 // unreachable code.
4042 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00004043 if (UnusedReturnSize)
4044 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00004045 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00004046
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004047 Builder.CreateUnreachable();
4048 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004049
Mike Stump18bb9282009-05-16 07:57:57 +00004050 // FIXME: For now, emit a dummy basic block because expr emitters in
4051 // generally are not ready to handle emitting expressions at unreachable
4052 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004053 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004054
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004055 // Return a reasonable RValue.
4056 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004057 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004058
John McCall12f23522016-04-04 18:33:08 +00004059 // Perform the swifterror writeback.
4060 if (swiftErrorTemp.isValid()) {
4061 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4062 Builder.CreateStore(errorResult, swiftErrorArg);
4063 }
4064
John McCallb92ab1a2016-10-26 23:46:34 +00004065 // Emit any call-associated writebacks immediately. Arguably this
4066 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004067 if (CallArgs.hasWritebacks())
4068 emitWritebacks(*this, CallArgs);
4069
Nico Weber8cdb3f92015-08-25 18:43:32 +00004070 // The stack cleanup for inalloca arguments has to run out of the normal
4071 // lexical order, so deactivate it and run it manually here.
4072 CallArgs.freeArgumentMemory(*this);
4073
John McCallb92ab1a2016-10-26 23:46:34 +00004074 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004075 RValue Ret = [&] {
4076 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004077 case ABIArgInfo::CoerceAndExpand: {
4078 auto coercionType = RetAI.getCoerceAndExpandType();
4079 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4080
4081 Address addr = SRetPtr;
4082 addr = Builder.CreateElementBitCast(addr, coercionType);
4083
John McCall12f23522016-04-04 18:33:08 +00004084 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4085 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4086
John McCallf26e73d2016-03-11 04:30:43 +00004087 unsigned unpaddedIndex = 0;
4088 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4089 llvm::Type *eltType = coercionType->getElementType(i);
4090 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4091 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004092 llvm::Value *elt = CI;
4093 if (requiresExtract)
4094 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4095 else
4096 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004097 Builder.CreateStore(elt, eltAddr);
4098 }
John McCall12f23522016-04-04 18:33:08 +00004099 // FALLTHROUGH
4100 }
4101
4102 case ABIArgInfo::InAlloca:
4103 case ABIArgInfo::Indirect: {
4104 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4105 if (UnusedReturnSize)
4106 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4107 SRetPtr.getPointer());
4108 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004109 }
4110
Hal Finkelee90a222014-09-26 05:04:30 +00004111 case ABIArgInfo::Ignore:
4112 // If we are ignoring an argument that had a result, make sure to
4113 // construct the appropriate return value for our caller.
4114 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004115
Hal Finkelee90a222014-09-26 05:04:30 +00004116 case ABIArgInfo::Extend:
4117 case ABIArgInfo::Direct: {
4118 llvm::Type *RetIRTy = ConvertType(RetTy);
4119 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4120 switch (getEvaluationKind(RetTy)) {
4121 case TEK_Complex: {
4122 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4123 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4124 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004125 }
Hal Finkelee90a222014-09-26 05:04:30 +00004126 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004127 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004128 bool DestIsVolatile = ReturnValue.isVolatile();
4129
John McCall7f416cc2015-09-08 08:05:57 +00004130 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004131 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4132 DestIsVolatile = false;
4133 }
John McCall7f416cc2015-09-08 08:05:57 +00004134 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004135 return RValue::getAggregate(DestPtr);
4136 }
4137 case TEK_Scalar: {
4138 // If the argument doesn't match, perform a bitcast to coerce it. This
4139 // can happen due to trivial type mismatches.
4140 llvm::Value *V = CI;
4141 if (V->getType() != RetIRTy)
4142 V = Builder.CreateBitCast(V, RetIRTy);
4143 return RValue::get(V);
4144 }
4145 }
4146 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004147 }
Hal Finkelee90a222014-09-26 05:04:30 +00004148
John McCall7f416cc2015-09-08 08:05:57 +00004149 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004150 bool DestIsVolatile = ReturnValue.isVolatile();
4151
John McCall7f416cc2015-09-08 08:05:57 +00004152 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004153 DestPtr = CreateMemTemp(RetTy, "coerce");
4154 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004155 }
Hal Finkelee90a222014-09-26 05:04:30 +00004156
4157 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004158 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4159 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004160
4161 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004162 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004163
Hal Finkelee90a222014-09-26 05:04:30 +00004164 case ABIArgInfo::Expand:
4165 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004166 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004167
Hal Finkelee90a222014-09-26 05:04:30 +00004168 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4169 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004170
John McCallb92ab1a2016-10-26 23:46:34 +00004171 // Emit the assume_aligned check on the return value.
4172 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
Hal Finkelee90a222014-09-26 05:04:30 +00004173 if (Ret.isScalar() && TargetDecl) {
4174 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4175 llvm::Value *OffsetValue = nullptr;
4176 if (const auto *Offset = AA->getOffset())
4177 OffsetValue = EmitScalarExpr(Offset);
4178
4179 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4180 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4181 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4182 OffsetValue);
4183 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004184 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004185
Hal Finkelee90a222014-09-26 05:04:30 +00004186 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004187}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004188
4189/* VarArg handling */
4190
Charles Davisc7d5c942015-09-17 20:55:33 +00004191Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4192 VAListAddr = VE->isMicrosoftABI()
4193 ? EmitMSVAListRef(VE->getSubExpr())
4194 : EmitVAListRef(VE->getSubExpr());
4195 QualType Ty = VE->getType();
4196 if (VE->isMicrosoftABI())
4197 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004198 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004199}