blob: d683b899022f158528b653c5d3fb4576b09f136c [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"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000033#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000036#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000037#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000038#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000039using namespace clang;
40using namespace CodeGen;
41
42/***/
43
John McCallab26cfa2010-02-05 21:31:56 +000044static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
45 switch (CC) {
46 default: return llvm::CallingConv::C;
47 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
48 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000049 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000050 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
51 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000052 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
53 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000054 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000055 // TODO: Add support for __pascal to LLVM.
56 case CC_X86Pascal: return llvm::CallingConv::C;
57 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000058 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000059 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
60 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000061 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
62 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000063 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000064 }
65}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Derives the 'this' type for codegen purposes, i.e. ignoring method
68/// qualification.
69/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000070static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
71 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
72 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000073}
74
John McCall8ee376f2010-02-24 07:14:12 +000075/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000076static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
77 return MD->getType()->getCanonicalTypeUnqualified()
78 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
81/// Returns the "extra-canonicalized" return type, which discards
82/// qualifiers on the return type. Codegen doesn't care about them,
83/// and it makes ABI code a little easier to be able to assume that
84/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000085static CanQualType GetReturnType(QualType RetTy) {
86 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000087}
88
John McCall8dda7b22012-07-07 06:41:13 +000089/// Arrange the argument and result information for a value of the given
90/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000091const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000092CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000093 // When translating an unprototyped function type, always use a
94 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000095 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000096 /*instanceMethod=*/false,
97 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000098 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000099}
100
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000101/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
102/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
103static void appendParameterTypes(const CodeGenTypes &CGT,
104 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000105 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000107 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000108 // Fill out paramInfos.
109 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
110 assert(paramInfos.size() <= prefix.size());
111 auto protoParamInfos = FPT->getExtParameterInfos();
112 paramInfos.reserve(prefix.size() + protoParamInfos.size());
113 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000114 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000115 }
116
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000117 // Fast path: unknown target.
118 if (FD == nullptr) {
119 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
120 return;
121 }
122
123 // In the vast majority cases, we'll have precisely FPT->getNumParams()
124 // parameters; the only thing that can change this is the presence of
125 // pass_object_size. So, we preallocate for the common case.
126 prefix.reserve(prefix.size() + FPT->getNumParams());
127
128 assert(FD->getNumParams() == FPT->getNumParams());
129 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
130 prefix.push_back(FPT->getParamType(I));
131 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
132 prefix.push_back(CGT.getContext().getSizeType());
133 }
134}
135
John McCall8dda7b22012-07-07 06:41:13 +0000136/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000137/// type, on top of any implicit parameters already stored.
138static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000139arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000141 CanQual<FunctionProtoType> FTP,
142 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000143 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000144 RequiredArgs Required =
145 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000146 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000147 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000148 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000149
Peter Collingbournef7706832014-12-12 23:41:25 +0000150 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
151 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000152 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000153 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000154}
155
John McCalla729c622012-02-17 03:33:10 +0000156/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000157/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000158const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000159CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
160 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000161 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000162 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000163 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000164}
165
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000166static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167 // Set the appropriate calling convention for the Function.
168 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000169 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170
171 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000172 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000173
Douglas Gregora941dca2010-05-18 16:57:00 +0000174 if (D->hasAttr<ThisCallAttr>())
175 return CC_X86ThisCall;
176
Reid Klecknerd7857f02014-10-24 17:42:17 +0000177 if (D->hasAttr<VectorCallAttr>())
178 return CC_X86VectorCall;
179
Dawn Perchik335e16b2010-09-03 01:29:35 +0000180 if (D->hasAttr<PascalAttr>())
181 return CC_X86Pascal;
182
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000183 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
184 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
185
Guy Benyeif0a014b2012-12-25 08:53:55 +0000186 if (D->hasAttr<IntelOclBiccAttr>())
187 return CC_IntelOclBicc;
188
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000189 if (D->hasAttr<MSABIAttr>())
190 return IsWindows ? CC_C : CC_X86_64Win64;
191
192 if (D->hasAttr<SysVABIAttr>())
193 return IsWindows ? CC_X86_64SysV : CC_C;
194
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000195 if (D->hasAttr<PreserveMostAttr>())
196 return CC_PreserveMost;
197
198 if (D->hasAttr<PreserveAllAttr>())
199 return CC_PreserveAll;
200
John McCallab26cfa2010-02-05 21:31:56 +0000201 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000202}
203
John McCalla729c622012-02-17 03:33:10 +0000204/// Arrange the argument and result information for a call to an
205/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000206/// (Zero value of RD means we don't have any meaningful "this" argument type,
207/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000208/// The member function must be an ordinary function, i.e. not a
209/// constructor or destructor.
210const CGFunctionInfo &
211CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000212 const FunctionProtoType *FTP,
213 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000214 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000215
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000216 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000217 if (RD)
218 argTypes.push_back(GetThisType(Context, RD));
219 else
220 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000221
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000222 return ::arrangeLLVMFunctionInfo(
223 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000224 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000225}
226
John McCalla729c622012-02-17 03:33:10 +0000227/// Arrange the argument and result information for a declaration or
228/// definition of the given C++ non-static member function. The
229/// member function must be an ordinary function, i.e. not a
230/// constructor or destructor.
231const CGFunctionInfo &
232CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000233 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000234 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
235
John McCalla729c622012-02-17 03:33:10 +0000236 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000237
John McCalla729c622012-02-17 03:33:10 +0000238 if (MD->isInstance()) {
239 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000240 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000241 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000242 }
243
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000244 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000245}
246
Richard Smith5179eb72016-06-28 19:03:57 +0000247bool CodeGenTypes::inheritingCtorHasParams(
248 const InheritedConstructor &Inherited, CXXCtorType Type) {
249 // Parameters are unnecessary if we're constructing a base class subobject
250 // and the inherited constructor lives in a virtual base.
251 return Type == Ctor_Complete ||
252 !Inherited.getShadowDecl()->constructsVirtualBase() ||
253 !Target.getCXXABI().hasConstructorVariants();
254 }
255
John McCalla729c622012-02-17 03:33:10 +0000256const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000257CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
258 StructorType Type) {
259
John McCalla729c622012-02-17 03:33:10 +0000260 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000261 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000262 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000263
Richard Smith5179eb72016-06-28 19:03:57 +0000264 bool PassParams = true;
265
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000266 GlobalDecl GD;
267 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
268 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000269
270 // A base class inheriting constructor doesn't get forwarded arguments
271 // needed to construct a virtual base (or base class thereof).
272 if (auto Inherited = CD->getInheritedConstructor())
273 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000274 } else {
275 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
276 GD = GlobalDecl(DD, toCXXDtorType(Type));
277 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000278
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000279 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000280
281 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000282 if (PassParams)
283 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000284
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000285 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000286
287 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000288 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
289 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000290
John McCall8dda7b22012-07-07 06:41:13 +0000291 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000292 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
293 ? argTypes.front()
294 : TheCXXABI.hasMostDerivedReturn(GD)
295 ? CGM.getContext().VoidPtrTy
296 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000297 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
298 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000299 paramInfos, required);
300}
301
302static SmallVector<CanQualType, 16>
303getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
304 SmallVector<CanQualType, 16> argTypes;
305 for (auto &arg : args)
306 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
307 return argTypes;
308}
309
310static SmallVector<CanQualType, 16>
311getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
312 SmallVector<CanQualType, 16> argTypes;
313 for (auto &arg : args)
314 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
315 return argTypes;
316}
317
318static void addExtParameterInfosForCall(
319 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
320 const FunctionProtoType *proto,
321 unsigned prefixArgs,
322 unsigned totalArgs) {
323 assert(proto->hasExtParameterInfos());
324 assert(paramInfos.size() <= prefixArgs);
325 assert(proto->getNumParams() + prefixArgs <= totalArgs);
326
327 // Add default infos for any prefix args that don't already have infos.
328 paramInfos.resize(prefixArgs);
329
330 // Add infos for the prototype.
331 auto protoInfos = proto->getExtParameterInfos();
332 paramInfos.append(protoInfos.begin(), protoInfos.end());
333
334 // Add default infos for the variadic arguments.
335 paramInfos.resize(totalArgs);
336}
337
338static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
339getExtParameterInfosForCall(const FunctionProtoType *proto,
340 unsigned prefixArgs, unsigned totalArgs) {
341 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
342 if (proto->hasExtParameterInfos()) {
343 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
344 }
345 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000346}
347
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000348/// Arrange a call to a C++ method, passing the given arguments.
349const CGFunctionInfo &
350CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
351 const CXXConstructorDecl *D,
352 CXXCtorType CtorKind,
353 unsigned ExtraArgs) {
354 // FIXME: Kill copy.
355 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000356 for (const auto &Arg : args)
357 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000358
359 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000360 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000361 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000362 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
363 ? ArgTypes.front()
364 : TheCXXABI.hasMostDerivedReturn(GD)
365 ? CGM.getContext().VoidPtrTy
366 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000367
368 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000369 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
370 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000371 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
372 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000373 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000374}
375
John McCalla729c622012-02-17 03:33:10 +0000376/// Arrange the argument and result information for the declaration or
377/// definition of the given function.
378const CGFunctionInfo &
379CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000380 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000381 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000382 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000383
John McCall2da83a32010-02-26 00:48:12 +0000384 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000385
John McCall2da83a32010-02-26 00:48:12 +0000386 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000387
388 // When declaring a function without a prototype, always use a
389 // non-variadic type.
390 if (isa<FunctionNoProtoType>(FTy)) {
391 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000392 return arrangeLLVMFunctionInfo(
393 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000394 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000395 }
396
John McCall2da83a32010-02-26 00:48:12 +0000397 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000398 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000399}
400
John McCalla729c622012-02-17 03:33:10 +0000401/// Arrange the argument and result information for the declaration or
402/// definition of an Objective-C method.
403const CGFunctionInfo &
404CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
405 // It happens that this is the same as a call with no optional
406 // arguments, except also using the formal 'self' type.
407 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
408}
409
410/// Arrange the argument and result information for the function type
411/// through which to perform a send to the given Objective-C method,
412/// using the given receiver type. The receiver type is not always
413/// the 'self' type of the method or even an Objective-C pointer type.
414/// This is *not* the right method for actually performing such a
415/// message send, due to the possibility of optional arguments.
416const CGFunctionInfo &
417CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
418 QualType receiverType) {
419 SmallVector<CanQualType, 16> argTys;
420 argTys.push_back(Context.getCanonicalParamType(receiverType));
421 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000422 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000423 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000424 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000425 }
John McCall31168b02011-06-15 23:02:42 +0000426
427 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000428 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
429 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000430
David Blaikiebbafb8a2012-03-11 07:00:24 +0000431 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000432 MD->hasAttr<NSReturnsRetainedAttr>())
433 einfo = einfo.withProducesResult(true);
434
John McCalla729c622012-02-17 03:33:10 +0000435 RequiredArgs required =
436 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
437
Peter Collingbournef7706832014-12-12 23:41:25 +0000438 return arrangeLLVMFunctionInfo(
439 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000440 /*chainCall=*/false, argTys, einfo, {}, required);
441}
442
443const CGFunctionInfo &
444CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
445 const CallArgList &args) {
446 auto argTypes = getArgTypesForCall(Context, args);
447 FunctionType::ExtInfo einfo;
448
449 return arrangeLLVMFunctionInfo(
450 GetReturnType(returnType), /*instanceMethod=*/false,
451 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000452}
453
John McCalla729c622012-02-17 03:33:10 +0000454const CGFunctionInfo &
455CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000456 // FIXME: Do we need to handle ObjCMethodDecl?
457 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000458
Anders Carlsson6710c532010-02-06 02:44:09 +0000459 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000460 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000461
462 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000463 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000464
John McCalla729c622012-02-17 03:33:10 +0000465 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000466}
467
Reid Klecknerc3473512014-08-29 21:43:29 +0000468/// Arrange a thunk that takes 'this' as the first parameter followed by
469/// varargs. Return a void pointer, regardless of the actual return type.
470/// The body of the thunk will end in a musttail call to a function of the
471/// correct type, and the caller will bitcast the function to the correct
472/// prototype.
473const CGFunctionInfo &
474CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
475 assert(MD->isVirtual() && "only virtual memptrs have thunks");
476 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
477 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000478 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
479 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000480 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000481}
482
David Majnemerdfa6d202015-03-11 18:36:39 +0000483const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000484CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
485 CXXCtorType CT) {
486 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
487
David Majnemerdfa6d202015-03-11 18:36:39 +0000488 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
489 SmallVector<CanQualType, 2> ArgTys;
490 const CXXRecordDecl *RD = CD->getParent();
491 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000492 if (CT == Ctor_CopyingClosure)
493 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000494 if (RD->getNumVBases() > 0)
495 ArgTys.push_back(Context.IntTy);
496 CallingConv CC = Context.getDefaultCallingConvention(
497 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
498 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
499 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000500 FunctionType::ExtInfo(CC), {},
501 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000502}
503
John McCallc818bbb2012-12-07 07:03:17 +0000504/// Arrange a call as unto a free function, except possibly with an
505/// additional number of formal parameters considered required.
506static const CGFunctionInfo &
507arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000508 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000509 const CallArgList &args,
510 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000511 unsigned numExtraRequiredArgs,
512 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000513 assert(args.size() >= numExtraRequiredArgs);
514
John McCallc56a8b32016-03-11 04:30:31 +0000515 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
516
John McCallc818bbb2012-12-07 07:03:17 +0000517 // In most cases, there are no optional arguments.
518 RequiredArgs required = RequiredArgs::All;
519
520 // If we have a variadic prototype, the required arguments are the
521 // extra prefix plus the arguments in the prototype.
522 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
523 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000524 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000525
John McCallc56a8b32016-03-11 04:30:31 +0000526 if (proto->hasExtParameterInfos())
527 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
528 args.size());
529
John McCallc818bbb2012-12-07 07:03:17 +0000530 // If we don't have a prototype at all, but we're supposed to
531 // explicitly use the variadic convention for unprototyped calls,
532 // treat all of the arguments as required but preserve the nominal
533 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000534 } else if (CGM.getTargetCodeGenInfo()
535 .isNoProtoCallVariadic(args,
536 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000537 required = RequiredArgs(args.size());
538 }
539
Peter Collingbournef7706832014-12-12 23:41:25 +0000540 // FIXME: Kill copy.
541 SmallVector<CanQualType, 16> argTypes;
542 for (const auto &arg : args)
543 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
544 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
545 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000546 argTypes, fnType->getExtInfo(), paramInfos,
547 required);
John McCallc818bbb2012-12-07 07:03:17 +0000548}
549
John McCalla729c622012-02-17 03:33:10 +0000550/// Figure out the rules for calling a function with the given formal
551/// type using the given arguments. The arguments are necessary
552/// because the function might be unprototyped, in which case it's
553/// target-dependent in crazy ways.
554const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000555CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000556 const FunctionType *fnType,
557 bool chainCall) {
558 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
559 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000560}
John McCalla729c622012-02-17 03:33:10 +0000561
John McCallc56a8b32016-03-11 04:30:31 +0000562/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000563/// extra implicit argument.
564const CGFunctionInfo &
565CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
566 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000567 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
568 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000569}
570
571const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000572CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
573 const FunctionArgList &params) {
574 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
575 auto argTypes = getArgTypesForDeclaration(Context, params);
576
George Burgess IV419996c2016-06-16 23:06:04 +0000577 return arrangeLLVMFunctionInfo(
578 GetReturnType(proto->getReturnType()),
579 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
580 proto->getExtInfo(), paramInfos,
581 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000582}
583
584const CGFunctionInfo &
585CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
586 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000587 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000588 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000589 for (const auto &Arg : args)
590 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000591 return arrangeLLVMFunctionInfo(
592 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000593 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
594 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000595}
596
John McCallc56a8b32016-03-11 04:30:31 +0000597const CGFunctionInfo &
598CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
599 const FunctionArgList &args) {
600 auto argTypes = getArgTypesForDeclaration(Context, args);
601
602 return arrangeLLVMFunctionInfo(
603 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
604 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
605}
606
607const CGFunctionInfo &
608CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
609 ArrayRef<CanQualType> argTypes) {
610 return arrangeLLVMFunctionInfo(
611 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
612 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
613}
614
John McCall8dda7b22012-07-07 06:41:13 +0000615/// Arrange a call to a C++ method, passing the given arguments.
616const CGFunctionInfo &
617CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000618 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000619 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000620 unsigned numRequiredArgs =
621 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
622 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
623 auto paramInfos =
624 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
625
John McCall8dda7b22012-07-07 06:41:13 +0000626 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000627 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000628
John McCallc56a8b32016-03-11 04:30:31 +0000629 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000630 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000631 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
632 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000633}
634
John McCalla729c622012-02-17 03:33:10 +0000635const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000636 return arrangeLLVMFunctionInfo(
637 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000638 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
639}
640
641const CGFunctionInfo &
642CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
643 const CallArgList &args) {
644 assert(signature.arg_size() <= args.size());
645 if (signature.arg_size() == args.size())
646 return signature;
647
648 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
649 auto sigParamInfos = signature.getExtParameterInfos();
650 if (!sigParamInfos.empty()) {
651 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
652 paramInfos.resize(args.size());
653 }
654
655 auto argTypes = getArgTypesForCall(Context, args);
656
657 assert(signature.getRequiredArgs().allowsOptionalArgs());
658 return arrangeLLVMFunctionInfo(signature.getReturnType(),
659 signature.isInstanceMethod(),
660 signature.isChainCall(),
661 argTypes,
662 signature.getExtInfo(),
663 paramInfos,
664 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000665}
666
John McCalla729c622012-02-17 03:33:10 +0000667/// Arrange the argument and result information for an abstract value
668/// of a given function type. This is the method which all of the
669/// above functions ultimately defer to.
670const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000671CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000672 bool instanceMethod,
673 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000674 ArrayRef<CanQualType> argTypes,
675 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000676 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000677 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000678 assert(std::all_of(argTypes.begin(), argTypes.end(),
679 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000680
Daniel Dunbare0be8292009-02-03 00:07:12 +0000681 // Lookup or create unique function info.
682 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000683 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
684 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000685
Craig Topper8a13c412014-05-21 05:09:00 +0000686 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000687 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000688 if (FI)
689 return *FI;
690
John McCallc56a8b32016-03-11 04:30:31 +0000691 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
692
John McCalla729c622012-02-17 03:33:10 +0000693 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000694 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000695 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000696 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000697
David Blaikie82e95a32014-11-19 07:49:47 +0000698 bool inserted = FunctionsBeingProcessed.insert(FI).second;
699 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000700 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000701
Daniel Dunbar313321e2009-02-03 05:31:23 +0000702 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000703 if (info.getCC() != CC_Swift) {
704 getABIInfo().computeInfo(*FI);
705 } else {
706 swiftcall::computeABIInfo(CGM, *FI);
707 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000708
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000709 // Loop over all of the computed argument and return value info. If any of
710 // them are direct or extend without a specified coerce type, specify the
711 // default now.
John McCalla729c622012-02-17 03:33:10 +0000712 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000713 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000714 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000715
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000716 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000717 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000718 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000719
John McCalla729c622012-02-17 03:33:10 +0000720 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
721 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000722
Daniel Dunbare0be8292009-02-03 00:07:12 +0000723 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000724}
725
John McCalla729c622012-02-17 03:33:10 +0000726CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000727 bool instanceMethod,
728 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000729 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000730 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000731 CanQualType resultType,
732 ArrayRef<CanQualType> argTypes,
733 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000734 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
735
736 void *buffer =
737 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
738 argTypes.size() + 1, paramInfos.size()));
739
John McCalla729c622012-02-17 03:33:10 +0000740 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
741 FI->CallingConvention = llvmCC;
742 FI->EffectiveCallingConvention = llvmCC;
743 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000744 FI->InstanceMethod = instanceMethod;
745 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000746 FI->NoReturn = info.getNoReturn();
747 FI->ReturnsRetained = info.getProducesResult();
748 FI->Required = required;
749 FI->HasRegParm = info.getHasRegParm();
750 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000751 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000752 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000753 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000754 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000755 FI->getArgsBuffer()[0].type = resultType;
756 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
757 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000758 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
759 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000760 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000761}
762
763/***/
764
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000765namespace {
766// ABIArgInfo::Expand implementation.
767
768// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
769struct TypeExpansion {
770 enum TypeExpansionKind {
771 // Elements of constant arrays are expanded recursively.
772 TEK_ConstantArray,
773 // Record fields are expanded recursively (but if record is a union, only
774 // the field with the largest size is expanded).
775 TEK_Record,
776 // For complex types, real and imaginary parts are expanded recursively.
777 TEK_Complex,
778 // All other types are not expandable.
779 TEK_None
780 };
781
782 const TypeExpansionKind Kind;
783
784 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000785 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000786};
787
788struct ConstantArrayExpansion : TypeExpansion {
789 QualType EltTy;
790 uint64_t NumElts;
791
792 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
793 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
794 static bool classof(const TypeExpansion *TE) {
795 return TE->Kind == TEK_ConstantArray;
796 }
797};
798
799struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000800 SmallVector<const CXXBaseSpecifier *, 1> Bases;
801
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000802 SmallVector<const FieldDecl *, 1> Fields;
803
Reid Klecknere9f6a712014-10-31 17:10:41 +0000804 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
805 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000806 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
807 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000808 static bool classof(const TypeExpansion *TE) {
809 return TE->Kind == TEK_Record;
810 }
811};
812
813struct ComplexExpansion : TypeExpansion {
814 QualType EltTy;
815
816 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
817 static bool classof(const TypeExpansion *TE) {
818 return TE->Kind == TEK_Complex;
819 }
820};
821
822struct NoExpansion : TypeExpansion {
823 NoExpansion() : TypeExpansion(TEK_None) {}
824 static bool classof(const TypeExpansion *TE) {
825 return TE->Kind == TEK_None;
826 }
827};
828} // namespace
829
830static std::unique_ptr<TypeExpansion>
831getTypeExpansion(QualType Ty, const ASTContext &Context) {
832 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
833 return llvm::make_unique<ConstantArrayExpansion>(
834 AT->getElementType(), AT->getSize().getZExtValue());
835 }
836 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000837 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000838 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000839 const RecordDecl *RD = RT->getDecl();
840 assert(!RD->hasFlexibleArrayMember() &&
841 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000842 if (RD->isUnion()) {
843 // Unions can be here only in degenerative cases - all the fields are same
844 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000845 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000846 CharUnits UnionSize = CharUnits::Zero();
847
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000848 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000849 // Skip zero length bitfields.
850 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
851 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000852 assert(!FD->isBitField() &&
853 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000854 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000855 if (UnionSize < FieldSize) {
856 UnionSize = FieldSize;
857 LargestFD = FD;
858 }
859 }
860 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000861 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000862 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000863 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
864 assert(!CXXRD->isDynamicClass() &&
865 "cannot expand vtable pointers in dynamic classes");
866 for (const CXXBaseSpecifier &BS : CXXRD->bases())
867 Bases.push_back(&BS);
868 }
869
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000870 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000871 // Skip zero length bitfields.
872 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
873 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000874 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000875 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000876 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000877 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000878 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000879 return llvm::make_unique<RecordExpansion>(std::move(Bases),
880 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000881 }
882 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
883 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
884 }
885 return llvm::make_unique<NoExpansion>();
886}
887
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000888static int getExpansionSize(QualType Ty, const ASTContext &Context) {
889 auto Exp = getTypeExpansion(Ty, Context);
890 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
891 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
892 }
893 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
894 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000895 for (auto BS : RExp->Bases)
896 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000897 for (auto FD : RExp->Fields)
898 Res += getExpansionSize(FD->getType(), Context);
899 return Res;
900 }
901 if (isa<ComplexExpansion>(Exp.get()))
902 return 2;
903 assert(isa<NoExpansion>(Exp.get()));
904 return 1;
905}
906
Alexey Samsonov153004f2014-09-29 22:08:00 +0000907void
908CodeGenTypes::getExpandedTypes(QualType Ty,
909 SmallVectorImpl<llvm::Type *>::iterator &TI) {
910 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000911 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
912 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000913 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000914 }
915 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000916 for (auto BS : RExp->Bases)
917 getExpandedTypes(BS->getType(), TI);
918 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000919 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000920 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
921 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000922 *TI++ = EltTy;
923 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000924 } else {
925 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000926 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000927 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000928}
929
John McCall7f416cc2015-09-08 08:05:57 +0000930static void forConstantArrayExpansion(CodeGenFunction &CGF,
931 ConstantArrayExpansion *CAE,
932 Address BaseAddr,
933 llvm::function_ref<void(Address)> Fn) {
934 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
935 CharUnits EltAlign =
936 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
937
938 for (int i = 0, n = CAE->NumElts; i < n; i++) {
939 llvm::Value *EltAddr =
940 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
941 Fn(Address(EltAddr, EltAlign));
942 }
943}
944
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000945void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000946 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000947 assert(LV.isSimple() &&
948 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000949
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000950 auto Exp = getTypeExpansion(Ty, getContext());
951 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000952 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
953 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000954 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
955 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000956 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000957 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000958 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000959 for (const CXXBaseSpecifier *BS : RExp->Bases) {
960 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000961 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000962 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
963 /*NullCheckValue=*/false, SourceLocation());
964 LValue SubLV = MakeAddrLValue(Base, BS->getType());
965
966 // Recurse onto bases.
967 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
968 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000969 for (auto FD : RExp->Fields) {
970 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000971 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000972 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000973 }
John McCall7f416cc2015-09-08 08:05:57 +0000974 } else if (isa<ComplexExpansion>(Exp.get())) {
975 auto realValue = *AI++;
976 auto imagValue = *AI++;
977 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000978 } else {
979 assert(isa<NoExpansion>(Exp.get()));
980 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000981 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000982}
983
984void CodeGenFunction::ExpandTypeToArgs(
985 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
986 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
987 auto Exp = getTypeExpansion(Ty, getContext());
988 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000989 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
990 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000991 RValue EltRV =
992 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
993 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000994 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000995 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000996 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000997 for (const CXXBaseSpecifier *BS : RExp->Bases) {
998 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000999 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001000 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1001 /*NullCheckValue=*/false, SourceLocation());
1002 RValue BaseRV = RValue::getAggregate(Base);
1003
1004 // Recurse onto bases.
1005 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1006 IRCallArgPos);
1007 }
1008
1009 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001010 for (auto FD : RExp->Fields) {
1011 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1012 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1013 IRCallArgPos);
1014 }
1015 } else if (isa<ComplexExpansion>(Exp.get())) {
1016 ComplexPairTy CV = RV.getComplexVal();
1017 IRCallArgs[IRCallArgPos++] = CV.first;
1018 IRCallArgs[IRCallArgPos++] = CV.second;
1019 } else {
1020 assert(isa<NoExpansion>(Exp.get()));
1021 assert(RV.isScalar() &&
1022 "Unexpected non-scalar rvalue during struct expansion.");
1023
1024 // Insert a bitcast as needed.
1025 llvm::Value *V = RV.getScalarVal();
1026 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1027 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1028 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1029
1030 IRCallArgs[IRCallArgPos++] = V;
1031 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001032}
1033
John McCall7f416cc2015-09-08 08:05:57 +00001034/// Create a temporary allocation for the purposes of coercion.
1035static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1036 CharUnits MinAlign) {
1037 // Don't use an alignment that's worse than what LLVM would prefer.
1038 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1039 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1040
1041 return CGF.CreateTempAlloca(Ty, Align);
1042}
1043
Chris Lattner895c52b2010-06-27 06:04:18 +00001044/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001045/// accessing some number of bytes out of it, try to gep into the struct to get
1046/// at its inner goodness. Dive as deep as possible without entering an element
1047/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001048static Address
1049EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001050 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001051 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001052 // We can't dive into a zero-element struct.
1053 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001054
Chris Lattner2192fe52011-07-18 04:24:23 +00001055 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001056
Chris Lattner1cd66982010-06-27 05:56:15 +00001057 // 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 +00001058 // first element is the same size as the whole struct, we can enter it. The
1059 // comparison must be made on the store size and not the alloca size. Using
1060 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001061 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001062 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001063 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001064 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001065 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001066
Chris Lattner1cd66982010-06-27 05:56:15 +00001067 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001068 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001069
Chris Lattner1cd66982010-06-27 05:56:15 +00001070 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001071 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001072 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001073 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001074
1075 return SrcPtr;
1076}
1077
Chris Lattner055097f2010-06-27 06:26:04 +00001078/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1079/// are either integers or pointers. This does a truncation of the value if it
1080/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001081///
1082/// This behaves as if the value were coerced through memory, so on big-endian
1083/// targets the high bits are preserved in a truncation, while little-endian
1084/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001085static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001086 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001087 CodeGenFunction &CGF) {
1088 if (Val->getType() == Ty)
1089 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001090
Chris Lattner055097f2010-06-27 06:26:04 +00001091 if (isa<llvm::PointerType>(Val->getType())) {
1092 // If this is Pointer->Pointer avoid conversion to and from int.
1093 if (isa<llvm::PointerType>(Ty))
1094 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001095
Chris Lattner055097f2010-06-27 06:26:04 +00001096 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001097 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001098 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001099
Chris Lattner2192fe52011-07-18 04:24:23 +00001100 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001101 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001102 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001103
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001104 if (Val->getType() != DestIntTy) {
1105 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1106 if (DL.isBigEndian()) {
1107 // Preserve the high bits on big-endian targets.
1108 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001109 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1110 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1111
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001112 if (SrcSize > DstSize) {
1113 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1114 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1115 } else {
1116 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1117 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1118 }
1119 } else {
1120 // Little-endian targets preserve the low bits. No shifts required.
1121 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1122 }
1123 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001124
Chris Lattner055097f2010-06-27 06:26:04 +00001125 if (isa<llvm::PointerType>(Ty))
1126 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1127 return Val;
1128}
1129
Chris Lattner1cd66982010-06-27 05:56:15 +00001130
1131
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001132/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001133/// a pointer to an object of type \arg Ty, known to be aligned to
1134/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001135///
1136/// This safely handles the case when the src type is smaller than the
1137/// destination type; in this situation the values of bits which not
1138/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001139static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001140 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001141 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001142
Chris Lattnerd200eda2010-06-28 22:51:39 +00001143 // If SrcTy and Ty are the same, just do a load.
1144 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001145 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001146
Micah Villmowdd31ca12012-10-08 16:25:52 +00001147 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001148
Chris Lattner2192fe52011-07-18 04:24:23 +00001149 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001150 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1151 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001152 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001153
Micah Villmowdd31ca12012-10-08 16:25:52 +00001154 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001155
Chris Lattner055097f2010-06-27 06:26:04 +00001156 // If the source and destination are integer or pointer types, just do an
1157 // extension or truncation to the desired type.
1158 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1159 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001160 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001161 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1162 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001163
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001164 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001165 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001166 // Generally SrcSize is never greater than DstSize, since this means we are
1167 // losing bits. However, this can happen in cases where the structure has
1168 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001169 //
Mike Stump18bb9282009-05-16 07:57:57 +00001170 // FIXME: Assert that we aren't truncating non-padding bits when have access
1171 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001172 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1173 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001174 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001175
John McCall7f416cc2015-09-08 08:05:57 +00001176 // Otherwise do coercion through memory. This is stupid, but simple.
1177 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1178 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1179 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001180 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1181 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001182 false);
1183 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001184}
1185
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001186// Function to store a first-class aggregate into memory. We prefer to
1187// store the elements rather than the aggregate to be more friendly to
1188// fast-isel.
1189// FIXME: Do we need to recurse here?
1190static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001191 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001192 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001193 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001194 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001195 const llvm::StructLayout *Layout =
1196 CGF.CGM.getDataLayout().getStructLayout(STy);
1197
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001198 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001199 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1200 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001201 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001202 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001203 }
1204 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001205 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001206 }
1207}
1208
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001209/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001210/// where the source and destination may have different types. The
1211/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001212///
1213/// This safely handles the case when the src type is larger than the
1214/// destination type; the upper bits of the src will be lost.
1215static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001216 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001217 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001218 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001219 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001220 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001221 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001222 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001223 return;
1224 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001225
Micah Villmowdd31ca12012-10-08 16:25:52 +00001226 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001227
Chris Lattner2192fe52011-07-18 04:24:23 +00001228 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001229 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1230 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001231 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001232
Chris Lattner055097f2010-06-27 06:26:04 +00001233 // If the source and destination are integer or pointer types, just do an
1234 // extension or truncation to the desired type.
1235 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1236 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1237 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001238 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001239 return;
1240 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001241
Micah Villmowdd31ca12012-10-08 16:25:52 +00001242 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001243
Daniel Dunbar313321e2009-02-03 05:31:23 +00001244 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001245 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001246 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1247 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001248 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001249 // Otherwise do coercion through memory. This is stupid, but
1250 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001251
1252 // Generally SrcSize is never greater than DstSize, since this means we are
1253 // losing bits. However, this can happen in cases where the structure has
1254 // additional padding, for example due to a user specified alignment.
1255 //
1256 // FIXME: Assert that we aren't truncating non-padding bits when have access
1257 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001258 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1259 CGF.Builder.CreateStore(Src, Tmp);
1260 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1261 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001262 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1263 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001264 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001265 }
1266}
1267
John McCall7f416cc2015-09-08 08:05:57 +00001268static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1269 const ABIArgInfo &info) {
1270 if (unsigned offset = info.getDirectOffset()) {
1271 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1272 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1273 CharUnits::fromQuantity(offset));
1274 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1275 }
1276 return addr;
1277}
1278
Alexey Samsonov153004f2014-09-29 22:08:00 +00001279namespace {
1280
1281/// Encapsulates information about the way function arguments from
1282/// CGFunctionInfo should be passed to actual LLVM IR function.
1283class ClangToLLVMArgMapping {
1284 static const unsigned InvalidIndex = ~0U;
1285 unsigned InallocaArgNo;
1286 unsigned SRetArgNo;
1287 unsigned TotalIRArgs;
1288
1289 /// Arguments of LLVM IR function corresponding to single Clang argument.
1290 struct IRArgs {
1291 unsigned PaddingArgIndex;
1292 // Argument is expanded to IR arguments at positions
1293 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1294 unsigned FirstArgIndex;
1295 unsigned NumberOfArgs;
1296
1297 IRArgs()
1298 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1299 NumberOfArgs(0) {}
1300 };
1301
1302 SmallVector<IRArgs, 8> ArgInfo;
1303
1304public:
1305 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1306 bool OnlyRequiredArgs = false)
1307 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1308 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1309 construct(Context, FI, OnlyRequiredArgs);
1310 }
1311
1312 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1313 unsigned getInallocaArgNo() const {
1314 assert(hasInallocaArg());
1315 return InallocaArgNo;
1316 }
1317
1318 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1319 unsigned getSRetArgNo() const {
1320 assert(hasSRetArg());
1321 return SRetArgNo;
1322 }
1323
1324 unsigned totalIRArgs() const { return TotalIRArgs; }
1325
1326 bool hasPaddingArg(unsigned ArgNo) const {
1327 assert(ArgNo < ArgInfo.size());
1328 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1329 }
1330 unsigned getPaddingArgNo(unsigned ArgNo) const {
1331 assert(hasPaddingArg(ArgNo));
1332 return ArgInfo[ArgNo].PaddingArgIndex;
1333 }
1334
1335 /// Returns index of first IR argument corresponding to ArgNo, and their
1336 /// quantity.
1337 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1338 assert(ArgNo < ArgInfo.size());
1339 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1340 ArgInfo[ArgNo].NumberOfArgs);
1341 }
1342
1343private:
1344 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1345 bool OnlyRequiredArgs);
1346};
1347
1348void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1349 const CGFunctionInfo &FI,
1350 bool OnlyRequiredArgs) {
1351 unsigned IRArgNo = 0;
1352 bool SwapThisWithSRet = false;
1353 const ABIArgInfo &RetAI = FI.getReturnInfo();
1354
1355 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1356 SwapThisWithSRet = RetAI.isSRetAfterThis();
1357 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1358 }
1359
1360 unsigned ArgNo = 0;
1361 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1362 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1363 ++I, ++ArgNo) {
1364 assert(I != FI.arg_end());
1365 QualType ArgType = I->type;
1366 const ABIArgInfo &AI = I->info;
1367 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1368 auto &IRArgs = ArgInfo[ArgNo];
1369
1370 if (AI.getPaddingType())
1371 IRArgs.PaddingArgIndex = IRArgNo++;
1372
1373 switch (AI.getKind()) {
1374 case ABIArgInfo::Extend:
1375 case ABIArgInfo::Direct: {
1376 // FIXME: handle sseregparm someday...
1377 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1378 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1379 IRArgs.NumberOfArgs = STy->getNumElements();
1380 } else {
1381 IRArgs.NumberOfArgs = 1;
1382 }
1383 break;
1384 }
1385 case ABIArgInfo::Indirect:
1386 IRArgs.NumberOfArgs = 1;
1387 break;
1388 case ABIArgInfo::Ignore:
1389 case ABIArgInfo::InAlloca:
1390 // ignore and inalloca doesn't have matching LLVM parameters.
1391 IRArgs.NumberOfArgs = 0;
1392 break;
John McCallf26e73d2016-03-11 04:30:43 +00001393 case ABIArgInfo::CoerceAndExpand:
1394 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1395 break;
1396 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001397 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1398 break;
1399 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001400
1401 if (IRArgs.NumberOfArgs > 0) {
1402 IRArgs.FirstArgIndex = IRArgNo;
1403 IRArgNo += IRArgs.NumberOfArgs;
1404 }
1405
1406 // Skip over the sret parameter when it comes second. We already handled it
1407 // above.
1408 if (IRArgNo == 1 && SwapThisWithSRet)
1409 IRArgNo++;
1410 }
1411 assert(ArgNo == ArgInfo.size());
1412
1413 if (FI.usesInAlloca())
1414 InallocaArgNo = IRArgNo++;
1415
1416 TotalIRArgs = IRArgNo;
1417}
1418} // namespace
1419
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001420/***/
1421
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001422bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001423 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001424}
1425
Tim Northovere77cc392014-03-29 13:28:05 +00001426bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1427 return ReturnTypeUsesSRet(FI) &&
1428 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1429}
1430
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001431bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1432 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1433 switch (BT->getKind()) {
1434 default:
1435 return false;
1436 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001437 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001438 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001439 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001440 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001441 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001442 }
1443 }
1444
1445 return false;
1446}
1447
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001448bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1449 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1450 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1451 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001452 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001453 }
1454 }
1455
1456 return false;
1457}
1458
Chris Lattnera5f58b02011-07-09 17:41:47 +00001459llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001460 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1461 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001462}
1463
Chris Lattnera5f58b02011-07-09 17:41:47 +00001464llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001465CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001466
David Blaikie82e95a32014-11-19 07:49:47 +00001467 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1468 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001469 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001470
Alexey Samsonov153004f2014-09-29 22:08:00 +00001471 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001472 const ABIArgInfo &retAI = FI.getReturnInfo();
1473 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001474 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001475 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001476
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001477 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001478 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001479 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001480 break;
1481
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001482 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001483 if (retAI.getInAllocaSRet()) {
1484 // sret things on win32 aren't void, they return the sret pointer.
1485 QualType ret = FI.getReturnType();
1486 llvm::Type *ty = ConvertType(ret);
1487 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1488 resultType = llvm::PointerType::get(ty, addressSpace);
1489 } else {
1490 resultType = llvm::Type::getVoidTy(getLLVMContext());
1491 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001492 break;
1493
John McCall7f416cc2015-09-08 08:05:57 +00001494 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001495 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001496 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001497 break;
John McCallf26e73d2016-03-11 04:30:43 +00001498
1499 case ABIArgInfo::CoerceAndExpand:
1500 resultType = retAI.getUnpaddedCoerceAndExpandType();
1501 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001502 }
Mike Stump11289f42009-09-09 15:08:12 +00001503
Alexey Samsonov153004f2014-09-29 22:08:00 +00001504 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1505 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1506
1507 // Add type for sret argument.
1508 if (IRFunctionArgs.hasSRetArg()) {
1509 QualType Ret = FI.getReturnType();
1510 llvm::Type *Ty = ConvertType(Ret);
1511 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1512 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1513 llvm::PointerType::get(Ty, AddressSpace);
1514 }
1515
1516 // Add type for inalloca argument.
1517 if (IRFunctionArgs.hasInallocaArg()) {
1518 auto ArgStruct = FI.getArgStruct();
1519 assert(ArgStruct);
1520 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1521 }
1522
John McCallc818bbb2012-12-07 07:03:17 +00001523 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001524 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001525 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1526 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001527 for (; it != ie; ++it, ++ArgNo) {
1528 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001529
Rafael Espindolafad28de2012-10-24 01:59:00 +00001530 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001531 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1532 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1533 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001534
Alexey Samsonov153004f2014-09-29 22:08:00 +00001535 unsigned FirstIRArg, NumIRArgs;
1536 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1537
1538 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001539 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001540 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001541 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001542 break;
1543
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001544 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001545 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001546 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001547 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001548 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001549 break;
1550 }
1551
1552 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001553 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001554 // Fast-isel and the optimizer generally like scalar values better than
1555 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001556 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001557 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001558 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1559 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001560 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001561 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001562 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001563 assert(NumIRArgs == 1);
1564 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001565 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001566 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCallf26e73d2016-03-11 04:30:43 +00001569 case ABIArgInfo::CoerceAndExpand: {
1570 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1571 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1572 *ArgTypesIter++ = EltTy;
1573 }
1574 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1575 break;
1576 }
1577
Daniel Dunbard3674e62008-09-11 01:48:57 +00001578 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001579 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1580 getExpandedTypes(it->type, ArgTypesIter);
1581 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001582 break;
1583 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001584 }
1585
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001586 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1587 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001588
1589 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001590}
1591
Chris Lattner2192fe52011-07-18 04:24:23 +00001592llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001593 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001594 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001595
Chris Lattner8806e322011-07-10 00:18:59 +00001596 if (!isFuncTypeConvertible(FPT))
1597 return llvm::StructType::get(getLLVMContext());
1598
1599 const CGFunctionInfo *Info;
1600 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001601 Info =
1602 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001603 else
John McCalla729c622012-02-17 03:33:10 +00001604 Info = &arrangeCXXMethodDeclaration(MD);
1605 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001606}
1607
Samuel Antao798f11c2015-11-23 22:04:44 +00001608static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1609 llvm::AttrBuilder &FuncAttrs,
1610 const FunctionProtoType *FPT) {
1611 if (!FPT)
1612 return;
1613
1614 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1615 FPT->isNothrow(Ctx))
1616 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1617}
1618
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001619void CodeGenModule::ConstructAttributeList(
1620 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1621 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001622 llvm::AttrBuilder FuncAttrs;
1623 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001624 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001625
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001626 CallingConv = FI.getEffectiveCallingConvention();
1627
John McCallab26cfa2010-02-05 21:31:56 +00001628 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001629 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001630
Samuel Antao798f11c2015-11-23 22:04:44 +00001631 // If we have information about the function prototype, we can learn
1632 // attributes form there.
1633 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1634 CalleeInfo.getCalleeFunctionProtoType());
1635
1636 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1637
Amjad Aboudfaea5602016-03-07 14:22:46 +00001638 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001639 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001640 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001641 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001642 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001643 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001644 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001645 if (TargetDecl->hasAttr<NoReturnAttr>())
1646 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001647 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1648 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001649
1650 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001651 AddAttributesFromFunctionProtoType(
1652 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001653 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1654 // These attributes are not inherited by overloads.
1655 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1656 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001657 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001658 }
1659
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001660 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001661 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001662 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1663 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001664 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001665 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1666 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001667 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1668 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1669 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001670 }
David Majnemer631a90b2015-02-04 07:23:21 +00001671 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001672 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001673 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1674 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001675
Amjad Aboudfaea5602016-03-07 14:22:46 +00001676 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001677 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001678 }
1679
Paul Robinson08556952014-12-11 20:14:04 +00001680 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1681 if (!HasOptnone) {
1682 if (CodeGenOpts.OptimizeSize)
1683 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1684 if (CodeGenOpts.OptimizeSize == 2)
1685 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1686 }
1687
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001688 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001689 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001690 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001691 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001692 if (CodeGenOpts.EnableSegmentedStacks &&
1693 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001694 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001695
Bill Wendling2f81db62013-02-22 20:53:29 +00001696 if (AttrOnCallSite) {
1697 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001698 if (!CodeGenOpts.SimplifyLibCalls ||
1699 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001700 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001701 if (!CodeGenOpts.TrapFuncName.empty())
1702 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001703 } else {
1704 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001705 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001706 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001707 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001708 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001709 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001710 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001711 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001712 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001713 }
1714
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001715 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001716 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001717 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001718 FuncAttrs.addAttribute(
1719 "disable-tail-calls",
1720 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001721
Bill Wendlingdabafea2013-03-13 22:24:33 +00001722 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001723 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001724 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001725 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001726 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001727 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001728 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001729 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001730 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001731 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001732 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001733 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001734
Akira Hatanakaaecca042015-09-11 18:55:09 +00001735 if (CodeGenOpts.StackRealignment)
1736 FuncAttrs.addAttribute("stackrealign");
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001737 if (CodeGenOpts.Backchain)
1738 FuncAttrs.addAttribute("backchain");
Eric Christopher70c16652015-03-25 23:14:47 +00001739
Eric Christopher11acf732015-06-12 01:35:52 +00001740 // Add target-cpu and target-features attributes to functions. If
1741 // we have a decl for the function and it has a target attribute then
1742 // parse that and add it to the feature set.
1743 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001744 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001745 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001746 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001747 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001748
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001749 // Produce the canonical string for this set of features.
1750 std::vector<std::string> Features;
1751 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1752 ie = FeatureMap.end();
1753 it != ie; ++it)
1754 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001755
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001756 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001757 // While we populated the feature map above, we still need to
1758 // get and parse the target attribute so we can get the cpu for
1759 // the function.
1760 const auto *TD = FD->getAttr<TargetAttr>();
1761 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1762 if (ParsedAttr.second != "")
1763 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001764 if (TargetCPU != "")
1765 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1766 if (!Features.empty()) {
1767 std::sort(Features.begin(), Features.end());
1768 FuncAttrs.addAttribute(
1769 "target-features",
1770 llvm::join(Features.begin(), Features.end(), ","));
1771 }
1772 } else {
1773 // Otherwise just add the existing target cpu and target features to the
1774 // function.
1775 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1776 if (TargetCPU != "")
1777 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1778 if (!Features.empty()) {
1779 std::sort(Features.begin(), Features.end());
1780 FuncAttrs.addAttribute(
1781 "target-features",
1782 llvm::join(Features.begin(), Features.end(), ","));
1783 }
Eric Christopher70c16652015-03-25 23:14:47 +00001784 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001785 }
1786
Justin Lebarddd97fa2016-02-24 21:55:11 +00001787 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1788 // Conservatively, mark all functions and calls in CUDA as convergent
1789 // (meaning, they may call an intrinsically convergent op, such as
1790 // __syncthreads(), and so can't have certain optimizations applied around
1791 // them). LLVM will remove this attribute where it safely can.
1792 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Justin Lebard3a44f62016-04-05 18:26:20 +00001793
1794 // Respect -fcuda-flush-denormals-to-zero.
1795 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1796 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
Justin Lebarddd97fa2016-02-24 21:55:11 +00001797 }
1798
Alexey Samsonov153004f2014-09-29 22:08:00 +00001799 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001800
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001801 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001802 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001803 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001804 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001805 if (RetTy->hasSignedIntegerRepresentation())
1806 RetAttrs.addAttribute(llvm::Attribute::SExt);
1807 else if (RetTy->hasUnsignedIntegerRepresentation())
1808 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001809 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001810 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001811 if (RetAI.getInReg())
1812 RetAttrs.addAttribute(llvm::Attribute::InReg);
1813 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001814 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001815 break;
1816
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001817 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001818 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001819 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001820 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1821 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001822 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001823 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001824
John McCallf26e73d2016-03-11 04:30:43 +00001825 case ABIArgInfo::CoerceAndExpand:
1826 break;
1827
Daniel Dunbard3674e62008-09-11 01:48:57 +00001828 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001829 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001830 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001831
Hal Finkela2347ba2014-07-18 15:52:10 +00001832 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1833 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001834 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001835 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1836 .getQuantity());
1837 else if (getContext().getTargetAddressSpace(PTy) == 0)
1838 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1839 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001840
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001841 // Attach return attributes.
1842 if (RetAttrs.hasAttributes()) {
1843 PAL.push_back(llvm::AttributeSet::get(
1844 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1845 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001846
John McCall12f23522016-04-04 18:33:08 +00001847 bool hasUsedSRet = false;
1848
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001849 // Attach attributes to sret.
1850 if (IRFunctionArgs.hasSRetArg()) {
1851 llvm::AttrBuilder SRETAttrs;
1852 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001853 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001854 if (RetAI.getInReg())
1855 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1856 PAL.push_back(llvm::AttributeSet::get(
1857 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1858 }
1859
1860 // Attach attributes to inalloca argument.
1861 if (IRFunctionArgs.hasInallocaArg()) {
1862 llvm::AttrBuilder Attrs;
1863 Attrs.addAttribute(llvm::Attribute::InAlloca);
1864 PAL.push_back(llvm::AttributeSet::get(
1865 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1866 }
1867
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001868 unsigned ArgNo = 0;
1869 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1870 E = FI.arg_end();
1871 I != E; ++I, ++ArgNo) {
1872 QualType ParamType = I->type;
1873 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001874 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001875
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001876 // Add attribute for padding argument, if necessary.
1877 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001878 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001879 PAL.push_back(llvm::AttributeSet::get(
1880 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1881 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001882 }
1883
John McCall39ec71f2010-03-27 00:47:27 +00001884 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1885 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001886 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001887 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001888 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001889 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001890 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001891 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1892 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1893 Attrs.addAttribute(llvm::Attribute::SExt);
1894 else
1895 Attrs.addAttribute(llvm::Attribute::ZExt);
1896 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001897 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001898 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001899 if (ArgNo == 0 && FI.isChainCall())
1900 Attrs.addAttribute(llvm::Attribute::Nest);
1901 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001902 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001903 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001904
James Y Knight71608572015-08-21 18:19:06 +00001905 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001906 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001907 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001908
Anders Carlsson20759ad2009-09-16 15:53:40 +00001909 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001910 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001911
John McCall7f416cc2015-09-08 08:05:57 +00001912 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001913
1914 // In a byval argument, it is important that the required
1915 // alignment of the type is honored, as LLVM might be creating a
1916 // *new* stack object, and needs to know what alignment to give
1917 // it. (Sometimes it can deduce a sensible alignment on its own,
1918 // but not if clang decides it must emit a packed struct, or the
1919 // user specifies increased alignment requirements.)
1920 //
1921 // This is different from indirect *not* byval, where the object
1922 // exists already, and the align attribute is purely
1923 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001924 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001925
John McCall7f416cc2015-09-08 08:05:57 +00001926 // For now, only add this when we have a byval argument.
1927 // TODO: be less lazy about updating test cases.
1928 if (AI.getIndirectByVal())
1929 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001930
Daniel Dunbarc2304432009-03-18 19:51:01 +00001931 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001932 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1933 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001934 break;
James Y Knight71608572015-08-21 18:19:06 +00001935 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001936 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001937 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001938 case ABIArgInfo::CoerceAndExpand:
1939 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001940
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001941 case ABIArgInfo::InAlloca:
1942 // inalloca disables readnone and readonly.
1943 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1944 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001945 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
Hal Finkela2347ba2014-07-18 15:52:10 +00001948 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1949 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001950 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001951 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1952 .getQuantity());
1953 else if (getContext().getTargetAddressSpace(PTy) == 0)
1954 Attrs.addAttribute(llvm::Attribute::NonNull);
1955 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001956
John McCall12f23522016-04-04 18:33:08 +00001957 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
1958 case ParameterABI::Ordinary:
1959 break;
1960
1961 case ParameterABI::SwiftIndirectResult: {
1962 // Add 'sret' if we haven't already used it for something, but
1963 // only if the result is void.
1964 if (!hasUsedSRet && RetTy->isVoidType()) {
1965 Attrs.addAttribute(llvm::Attribute::StructRet);
1966 hasUsedSRet = true;
1967 }
1968
1969 // Add 'noalias' in either case.
1970 Attrs.addAttribute(llvm::Attribute::NoAlias);
1971
1972 // Add 'dereferenceable' and 'alignment'.
1973 auto PTy = ParamType->getPointeeType();
1974 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
1975 auto info = getContext().getTypeInfoInChars(PTy);
1976 Attrs.addDereferenceableAttr(info.first.getQuantity());
1977 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
1978 info.second.getQuantity()));
1979 }
1980 break;
1981 }
1982
1983 case ParameterABI::SwiftErrorResult:
1984 Attrs.addAttribute(llvm::Attribute::SwiftError);
1985 break;
1986
1987 case ParameterABI::SwiftContext:
1988 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
1989 break;
1990 }
1991
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001992 if (Attrs.hasAttributes()) {
1993 unsigned FirstIRArg, NumIRArgs;
1994 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1995 for (unsigned i = 0; i < NumIRArgs; i++)
1996 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1997 FirstIRArg + i + 1, Attrs));
1998 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001999 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002000 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002001
Bill Wendlinga7912f82012-10-10 07:36:56 +00002002 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002003 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002004 AttributeSet::get(getLLVMContext(),
2005 llvm::AttributeSet::FunctionIndex,
2006 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002007}
2008
John McCalla738c252011-03-09 04:27:21 +00002009/// An argument came in as a promoted argument; demote it back to its
2010/// declared type.
2011static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2012 const VarDecl *var,
2013 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002014 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002015
2016 // This can happen with promotions that actually don't change the
2017 // underlying type, like the enum promotions.
2018 if (value->getType() == varType) return value;
2019
2020 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2021 && "unexpected promotion type");
2022
2023 if (isa<llvm::IntegerType>(varType))
2024 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2025
2026 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2027}
2028
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002029/// Returns the attribute (either parameter attribute, or function
2030/// attribute), which declares argument ArgNo to be non-null.
2031static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2032 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002033 // FIXME: __attribute__((nonnull)) can also be applied to:
2034 // - references to pointers, where the pointee is known to be
2035 // nonnull (apparently a Clang extension)
2036 // - transparent unions containing pointers
2037 // In the former case, LLVM IR cannot represent the constraint. In
2038 // the latter case, we have no guarantee that the transparent union
2039 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002040 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2041 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002042 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002043 if (PVD) {
2044 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2045 return ParmNNAttr;
2046 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002047 // Check function attributes.
2048 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002049 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002050 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002051 if (NNAttr->isNonNull(ArgNo))
2052 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002053 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002054 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002055}
2056
John McCall12f23522016-04-04 18:33:08 +00002057namespace {
2058 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2059 Address Temp;
2060 Address Arg;
2061 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2062 void Emit(CodeGenFunction &CGF, Flags flags) override {
2063 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2064 CGF.Builder.CreateStore(errorValue, Arg);
2065 }
2066 };
2067}
2068
Daniel Dunbard931a872009-02-02 22:03:45 +00002069void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2070 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002071 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002072 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2073 // Naked functions don't have prologues.
2074 return;
2075
John McCallcaa19452009-07-28 01:00:58 +00002076 // If this is an implicit-return-zero function, go ahead and
2077 // initialize the return value. TODO: it might be nice to have
2078 // a more general mechanism for this that didn't require synthesized
2079 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002080 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002081 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002082 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002083 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002084 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002085 Builder.CreateStore(Zero, ReturnValue);
2086 }
2087 }
2088
Mike Stump18bb9282009-05-16 07:57:57 +00002089 // FIXME: We no longer need the types from FunctionArgList; lift up and
2090 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002091
Alexey Samsonov153004f2014-09-29 22:08:00 +00002092 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002093 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002094 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002095 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2096 for (auto &Arg : Fn->args()) {
2097 FnArgs.push_back(&Arg);
2098 }
2099 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002100
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002101 // If we're using inalloca, all the memory arguments are GEPs off of the last
2102 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002103 Address ArgStruct = Address::invalid();
2104 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002105 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002106 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2107 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2108 FI.getArgStructAlignment());
2109
2110 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002111 }
2112
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002113 // Name the struct return parameter.
2114 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002115 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002116 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002117 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002118 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002121 // Track if we received the parameter as a pointer (indirect, byval, or
2122 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2123 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002124 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002125 ArgVals.reserve(Args.size());
2126
Reid Kleckner739756c2013-12-04 19:23:12 +00002127 // Create a pointer value for every parameter declaration. This usually
2128 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2129 // any cleanups or do anything that might unwind. We do that separately, so
2130 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002131 assert(FI.arg_size() == Args.size() &&
2132 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002133 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002134 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002135 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002136 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002137 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002138 QualType Ty = info_it->type;
2139 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002140
John McCalla738c252011-03-09 04:27:21 +00002141 bool isPromoted =
2142 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2143
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002144 unsigned FirstIRArg, NumIRArgs;
2145 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002146
Daniel Dunbard3674e62008-09-11 01:48:57 +00002147 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002148 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002149 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002150 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2151 CharUnits FieldOffset =
2152 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2153 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2154 Arg->getName());
2155 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002156 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002157 }
2158
Daniel Dunbar747865a2009-02-05 09:16:39 +00002159 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002160 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002161 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002162
John McCall47fb9502013-03-07 21:37:08 +00002163 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002164 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002165 // need to do is realign the value, if requested.
2166 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002167 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002168 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002169
2170 // Copy from the incoming argument pointer to the temporary with the
2171 // appropriate alignment.
2172 //
2173 // FIXME: We should have a common utility for generating an aggregate
2174 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002175 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002176 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2177 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2178 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2179 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002180 V = AlignedTemp;
2181 }
John McCall7f416cc2015-09-08 08:05:57 +00002182 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002183 } else {
2184 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002185 llvm::Value *V =
2186 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002187
2188 if (isPromoted)
2189 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002190 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002191 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002192 break;
2193 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002194
2195 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002196 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002197
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002198 // If we have the trivial case, handle it with no muss and fuss.
2199 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002200 ArgI.getCoerceToType() == ConvertType(Ty) &&
2201 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002202 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002203 llvm::Value *V = FnArgs[FirstIRArg];
2204 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002205
Hal Finkel48d53e22014-07-19 01:41:07 +00002206 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002207 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2208 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002209 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2210 AI->getArgNo() + 1,
2211 llvm::Attribute::NonNull));
2212
Hal Finkel48d53e22014-07-19 01:41:07 +00002213 QualType OTy = PVD->getOriginalType();
2214 if (const auto *ArrTy =
2215 getContext().getAsConstantArrayType(OTy)) {
2216 // A C99 array parameter declaration with the static keyword also
2217 // indicates dereferenceability, and if the size is constant we can
2218 // use the dereferenceable attribute (which requires the size in
2219 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002220 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002221 QualType ETy = ArrTy->getElementType();
2222 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2223 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2224 ArrSize) {
2225 llvm::AttrBuilder Attrs;
2226 Attrs.addDereferenceableAttr(
2227 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2228 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2229 AI->getArgNo() + 1, Attrs));
2230 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2231 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2232 AI->getArgNo() + 1,
2233 llvm::Attribute::NonNull));
2234 }
2235 }
2236 } else if (const auto *ArrTy =
2237 getContext().getAsVariableArrayType(OTy)) {
2238 // For C99 VLAs with the static keyword, we don't know the size so
2239 // we can't use the dereferenceable attribute, but in addrspace(0)
2240 // we know that it must be nonnull.
2241 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2242 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2243 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2244 AI->getArgNo() + 1,
2245 llvm::Attribute::NonNull));
2246 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002247
2248 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2249 if (!AVAttr)
2250 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2251 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2252 if (AVAttr) {
2253 llvm::Value *AlignmentValue =
2254 EmitScalarExpr(AVAttr->getAlignment());
2255 llvm::ConstantInt *AlignmentCI =
2256 cast<llvm::ConstantInt>(AlignmentValue);
2257 unsigned Alignment =
2258 std::min((unsigned) AlignmentCI->getZExtValue(),
2259 +llvm::Value::MaximumAlignment);
2260
2261 llvm::AttrBuilder Attrs;
2262 Attrs.addAlignmentAttr(Alignment);
2263 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2264 AI->getArgNo() + 1, Attrs));
2265 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002266 }
2267
Bill Wendling507c3512012-10-16 05:23:44 +00002268 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002269 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2270 AI->getArgNo() + 1,
2271 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002272
John McCall12f23522016-04-04 18:33:08 +00002273 // LLVM expects swifterror parameters to be used in very restricted
2274 // ways. Copy the value into a less-restricted temporary.
2275 if (FI.getExtParameterInfo(ArgNo).getABI()
2276 == ParameterABI::SwiftErrorResult) {
2277 QualType pointeeTy = Ty->getPointeeType();
2278 assert(pointeeTy->isPointerType());
2279 Address temp =
2280 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2281 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2282 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2283 Builder.CreateStore(incomingErrorValue, temp);
2284 V = temp.getPointer();
2285
2286 // Push a cleanup to copy the value back at the end of the function.
2287 // The convention does not guarantee that the value will be written
2288 // back if the function exits with an unwind exception.
2289 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2290 }
2291
Chris Lattner7369c142011-07-20 06:29:00 +00002292 // Ensure the argument is the correct type.
2293 if (V->getType() != ArgI.getCoerceToType())
2294 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2295
John McCalla738c252011-03-09 04:27:21 +00002296 if (isPromoted)
2297 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002298
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002299 if (const CXXMethodDecl *MD =
2300 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002301 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002302 V = CGM.getCXXABI().
2303 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002304 }
2305
Rafael Espindola8778c282012-11-29 16:09:03 +00002306 // Because of merging of function types from multiple decls it is
2307 // possible for the type of an argument to not match the corresponding
2308 // type in the function type. Since we are codegening the callee
2309 // in here, add a cast to the argument type.
2310 llvm::Type *LTy = ConvertType(Arg->getType());
2311 if (V->getType() != LTy)
2312 V = Builder.CreateBitCast(V, LTy);
2313
John McCall7f416cc2015-09-08 08:05:57 +00002314 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002315 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002316 }
Mike Stump11289f42009-09-09 15:08:12 +00002317
John McCall7f416cc2015-09-08 08:05:57 +00002318 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2319 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002320
John McCall7f416cc2015-09-08 08:05:57 +00002321 // Pointer to store into.
2322 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002323
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002324 // Fast-isel and the optimizer generally like scalar values better than
2325 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002326 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002327 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2328 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002329 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002330 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002331 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002332 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002333
John McCall7f416cc2015-09-08 08:05:57 +00002334 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002335 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002336 AddrToStoreInto =
2337 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002338 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002339 AddrToStoreInto =
2340 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002341 }
John McCall7f416cc2015-09-08 08:05:57 +00002342
2343 assert(STy->getNumElements() == NumIRArgs);
2344 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2345 auto AI = FnArgs[FirstIRArg + i];
2346 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2347 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2348 Address EltPtr =
2349 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2350 Builder.CreateStore(AI, EltPtr);
2351 }
2352
2353 if (SrcSize > DstSize) {
2354 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2355 }
2356
Chris Lattner15ec3612010-06-29 00:06:42 +00002357 } else {
2358 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002359 assert(NumIRArgs == 1);
2360 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002361 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002362 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002363 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002364
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002365 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002366 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002367 llvm::Value *V =
2368 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002369 if (isPromoted)
2370 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002371 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002372 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002373 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002374 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002375 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002376 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002377
John McCallf26e73d2016-03-11 04:30:43 +00002378 case ABIArgInfo::CoerceAndExpand: {
2379 // Reconstruct into a temporary.
2380 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2381 ArgVals.push_back(ParamValue::forIndirect(alloca));
2382
2383 auto coercionType = ArgI.getCoerceAndExpandType();
2384 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2385 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2386
2387 unsigned argIndex = FirstIRArg;
2388 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2389 llvm::Type *eltType = coercionType->getElementType(i);
2390 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2391 continue;
2392
2393 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2394 auto elt = FnArgs[argIndex++];
2395 Builder.CreateStore(elt, eltAddr);
2396 }
2397 assert(argIndex == FirstIRArg + NumIRArgs);
2398 break;
2399 }
2400
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002401 case ABIArgInfo::Expand: {
2402 // If this structure was expanded into multiple arguments then
2403 // we need to create a temporary and reconstruct it from the
2404 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002405 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2406 LValue LV = MakeAddrLValue(Alloca, Ty);
2407 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002408
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002409 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2410 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2411 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2412 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2413 auto AI = FnArgs[FirstIRArg + i];
2414 AI->setName(Arg->getName() + "." + Twine(i));
2415 }
2416 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002417 }
2418
2419 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002420 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002421 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002422 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002423 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002424 } else {
2425 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002426 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002427 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002428 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002429 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002430 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002431
Reid Kleckner739756c2013-12-04 19:23:12 +00002432 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2433 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002434 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002435 } else {
2436 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002437 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002438 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002439}
2440
John McCallffa2c1a2012-01-29 07:46:59 +00002441static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2442 while (insn->use_empty()) {
2443 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2444 if (!bitcast) return;
2445
2446 // This is "safe" because we would have used a ConstantExpr otherwise.
2447 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2448 bitcast->eraseFromParent();
2449 }
2450}
2451
John McCall31168b02011-06-15 23:02:42 +00002452/// Try to emit a fused autorelease of a return result.
2453static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2454 llvm::Value *result) {
2455 // We must be immediately followed the cast.
2456 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002457 if (BB->empty()) return nullptr;
2458 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002459
Chris Lattner2192fe52011-07-18 04:24:23 +00002460 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002461
2462 // result is in a BasicBlock and is therefore an Instruction.
2463 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2464
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002465 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002466
2467 // Look for:
2468 // %generator = bitcast %type1* %generator2 to %type2*
2469 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2470 // We would have emitted this as a constant if the operand weren't
2471 // an Instruction.
2472 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2473
2474 // Require the generator to be immediately followed by the cast.
2475 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002476 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002477
2478 insnsToKill.push_back(bitcast);
2479 }
2480
2481 // Look for:
2482 // %generator = call i8* @objc_retain(i8* %originalResult)
2483 // or
2484 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2485 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002486 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002487
2488 bool doRetainAutorelease;
2489
John McCallb04ecb72015-10-21 18:06:43 +00002490 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002491 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002492 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002493 .objc_retainAutoreleasedReturnValue) {
2494 doRetainAutorelease = false;
2495
John McCallcfa4e9b2012-09-07 23:30:50 +00002496 // If we emitted an assembly marker for this call (and the
2497 // ARCEntrypoints field should have been set if so), go looking
2498 // for that call. If we can't find it, we can't do this
2499 // optimization. But it should always be the immediately previous
2500 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002501 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002502 llvm::Instruction *prev = call->getPrevNode();
2503 assert(prev);
2504 if (isa<llvm::BitCastInst>(prev)) {
2505 prev = prev->getPrevNode();
2506 assert(prev);
2507 }
2508 assert(isa<llvm::CallInst>(prev));
2509 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002510 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002511 insnsToKill.push_back(prev);
2512 }
John McCall31168b02011-06-15 23:02:42 +00002513 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002514 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002515 }
2516
2517 result = call->getArgOperand(0);
2518 insnsToKill.push_back(call);
2519
2520 // Keep killing bitcasts, for sanity. Note that we no longer care
2521 // about precise ordering as long as there's exactly one use.
2522 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2523 if (!bitcast->hasOneUse()) break;
2524 insnsToKill.push_back(bitcast);
2525 result = bitcast->getOperand(0);
2526 }
2527
2528 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002529 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002530 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2531 (*i)->eraseFromParent();
2532
2533 // Do the fused retain/autorelease if we were asked to.
2534 if (doRetainAutorelease)
2535 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2536
2537 // Cast back to the result type.
2538 return CGF.Builder.CreateBitCast(result, resultType);
2539}
2540
John McCallffa2c1a2012-01-29 07:46:59 +00002541/// If this is a +1 of the value of an immutable 'self', remove it.
2542static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2543 llvm::Value *result) {
2544 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002545 const ObjCMethodDecl *method =
2546 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002547 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002548 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002549 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002550
2551 // Look for a retain call.
2552 llvm::CallInst *retainCall =
2553 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2554 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002555 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002556 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002557
2558 // Look for an ordinary load of 'self'.
2559 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2560 llvm::LoadInst *load =
2561 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2562 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002563 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002564 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002565
2566 // Okay! Burn it all down. This relies for correctness on the
2567 // assumption that the retain is emitted as part of the return and
2568 // that thereafter everything is used "linearly".
2569 llvm::Type *resultType = result->getType();
2570 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2571 assert(retainCall->use_empty());
2572 retainCall->eraseFromParent();
2573 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2574
2575 return CGF.Builder.CreateBitCast(load, resultType);
2576}
2577
John McCall31168b02011-06-15 23:02:42 +00002578/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002579///
2580/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002581static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2582 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002583 // If we're returning 'self', kill the initial retain. This is a
2584 // heuristic attempt to "encourage correctness" in the really unfortunate
2585 // case where we have a return of self during a dealloc and we desperately
2586 // need to avoid the possible autorelease.
2587 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2588 return self;
2589
John McCall31168b02011-06-15 23:02:42 +00002590 // At -O0, try to emit a fused retain/autorelease.
2591 if (CGF.shouldUseFusedARCCalls())
2592 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2593 return fused;
2594
2595 return CGF.EmitARCAutoreleaseReturnValue(result);
2596}
2597
John McCall6e1c0122012-01-29 02:35:02 +00002598/// Heuristically search for a dominating store to the return-value slot.
2599static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002600 // Check if a User is a store which pointerOperand is the ReturnValue.
2601 // We are looking for stores to the ReturnValue, not for stores of the
2602 // ReturnValue to some other location.
2603 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2604 auto *SI = dyn_cast<llvm::StoreInst>(U);
2605 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2606 return nullptr;
2607 // These aren't actually possible for non-coerced returns, and we
2608 // only care about non-coerced returns on this code path.
2609 assert(!SI->isAtomic() && !SI->isVolatile());
2610 return SI;
2611 };
John McCall6e1c0122012-01-29 02:35:02 +00002612 // If there are multiple uses of the return-value slot, just check
2613 // for something immediately preceding the IP. Sometimes this can
2614 // happen with how we generate implicit-returns; it can also happen
2615 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002616 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002617 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002618 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002619 llvm::Instruction *I = &IP->back();
2620
2621 // Skip lifetime markers
2622 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2623 IE = IP->rend();
2624 II != IE; ++II) {
2625 if (llvm::IntrinsicInst *Intrinsic =
2626 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2627 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2628 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2629 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002630 if (II == IE)
2631 break;
2632 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2633 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002634 }
2635 }
2636 I = &*II;
2637 break;
2638 }
2639
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002640 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002641 }
2642
2643 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002644 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002645 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002646
John McCall6e1c0122012-01-29 02:35:02 +00002647 // Now do a first-and-dirty dominance check: just walk up the
2648 // single-predecessors chain from the current insertion point.
2649 llvm::BasicBlock *StoreBB = store->getParent();
2650 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2651 while (IP != StoreBB) {
2652 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002653 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002654 }
2655
2656 // Okay, the store's basic block dominates the insertion point; we
2657 // can do our thing.
2658 return store;
2659}
2660
Adrian Prantl3be10542013-05-02 17:30:20 +00002661void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002662 bool EmitRetDbgLoc,
2663 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002664 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2665 // Naked functions don't have epilogues.
2666 Builder.CreateUnreachable();
2667 return;
2668 }
2669
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002670 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002671 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002672 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002673 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002674 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002675
Dan Gohman481e40c2010-07-20 20:13:52 +00002676 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002677 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002678 QualType RetTy = FI.getReturnType();
2679 const ABIArgInfo &RetAI = FI.getReturnInfo();
2680
2681 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002682 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002683 // Aggregrates get evaluated directly into the destination. Sometimes we
2684 // need to return the sret value in a register, though.
2685 assert(hasAggregateEvaluationKind(RetTy));
2686 if (RetAI.getInAllocaSRet()) {
2687 llvm::Function::arg_iterator EI = CurFn->arg_end();
2688 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002689 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002690 llvm::Value *SRet = Builder.CreateStructGEP(
2691 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002692 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002693 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002694 break;
2695
Daniel Dunbar03816342010-08-21 02:24:36 +00002696 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002697 auto AI = CurFn->arg_begin();
2698 if (RetAI.isSRetAfterThis())
2699 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002700 switch (getEvaluationKind(RetTy)) {
2701 case TEK_Complex: {
2702 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002703 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002704 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002705 /*isInit*/ true);
2706 break;
2707 }
2708 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002709 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002710 break;
2711 case TEK_Scalar:
2712 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002713 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002714 /*isInit*/ true);
2715 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002716 }
2717 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002718 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002719
2720 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002721 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002722 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2723 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002724 // The internal return value temp always will have pointer-to-return-type
2725 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002726
John McCall6e1c0122012-01-29 02:35:02 +00002727 // If there is a dominating store to ReturnValue, we can elide
2728 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002729 if (llvm::StoreInst *SI =
2730 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002731 // Reuse the debug location from the store unless there is
2732 // cleanup code to be emitted between the store and return
2733 // instruction.
2734 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002735 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002736 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002737 RV = SI->getValueOperand();
2738 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002739
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002740 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002741 auto returnValueInst = ReturnValue.getPointer();
2742 if (returnValueInst->use_empty()) {
2743 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2744 alloca->eraseFromParent();
2745 ReturnValue = Address::invalid();
2746 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002747 }
John McCall6e1c0122012-01-29 02:35:02 +00002748
2749 // Otherwise, we have to do a simple load.
2750 } else {
2751 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002752 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002753 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002754 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002755 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002756
John McCall7f416cc2015-09-08 08:05:57 +00002757 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002758 }
John McCall31168b02011-06-15 23:02:42 +00002759
2760 // In ARC, end functions that return a retainable type with a call
2761 // to objc_autoreleaseReturnValue.
2762 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002763#ifndef NDEBUG
2764 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2765 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2766 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2767 // CurCodeDecl or BlockInfo.
2768 QualType RT;
2769
2770 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2771 RT = FD->getReturnType();
2772 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2773 RT = MD->getReturnType();
2774 else if (isa<BlockDecl>(CurCodeDecl))
2775 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2776 else
2777 llvm_unreachable("Unexpected function/method type");
2778
David Blaikiebbafb8a2012-03-11 07:00:24 +00002779 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002780 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002781 RT->isObjCRetainableType());
2782#endif
John McCall31168b02011-06-15 23:02:42 +00002783 RV = emitAutoreleaseOfResult(*this, RV);
2784 }
2785
Chris Lattner726b3d02010-06-26 23:13:19 +00002786 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002787
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002788 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002789 break;
2790
John McCallf26e73d2016-03-11 04:30:43 +00002791 case ABIArgInfo::CoerceAndExpand: {
2792 auto coercionType = RetAI.getCoerceAndExpandType();
2793 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2794
2795 // Load all of the coerced elements out into results.
2796 llvm::SmallVector<llvm::Value*, 4> results;
2797 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2798 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2799 auto coercedEltType = coercionType->getElementType(i);
2800 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2801 continue;
2802
2803 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2804 auto elt = Builder.CreateLoad(eltAddr);
2805 results.push_back(elt);
2806 }
2807
2808 // If we have one result, it's the single direct result type.
2809 if (results.size() == 1) {
2810 RV = results[0];
2811
2812 // Otherwise, we need to make a first-class aggregate.
2813 } else {
2814 // Construct a return type that lacks padding elements.
2815 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2816
2817 RV = llvm::UndefValue::get(returnType);
2818 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2819 RV = Builder.CreateInsertValue(RV, results[i], i);
2820 }
2821 }
2822 break;
2823 }
2824
Chris Lattner726b3d02010-06-26 23:13:19 +00002825 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002826 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002827 }
2828
Alexey Samsonovde443c52014-08-13 00:26:40 +00002829 llvm::Instruction *Ret;
2830 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002831 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2832 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002833 SanitizerScope SanScope(this);
2834 llvm::Value *Cond = Builder.CreateICmpNE(
2835 RV, llvm::Constant::getNullValue(RV->getType()));
2836 llvm::Constant *StaticData[] = {
2837 EmitCheckSourceLocation(EndLoc),
2838 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2839 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002840 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2841 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002842 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002843 }
2844 Ret = Builder.CreateRet(RV);
2845 } else {
2846 Ret = Builder.CreateRetVoid();
2847 }
2848
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002849 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002850 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002851}
2852
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002853static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2854 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2855 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2856}
2857
John McCall7f416cc2015-09-08 08:05:57 +00002858static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2859 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002860 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2861 // placeholders.
2862 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2863 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002864 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2865 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2866
2867 // FIXME: When we generate this IR in one pass, we shouldn't need
2868 // this win32-specific alignment hack.
2869 CharUnits Align = CharUnits::fromQuantity(4);
2870
2871 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002872 Ty.getQualifiers(),
2873 AggValueSlot::IsNotDestructed,
2874 AggValueSlot::DoesNotNeedGCBarriers,
2875 AggValueSlot::IsNotAliased);
2876}
2877
John McCall32ea9692011-03-11 20:59:21 +00002878void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002879 const VarDecl *param,
2880 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002881 // StartFunction converted the ABI-lowered parameter(s) into a
2882 // local alloca. We need to turn that into an r-value suitable
2883 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002884 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002885
John McCall32ea9692011-03-11 20:59:21 +00002886 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002887
Reid Klecknerab2090d2014-07-26 01:34:32 +00002888 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2889 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002890
Richard Smithd62d4982016-06-14 01:13:21 +00002891 // For the most part, we just need to load the alloca, except that
2892 // aggregate r-values are actually pointers to temporaries.
2893 if (type->isReferenceType())
2894 args.add(RValue::get(Builder.CreateLoad(local)), type);
2895 else
2896 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002897}
2898
John McCall31168b02011-06-15 23:02:42 +00002899static bool isProvablyNull(llvm::Value *addr) {
2900 return isa<llvm::ConstantPointerNull>(addr);
2901}
2902
2903static bool isProvablyNonNull(llvm::Value *addr) {
2904 return isa<llvm::AllocaInst>(addr);
2905}
2906
2907/// Emit the actual writing-back of a writeback.
2908static void emitWriteback(CodeGenFunction &CGF,
2909 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002910 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002911 Address srcAddr = srcLV.getAddress();
2912 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002913 "shouldn't have writeback for provably null argument");
2914
Craig Topper8a13c412014-05-21 05:09:00 +00002915 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002916
2917 // If the argument wasn't provably non-null, we need to null check
2918 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002919 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002920 if (!provablyNonNull) {
2921 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2922 contBB = CGF.createBasicBlock("icr.done");
2923
John McCall7f416cc2015-09-08 08:05:57 +00002924 llvm::Value *isNull =
2925 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002926 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2927 CGF.EmitBlock(writebackBB);
2928 }
2929
2930 // Load the value to writeback.
2931 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2932
2933 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002934 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2935 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002936
2937 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002938
2939 // If we have a "to use" value, it's something we need to emit a use
2940 // of. This has to be carefully threaded in: if it's done after the
2941 // release it's potentially undefined behavior (and the optimizer
2942 // will ignore it), and if it happens before the retain then the
2943 // optimizer could move the release there.
2944 if (writeback.ToUse) {
2945 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2946
2947 // Retain the new value. No need to block-copy here: the block's
2948 // being passed up the stack.
2949 value = CGF.EmitARCRetainNonBlock(value);
2950
2951 // Emit the intrinsic use here.
2952 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2953
2954 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002955 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002956
2957 // Put the new value in place (primitively).
2958 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2959
2960 // Release the old value.
2961 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2962
2963 // Otherwise, we can just do a normal lvalue store.
2964 } else {
2965 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2966 }
John McCall31168b02011-06-15 23:02:42 +00002967
2968 // Jump to the continuation block.
2969 if (!provablyNonNull)
2970 CGF.EmitBlock(contBB);
2971}
2972
2973static void emitWritebacks(CodeGenFunction &CGF,
2974 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002975 for (const auto &I : args.writebacks())
2976 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002977}
2978
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002979static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2980 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002981 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002982 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2983 CallArgs.getCleanupsToDeactivate();
2984 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002985 for (const auto &I : llvm::reverse(Cleanups)) {
2986 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2987 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002988 }
2989}
2990
John McCalleff18842013-03-23 02:35:54 +00002991static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2992 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2993 if (uop->getOpcode() == UO_AddrOf)
2994 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002995 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002996}
2997
John McCall31168b02011-06-15 23:02:42 +00002998/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002999/// we are passing the address of an __autoreleased temporary; it
3000/// might be copy-initialized with the current value of the given
3001/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003002static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3003 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003004 LValue srcLV;
3005
3006 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003007 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003008 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3009 srcLV = CGF.EmitLValue(lvExpr);
3010
3011 // Otherwise, just emit it as a scalar.
3012 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003013 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003014
3015 QualType srcAddrType =
3016 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003017 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003018 }
John McCall7f416cc2015-09-08 08:05:57 +00003019 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003020
3021 // The dest and src types don't necessarily match in LLVM terms
3022 // because of the crazy ObjC compatibility rules.
3023
Chris Lattner2192fe52011-07-18 04:24:23 +00003024 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003025 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3026
3027 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003028 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003029 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3030 CRE->getType());
3031 return;
3032 }
3033
John McCall31168b02011-06-15 23:02:42 +00003034 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003035 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3036 CGF.getPointerAlign(),
3037 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003038 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3039 // and that cleanup will be conditional if we can't prove that the l-value
3040 // isn't null, so we need to register a dominating point so that the cleanups
3041 // system will make valid IR.
3042 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3043
John McCall31168b02011-06-15 23:02:42 +00003044 // Zero-initialize it if we're not doing a copy-initialization.
3045 bool shouldCopy = CRE->shouldCopy();
3046 if (!shouldCopy) {
3047 llvm::Value *null =
3048 llvm::ConstantPointerNull::get(
3049 cast<llvm::PointerType>(destType->getElementType()));
3050 CGF.Builder.CreateStore(null, temp);
3051 }
Craig Topper8a13c412014-05-21 05:09:00 +00003052
3053 llvm::BasicBlock *contBB = nullptr;
3054 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003055
3056 // If the address is *not* known to be non-null, we need to switch.
3057 llvm::Value *finalArgument;
3058
John McCall7f416cc2015-09-08 08:05:57 +00003059 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003060 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003061 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003062 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003063 llvm::Value *isNull =
3064 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003065
3066 finalArgument = CGF.Builder.CreateSelect(isNull,
3067 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003068 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003069
3070 // If we need to copy, then the load has to be conditional, which
3071 // means we need control flow.
3072 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003073 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003074 contBB = CGF.createBasicBlock("icr.cont");
3075 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3076 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3077 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003078 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003079 }
3080 }
3081
Craig Topper8a13c412014-05-21 05:09:00 +00003082 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003083
John McCall31168b02011-06-15 23:02:42 +00003084 // Perform a copy if necessary.
3085 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003086 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003087 assert(srcRV.isScalar());
3088
3089 llvm::Value *src = srcRV.getScalarVal();
3090 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3091 "icr.cast");
3092
3093 // Use an ordinary store, not a store-to-lvalue.
3094 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003095
3096 // If optimization is enabled, and the value was held in a
3097 // __strong variable, we need to tell the optimizer that this
3098 // value has to stay alive until we're doing the store back.
3099 // This is because the temporary is effectively unretained,
3100 // and so otherwise we can violate the high-level semantics.
3101 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3102 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3103 valueToUse = src;
3104 }
John McCall31168b02011-06-15 23:02:42 +00003105 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003106
John McCall31168b02011-06-15 23:02:42 +00003107 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003108 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003109 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003110 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003111
3112 // Make a phi for the value to intrinsically use.
3113 if (valueToUse) {
3114 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3115 "icr.to-use");
3116 phiToUse->addIncoming(valueToUse, copyBB);
3117 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3118 originBB);
3119 valueToUse = phiToUse;
3120 }
3121
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003122 condEval.end(CGF);
3123 }
John McCall31168b02011-06-15 23:02:42 +00003124
John McCalleff18842013-03-23 02:35:54 +00003125 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003126 args.add(RValue::get(finalArgument), CRE->getType());
3127}
3128
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003129void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3130 assert(!StackBase && !StackCleanup.isValid());
3131
3132 // Save the stack.
3133 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003134 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003135}
3136
Nico Weber8cdb3f92015-08-25 18:43:32 +00003137void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3138 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003139 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003140 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003141 CGF.Builder.CreateCall(F, StackBase);
3142 }
3143}
3144
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003145void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3146 SourceLocation ArgLoc,
3147 const FunctionDecl *FD,
3148 unsigned ParmNum) {
3149 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003150 return;
3151 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3152 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3153 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3154 if (!NNAttr)
3155 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003156 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003157 assert(RV.isScalar());
3158 llvm::Value *V = RV.getScalarVal();
3159 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003160 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003161 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003162 EmitCheckSourceLocation(ArgLoc),
3163 EmitCheckSourceLocation(NNAttr->getLocation()),
3164 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003165 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003166 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003167 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003168}
3169
David Blaikief05779e2015-07-21 18:37:18 +00003170void CodeGenFunction::EmitCallArgs(
3171 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3172 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3173 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3174 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003175
3176 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3177 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3178 return;
3179 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3180 if (PS == nullptr)
3181 return;
3182
3183 const auto &Context = getContext();
3184 auto SizeTy = Context.getSizeType();
3185 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3186 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3187 Args.add(RValue::get(V), SizeTy);
3188 };
3189
Reid Kleckner739756c2013-12-04 19:23:12 +00003190 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3191 // because arguments are destroyed left to right in the callee.
3192 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003193 // Insert a stack save if we're going to need any inalloca args.
3194 bool HasInAllocaArgs = false;
3195 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3196 I != E && !HasInAllocaArgs; ++I)
3197 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3198 if (HasInAllocaArgs) {
3199 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3200 Args.allocateArgumentMemory(*this);
3201 }
3202
3203 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003204 size_t CallArgsStart = Args.size();
3205 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003206 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Richard Smith5179eb72016-06-28 19:03:57 +00003207 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003208 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003209 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003210 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00003211 }
3212
3213 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3214 // IR function.
3215 std::reverse(Args.begin() + CallArgsStart, Args.end());
3216 return;
3217 }
3218
3219 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003220 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3221 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003222 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003223 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003224 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003225 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003226 }
3227}
3228
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003229namespace {
3230
David Blaikie7e70d682015-08-18 22:40:54 +00003231struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003232 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003233 : Addr(Addr), Ty(Ty) {}
3234
John McCall7f416cc2015-09-08 08:05:57 +00003235 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003236 QualType Ty;
3237
Craig Topper4f12f102014-03-12 06:41:41 +00003238 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003239 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3240 assert(!Dtor->isTrivial());
3241 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3242 /*Delegating=*/false, Addr);
3243 }
3244};
3245
David Blaikie38b25912015-02-09 19:13:51 +00003246struct DisableDebugLocationUpdates {
3247 CodeGenFunction &CGF;
3248 bool disabledDebugInfo;
3249 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3250 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3251 CGF.disableDebugInfo();
3252 }
3253 ~DisableDebugLocationUpdates() {
3254 if (disabledDebugInfo)
3255 CGF.enableDebugInfo();
3256 }
3257};
3258
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003259} // end anonymous namespace
3260
John McCall32ea9692011-03-11 20:59:21 +00003261void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3262 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003263 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003264 if (const ObjCIndirectCopyRestoreExpr *CRE
3265 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003266 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003267 assert(getContext().hasSameType(E->getType(), type));
3268 return emitWritebackArg(*this, args, CRE);
3269 }
3270
John McCall0a76c0c2011-08-26 18:42:59 +00003271 assert(type->isReferenceType() == E->isGLValue() &&
3272 "reference binding to unmaterialized r-value!");
3273
John McCall17054bd62011-08-26 21:08:13 +00003274 if (E->isGLValue()) {
3275 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003276 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003279 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3280
3281 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3282 // However, we still have to push an EH-only cleanup in case we unwind before
3283 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003284 if (HasAggregateEvalKind &&
3285 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3286 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003287 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003288 AggValueSlot Slot;
3289 if (args.isUsingInAlloca())
3290 Slot = createPlaceholderSlot(*this, type);
3291 else
3292 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003293
3294 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3295 bool DestroyedInCallee =
3296 RD && RD->hasNonTrivialDestructor() &&
3297 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3298 if (DestroyedInCallee)
3299 Slot.setExternallyDestructed();
3300
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003301 EmitAggExpr(E, Slot);
3302 RValue RV = Slot.asRValue();
3303 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003304
Reid Klecknere39ee212014-05-03 00:33:28 +00003305 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003306 // Create a no-op GEP between the placeholder and the cleanup so we can
3307 // RAUW it successfully. It also serves as a marker of the first
3308 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003309 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3310 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003311 // This unreachable is a temporary marker which will be removed later.
3312 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3313 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003314 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003315 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003316 }
3317
3318 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003319 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3320 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3321 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003322 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3323 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3324 } else {
3325 // We can't represent a misaligned lvalue in the CallArgList, so copy
3326 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003327 Address tmp = CreateMemTemp(type);
3328 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003329 args.add(RValue::getAggregate(tmp), type);
3330 }
Eli Friedmandf968192011-05-26 00:10:27 +00003331 return;
3332 }
3333
John McCall32ea9692011-03-11 20:59:21 +00003334 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003335}
3336
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003337QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3338 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3339 // implicitly widens null pointer constants that are arguments to varargs
3340 // functions to pointer-sized ints.
3341 if (!getTarget().getTriple().isOSWindows())
3342 return Arg->getType();
3343
3344 if (Arg->getType()->isIntegerType() &&
3345 getContext().getTypeSize(Arg->getType()) <
3346 getContext().getTargetInfo().getPointerWidth(0) &&
3347 Arg->isNullPointerConstant(getContext(),
3348 Expr::NPC_ValueDependentIsNotNull)) {
3349 return getContext().getIntPtrType();
3350 }
3351
3352 return Arg->getType();
3353}
3354
Dan Gohman515a60d2012-02-16 00:57:37 +00003355// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3356// optimizer it can aggressively ignore unwind edges.
3357void
3358CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3359 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3360 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3361 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3362 CGM.getNoObjCARCExceptionsMetadata());
3363}
3364
John McCall882987f2013-02-28 19:01:20 +00003365/// Emits a call to the given no-arguments nounwind runtime function.
3366llvm::CallInst *
3367CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3368 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003369 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003370}
3371
3372/// Emits a call to the given nounwind runtime function.
3373llvm::CallInst *
3374CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3375 ArrayRef<llvm::Value*> args,
3376 const llvm::Twine &name) {
3377 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3378 call->setDoesNotThrow();
3379 return call;
3380}
3381
3382/// Emits a simple call (never an invoke) to the given no-arguments
3383/// runtime function.
3384llvm::CallInst *
3385CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3386 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003387 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003388}
3389
David Majnemer0b17d442015-12-15 21:27:59 +00003390// Calls which may throw must have operand bundles indicating which funclet
3391// they are nested within.
3392static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003393getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003394 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003395 // There is no need for a funclet operand bundle if we aren't inside a
3396 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003397 if (!CurrentFuncletPad)
3398 return;
3399
3400 // Skip intrinsics which cannot throw.
3401 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3402 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3403 return;
3404
3405 BundleList.emplace_back("funclet", CurrentFuncletPad);
3406}
3407
David Majnemer971d31b2016-02-24 17:02:45 +00003408/// Emits a simple call (never an invoke) to the given runtime function.
3409llvm::CallInst *
3410CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3411 ArrayRef<llvm::Value*> args,
3412 const llvm::Twine &name) {
3413 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3414 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3415
3416 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3417 call->setCallingConv(getRuntimeCC());
3418 return call;
3419}
3420
John McCall882987f2013-02-28 19:01:20 +00003421/// Emits a call or invoke to the given noreturn runtime function.
3422void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3423 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003424 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3425 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3426
John McCall882987f2013-02-28 19:01:20 +00003427 if (getInvokeDest()) {
3428 llvm::InvokeInst *invoke =
3429 Builder.CreateInvoke(callee,
3430 getUnreachableBlock(),
3431 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003432 args,
3433 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003434 invoke->setDoesNotReturn();
3435 invoke->setCallingConv(getRuntimeCC());
3436 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003437 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003438 call->setDoesNotReturn();
3439 call->setCallingConv(getRuntimeCC());
3440 Builder.CreateUnreachable();
3441 }
3442}
3443
Sanjay Patel846b63b2016-01-18 22:15:33 +00003444/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003445llvm::CallSite
3446CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3447 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003448 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003449}
3450
3451/// Emits a call or invoke instruction to the given runtime function.
3452llvm::CallSite
3453CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3454 ArrayRef<llvm::Value*> args,
3455 const Twine &name) {
3456 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3457 callSite.setCallingConv(getRuntimeCC());
3458 return callSite;
3459}
3460
John McCallbd309292010-07-06 01:34:17 +00003461/// Emits a call or invoke instruction to the given function, depending
3462/// on the current state of the EH stack.
3463llvm::CallSite
3464CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003465 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003466 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003467 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003468 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3469 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003470
Dan Gohman515a60d2012-02-16 00:57:37 +00003471 llvm::Instruction *Inst;
3472 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003473 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003474 else {
3475 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003476 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3477 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003478 EmitBlock(ContBB);
3479 }
3480
3481 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3482 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003483 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003484 AddObjCARCExceptionMetadata(Inst);
3485
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003486 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003487}
3488
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003489/// \brief Store a non-aggregate value to an address to initialize it. For
3490/// initialization, a non-atomic store will be used.
3491static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3492 LValue Dst) {
3493 if (Src.isScalar())
3494 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3495 else
3496 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3497}
3498
3499void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3500 llvm::Value *New) {
3501 DeferredReplacements.push_back(std::make_pair(Old, New));
3502}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003503
Daniel Dunbard931a872009-02-02 22:03:45 +00003504RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003505 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003506 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003507 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003508 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003509 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003510 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003511
3512 // Handle struct-return functions by passing a pointer to the
3513 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003514 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003515 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003516
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003517 llvm::FunctionType *IRFuncTy =
3518 cast<llvm::FunctionType>(
3519 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003520
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003521 // If we're using inalloca, insert the allocation after the stack save.
3522 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003523 Address ArgMemory = Address::invalid();
3524 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003525 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003526 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003527 llvm::Instruction *IP = CallArgs.getStackBase();
3528 llvm::AllocaInst *AI;
3529 if (IP) {
3530 IP = IP->getNextNode();
3531 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3532 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003533 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003534 }
John McCall7f416cc2015-09-08 08:05:57 +00003535 auto Align = CallInfo.getArgStructAlignment();
3536 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003537 AI->setUsedWithInAlloca(true);
3538 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003539 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003540 }
3541
John McCall7f416cc2015-09-08 08:05:57 +00003542 // Helper function to drill into the inalloca allocation.
3543 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3544 auto FieldOffset =
3545 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3546 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3547 };
3548
Alexey Samsonov153004f2014-09-29 22:08:00 +00003549 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003550 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3551
Chris Lattner4ca97c32009-06-13 00:26:38 +00003552 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003553 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003554 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003555 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003556 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003557 if (!ReturnValue.isNull()) {
3558 SRetPtr = ReturnValue.getValue();
3559 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003560 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003561 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3562 uint64_t size =
3563 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003564 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003565 UnusedReturnSize = size;
3566 }
3567 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003568 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003569 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003570 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003571 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3572 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003573 }
Anders Carlsson17490832009-12-24 20:40:36 +00003574 }
Mike Stump11289f42009-09-09 15:08:12 +00003575
John McCall12f23522016-04-04 18:33:08 +00003576 Address swiftErrorTemp = Address::invalid();
3577 Address swiftErrorArg = Address::invalid();
3578
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003579 assert(CallInfo.arg_size() == CallArgs.size() &&
3580 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003581 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003582 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003583 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003584 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003585 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003586 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003587
Rafael Espindolafad28de2012-10-24 01:59:00 +00003588 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003589 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3590 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3591 llvm::UndefValue::get(ArgInfo.getPaddingType());
3592
3593 unsigned FirstIRArg, NumIRArgs;
3594 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003595
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003596 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003597 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003598 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003599 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3600 if (RV.isAggregate()) {
3601 // Replace the placeholder with the appropriate argument slot GEP.
3602 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003603 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003604 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3605 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003606 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003607 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003608 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003609 } else {
3610 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003611 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3612 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003613 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3614 // There are some cases where a trivial bitcast is not avoidable. The
3615 // definition of a type later in a translation unit may change it's type
3616 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003617 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003618 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003619 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003620 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3621 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003622 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003623 }
3624
Daniel Dunbar03816342010-08-21 02:24:36 +00003625 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003626 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003627 if (RV.isScalar() || RV.isComplex()) {
3628 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003629 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3630 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003631
John McCall7f416cc2015-09-08 08:05:57 +00003632 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003633 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003634 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003635 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003636 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003637 // 1. If the argument is not byval, and we are required to copy the
3638 // source. (This case doesn't occur on any common architecture.)
3639 // 2. If the argument is byval, RV is not sufficiently aligned, and
3640 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003641 // 3. If the argument is byval, but RV is located in an address space
3642 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003643 Address Addr = RV.getAggregateAddress();
3644 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003645 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003646 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003647 const unsigned ArgAddrSpace =
3648 (FirstIRArg < IRFuncTy->getNumParams()
3649 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3650 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003651 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003652 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3653 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3654 Align.getQuantity(), *TD)
3655 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003656 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003657 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003658 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3659 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003660 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003661 } else {
3662 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003663 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003664 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003665 }
3666 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003667 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003668
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003669 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003670 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003671 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003672
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003673 case ABIArgInfo::Extend:
3674 case ABIArgInfo::Direct: {
3675 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003676 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3677 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003678 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003679 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003680 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003681 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003682 else
John McCall7f416cc2015-09-08 08:05:57 +00003683 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003684
John McCall12f23522016-04-04 18:33:08 +00003685 // Implement swifterror by copying into a new swifterror argument.
3686 // We'll write back in the normal path out of the call.
3687 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3688 == ParameterABI::SwiftErrorResult) {
3689 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3690
3691 QualType pointeeTy = I->Ty->getPointeeType();
3692 swiftErrorArg =
3693 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3694
3695 swiftErrorTemp =
3696 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3697 V = swiftErrorTemp.getPointer();
3698 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3699
3700 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3701 Builder.CreateStore(errorValue, swiftErrorTemp);
3702 }
3703
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003704 // We might have to widen integers, but we should never truncate.
3705 if (ArgInfo.getCoerceToType() != V->getType() &&
3706 V->getType()->isIntegerTy())
3707 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3708
Chris Lattner3ce86682011-07-12 04:53:39 +00003709 // If the argument doesn't match, perform a bitcast to coerce it. This
3710 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003711 if (FirstIRArg < IRFuncTy->getNumParams() &&
3712 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3713 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003714
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003715 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003716 break;
3717 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003718
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003719 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003720 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003721 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003722 Src = CreateMemTemp(I->Ty, "coerce");
3723 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003724 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003725 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003726 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003727 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003728
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003729 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003730 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003731
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003732 // Fast-isel and the optimizer generally like scalar values better than
3733 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003734 llvm::StructType *STy =
3735 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003736 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003737 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003738 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3739 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3740
3741 // If the source type is smaller than the destination type of the
3742 // coerce-to logic, copy the source value into a temp alloca the size
3743 // of the destination type to allow loading all of it. The bits past
3744 // the source value are left undef.
3745 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003746 Address TempAlloca
3747 = CreateTempAlloca(STy, Src.getAlignment(),
3748 Src.getName() + ".coerce");
3749 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3750 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003751 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003752 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003753 }
3754
John McCall7f416cc2015-09-08 08:05:57 +00003755 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003756 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003757 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003758 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3759 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3760 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003761 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003762 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003763 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003764 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003765 assert(NumIRArgs == 1);
3766 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003767 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003768 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003769
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003770 break;
3771 }
3772
John McCallf26e73d2016-03-11 04:30:43 +00003773 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003774 auto coercionType = ArgInfo.getCoerceAndExpandType();
3775 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3776
John McCall12f23522016-04-04 18:33:08 +00003777 llvm::Value *tempSize = nullptr;
3778 Address addr = Address::invalid();
3779 if (RV.isAggregate()) {
3780 addr = RV.getAggregateAddress();
3781 } else {
3782 assert(RV.isScalar()); // complex should always just be direct
3783
3784 llvm::Type *scalarType = RV.getScalarVal()->getType();
3785 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3786 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3787
3788 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3789
3790 // Materialize to a temporary.
3791 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3792 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3793 scalarAlign)));
3794 EmitLifetimeStart(scalarSize, addr.getPointer());
3795
3796 Builder.CreateStore(RV.getScalarVal(), addr);
3797 }
3798
John McCallf26e73d2016-03-11 04:30:43 +00003799 addr = Builder.CreateElementBitCast(addr, coercionType);
3800
3801 unsigned IRArgPos = FirstIRArg;
3802 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3803 llvm::Type *eltType = coercionType->getElementType(i);
3804 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3805 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3806 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3807 IRCallArgs[IRArgPos++] = elt;
3808 }
3809 assert(IRArgPos == FirstIRArg + NumIRArgs);
3810
John McCall12f23522016-04-04 18:33:08 +00003811 if (tempSize) {
3812 EmitLifetimeEnd(tempSize, addr.getPointer());
3813 }
3814
John McCallf26e73d2016-03-11 04:30:43 +00003815 break;
3816 }
3817
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003818 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003819 unsigned IRArgPos = FirstIRArg;
3820 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3821 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003822 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003823 }
3824 }
Mike Stump11289f42009-09-09 15:08:12 +00003825
John McCall7f416cc2015-09-08 08:05:57 +00003826 if (ArgMemory.isValid()) {
3827 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003828 if (CallInfo.isVariadic()) {
3829 // When passing non-POD arguments by value to variadic functions, we will
3830 // end up with a variadic prototype and an inalloca call site. In such
3831 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3832 // the callee.
3833 unsigned CalleeAS =
3834 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3835 Callee = Builder.CreateBitCast(
3836 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3837 } else {
3838 llvm::Type *LastParamTy =
3839 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3840 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003841#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003842 // Assert that these structs have equivalent element types.
3843 llvm::StructType *FullTy = CallInfo.getArgStruct();
3844 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3845 cast<llvm::PointerType>(LastParamTy)->getElementType());
3846 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3847 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3848 DE = DeclaredTy->element_end(),
3849 FI = FullTy->element_begin();
3850 DI != DE; ++DI, ++FI)
3851 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003852#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003853 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3854 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003855 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003856 assert(IRFunctionArgs.hasInallocaArg());
3857 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003858 }
3859
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003860 if (!CallArgs.getCleanupsToDeactivate().empty())
3861 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3862
Chris Lattner4ca97c32009-06-13 00:26:38 +00003863 // If the callee is a bitcast of a function to a varargs pointer to function
3864 // type, check to see if we can remove the bitcast. This handles some cases
3865 // with unprototyped functions.
3866 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3867 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003868 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3869 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003870 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003871 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003872
Chris Lattner4ca97c32009-06-13 00:26:38 +00003873 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3874 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003875 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003876 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003877 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003878 bool ArgsMatch = true;
3879 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3880 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3881 ArgsMatch = false;
3882 break;
3883 }
Mike Stump11289f42009-09-09 15:08:12 +00003884
Chris Lattner4ca97c32009-06-13 00:26:38 +00003885 // Strip the cast if we can get away with it. This is a nice cleanup,
3886 // but also allows us to inline the function at -O0 if it is marked
3887 // always_inline.
3888 if (ArgsMatch)
3889 Callee = CalleeF;
3890 }
3891 }
Mike Stump11289f42009-09-09 15:08:12 +00003892
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003893 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3894 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3895 // Inalloca argument can have different type.
3896 if (IRFunctionArgs.hasInallocaArg() &&
3897 i == IRFunctionArgs.getInallocaArgNo())
3898 continue;
3899 if (i < IRFuncTy->getNumParams())
3900 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3901 }
3902
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003903 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003904 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003905 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3906 AttributeList, CallingConv,
3907 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003908 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003909 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003910
David Majnemer4e52d6f2015-12-12 05:39:21 +00003911 bool CannotThrow;
3912 if (currentFunctionUsesSEHTry()) {
3913 // SEH cares about asynchronous exceptions, everything can "throw."
3914 CannotThrow = false;
3915 } else if (isCleanupPadScope() &&
3916 EHPersonality::get(*this).isMSVCXXPersonality()) {
3917 // The MSVC++ personality will implicitly terminate the program if an
3918 // exception is thrown. An unwind edge cannot be reached.
3919 CannotThrow = true;
3920 } else {
3921 // Otherwise, nowunind callsites will never throw.
3922 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3923 llvm::Attribute::NoUnwind);
3924 }
3925 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003926
David Majnemer0b17d442015-12-15 21:27:59 +00003927 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3928 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3929
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003930 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003931 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003932 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003933 } else {
3934 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003935 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3936 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003937 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003938 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003939 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003940 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003941
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003942 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3943 !CS.hasFnAttr(llvm::Attribute::NoInline))
3944 Attrs =
3945 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3946 llvm::Attribute::AlwaysInline);
3947
David Majnemer4e52d6f2015-12-12 05:39:21 +00003948 // Disable inlining inside SEH __try blocks.
3949 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003950 Attrs =
3951 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3952 llvm::Attribute::NoInline);
3953
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003954 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003955 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003956
Adam Nemet1e217bc2016-03-28 22:18:53 +00003957 // Insert instrumentation or attach profile metadata at indirect call sites.
3958 // For more details, see the comment before the definition of
3959 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003960 if (!CS.getCalledFunction())
3961 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3962 CS.getInstruction(), Callee);
3963
Dan Gohman515a60d2012-02-16 00:57:37 +00003964 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3965 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003966 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003967 AddObjCARCExceptionMetadata(CS.getInstruction());
3968
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003969 // If the call doesn't return, finish the basic block and clear the
3970 // insertion point; this allows the rest of IRgen to discard
3971 // unreachable code.
3972 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003973 if (UnusedReturnSize)
3974 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003975 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003976
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003977 Builder.CreateUnreachable();
3978 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003979
Mike Stump18bb9282009-05-16 07:57:57 +00003980 // FIXME: For now, emit a dummy basic block because expr emitters in
3981 // generally are not ready to handle emitting expressions at unreachable
3982 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003983 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003984
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003985 // Return a reasonable RValue.
3986 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003987 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003988
3989 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00003990 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003991 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003992
John McCall12f23522016-04-04 18:33:08 +00003993 // Perform the swifterror writeback.
3994 if (swiftErrorTemp.isValid()) {
3995 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
3996 Builder.CreateStore(errorResult, swiftErrorArg);
3997 }
3998
John McCall31168b02011-06-15 23:02:42 +00003999 // Emit any writebacks immediately. Arguably this should happen
4000 // after any return-value munging.
4001 if (CallArgs.hasWritebacks())
4002 emitWritebacks(*this, CallArgs);
4003
Nico Weber8cdb3f92015-08-25 18:43:32 +00004004 // The stack cleanup for inalloca arguments has to run out of the normal
4005 // lexical order, so deactivate it and run it manually here.
4006 CallArgs.freeArgumentMemory(*this);
4007
Samuel Antao798f11c2015-11-23 22:04:44 +00004008 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4009 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00004010 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4011 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00004012 }
Akira Hatanakac8667622015-11-06 23:56:15 +00004013
Hal Finkelee90a222014-09-26 05:04:30 +00004014 RValue Ret = [&] {
4015 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004016 case ABIArgInfo::CoerceAndExpand: {
4017 auto coercionType = RetAI.getCoerceAndExpandType();
4018 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4019
4020 Address addr = SRetPtr;
4021 addr = Builder.CreateElementBitCast(addr, coercionType);
4022
John McCall12f23522016-04-04 18:33:08 +00004023 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4024 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4025
John McCallf26e73d2016-03-11 04:30:43 +00004026 unsigned unpaddedIndex = 0;
4027 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4028 llvm::Type *eltType = coercionType->getElementType(i);
4029 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4030 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004031 llvm::Value *elt = CI;
4032 if (requiresExtract)
4033 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4034 else
4035 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004036 Builder.CreateStore(elt, eltAddr);
4037 }
John McCall12f23522016-04-04 18:33:08 +00004038 // FALLTHROUGH
4039 }
4040
4041 case ABIArgInfo::InAlloca:
4042 case ABIArgInfo::Indirect: {
4043 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4044 if (UnusedReturnSize)
4045 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4046 SRetPtr.getPointer());
4047 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004048 }
4049
Hal Finkelee90a222014-09-26 05:04:30 +00004050 case ABIArgInfo::Ignore:
4051 // If we are ignoring an argument that had a result, make sure to
4052 // construct the appropriate return value for our caller.
4053 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004054
Hal Finkelee90a222014-09-26 05:04:30 +00004055 case ABIArgInfo::Extend:
4056 case ABIArgInfo::Direct: {
4057 llvm::Type *RetIRTy = ConvertType(RetTy);
4058 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4059 switch (getEvaluationKind(RetTy)) {
4060 case TEK_Complex: {
4061 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4062 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4063 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004064 }
Hal Finkelee90a222014-09-26 05:04:30 +00004065 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004066 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004067 bool DestIsVolatile = ReturnValue.isVolatile();
4068
John McCall7f416cc2015-09-08 08:05:57 +00004069 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004070 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4071 DestIsVolatile = false;
4072 }
John McCall7f416cc2015-09-08 08:05:57 +00004073 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004074 return RValue::getAggregate(DestPtr);
4075 }
4076 case TEK_Scalar: {
4077 // If the argument doesn't match, perform a bitcast to coerce it. This
4078 // can happen due to trivial type mismatches.
4079 llvm::Value *V = CI;
4080 if (V->getType() != RetIRTy)
4081 V = Builder.CreateBitCast(V, RetIRTy);
4082 return RValue::get(V);
4083 }
4084 }
4085 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004086 }
Hal Finkelee90a222014-09-26 05:04:30 +00004087
John McCall7f416cc2015-09-08 08:05:57 +00004088 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004089 bool DestIsVolatile = ReturnValue.isVolatile();
4090
John McCall7f416cc2015-09-08 08:05:57 +00004091 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004092 DestPtr = CreateMemTemp(RetTy, "coerce");
4093 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004094 }
Hal Finkelee90a222014-09-26 05:04:30 +00004095
4096 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004097 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4098 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004099
4100 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004101 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004102
Hal Finkelee90a222014-09-26 05:04:30 +00004103 case ABIArgInfo::Expand:
4104 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004105 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004106
Hal Finkelee90a222014-09-26 05:04:30 +00004107 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4108 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004109
Samuel Antao798f11c2015-11-23 22:04:44 +00004110 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4111
Hal Finkelee90a222014-09-26 05:04:30 +00004112 if (Ret.isScalar() && TargetDecl) {
4113 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4114 llvm::Value *OffsetValue = nullptr;
4115 if (const auto *Offset = AA->getOffset())
4116 OffsetValue = EmitScalarExpr(Offset);
4117
4118 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4119 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4120 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4121 OffsetValue);
4122 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004123 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004124
Hal Finkelee90a222014-09-26 05:04:30 +00004125 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004126}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004127
4128/* VarArg handling */
4129
Charles Davisc7d5c942015-09-17 20:55:33 +00004130Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4131 VAListAddr = VE->isMicrosoftABI()
4132 ? EmitMSVAListRef(VE->getSubExpr())
4133 : EmitVAListRef(VE->getSubExpr());
4134 QualType Ty = VE->getType();
4135 if (VE->isMicrosoftABI())
4136 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004137 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004138}