blob: ed582552314eae81f5d5c6e12c475c67f1823dc1 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00006//
7//===----------------------------------------------------------------------===//
8//
9// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000015#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000016#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000018#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000019#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000020#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000021#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000022#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000024#include "clang/AST/DeclObjC.h"
Richard Trieu63688182018-12-11 03:18:39 +000025#include "clang/Basic/CodeGenOptions.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"
Bill Wendling706469b2013-02-28 22:49:57 +000030#include "llvm/ADT/StringExtras.h"
David Blaikie181a6132018-06-04 21:23:29 +000031#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyd9bce502016-09-20 15:49:58 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Attributes.h"
David Blaikief47ca252018-03-21 22:34:27 +000034#include "llvm/IR/CallingConv.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000037#include "llvm/IR/IntrinsicInst.h"
David Blaikief47ca252018-03-21 22:34:27 +000038#include "llvm/IR/Intrinsics.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000039using namespace clang;
40using namespace CodeGen;
41
42/***/
43
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000044unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000045 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;
Erich Keane757d3172016-11-02 18:29:35 +000049 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000050 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Martin Storsjo022e7822017-07-17 20:49:45 +000051 case CC_Win64: return llvm::CallingConv::Win64;
Charles Davisb5a214e2013-08-30 04:39:01 +000052 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000053 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
54 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000055 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000056 // TODO: Add support for __pascal to LLVM.
57 case CC_X86Pascal: return llvm::CallingConv::C;
58 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000059 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Sander de Smalen44a22532018-11-26 16:38:37 +000060 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000061 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000062 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000063 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
64 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000065 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000066 }
67}
68
Mikael Nilsson9d2872d2018-12-13 10:15:27 +000069/// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
James Y Knightb92d2902019-02-05 16:05:50 +000070/// qualification. Either or both of RD and MD may be null. A null RD indicates
71/// that there is no meaningful 'this' type, and a null MD can occur when
72/// calling a method pointer.
73CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
74 const CXXMethodDecl *MD) {
75 QualType RecTy;
76 if (RD)
77 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
78 else
79 RecTy = Context.VoidTy;
80
Mikael Nilsson9d2872d2018-12-13 10:15:27 +000081 if (MD)
Anastasia Stulovac61eaa52019-01-28 11:37:49 +000082 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
John McCall2da83a32010-02-26 00:48:12 +000083 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000084}
85
John McCall8ee376f2010-02-24 07:14:12 +000086/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000087static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
88 return MD->getType()->getCanonicalTypeUnqualified()
89 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000090}
91
92/// Returns the "extra-canonicalized" return type, which discards
93/// qualifiers on the return type. Codegen doesn't care about them,
94/// and it makes ABI code a little easier to be able to assume that
95/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000096static CanQualType GetReturnType(QualType RetTy) {
97 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000098}
99
John McCall8dda7b22012-07-07 06:41:13 +0000100/// Arrange the argument and result information for a value of the given
101/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000102const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000103CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +0000104 // When translating an unprototyped function type, always use a
105 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +0000106 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +0000107 /*instanceMethod=*/false,
108 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000109 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000110}
111
George Burgess IVb7760212017-02-24 02:49:47 +0000112static void addExtParameterInfosForCall(
113 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
114 const FunctionProtoType *proto,
115 unsigned prefixArgs,
116 unsigned totalArgs) {
117 assert(proto->hasExtParameterInfos());
118 assert(paramInfos.size() <= prefixArgs);
119 assert(proto->getNumParams() + prefixArgs <= totalArgs);
120
121 paramInfos.reserve(totalArgs);
122
123 // Add default infos for any prefix args that don't already have infos.
124 paramInfos.resize(prefixArgs);
125
126 // Add infos for the prototype.
127 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
128 paramInfos.push_back(ParamInfo);
129 // pass_object_size params have no parameter info.
130 if (ParamInfo.hasPassObjectSize())
131 paramInfos.emplace_back();
132 }
133
134 assert(paramInfos.size() <= totalArgs &&
135 "Did we forget to insert pass_object_size args?");
136 // Add default infos for the variadic and/or suffix arguments.
137 paramInfos.resize(totalArgs);
138}
139
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +0000140/// Adds the formal parameters in FPT to the given prefix. If any parameter in
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000141/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
142static void appendParameterTypes(const CodeGenTypes &CGT,
143 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000144 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
George Burgess IVb7760212017-02-24 02:49:47 +0000145 CanQual<FunctionProtoType> FPT) {
146 // Fast path: don't touch param info if we don't need to.
147 if (!FPT->hasExtParameterInfos()) {
148 assert(paramInfos.empty() &&
149 "We have paramInfos, but the prototype doesn't?");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000150 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
151 return;
152 }
153
George Burgess IVb7760212017-02-24 02:49:47 +0000154 unsigned PrefixSize = prefix.size();
155 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000156 // parameters; the only thing that can change this is the presence of
157 // pass_object_size. So, we preallocate for the common case.
158 prefix.reserve(prefix.size() + FPT->getNumParams());
159
George Burgess IVb7760212017-02-24 02:49:47 +0000160 auto ExtInfos = FPT->getExtParameterInfos();
161 assert(ExtInfos.size() == FPT->getNumParams());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
163 prefix.push_back(FPT->getParamType(I));
George Burgess IVb7760212017-02-24 02:49:47 +0000164 if (ExtInfos[I].hasPassObjectSize())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000165 prefix.push_back(CGT.getContext().getSizeType());
166 }
George Burgess IVb7760212017-02-24 02:49:47 +0000167
168 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
169 prefix.size());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000170}
171
John McCall8dda7b22012-07-07 06:41:13 +0000172/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000173/// type, on top of any implicit parameters already stored.
174static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000175arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000176 SmallVectorImpl<CanQualType> &prefix,
James Y Knight916db652019-02-02 01:48:23 +0000177 CanQual<FunctionProtoType> FTP) {
John McCallc56a8b32016-03-11 04:30:31 +0000178 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
James Y Knight916db652019-02-02 01:48:23 +0000179 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000180 // FIXME: Kill copy.
George Burgess IVb7760212017-02-24 02:49:47 +0000181 appendParameterTypes(CGT, prefix, paramInfos, FTP);
Alp Toker314cc812014-01-25 16:55:45 +0000182 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000183
Peter Collingbournef7706832014-12-12 23:41:25 +0000184 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
185 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000186 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000187 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000188}
189
John McCalla729c622012-02-17 03:33:10 +0000190/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000191/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000192const CGFunctionInfo &
James Y Knight916db652019-02-02 01:48:23 +0000193CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000194 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000195 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
James Y Knight916db652019-02-02 01:48:23 +0000196 FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000197}
198
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000199static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000200 // Set the appropriate calling convention for the Function.
201 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000202 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000203
204 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000205 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000206
Erich Keane757d3172016-11-02 18:29:35 +0000207 if (D->hasAttr<RegCallAttr>())
208 return CC_X86RegCall;
209
Douglas Gregora941dca2010-05-18 16:57:00 +0000210 if (D->hasAttr<ThisCallAttr>())
211 return CC_X86ThisCall;
212
Reid Klecknerd7857f02014-10-24 17:42:17 +0000213 if (D->hasAttr<VectorCallAttr>())
214 return CC_X86VectorCall;
215
Dawn Perchik335e16b2010-09-03 01:29:35 +0000216 if (D->hasAttr<PascalAttr>())
217 return CC_X86Pascal;
218
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000219 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
220 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
221
Sander de Smalen44a22532018-11-26 16:38:37 +0000222 if (D->hasAttr<AArch64VectorPcsAttr>())
223 return CC_AArch64VectorCall;
224
Guy Benyeif0a014b2012-12-25 08:53:55 +0000225 if (D->hasAttr<IntelOclBiccAttr>())
226 return CC_IntelOclBicc;
227
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000228 if (D->hasAttr<MSABIAttr>())
Martin Storsjo022e7822017-07-17 20:49:45 +0000229 return IsWindows ? CC_C : CC_Win64;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000230
231 if (D->hasAttr<SysVABIAttr>())
232 return IsWindows ? CC_X86_64SysV : CC_C;
233
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000234 if (D->hasAttr<PreserveMostAttr>())
235 return CC_PreserveMost;
236
237 if (D->hasAttr<PreserveAllAttr>())
238 return CC_PreserveAll;
239
John McCallab26cfa2010-02-05 21:31:56 +0000240 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000241}
242
John McCalla729c622012-02-17 03:33:10 +0000243/// Arrange the argument and result information for a call to an
244/// unknown C++ non-static member function of the given abstract type.
James Y Knightb92d2902019-02-05 16:05:50 +0000245/// (A null RD means we don't have any meaningful "this" argument type,
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000246/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000247/// The member function must be an ordinary function, i.e. not a
248/// constructor or destructor.
249const CGFunctionInfo &
250CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000251 const FunctionProtoType *FTP,
252 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000253 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000254
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000255 // Add the 'this' pointer.
James Y Knightb92d2902019-02-05 16:05:50 +0000256 argTypes.push_back(DeriveThisType(RD, MD));
John McCall8ee376f2010-02-24 07:14:12 +0000257
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000258 return ::arrangeLLVMFunctionInfo(
259 *this, true, argTypes,
James Y Knight916db652019-02-02 01:48:23 +0000260 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000261}
262
Yaxun Liu6c10a662018-06-12 00:16:33 +0000263/// Set calling convention for CUDA/HIP kernel.
264static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
265 const FunctionDecl *FD) {
266 if (FD->hasAttr<CUDAGlobalAttr>()) {
267 const FunctionType *FT = FTy->getAs<FunctionType>();
268 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
269 FTy = FT->getCanonicalTypeUnqualified();
270 }
271}
272
John McCalla729c622012-02-17 03:33:10 +0000273/// Arrange the argument and result information for a declaration or
274/// definition of the given C++ non-static member function. The
275/// member function must be an ordinary function, i.e. not a
276/// constructor or destructor.
277const CGFunctionInfo &
278CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000279 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000280 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
281
Yaxun Liu6c10a662018-06-12 00:16:33 +0000282 CanQualType FT = GetFormalType(MD).getAs<Type>();
283 setCUDAKernelCallingConvention(FT, CGM, MD);
284 auto prototype = FT.getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000285
John McCalla729c622012-02-17 03:33:10 +0000286 if (MD->isInstance()) {
287 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000288 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000289 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000290 }
291
James Y Knight916db652019-02-02 01:48:23 +0000292 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000293}
294
Richard Smith5179eb72016-06-28 19:03:57 +0000295bool CodeGenTypes::inheritingCtorHasParams(
296 const InheritedConstructor &Inherited, CXXCtorType Type) {
297 // Parameters are unnecessary if we're constructing a base class subobject
298 // and the inherited constructor lives in a virtual base.
299 return Type == Ctor_Complete ||
300 !Inherited.getShadowDecl()->constructsVirtualBase() ||
301 !Target.getCXXABI().hasConstructorVariants();
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000302}
Richard Smith5179eb72016-06-28 19:03:57 +0000303
John McCalla729c622012-02-17 03:33:10 +0000304const CGFunctionInfo &
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000305CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
306 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000307
John McCalla729c622012-02-17 03:33:10 +0000308 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000309 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
James Y Knightb92d2902019-02-05 16:05:50 +0000310 argTypes.push_back(DeriveThisType(MD->getParent(), MD));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000311
Richard Smith5179eb72016-06-28 19:03:57 +0000312 bool PassParams = true;
313
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000314 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
Richard Smith5179eb72016-06-28 19:03:57 +0000315 // A base class inheriting constructor doesn't get forwarded arguments
316 // needed to construct a virtual base (or base class thereof).
317 if (auto Inherited = CD->getInheritedConstructor())
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000318 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000319 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000320
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000321 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000322
323 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000324 if (PassParams)
George Burgess IVb7760212017-02-24 02:49:47 +0000325 appendParameterTypes(*this, argTypes, paramInfos, FTP);
John McCall5d865c322010-08-31 07:33:07 +0000326
George Burgess IV75b34a92017-02-22 22:38:25 +0000327 CGCXXABI::AddedStructorArgs AddedArgs =
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000328 TheCXXABI.buildStructorSignature(GD, argTypes);
George Burgess IV75b34a92017-02-22 22:38:25 +0000329 if (!paramInfos.empty()) {
330 // Note: prefix implies after the first param.
331 if (AddedArgs.Prefix)
332 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
333 FunctionProtoType::ExtParameterInfo{});
334 if (AddedArgs.Suffix)
335 paramInfos.append(AddedArgs.Suffix,
336 FunctionProtoType::ExtParameterInfo{});
337 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000338
339 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000340 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
341 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000342
John McCall8dda7b22012-07-07 06:41:13 +0000343 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000344 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
345 ? argTypes.front()
346 : TheCXXABI.hasMostDerivedReturn(GD)
347 ? CGM.getContext().VoidPtrTy
348 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000349 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
350 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000351 paramInfos, required);
352}
353
354static SmallVector<CanQualType, 16>
355getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
356 SmallVector<CanQualType, 16> argTypes;
357 for (auto &arg : args)
358 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
359 return argTypes;
360}
361
362static SmallVector<CanQualType, 16>
363getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
364 SmallVector<CanQualType, 16> argTypes;
365 for (auto &arg : args)
366 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
367 return argTypes;
368}
369
John McCallc56a8b32016-03-11 04:30:31 +0000370static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
371getExtParameterInfosForCall(const FunctionProtoType *proto,
372 unsigned prefixArgs, unsigned totalArgs) {
373 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
374 if (proto->hasExtParameterInfos()) {
375 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
376 }
377 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000378}
379
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000380/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000381///
382/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
383/// parameter.
384/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
385/// args.
386/// PassProtoArgs indicates whether `args` has args for the parameters in the
387/// given CXXConstructorDecl.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000388const CGFunctionInfo &
389CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
390 const CXXConstructorDecl *D,
391 CXXCtorType CtorKind,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000392 unsigned ExtraPrefixArgs,
393 unsigned ExtraSuffixArgs,
394 bool PassProtoArgs) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000395 // FIXME: Kill copy.
396 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000397 for (const auto &Arg : args)
398 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000399
George Burgess IVd0a9e802017-02-23 22:07:35 +0000400 // +1 for implicit this, which should always be args[0].
401 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
402
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000403 CanQual<FunctionProtoType> FPT = GetFormalType(D);
James Y Knightb92d2902019-02-05 16:05:50 +0000404 RequiredArgs Required = PassProtoArgs
405 ? RequiredArgs::forPrototypePlus(
406 FPT, TotalPrefixArgs + ExtraSuffixArgs)
407 : RequiredArgs::All;
408
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000409 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000410 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
411 ? ArgTypes.front()
412 : TheCXXABI.hasMostDerivedReturn(GD)
413 ? CGM.getContext().VoidPtrTy
414 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000415
416 FunctionType::ExtInfo Info = FPT->getExtInfo();
George Burgess IVd0a9e802017-02-23 22:07:35 +0000417 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
418 // If the prototype args are elided, we should only have ABI-specific args,
419 // which never have param info.
420 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
421 // ABI-specific suffix arguments are treated the same as variadic arguments.
422 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
423 ArgTypes.size());
424 }
Peter Collingbournef7706832014-12-12 23:41:25 +0000425 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
426 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000427 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000428}
429
John McCalla729c622012-02-17 03:33:10 +0000430/// Arrange the argument and result information for the declaration or
431/// definition of the given function.
432const CGFunctionInfo &
433CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000434 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000435 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000436 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000437
John McCall2da83a32010-02-26 00:48:12 +0000438 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000439
John McCall2da83a32010-02-26 00:48:12 +0000440 assert(isa<FunctionType>(FTy));
Yaxun Liu6c10a662018-06-12 00:16:33 +0000441 setCUDAKernelCallingConvention(FTy, CGM, FD);
John McCalla729c622012-02-17 03:33:10 +0000442
443 // When declaring a function without a prototype, always use a
444 // non-variadic type.
George Burgess IV35cfca22017-01-06 19:10:48 +0000445 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000446 return arrangeLLVMFunctionInfo(
447 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000448 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000449 }
450
James Y Knight916db652019-02-02 01:48:23 +0000451 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000452}
453
John McCalla729c622012-02-17 03:33:10 +0000454/// Arrange the argument and result information for the declaration or
455/// definition of an Objective-C method.
456const CGFunctionInfo &
457CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
458 // It happens that this is the same as a call with no optional
459 // arguments, except also using the formal 'self' type.
460 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
461}
462
463/// Arrange the argument and result information for the function type
464/// through which to perform a send to the given Objective-C method,
465/// using the given receiver type. The receiver type is not always
466/// the 'self' type of the method or even an Objective-C pointer type.
467/// This is *not* the right method for actually performing such a
468/// message send, due to the possibility of optional arguments.
469const CGFunctionInfo &
470CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
471 QualType receiverType) {
472 SmallVector<CanQualType, 16> argTys;
Akira Hatanaka98a49332017-09-22 00:41:05 +0000473 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
John McCalla729c622012-02-17 03:33:10 +0000474 argTys.push_back(Context.getCanonicalParamType(receiverType));
475 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000476 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000477 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000478 argTys.push_back(Context.getCanonicalParamType(I->getType()));
Akira Hatanaka98a49332017-09-22 00:41:05 +0000479 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
480 I->hasAttr<NoEscapeAttr>());
481 extParamInfos.push_back(extParamInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000482 }
John McCall31168b02011-06-15 23:02:42 +0000483
484 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000485 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
486 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000487
David Blaikiebbafb8a2012-03-11 07:00:24 +0000488 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000489 MD->hasAttr<NSReturnsRetainedAttr>())
490 einfo = einfo.withProducesResult(true);
491
John McCalla729c622012-02-17 03:33:10 +0000492 RequiredArgs required =
493 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
494
Peter Collingbournef7706832014-12-12 23:41:25 +0000495 return arrangeLLVMFunctionInfo(
496 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
Akira Hatanaka98a49332017-09-22 00:41:05 +0000497 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
John McCallc56a8b32016-03-11 04:30:31 +0000498}
499
500const CGFunctionInfo &
501CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
502 const CallArgList &args) {
503 auto argTypes = getArgTypesForCall(Context, args);
504 FunctionType::ExtInfo einfo;
505
506 return arrangeLLVMFunctionInfo(
507 GetReturnType(returnType), /*instanceMethod=*/false,
508 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000509}
510
John McCalla729c622012-02-17 03:33:10 +0000511const CGFunctionInfo &
512CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000513 // FIXME: Do we need to handle ObjCMethodDecl?
514 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000515
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000516 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
517 isa<CXXDestructorDecl>(GD.getDecl()))
518 return arrangeCXXStructorDeclaration(GD);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000519
John McCalla729c622012-02-17 03:33:10 +0000520 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000521}
522
Reid Klecknerc3473512014-08-29 21:43:29 +0000523/// Arrange a thunk that takes 'this' as the first parameter followed by
524/// varargs. Return a void pointer, regardless of the actual return type.
525/// The body of the thunk will end in a musttail call to a function of the
526/// correct type, and the caller will bitcast the function to the correct
527/// prototype.
528const CGFunctionInfo &
Reid Kleckner399d96e2018-04-02 20:20:33 +0000529CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
530 assert(MD->isVirtual() && "only methods have thunks");
Reid Klecknerc3473512014-08-29 21:43:29 +0000531 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
James Y Knightb92d2902019-02-05 16:05:50 +0000532 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
Peter Collingbournef7706832014-12-12 23:41:25 +0000533 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
534 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000535 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000536}
537
David Majnemerdfa6d202015-03-11 18:36:39 +0000538const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000539CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
540 CXXCtorType CT) {
541 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
542
David Majnemerdfa6d202015-03-11 18:36:39 +0000543 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
544 SmallVector<CanQualType, 2> ArgTys;
545 const CXXRecordDecl *RD = CD->getParent();
James Y Knightb92d2902019-02-05 16:05:50 +0000546 ArgTys.push_back(DeriveThisType(RD, CD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000547 if (CT == Ctor_CopyingClosure)
548 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000549 if (RD->getNumVBases() > 0)
550 ArgTys.push_back(Context.IntTy);
551 CallingConv CC = Context.getDefaultCallingConvention(
552 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
553 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
554 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000555 FunctionType::ExtInfo(CC), {},
556 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000557}
558
John McCallc818bbb2012-12-07 07:03:17 +0000559/// Arrange a call as unto a free function, except possibly with an
560/// additional number of formal parameters considered required.
561static const CGFunctionInfo &
562arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000563 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000564 const CallArgList &args,
565 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000566 unsigned numExtraRequiredArgs,
567 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000568 assert(args.size() >= numExtraRequiredArgs);
569
John McCallc56a8b32016-03-11 04:30:31 +0000570 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
571
John McCallc818bbb2012-12-07 07:03:17 +0000572 // In most cases, there are no optional arguments.
573 RequiredArgs required = RequiredArgs::All;
574
575 // If we have a variadic prototype, the required arguments are the
576 // extra prefix plus the arguments in the prototype.
577 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
578 if (proto->isVariadic())
James Y Knightb92d2902019-02-05 16:05:50 +0000579 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000580
John McCallc56a8b32016-03-11 04:30:31 +0000581 if (proto->hasExtParameterInfos())
582 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
583 args.size());
584
John McCallc818bbb2012-12-07 07:03:17 +0000585 // If we don't have a prototype at all, but we're supposed to
586 // explicitly use the variadic convention for unprototyped calls,
587 // treat all of the arguments as required but preserve the nominal
588 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000589 } else if (CGM.getTargetCodeGenInfo()
590 .isNoProtoCallVariadic(args,
591 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000592 required = RequiredArgs(args.size());
593 }
594
Peter Collingbournef7706832014-12-12 23:41:25 +0000595 // FIXME: Kill copy.
596 SmallVector<CanQualType, 16> argTypes;
597 for (const auto &arg : args)
598 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
599 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
600 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000601 argTypes, fnType->getExtInfo(), paramInfos,
602 required);
John McCallc818bbb2012-12-07 07:03:17 +0000603}
604
John McCalla729c622012-02-17 03:33:10 +0000605/// Figure out the rules for calling a function with the given formal
606/// type using the given arguments. The arguments are necessary
607/// because the function might be unprototyped, in which case it's
608/// target-dependent in crazy ways.
609const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000610CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000611 const FunctionType *fnType,
612 bool chainCall) {
613 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
614 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000615}
John McCalla729c622012-02-17 03:33:10 +0000616
John McCallc56a8b32016-03-11 04:30:31 +0000617/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000618/// extra implicit argument.
619const CGFunctionInfo &
620CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
621 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000622 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
623 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000624}
625
626const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000627CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
628 const FunctionArgList &params) {
629 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
630 auto argTypes = getArgTypesForDeclaration(Context, params);
631
James Y Knight916db652019-02-02 01:48:23 +0000632 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
633 /*instanceMethod*/ false, /*chainCall*/ false,
634 argTypes, proto->getExtInfo(), paramInfos,
635 RequiredArgs::forPrototypePlus(proto, 1));
John McCallc56a8b32016-03-11 04:30:31 +0000636}
637
638const CGFunctionInfo &
639CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
640 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000641 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000642 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000643 for (const auto &Arg : args)
644 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000645 return arrangeLLVMFunctionInfo(
646 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000647 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
648 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000649}
650
John McCallc56a8b32016-03-11 04:30:31 +0000651const CGFunctionInfo &
652CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
653 const FunctionArgList &args) {
654 auto argTypes = getArgTypesForDeclaration(Context, args);
655
656 return arrangeLLVMFunctionInfo(
657 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
658 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
659}
660
661const CGFunctionInfo &
662CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
663 ArrayRef<CanQualType> argTypes) {
664 return arrangeLLVMFunctionInfo(
665 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
666 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
667}
668
John McCall8dda7b22012-07-07 06:41:13 +0000669/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000670///
671/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
672/// does not count `this`.
John McCall8dda7b22012-07-07 06:41:13 +0000673const CGFunctionInfo &
674CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000675 const FunctionProtoType *proto,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000676 RequiredArgs required,
677 unsigned numPrefixArgs) {
678 assert(numPrefixArgs + 1 <= args.size() &&
679 "Emitting a call with less args than the required prefix?");
680 // Add one to account for `this`. It's a bit awkward here, but we don't count
681 // `this` in similar places elsewhere.
John McCallc56a8b32016-03-11 04:30:31 +0000682 auto paramInfos =
George Burgess IVd0a9e802017-02-23 22:07:35 +0000683 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
John McCallc56a8b32016-03-11 04:30:31 +0000684
John McCall8dda7b22012-07-07 06:41:13 +0000685 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000686 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000687
John McCallc56a8b32016-03-11 04:30:31 +0000688 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000689 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000690 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
691 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000692}
693
John McCalla729c622012-02-17 03:33:10 +0000694const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000695 return arrangeLLVMFunctionInfo(
696 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000697 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
698}
699
700const CGFunctionInfo &
701CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
702 const CallArgList &args) {
703 assert(signature.arg_size() <= args.size());
704 if (signature.arg_size() == args.size())
705 return signature;
706
707 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
708 auto sigParamInfos = signature.getExtParameterInfos();
709 if (!sigParamInfos.empty()) {
710 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
711 paramInfos.resize(args.size());
712 }
713
714 auto argTypes = getArgTypesForCall(Context, args);
715
716 assert(signature.getRequiredArgs().allowsOptionalArgs());
717 return arrangeLLVMFunctionInfo(signature.getReturnType(),
718 signature.isInstanceMethod(),
719 signature.isChainCall(),
720 argTypes,
721 signature.getExtInfo(),
722 paramInfos,
723 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000724}
725
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000726namespace clang {
727namespace CodeGen {
728void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
729}
730}
731
John McCalla729c622012-02-17 03:33:10 +0000732/// Arrange the argument and result information for an abstract value
733/// of a given function type. This is the method which all of the
734/// above functions ultimately defer to.
735const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000736CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000737 bool instanceMethod,
738 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000739 ArrayRef<CanQualType> argTypes,
740 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000741 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000742 RequiredArgs required) {
Fangrui Song3117b172018-10-20 17:53:42 +0000743 assert(llvm::all_of(argTypes,
744 [](CanQualType T) { return T.isCanonicalAsParam(); }));
John McCall2da83a32010-02-26 00:48:12 +0000745
Daniel Dunbare0be8292009-02-03 00:07:12 +0000746 // Lookup or create unique function info.
747 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000748 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
749 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000750
Craig Topper8a13c412014-05-21 05:09:00 +0000751 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000752 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000753 if (FI)
754 return *FI;
755
John McCallc56a8b32016-03-11 04:30:31 +0000756 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
757
John McCalla729c622012-02-17 03:33:10 +0000758 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000759 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000760 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000761 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000762
David Blaikie82e95a32014-11-19 07:49:47 +0000763 bool inserted = FunctionsBeingProcessed.insert(FI).second;
764 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000765 assert(inserted && "Recursively being processed?");
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000766
Daniel Dunbar313321e2009-02-03 05:31:23 +0000767 // Compute ABI information.
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000768 if (CC == llvm::CallingConv::SPIR_KERNEL) {
769 // Force target independent argument handling for the host visible
770 // kernel functions.
771 computeSPIRKernelABIInfo(CGM, *FI);
772 } else if (info.getCC() == CC_Swift) {
John McCall12f23522016-04-04 18:33:08 +0000773 swiftcall::computeABIInfo(CGM, *FI);
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000774 } else {
775 getABIInfo().computeInfo(*FI);
John McCall12f23522016-04-04 18:33:08 +0000776 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000777
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000778 // Loop over all of the computed argument and return value info. If any of
779 // them are direct or extend without a specified coerce type, specify the
780 // default now.
John McCalla729c622012-02-17 03:33:10 +0000781 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000782 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000783 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000784
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000785 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000786 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000787 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000788
John McCalla729c622012-02-17 03:33:10 +0000789 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
790 assert(erased && "Not in set?");
Fangrui Song6907ce22018-07-30 19:24:48 +0000791
Daniel Dunbare0be8292009-02-03 00:07:12 +0000792 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000793}
794
John McCalla729c622012-02-17 03:33:10 +0000795CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000796 bool instanceMethod,
797 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000798 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000799 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000800 CanQualType resultType,
801 ArrayRef<CanQualType> argTypes,
802 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000803 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
James Y Knightb92d2902019-02-05 16:05:50 +0000804 assert(!required.allowsOptionalArgs() ||
805 required.getNumRequiredArgs() <= argTypes.size());
John McCallc56a8b32016-03-11 04:30:31 +0000806
807 void *buffer =
808 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
809 argTypes.size() + 1, paramInfos.size()));
810
John McCalla729c622012-02-17 03:33:10 +0000811 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
812 FI->CallingConvention = llvmCC;
813 FI->EffectiveCallingConvention = llvmCC;
814 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000815 FI->InstanceMethod = instanceMethod;
816 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000817 FI->NoReturn = info.getNoReturn();
818 FI->ReturnsRetained = info.getProducesResult();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000819 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000820 FI->NoCfCheck = info.getNoCfCheck();
John McCalla729c622012-02-17 03:33:10 +0000821 FI->Required = required;
822 FI->HasRegParm = info.getHasRegParm();
823 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000824 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000825 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000826 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000827 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000828 FI->getArgsBuffer()[0].type = resultType;
829 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
830 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000831 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
832 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000833 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000834}
835
836/***/
837
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000838namespace {
839// ABIArgInfo::Expand implementation.
840
841// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
842struct TypeExpansion {
843 enum TypeExpansionKind {
844 // Elements of constant arrays are expanded recursively.
845 TEK_ConstantArray,
846 // Record fields are expanded recursively (but if record is a union, only
847 // the field with the largest size is expanded).
848 TEK_Record,
849 // For complex types, real and imaginary parts are expanded recursively.
850 TEK_Complex,
851 // All other types are not expandable.
852 TEK_None
853 };
854
855 const TypeExpansionKind Kind;
856
857 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000858 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000859};
860
861struct ConstantArrayExpansion : TypeExpansion {
862 QualType EltTy;
863 uint64_t NumElts;
864
865 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
866 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
867 static bool classof(const TypeExpansion *TE) {
868 return TE->Kind == TEK_ConstantArray;
869 }
870};
871
872struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000873 SmallVector<const CXXBaseSpecifier *, 1> Bases;
874
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000875 SmallVector<const FieldDecl *, 1> Fields;
876
Reid Klecknere9f6a712014-10-31 17:10:41 +0000877 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
878 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000879 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
880 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000881 static bool classof(const TypeExpansion *TE) {
882 return TE->Kind == TEK_Record;
883 }
884};
885
886struct ComplexExpansion : TypeExpansion {
887 QualType EltTy;
888
889 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
890 static bool classof(const TypeExpansion *TE) {
891 return TE->Kind == TEK_Complex;
892 }
893};
894
895struct NoExpansion : TypeExpansion {
896 NoExpansion() : TypeExpansion(TEK_None) {}
897 static bool classof(const TypeExpansion *TE) {
898 return TE->Kind == TEK_None;
899 }
900};
901} // namespace
902
903static std::unique_ptr<TypeExpansion>
904getTypeExpansion(QualType Ty, const ASTContext &Context) {
905 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
906 return llvm::make_unique<ConstantArrayExpansion>(
907 AT->getElementType(), AT->getSize().getZExtValue());
908 }
909 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000910 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000911 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000912 const RecordDecl *RD = RT->getDecl();
913 assert(!RD->hasFlexibleArrayMember() &&
914 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000915 if (RD->isUnion()) {
916 // Unions can be here only in degenerative cases - all the fields are same
917 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000918 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000919 CharUnits UnionSize = CharUnits::Zero();
920
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000921 for (const auto *FD : RD->fields()) {
Richard Smith866dee42018-04-02 18:29:43 +0000922 if (FD->isZeroLengthBitField(Context))
Reid Kleckner80944df2014-10-31 22:00:51 +0000923 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000924 assert(!FD->isBitField() &&
925 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000926 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000927 if (UnionSize < FieldSize) {
928 UnionSize = FieldSize;
929 LargestFD = FD;
930 }
931 }
932 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000933 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000934 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000935 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
936 assert(!CXXRD->isDynamicClass() &&
937 "cannot expand vtable pointers in dynamic classes");
938 for (const CXXBaseSpecifier &BS : CXXRD->bases())
939 Bases.push_back(&BS);
940 }
941
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000942 for (const auto *FD : RD->fields()) {
Richard Smith866dee42018-04-02 18:29:43 +0000943 if (FD->isZeroLengthBitField(Context))
Reid Kleckner80944df2014-10-31 22:00:51 +0000944 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000945 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000946 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000947 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000948 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000949 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000950 return llvm::make_unique<RecordExpansion>(std::move(Bases),
951 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000952 }
953 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
954 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
955 }
956 return llvm::make_unique<NoExpansion>();
957}
958
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000959static int getExpansionSize(QualType Ty, const ASTContext &Context) {
960 auto Exp = getTypeExpansion(Ty, Context);
961 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
962 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
963 }
964 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
965 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000966 for (auto BS : RExp->Bases)
967 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000968 for (auto FD : RExp->Fields)
969 Res += getExpansionSize(FD->getType(), Context);
970 return Res;
971 }
972 if (isa<ComplexExpansion>(Exp.get()))
973 return 2;
974 assert(isa<NoExpansion>(Exp.get()));
975 return 1;
976}
977
Alexey Samsonov153004f2014-09-29 22:08:00 +0000978void
979CodeGenTypes::getExpandedTypes(QualType Ty,
980 SmallVectorImpl<llvm::Type *>::iterator &TI) {
981 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000982 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
983 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000984 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000985 }
986 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000987 for (auto BS : RExp->Bases)
988 getExpandedTypes(BS->getType(), TI);
989 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000990 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000991 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
992 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000993 *TI++ = EltTy;
994 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000995 } else {
996 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000997 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000998 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000999}
1000
John McCall7f416cc2015-09-08 08:05:57 +00001001static void forConstantArrayExpansion(CodeGenFunction &CGF,
1002 ConstantArrayExpansion *CAE,
1003 Address BaseAddr,
1004 llvm::function_ref<void(Address)> Fn) {
1005 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1006 CharUnits EltAlign =
1007 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1008
1009 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1010 llvm::Value *EltAddr =
1011 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
1012 Fn(Address(EltAddr, EltAlign));
1013 }
1014}
1015
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001016void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +00001017 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +00001018 assert(LV.isSimple() &&
1019 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001020
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001021 auto Exp = getTypeExpansion(Ty, getContext());
1022 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001023 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
1024 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001025 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1026 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +00001027 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001028 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001029 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001030 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1031 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001032 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001033 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1034 /*NullCheckValue=*/false, SourceLocation());
1035 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1036
1037 // Recurse onto bases.
1038 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1039 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001040 for (auto FD : RExp->Fields) {
1041 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +00001042 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001043 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +00001044 }
John McCall7f416cc2015-09-08 08:05:57 +00001045 } else if (isa<ComplexExpansion>(Exp.get())) {
1046 auto realValue = *AI++;
1047 auto imagValue = *AI++;
1048 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001049 } else {
1050 assert(isa<NoExpansion>(Exp.get()));
1051 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001052 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001053}
1054
1055void CodeGenFunction::ExpandTypeToArgs(
Yaxun Liu5b330e82018-03-15 15:25:19 +00001056 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001057 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1058 auto Exp = getTypeExpansion(Ty, getContext());
1059 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001060 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1061 : Arg.getKnownRValue().getAggregateAddress();
1062 forConstantArrayExpansion(
1063 *this, CAExp, Addr, [&](Address EltAddr) {
1064 CallArg EltArg = CallArg(
1065 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1066 CAExp->EltTy);
1067 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1068 IRCallArgPos);
1069 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001070 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001071 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1072 : Arg.getKnownRValue().getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001073 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1074 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001075 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001076 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1077 /*NullCheckValue=*/false, SourceLocation());
Yaxun Liu5b330e82018-03-15 15:25:19 +00001078 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
Reid Klecknere9f6a712014-10-31 17:10:41 +00001079
1080 // Recurse onto bases.
Yaxun Liu5b330e82018-03-15 15:25:19 +00001081 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
Reid Klecknere9f6a712014-10-31 17:10:41 +00001082 IRCallArgPos);
1083 }
1084
1085 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001086 for (auto FD : RExp->Fields) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001087 CallArg FldArg =
1088 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1089 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001090 IRCallArgPos);
1091 }
1092 } else if (isa<ComplexExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001093 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001094 IRCallArgs[IRCallArgPos++] = CV.first;
1095 IRCallArgs[IRCallArgPos++] = CV.second;
1096 } else {
1097 assert(isa<NoExpansion>(Exp.get()));
Yaxun Liu5b330e82018-03-15 15:25:19 +00001098 auto RV = Arg.getKnownRValue();
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001099 assert(RV.isScalar() &&
1100 "Unexpected non-scalar rvalue during struct expansion.");
1101
1102 // Insert a bitcast as needed.
1103 llvm::Value *V = RV.getScalarVal();
1104 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1105 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1106 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1107
1108 IRCallArgs[IRCallArgPos++] = V;
1109 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001110}
1111
John McCall7f416cc2015-09-08 08:05:57 +00001112/// Create a temporary allocation for the purposes of coercion.
1113static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1114 CharUnits MinAlign) {
1115 // Don't use an alignment that's worse than what LLVM would prefer.
1116 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1117 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1118
1119 return CGF.CreateTempAlloca(Ty, Align);
1120}
1121
Chris Lattner895c52b2010-06-27 06:04:18 +00001122/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001123/// accessing some number of bytes out of it, try to gep into the struct to get
1124/// at its inner goodness. Dive as deep as possible without entering an element
1125/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001126static Address
1127EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001128 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001129 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001130 // We can't dive into a zero-element struct.
1131 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001132
Chris Lattner2192fe52011-07-18 04:24:23 +00001133 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001134
Chris Lattner1cd66982010-06-27 05:56:15 +00001135 // 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 +00001136 // first element is the same size as the whole struct, we can enter it. The
1137 // comparison must be made on the store size and not the alloca size. Using
1138 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001139 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001140 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001141 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001142 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001143 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001144
Chris Lattner1cd66982010-06-27 05:56:15 +00001145 // GEP into the first element.
James Y Knight751fe282019-02-09 22:22:28 +00001146 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001147
Chris Lattner1cd66982010-06-27 05:56:15 +00001148 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001149 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001150 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001151 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001152
1153 return SrcPtr;
1154}
1155
Chris Lattner055097f2010-06-27 06:26:04 +00001156/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1157/// are either integers or pointers. This does a truncation of the value if it
1158/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001159///
1160/// This behaves as if the value were coerced through memory, so on big-endian
1161/// targets the high bits are preserved in a truncation, while little-endian
1162/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001163static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001164 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001165 CodeGenFunction &CGF) {
1166 if (Val->getType() == Ty)
1167 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001168
Chris Lattner055097f2010-06-27 06:26:04 +00001169 if (isa<llvm::PointerType>(Val->getType())) {
1170 // If this is Pointer->Pointer avoid conversion to and from int.
1171 if (isa<llvm::PointerType>(Ty))
1172 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001173
Chris Lattner055097f2010-06-27 06:26:04 +00001174 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001175 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001176 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001177
Chris Lattner2192fe52011-07-18 04:24:23 +00001178 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001179 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001180 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001181
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001182 if (Val->getType() != DestIntTy) {
1183 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1184 if (DL.isBigEndian()) {
1185 // Preserve the high bits on big-endian targets.
1186 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001187 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1188 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1189
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001190 if (SrcSize > DstSize) {
1191 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1192 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1193 } else {
1194 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1195 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1196 }
1197 } else {
1198 // Little-endian targets preserve the low bits. No shifts required.
1199 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1200 }
1201 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001202
Chris Lattner055097f2010-06-27 06:26:04 +00001203 if (isa<llvm::PointerType>(Ty))
1204 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1205 return Val;
1206}
1207
Chris Lattner1cd66982010-06-27 05:56:15 +00001208
1209
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001210/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001211/// a pointer to an object of type \arg Ty, known to be aligned to
1212/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001213///
1214/// This safely handles the case when the src type is smaller than the
1215/// destination type; in this situation the values of bits which not
1216/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001217static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001218 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001219 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001220
Chris Lattnerd200eda2010-06-28 22:51:39 +00001221 // If SrcTy and Ty are the same, just do a load.
1222 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001223 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001224
Micah Villmowdd31ca12012-10-08 16:25:52 +00001225 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001226
Chris Lattner2192fe52011-07-18 04:24:23 +00001227 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001228 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1229 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001230 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001231
Micah Villmowdd31ca12012-10-08 16:25:52 +00001232 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001233
Chris Lattner055097f2010-06-27 06:26:04 +00001234 // If the source and destination are integer or pointer types, just do an
1235 // extension or truncation to the desired type.
1236 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1237 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001238 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001239 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1240 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001241
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001242 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001243 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001244 // Generally SrcSize is never greater than DstSize, since this means we are
1245 // losing bits. However, this can happen in cases where the structure has
1246 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001247 //
Mike Stump18bb9282009-05-16 07:57:57 +00001248 // FIXME: Assert that we aren't truncating non-padding bits when have access
1249 // to that information.
Matt Arsenault7a124f32017-08-01 20:36:57 +00001250 Src = CGF.Builder.CreateBitCast(Src,
1251 Ty->getPointerTo(Src.getAddressSpace()));
John McCall7f416cc2015-09-08 08:05:57 +00001252 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001253 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001254
John McCall7f416cc2015-09-08 08:05:57 +00001255 // Otherwise do coercion through memory. This is stupid, but simple.
1256 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
Yaxun Liu4bbdebc2018-11-08 16:55:46 +00001257 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
1258 Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty);
Manman Ren84b921f2012-11-28 22:08:52 +00001259 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1260 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001261 false);
1262 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001263}
1264
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001265// Function to store a first-class aggregate into memory. We prefer to
1266// store the elements rather than the aggregate to be more friendly to
1267// fast-isel.
1268// FIXME: Do we need to recurse here?
1269static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001270 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001271 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001272 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001273 dyn_cast<llvm::StructType>(Val->getType())) {
1274 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
James Y Knight751fe282019-02-09 22:22:28 +00001275 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001276 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001277 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001278 }
1279 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001280 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001281 }
1282}
1283
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001284/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001285/// where the source and destination may have different types. The
1286/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001287///
1288/// This safely handles the case when the src type is larger than the
1289/// destination type; the upper bits of the src will be lost.
1290static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001291 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001292 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001293 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001294 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001295 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001296 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001297 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001298 return;
1299 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001300
Micah Villmowdd31ca12012-10-08 16:25:52 +00001301 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001302
Chris Lattner2192fe52011-07-18 04:24:23 +00001303 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001304 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1305 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001306 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001307
Chris Lattner055097f2010-06-27 06:26:04 +00001308 // If the source and destination are integer or pointer types, just do an
1309 // extension or truncation to the desired type.
1310 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1311 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1312 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001313 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001314 return;
1315 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001316
Micah Villmowdd31ca12012-10-08 16:25:52 +00001317 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001318
Daniel Dunbar313321e2009-02-03 05:31:23 +00001319 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001320 if (SrcSize <= DstSize) {
Yaxun Liue9e5c4f2017-06-29 18:47:45 +00001321 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
John McCall7f416cc2015-09-08 08:05:57 +00001322 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001323 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001324 // Otherwise do coercion through memory. This is stupid, but
1325 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001326
1327 // Generally SrcSize is never greater than DstSize, since this means we are
1328 // losing bits. However, this can happen in cases where the structure has
1329 // additional padding, for example due to a user specified alignment.
1330 //
1331 // FIXME: Assert that we aren't truncating non-padding bits when have access
1332 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001333 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1334 CGF.Builder.CreateStore(Src, Tmp);
Yaxun Liu4bbdebc2018-11-08 16:55:46 +00001335 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
1336 Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty);
Manman Ren84b921f2012-11-28 22:08:52 +00001337 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1338 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001339 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001340 }
1341}
1342
John McCall7f416cc2015-09-08 08:05:57 +00001343static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
Fangrui Song6907ce22018-07-30 19:24:48 +00001344 const ABIArgInfo &info) {
John McCall7f416cc2015-09-08 08:05:57 +00001345 if (unsigned offset = info.getDirectOffset()) {
1346 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1347 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1348 CharUnits::fromQuantity(offset));
1349 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1350 }
1351 return addr;
1352}
1353
Alexey Samsonov153004f2014-09-29 22:08:00 +00001354namespace {
1355
1356/// Encapsulates information about the way function arguments from
1357/// CGFunctionInfo should be passed to actual LLVM IR function.
1358class ClangToLLVMArgMapping {
1359 static const unsigned InvalidIndex = ~0U;
1360 unsigned InallocaArgNo;
1361 unsigned SRetArgNo;
1362 unsigned TotalIRArgs;
1363
1364 /// Arguments of LLVM IR function corresponding to single Clang argument.
1365 struct IRArgs {
1366 unsigned PaddingArgIndex;
1367 // Argument is expanded to IR arguments at positions
1368 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1369 unsigned FirstArgIndex;
1370 unsigned NumberOfArgs;
1371
1372 IRArgs()
1373 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1374 NumberOfArgs(0) {}
1375 };
1376
1377 SmallVector<IRArgs, 8> ArgInfo;
1378
1379public:
1380 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1381 bool OnlyRequiredArgs = false)
1382 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1383 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1384 construct(Context, FI, OnlyRequiredArgs);
1385 }
1386
1387 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1388 unsigned getInallocaArgNo() const {
1389 assert(hasInallocaArg());
1390 return InallocaArgNo;
1391 }
1392
1393 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1394 unsigned getSRetArgNo() const {
1395 assert(hasSRetArg());
1396 return SRetArgNo;
1397 }
1398
1399 unsigned totalIRArgs() const { return TotalIRArgs; }
1400
1401 bool hasPaddingArg(unsigned ArgNo) const {
1402 assert(ArgNo < ArgInfo.size());
1403 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1404 }
1405 unsigned getPaddingArgNo(unsigned ArgNo) const {
1406 assert(hasPaddingArg(ArgNo));
1407 return ArgInfo[ArgNo].PaddingArgIndex;
1408 }
1409
1410 /// Returns index of first IR argument corresponding to ArgNo, and their
1411 /// quantity.
1412 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1413 assert(ArgNo < ArgInfo.size());
1414 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1415 ArgInfo[ArgNo].NumberOfArgs);
1416 }
1417
1418private:
1419 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1420 bool OnlyRequiredArgs);
1421};
1422
1423void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1424 const CGFunctionInfo &FI,
1425 bool OnlyRequiredArgs) {
1426 unsigned IRArgNo = 0;
1427 bool SwapThisWithSRet = false;
1428 const ABIArgInfo &RetAI = FI.getReturnInfo();
1429
1430 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1431 SwapThisWithSRet = RetAI.isSRetAfterThis();
1432 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1433 }
1434
1435 unsigned ArgNo = 0;
1436 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1437 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1438 ++I, ++ArgNo) {
1439 assert(I != FI.arg_end());
1440 QualType ArgType = I->type;
1441 const ABIArgInfo &AI = I->info;
1442 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1443 auto &IRArgs = ArgInfo[ArgNo];
1444
1445 if (AI.getPaddingType())
1446 IRArgs.PaddingArgIndex = IRArgNo++;
1447
1448 switch (AI.getKind()) {
1449 case ABIArgInfo::Extend:
1450 case ABIArgInfo::Direct: {
1451 // FIXME: handle sseregparm someday...
1452 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1453 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1454 IRArgs.NumberOfArgs = STy->getNumElements();
1455 } else {
1456 IRArgs.NumberOfArgs = 1;
1457 }
1458 break;
1459 }
1460 case ABIArgInfo::Indirect:
1461 IRArgs.NumberOfArgs = 1;
1462 break;
1463 case ABIArgInfo::Ignore:
1464 case ABIArgInfo::InAlloca:
1465 // ignore and inalloca doesn't have matching LLVM parameters.
1466 IRArgs.NumberOfArgs = 0;
1467 break;
John McCallf26e73d2016-03-11 04:30:43 +00001468 case ABIArgInfo::CoerceAndExpand:
1469 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1470 break;
1471 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001472 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1473 break;
1474 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001475
1476 if (IRArgs.NumberOfArgs > 0) {
1477 IRArgs.FirstArgIndex = IRArgNo;
1478 IRArgNo += IRArgs.NumberOfArgs;
1479 }
1480
1481 // Skip over the sret parameter when it comes second. We already handled it
1482 // above.
1483 if (IRArgNo == 1 && SwapThisWithSRet)
1484 IRArgNo++;
1485 }
1486 assert(ArgNo == ArgInfo.size());
1487
1488 if (FI.usesInAlloca())
1489 InallocaArgNo = IRArgNo++;
1490
1491 TotalIRArgs = IRArgNo;
1492}
1493} // namespace
1494
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001495/***/
1496
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001497bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Saleem Abdulrasoolf181f1a2018-02-28 20:16:12 +00001498 const auto &RI = FI.getReturnInfo();
1499 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001500}
1501
Tim Northovere77cc392014-03-29 13:28:05 +00001502bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1503 return ReturnTypeUsesSRet(FI) &&
1504 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1505}
1506
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001507bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1508 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1509 switch (BT->getKind()) {
1510 default:
1511 return false;
1512 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001513 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001514 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001515 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001516 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001517 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001518 }
1519 }
1520
1521 return false;
1522}
1523
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001524bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1525 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1526 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1527 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001528 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001529 }
1530 }
1531
1532 return false;
1533}
1534
Chris Lattnera5f58b02011-07-09 17:41:47 +00001535llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001536 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1537 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001538}
1539
Chris Lattnera5f58b02011-07-09 17:41:47 +00001540llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001541CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001542
David Blaikie82e95a32014-11-19 07:49:47 +00001543 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1544 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001545 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001546
Alexey Samsonov153004f2014-09-29 22:08:00 +00001547 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001548 const ABIArgInfo &retAI = FI.getReturnInfo();
1549 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001550 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001551 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001552
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001553 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001554 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001555 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001556 break;
1557
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001558 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001559 if (retAI.getInAllocaSRet()) {
1560 // sret things on win32 aren't void, they return the sret pointer.
1561 QualType ret = FI.getReturnType();
1562 llvm::Type *ty = ConvertType(ret);
1563 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1564 resultType = llvm::PointerType::get(ty, addressSpace);
1565 } else {
1566 resultType = llvm::Type::getVoidTy(getLLVMContext());
1567 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001568 break;
1569
John McCall7f416cc2015-09-08 08:05:57 +00001570 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001571 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001572 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001573 break;
John McCallf26e73d2016-03-11 04:30:43 +00001574
1575 case ABIArgInfo::CoerceAndExpand:
1576 resultType = retAI.getUnpaddedCoerceAndExpandType();
1577 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
Alexey Samsonov153004f2014-09-29 22:08:00 +00001580 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1581 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1582
1583 // Add type for sret argument.
1584 if (IRFunctionArgs.hasSRetArg()) {
1585 QualType Ret = FI.getReturnType();
1586 llvm::Type *Ty = ConvertType(Ret);
1587 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1588 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1589 llvm::PointerType::get(Ty, AddressSpace);
1590 }
1591
1592 // Add type for inalloca argument.
1593 if (IRFunctionArgs.hasInallocaArg()) {
1594 auto ArgStruct = FI.getArgStruct();
1595 assert(ArgStruct);
1596 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1597 }
1598
John McCallc818bbb2012-12-07 07:03:17 +00001599 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001600 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001601 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1602 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001603 for (; it != ie; ++it, ++ArgNo) {
1604 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001605
Rafael Espindolafad28de2012-10-24 01:59:00 +00001606 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001607 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1608 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1609 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001610
Alexey Samsonov153004f2014-09-29 22:08:00 +00001611 unsigned FirstIRArg, NumIRArgs;
1612 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1613
1614 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001615 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001616 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001617 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001618 break;
1619
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001620 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001621 assert(NumIRArgs == 1);
Yaxun Liud7523282017-04-17 20:10:44 +00001622 // indirect arguments are always on the stack, which is alloca addr space.
Chris Lattner2192fe52011-07-18 04:24:23 +00001623 llvm::Type *LTy = ConvertTypeForMem(it->type);
Yaxun Liud7523282017-04-17 20:10:44 +00001624 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1625 CGM.getDataLayout().getAllocaAddrSpace());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001626 break;
1627 }
1628
1629 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001630 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001631 // Fast-isel and the optimizer generally like scalar values better than
1632 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001633 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001634 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001635 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1636 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001637 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001638 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001639 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001640 assert(NumIRArgs == 1);
1641 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001642 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001643 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001644 }
Mike Stump11289f42009-09-09 15:08:12 +00001645
John McCallf26e73d2016-03-11 04:30:43 +00001646 case ABIArgInfo::CoerceAndExpand: {
1647 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1648 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1649 *ArgTypesIter++ = EltTy;
1650 }
1651 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1652 break;
1653 }
1654
Daniel Dunbard3674e62008-09-11 01:48:57 +00001655 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001656 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1657 getExpandedTypes(it->type, ArgTypesIter);
1658 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001659 break;
1660 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001661 }
1662
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001663 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1664 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001665
1666 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001667}
1668
Chris Lattner2192fe52011-07-18 04:24:23 +00001669llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001670 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001671 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001672
Chris Lattner8806e322011-07-10 00:18:59 +00001673 if (!isFuncTypeConvertible(FPT))
1674 return llvm::StructType::get(getLLVMContext());
Fangrui Song6907ce22018-07-30 19:24:48 +00001675
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001676 return GetFunctionType(GD);
Anders Carlsson64457732009-11-24 05:08:52 +00001677}
1678
Samuel Antao798f11c2015-11-23 22:04:44 +00001679static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1680 llvm::AttrBuilder &FuncAttrs,
1681 const FunctionProtoType *FPT) {
1682 if (!FPT)
1683 return;
1684
1685 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
Richard Smitheaf11ad2018-05-03 03:58:32 +00001686 FPT->isNothrow())
Samuel Antao798f11c2015-11-23 22:04:44 +00001687 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1688}
1689
Justin Lebarb080b632017-01-25 21:29:48 +00001690void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1691 bool AttrOnCallSite,
1692 llvm::AttrBuilder &FuncAttrs) {
1693 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1694 if (!HasOptnone) {
1695 if (CodeGenOpts.OptimizeSize)
1696 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1697 if (CodeGenOpts.OptimizeSize == 2)
1698 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1699 }
1700
1701 if (CodeGenOpts.DisableRedZone)
1702 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Kristina Brooks7f569b72018-10-18 14:07:02 +00001703 if (CodeGenOpts.IndirectTlsSegRefs)
1704 FuncAttrs.addAttribute("indirect-tls-seg-refs");
Justin Lebarb080b632017-01-25 21:29:48 +00001705 if (CodeGenOpts.NoImplicitFloat)
1706 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1707
1708 if (AttrOnCallSite) {
1709 // Attributes that should go on the call site only.
1710 if (!CodeGenOpts.SimplifyLibCalls ||
1711 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1712 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1713 if (!CodeGenOpts.TrapFuncName.empty())
1714 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1715 } else {
1716 // Attributes that should go on the function, but not the call site.
1717 if (!CodeGenOpts.DisableFPElim) {
1718 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1719 } else if (CodeGenOpts.OmitLeafFramePointer) {
1720 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1721 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1722 } else {
1723 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1724 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1725 }
1726
1727 FuncAttrs.addAttribute("less-precise-fpmad",
1728 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1729
Manoj Guptada08f6a2018-07-19 00:44:52 +00001730 if (CodeGenOpts.NullPointerIsValid)
1731 FuncAttrs.addAttribute("null-pointer-is-valid", "true");
Justin Lebarb080b632017-01-25 21:29:48 +00001732 if (!CodeGenOpts.FPDenormalMode.empty())
1733 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1734
1735 FuncAttrs.addAttribute("no-trapping-math",
1736 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1737
Sanjay Patelc81450e2018-04-30 18:19:03 +00001738 // Strict (compliant) code is the default, so only add this attribute to
1739 // indicate that we are trying to workaround a problem case.
1740 if (!CodeGenOpts.StrictFloatCastOverflow)
1741 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
Sanjay Pateld1754762018-04-27 14:22:48 +00001742
Justin Lebarb080b632017-01-25 21:29:48 +00001743 // TODO: Are these all needed?
1744 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1745 FuncAttrs.addAttribute("no-infs-fp-math",
1746 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1747 FuncAttrs.addAttribute("no-nans-fp-math",
1748 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1749 FuncAttrs.addAttribute("unsafe-fp-math",
1750 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1751 FuncAttrs.addAttribute("use-soft-float",
1752 llvm::toStringRef(CodeGenOpts.SoftFloat));
1753 FuncAttrs.addAttribute("stack-protector-buffer-size",
1754 llvm::utostr(CodeGenOpts.SSPBufferSize));
1755 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1756 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1757 FuncAttrs.addAttribute(
1758 "correctly-rounded-divide-sqrt-fp-math",
1759 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1760
Alexey Sotkin3858e262018-04-20 08:08:04 +00001761 if (getLangOpts().OpenCL)
1762 FuncAttrs.addAttribute("denorms-are-zero",
1763 llvm::toStringRef(CodeGenOpts.FlushDenorm));
1764
Justin Lebarb080b632017-01-25 21:29:48 +00001765 // TODO: Reciprocal estimate codegen options should apply to instructions?
Craig Topper402b4312017-11-20 17:09:22 +00001766 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
Justin Lebarb080b632017-01-25 21:29:48 +00001767 if (!Recips.empty())
1768 FuncAttrs.addAttribute("reciprocal-estimates",
Erich Keane857ac592017-10-27 18:45:06 +00001769 llvm::join(Recips, ","));
Justin Lebarb080b632017-01-25 21:29:48 +00001770
Craig Topper9a724aa2017-12-11 21:09:19 +00001771 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1772 CodeGenOpts.PreferVectorWidth != "none")
1773 FuncAttrs.addAttribute("prefer-vector-width",
1774 CodeGenOpts.PreferVectorWidth);
1775
Justin Lebarb080b632017-01-25 21:29:48 +00001776 if (CodeGenOpts.StackRealignment)
1777 FuncAttrs.addAttribute("stackrealign");
1778 if (CodeGenOpts.Backchain)
1779 FuncAttrs.addAttribute("backchain");
Chandler Carruth664aa862018-09-04 12:38:00 +00001780
1781 if (CodeGenOpts.SpeculativeLoadHardening)
1782 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
Justin Lebarb080b632017-01-25 21:29:48 +00001783 }
1784
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001785 if (getLangOpts().assumeFunctionsAreConvergent()) {
1786 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1787 // convergent (meaning, they may call an intrinsically convergent op, such
1788 // as __syncthreads() / barrier(), and so can't have certain optimizations
1789 // applied around them). LLVM will remove this attribute where it safely
1790 // can.
Justin Lebarb080b632017-01-25 21:29:48 +00001791 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001792 }
Justin Lebarb080b632017-01-25 21:29:48 +00001793
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001794 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
Justin Lebarb080b632017-01-25 21:29:48 +00001795 // Exceptions aren't supported in CUDA device code.
1796 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1797
1798 // Respect -fcuda-flush-denormals-to-zero.
Yaxun Liue1bfbc52018-07-21 02:02:22 +00001799 if (CodeGenOpts.FlushDenorm)
Justin Lebarb080b632017-01-25 21:29:48 +00001800 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1801 }
Peter Collingbourne87f477b2019-01-04 19:27:04 +00001802
1803 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1804 StringRef Var, Value;
1805 std::tie(Var, Value) = Attr.split('=');
1806 FuncAttrs.addAttribute(Var, Value);
1807 }
Justin Lebarb080b632017-01-25 21:29:48 +00001808}
1809
1810void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1811 llvm::AttrBuilder FuncAttrs;
Evandro Menezes85bd3972019-04-04 22:40:06 +00001812 ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(),
Justin Lebarb080b632017-01-25 21:29:48 +00001813 /* AttrOnCallsite = */ false, FuncAttrs);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001814 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
Justin Lebarb080b632017-01-25 21:29:48 +00001815}
1816
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001817void CodeGenModule::ConstructAttributeList(
1818 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
Reid Klecknercdd26792017-04-18 23:50:03 +00001819 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001820 llvm::AttrBuilder FuncAttrs;
1821 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001822
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001823 CallingConv = FI.getEffectiveCallingConvention();
John McCallab26cfa2010-02-05 21:31:56 +00001824 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001825 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001826
Samuel Antao798f11c2015-11-23 22:04:44 +00001827 // If we have information about the function prototype, we can learn
Craig Topper13d759f2018-04-30 22:02:48 +00001828 // attributes from there.
Samuel Antao798f11c2015-11-23 22:04:44 +00001829 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1830 CalleeInfo.getCalleeFunctionProtoType());
1831
Erich Keanede6480a32018-11-13 15:48:08 +00001832 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00001833
Justin Lebarb080b632017-01-25 21:29:48 +00001834 bool HasOptnone = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001835 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001836 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001837 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001838 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001839 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001840 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001841 if (TargetDecl->hasAttr<NoReturnAttr>())
1842 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Xinliang David Li4ec36062017-06-13 21:14:07 +00001843 if (TargetDecl->hasAttr<ColdAttr>())
1844 FuncAttrs.addAttribute(llvm::Attribute::Cold);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001845 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1846 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Yaxun Liu7d07ae72016-11-01 18:45:32 +00001847 if (TargetDecl->hasAttr<ConvergentAttr>())
1848 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Richard Smithdebc59d2013-01-30 05:45:05 +00001849
Chandler Carruth45bbe012017-03-24 09:11:57 +00001850 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001851 AddAttributesFromFunctionProtoType(
Chandler Carruth45bbe012017-03-24 09:11:57 +00001852 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001853 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1854 // These attributes are not inherited by overloads.
Chandler Carruth45bbe012017-03-24 09:11:57 +00001855 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1856 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001857 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001858 }
1859
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001860 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001861 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001862 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1863 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001864 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001865 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1866 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001867 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1868 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1869 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001870 }
David Majnemer631a90b2015-02-04 07:23:21 +00001871 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001872 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Manoj Guptada08f6a2018-07-19 00:44:52 +00001873 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
1874 !CodeGenOpts.NullPointerIsValid)
Hal Finkeld8442b12014-07-12 04:51:04 +00001875 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001876 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1877 FuncAttrs.addAttribute("no_caller_saved_registers");
Oren Ben Simhon220671a2018-03-17 13:31:35 +00001878 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
1879 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
Paul Robinson08556952014-12-11 20:14:04 +00001880
1881 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
George Burgess IVe3763372016-12-22 02:50:20 +00001882 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1883 Optional<unsigned> NumElemsParam;
Joel E. Denny81508102018-03-13 14:51:22 +00001884 if (AllocSize->getNumElemsParam().isValid())
1885 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
1886 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
George Burgess IVe3763372016-12-22 02:50:20 +00001887 NumElemsParam);
1888 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001889 }
1890
Justin Lebarb080b632017-01-25 21:29:48 +00001891 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
Paul Robinson08556952014-12-11 20:14:04 +00001892
Zola Bridges826ef592019-01-18 17:20:46 +00001893 // This must run after constructing the default function attribute list
1894 // to ensure that the speculative load hardening attribute is removed
1895 // in the case where the -mspeculative-load-hardening flag was passed.
1896 if (TargetDecl) {
1897 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
1898 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
1899 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
1900 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1901 }
1902
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001903 if (CodeGenOpts.EnableSegmentedStacks &&
1904 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001905 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001906
Sriraman Tallam5c651482017-11-07 19:37:51 +00001907 // Add NonLazyBind attribute to function declarations when -fno-plt
1908 // is used.
1909 if (TargetDecl && CodeGenOpts.NoPLT) {
1910 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1911 if (!Fn->isDefined() && !AttrOnCallSite) {
1912 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
1913 }
1914 }
1915 }
1916
Alexey Sotkin20f65922018-02-22 11:54:14 +00001917 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
1918 if (getLangOpts().OpenCLVersion <= 120) {
1919 // OpenCL v1.2 Work groups are always uniform
1920 FuncAttrs.addAttribute("uniform-work-group-size", "true");
1921 } else {
1922 // OpenCL v2.0 Work groups may be whether uniform or not.
1923 // '-cl-uniform-work-group-size' compile option gets a hint
1924 // to the compiler that the global work-size be a multiple of
1925 // the work-group size specified to clEnqueueNDRangeKernel
1926 // (i.e. work groups are uniform).
1927 FuncAttrs.addAttribute("uniform-work-group-size",
1928 llvm::toStringRef(CodeGenOpts.UniformWGSize));
1929 }
1930 }
1931
Justin Lebarb080b632017-01-25 21:29:48 +00001932 if (!AttrOnCallSite) {
Akira Hatanaka627586b2018-03-02 01:53:15 +00001933 bool DisableTailCalls = false;
1934
1935 if (CodeGenOpts.DisableTailCalls)
1936 DisableTailCalls = true;
1937 else if (TargetDecl) {
1938 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1939 TargetDecl->hasAttr<AnyX86InterruptAttr>())
1940 DisableTailCalls = true;
1941 else if (CodeGenOpts.NoEscapingBlockTailCalls) {
1942 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
1943 if (!BD->doesNotEscape())
1944 DisableTailCalls = true;
1945 }
1946 }
1947
Justin Lebarb080b632017-01-25 21:29:48 +00001948 FuncAttrs.addAttribute("disable-tail-calls",
1949 llvm::toStringRef(DisableTailCalls));
Erich Keanede6480a32018-11-13 15:48:08 +00001950 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
Bill Wendling985d1c52013-02-15 21:30:01 +00001951 }
1952
Alexey Samsonov153004f2014-09-29 22:08:00 +00001953 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001954
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001955 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001956 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001957 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001958 case ABIArgInfo::Extend:
Alex Bradburye41a5e22018-01-12 20:08:16 +00001959 if (RetAI.isSignExt())
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001960 RetAttrs.addAttribute(llvm::Attribute::SExt);
Alex Bradburye41a5e22018-01-12 20:08:16 +00001961 else
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001962 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001963 LLVM_FALLTHROUGH;
Daniel Dunbar67dace892009-02-03 06:17:37 +00001964 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001965 if (RetAI.getInReg())
1966 RetAttrs.addAttribute(llvm::Attribute::InReg);
1967 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001968 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001969 break;
1970
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001971 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001972 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001973 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001974 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1975 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001976 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001977 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001978
John McCallf26e73d2016-03-11 04:30:43 +00001979 case ABIArgInfo::CoerceAndExpand:
1980 break;
1981
Daniel Dunbard3674e62008-09-11 01:48:57 +00001982 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001983 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001984 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001985
Hal Finkela2347ba2014-07-18 15:52:10 +00001986 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1987 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001988 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001989 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1990 .getQuantity());
Manoj Guptada08f6a2018-07-19 00:44:52 +00001991 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
1992 !CodeGenOpts.NullPointerIsValid)
Hal Finkela2347ba2014-07-18 15:52:10 +00001993 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1994 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001995
John McCall12f23522016-04-04 18:33:08 +00001996 bool hasUsedSRet = false;
Reid Klecknercdd26792017-04-18 23:50:03 +00001997 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
John McCall12f23522016-04-04 18:33:08 +00001998
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001999 // Attach attributes to sret.
2000 if (IRFunctionArgs.hasSRetArg()) {
2001 llvm::AttrBuilder SRETAttrs;
Mandeep Singh Grang2a153102018-07-26 18:07:59 +00002002 if (!RetAI.getSuppressSRet())
2003 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00002004 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002005 if (RetAI.getInReg())
2006 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Reid Klecknercdd26792017-04-18 23:50:03 +00002007 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2008 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002009 }
2010
2011 // Attach attributes to inalloca argument.
2012 if (IRFunctionArgs.hasInallocaArg()) {
2013 llvm::AttrBuilder Attrs;
2014 Attrs.addAttribute(llvm::Attribute::InAlloca);
Reid Klecknercdd26792017-04-18 23:50:03 +00002015 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2016 llvm::AttributeSet::get(getLLVMContext(), Attrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002017 }
2018
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002019 unsigned ArgNo = 0;
2020 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2021 E = FI.arg_end();
2022 I != E; ++I, ++ArgNo) {
2023 QualType ParamType = I->type;
2024 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002025 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00002026
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002027 // Add attribute for padding argument, if necessary.
2028 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Reid Klecknercdd26792017-04-18 23:50:03 +00002029 if (AI.getPaddingInReg()) {
2030 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2031 llvm::AttributeSet::get(
2032 getLLVMContext(),
2033 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2034 }
Rafael Espindolafad28de2012-10-24 01:59:00 +00002035 }
2036
John McCall39ec71f2010-03-27 00:47:27 +00002037 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2038 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00002039 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00002040 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002041 case ABIArgInfo::Extend:
Alex Bradburye41a5e22018-01-12 20:08:16 +00002042 if (AI.isSignExt())
Bill Wendling207f0532012-12-20 19:27:06 +00002043 Attrs.addAttribute(llvm::Attribute::SExt);
Alex Bradburye41a5e22018-01-12 20:08:16 +00002044 else
2045 Attrs.addAttribute(llvm::Attribute::ZExt);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00002046 LLVM_FALLTHROUGH;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002047 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00002048 if (ArgNo == 0 && FI.isChainCall())
2049 Attrs.addAttribute(llvm::Attribute::Nest);
2050 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00002051 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002052 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002053
James Y Knight71608572015-08-21 18:19:06 +00002054 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00002055 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00002056 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00002057
Anders Carlsson20759ad2009-09-16 15:53:40 +00002058 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00002059 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002060
John McCall7f416cc2015-09-08 08:05:57 +00002061 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00002062
2063 // In a byval argument, it is important that the required
2064 // alignment of the type is honored, as LLVM might be creating a
2065 // *new* stack object, and needs to know what alignment to give
2066 // it. (Sometimes it can deduce a sensible alignment on its own,
2067 // but not if clang decides it must emit a packed struct, or the
2068 // user specifies increased alignment requirements.)
2069 //
2070 // This is different from indirect *not* byval, where the object
2071 // exists already, and the align attribute is purely
2072 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00002073 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00002074
John McCall7f416cc2015-09-08 08:05:57 +00002075 // For now, only add this when we have a byval argument.
2076 // TODO: be less lazy about updating test cases.
2077 if (AI.getIndirectByVal())
2078 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00002079
Daniel Dunbarc2304432009-03-18 19:51:01 +00002080 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00002081 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2082 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00002083 break;
James Y Knight71608572015-08-21 18:19:06 +00002084 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002085 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002086 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00002087 case ABIArgInfo::CoerceAndExpand:
2088 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002089
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002090 case ABIArgInfo::InAlloca:
2091 // inalloca disables readnone and readonly.
2092 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2093 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002094 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Hal Finkela2347ba2014-07-18 15:52:10 +00002097 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2098 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00002099 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00002100 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2101 .getQuantity());
Manoj Guptada08f6a2018-07-19 00:44:52 +00002102 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
2103 !CodeGenOpts.NullPointerIsValid)
Hal Finkela2347ba2014-07-18 15:52:10 +00002104 Attrs.addAttribute(llvm::Attribute::NonNull);
2105 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00002106
John McCall12f23522016-04-04 18:33:08 +00002107 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2108 case ParameterABI::Ordinary:
2109 break;
2110
2111 case ParameterABI::SwiftIndirectResult: {
2112 // Add 'sret' if we haven't already used it for something, but
2113 // only if the result is void.
2114 if (!hasUsedSRet && RetTy->isVoidType()) {
2115 Attrs.addAttribute(llvm::Attribute::StructRet);
2116 hasUsedSRet = true;
2117 }
2118
2119 // Add 'noalias' in either case.
2120 Attrs.addAttribute(llvm::Attribute::NoAlias);
2121
2122 // Add 'dereferenceable' and 'alignment'.
2123 auto PTy = ParamType->getPointeeType();
2124 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2125 auto info = getContext().getTypeInfoInChars(PTy);
2126 Attrs.addDereferenceableAttr(info.first.getQuantity());
2127 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2128 info.second.getQuantity()));
2129 }
2130 break;
2131 }
2132
2133 case ParameterABI::SwiftErrorResult:
2134 Attrs.addAttribute(llvm::Attribute::SwiftError);
2135 break;
2136
2137 case ParameterABI::SwiftContext:
2138 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2139 break;
2140 }
2141
Akira Hatanaka98a49332017-09-22 00:41:05 +00002142 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2143 Attrs.addAttribute(llvm::Attribute::NoCapture);
2144
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002145 if (Attrs.hasAttributes()) {
2146 unsigned FirstIRArg, NumIRArgs;
2147 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2148 for (unsigned i = 0; i < NumIRArgs; i++)
Reid Klecknercdd26792017-04-18 23:50:03 +00002149 ArgAttrs[FirstIRArg + i] =
2150 llvm::AttributeSet::get(getLLVMContext(), Attrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002151 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002152 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002153 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002154
Reid Klecknercdd26792017-04-18 23:50:03 +00002155 AttrList = llvm::AttributeList::get(
2156 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2157 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002158}
2159
John McCalla738c252011-03-09 04:27:21 +00002160/// An argument came in as a promoted argument; demote it back to its
2161/// declared type.
2162static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2163 const VarDecl *var,
2164 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002165 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002166
2167 // This can happen with promotions that actually don't change the
2168 // underlying type, like the enum promotions.
2169 if (value->getType() == varType) return value;
2170
2171 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2172 && "unexpected promotion type");
2173
2174 if (isa<llvm::IntegerType>(varType))
2175 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2176
2177 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2178}
2179
Chandler Carruth45bbe012017-03-24 09:11:57 +00002180/// Returns the attribute (either parameter attribute, or function
2181/// attribute), which declares argument ArgNo to be non-null.
2182static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2183 QualType ArgType, unsigned ArgNo) {
2184 // FIXME: __attribute__((nonnull)) can also be applied to:
2185 // - references to pointers, where the pointee is known to be
2186 // nonnull (apparently a Clang extension)
2187 // - transparent unions containing pointers
2188 // In the former case, LLVM IR cannot represent the constraint. In
2189 // the latter case, we have no guarantee that the transparent union
2190 // is in fact passed as a pointer.
2191 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2192 return nullptr;
2193 // First, check attribute on parameter itself.
2194 if (PVD) {
2195 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2196 return ParmNNAttr;
2197 }
2198 // Check function attributes.
2199 if (!FD)
2200 return nullptr;
2201 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2202 if (NNAttr->isNonNull(ArgNo))
2203 return NNAttr;
2204 }
2205 return nullptr;
2206}
2207
John McCall12f23522016-04-04 18:33:08 +00002208namespace {
2209 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2210 Address Temp;
2211 Address Arg;
2212 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2213 void Emit(CodeGenFunction &CGF, Flags flags) override {
2214 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2215 CGF.Builder.CreateStore(errorValue, Arg);
2216 }
2217 };
2218}
2219
Daniel Dunbard931a872009-02-02 22:03:45 +00002220void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2221 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002222 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002223 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2224 // Naked functions don't have prologues.
2225 return;
2226
John McCallcaa19452009-07-28 01:00:58 +00002227 // If this is an implicit-return-zero function, go ahead and
2228 // initialize the return value. TODO: it might be nice to have
2229 // a more general mechanism for this that didn't require synthesized
2230 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002231 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002232 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002233 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002234 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002235 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002236 Builder.CreateStore(Zero, ReturnValue);
2237 }
2238 }
2239
Mike Stump18bb9282009-05-16 07:57:57 +00002240 // FIXME: We no longer need the types from FunctionArgList; lift up and
2241 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002242
Alexey Samsonov153004f2014-09-29 22:08:00 +00002243 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002244 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002245 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002246 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2247 for (auto &Arg : Fn->args()) {
2248 FnArgs.push_back(&Arg);
2249 }
2250 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002251
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002252 // If we're using inalloca, all the memory arguments are GEPs off of the last
2253 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002254 Address ArgStruct = Address::invalid();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002255 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002256 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2257 FI.getArgStructAlignment());
2258
2259 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002260 }
2261
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002262 // Name the struct return parameter.
2263 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002264 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002265 AI->setName("agg.result");
Reid Klecknercdd26792017-04-18 23:50:03 +00002266 AI->addAttr(llvm::Attribute::NoAlias);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002269 // Track if we received the parameter as a pointer (indirect, byval, or
2270 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2271 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002272 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002273 ArgVals.reserve(Args.size());
2274
Reid Kleckner739756c2013-12-04 19:23:12 +00002275 // Create a pointer value for every parameter declaration. This usually
2276 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2277 // any cleanups or do anything that might unwind. We do that separately, so
2278 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002279 assert(FI.arg_size() == Args.size() &&
2280 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002281 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002282 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002283 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002284 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002285 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002286 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002287
John McCalla738c252011-03-09 04:27:21 +00002288 bool isPromoted =
2289 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
Volodymyr Sapsai17ebdb22018-01-22 22:29:24 +00002290 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2291 // the parameter is promoted. In this case we convert to
2292 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2293 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2294 assert(hasScalarEvaluationKind(Ty) ==
2295 hasScalarEvaluationKind(Arg->getType()));
John McCalla738c252011-03-09 04:27:21 +00002296
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002297 unsigned FirstIRArg, NumIRArgs;
2298 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002299
Daniel Dunbard3674e62008-09-11 01:48:57 +00002300 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002301 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002302 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002303 auto FieldIndex = ArgI.getInAllocaFieldIndex();
James Y Knight751fe282019-02-09 22:22:28 +00002304 Address V =
2305 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
John McCall7f416cc2015-09-08 08:05:57 +00002306 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002307 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002308 }
2309
Daniel Dunbar747865a2009-02-05 09:16:39 +00002310 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002311 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002312 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002313
John McCall47fb9502013-03-07 21:37:08 +00002314 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002315 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002316 // need to do is realign the value, if requested.
2317 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002318 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002319 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002320
2321 // Copy from the incoming argument pointer to the temporary with the
2322 // appropriate alignment.
2323 //
2324 // FIXME: We should have a common utility for generating an aggregate
2325 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002326 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002327 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2328 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2329 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2330 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002331 V = AlignedTemp;
2332 }
John McCall7f416cc2015-09-08 08:05:57 +00002333 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002334 } else {
2335 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002336 llvm::Value *V =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002337 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
John McCalla738c252011-03-09 04:27:21 +00002338
2339 if (isPromoted)
2340 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002341 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002342 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002343 break;
2344 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002345
2346 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002347 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002348
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002349 // If we have the trivial case, handle it with no muss and fuss.
2350 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002351 ArgI.getCoerceToType() == ConvertType(Ty) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002352 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002353 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002354 llvm::Value *V = FnArgs[FirstIRArg];
2355 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002356
Hal Finkel48d53e22014-07-19 01:41:07 +00002357 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002358 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
Manoj Guptada08f6a2018-07-19 00:44:52 +00002359 PVD->getFunctionScopeIndex()) &&
2360 !CGM.getCodeGenOpts().NullPointerIsValid)
Reid Klecknercdd26792017-04-18 23:50:03 +00002361 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel82504f02014-07-11 17:35:21 +00002362
Hal Finkel48d53e22014-07-19 01:41:07 +00002363 QualType OTy = PVD->getOriginalType();
2364 if (const auto *ArrTy =
2365 getContext().getAsConstantArrayType(OTy)) {
2366 // A C99 array parameter declaration with the static keyword also
2367 // indicates dereferenceability, and if the size is constant we can
2368 // use the dereferenceable attribute (which requires the size in
2369 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002370 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002371 QualType ETy = ArrTy->getElementType();
2372 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2373 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2374 ArrSize) {
2375 llvm::AttrBuilder Attrs;
2376 Attrs.addDereferenceableAttr(
2377 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
Reid Kleckner9d16fa02017-04-19 17:28:52 +00002378 AI->addAttrs(Attrs);
Manoj Guptada08f6a2018-07-19 00:44:52 +00002379 } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
2380 !CGM.getCodeGenOpts().NullPointerIsValid) {
Reid Klecknercdd26792017-04-18 23:50:03 +00002381 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel48d53e22014-07-19 01:41:07 +00002382 }
2383 }
2384 } else if (const auto *ArrTy =
2385 getContext().getAsVariableArrayType(OTy)) {
2386 // For C99 VLAs with the static keyword, we don't know the size so
2387 // we can't use the dereferenceable attribute, but in addrspace(0)
2388 // we know that it must be nonnull.
2389 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
Manoj Guptada08f6a2018-07-19 00:44:52 +00002390 !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
2391 !CGM.getCodeGenOpts().NullPointerIsValid)
Reid Klecknercdd26792017-04-18 23:50:03 +00002392 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel48d53e22014-07-19 01:41:07 +00002393 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002394
2395 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2396 if (!AVAttr)
2397 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2398 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
Roman Lebedevbd1c0872019-01-15 09:44:25 +00002399 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2400 // If alignment-assumption sanitizer is enabled, we do *not* add
2401 // alignment attribute here, but emit normal alignment assumption,
2402 // so the UBSAN check could function.
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002403 llvm::Value *AlignmentValue =
2404 EmitScalarExpr(AVAttr->getAlignment());
2405 llvm::ConstantInt *AlignmentCI =
2406 cast<llvm::ConstantInt>(AlignmentValue);
Reid Kleckner9d16fa02017-04-19 17:28:52 +00002407 unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
2408 +llvm::Value::MaximumAlignment);
2409 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002410 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002411 }
2412
Bill Wendling507c3512012-10-16 05:23:44 +00002413 if (Arg->getType().isRestrictQualified())
Reid Klecknercdd26792017-04-18 23:50:03 +00002414 AI->addAttr(llvm::Attribute::NoAlias);
John McCall39ec71f2010-03-27 00:47:27 +00002415
John McCall12f23522016-04-04 18:33:08 +00002416 // LLVM expects swifterror parameters to be used in very restricted
2417 // ways. Copy the value into a less-restricted temporary.
2418 if (FI.getExtParameterInfo(ArgNo).getABI()
2419 == ParameterABI::SwiftErrorResult) {
2420 QualType pointeeTy = Ty->getPointeeType();
2421 assert(pointeeTy->isPointerType());
2422 Address temp =
2423 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2424 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2425 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2426 Builder.CreateStore(incomingErrorValue, temp);
2427 V = temp.getPointer();
2428
2429 // Push a cleanup to copy the value back at the end of the function.
2430 // The convention does not guarantee that the value will be written
2431 // back if the function exits with an unwind exception.
2432 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2433 }
2434
Chris Lattner7369c142011-07-20 06:29:00 +00002435 // Ensure the argument is the correct type.
2436 if (V->getType() != ArgI.getCoerceToType())
2437 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2438
John McCalla738c252011-03-09 04:27:21 +00002439 if (isPromoted)
2440 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002441
2442 // Because of merging of function types from multiple decls it is
2443 // possible for the type of an argument to not match the corresponding
2444 // type in the function type. Since we are codegening the callee
2445 // in here, add a cast to the argument type.
2446 llvm::Type *LTy = ConvertType(Arg->getType());
2447 if (V->getType() != LTy)
2448 V = Builder.CreateBitCast(V, LTy);
2449
John McCall7f416cc2015-09-08 08:05:57 +00002450 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002451 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002454 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2455 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002456
John McCall7f416cc2015-09-08 08:05:57 +00002457 // Pointer to store into.
2458 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002459
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002460 // Fast-isel and the optimizer generally like scalar values better than
2461 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002462 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002463 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2464 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002465 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002466 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002467 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002468
John McCall7f416cc2015-09-08 08:05:57 +00002469 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002470 if (SrcSize <= DstSize) {
Yaxun Liue9e5c4f2017-06-29 18:47:45 +00002471 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002472 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002473 AddrToStoreInto =
2474 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002475 }
John McCall7f416cc2015-09-08 08:05:57 +00002476
2477 assert(STy->getNumElements() == NumIRArgs);
2478 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2479 auto AI = FnArgs[FirstIRArg + i];
2480 AI->setName(Arg->getName() + ".coerce" + Twine(i));
James Y Knight751fe282019-02-09 22:22:28 +00002481 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
John McCall7f416cc2015-09-08 08:05:57 +00002482 Builder.CreateStore(AI, EltPtr);
2483 }
2484
2485 if (SrcSize > DstSize) {
2486 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2487 }
2488
Chris Lattner15ec3612010-06-29 00:06:42 +00002489 } else {
2490 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002491 assert(NumIRArgs == 1);
2492 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002493 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002494 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002495 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002496
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002497 // Match to what EmitParmDecl is expecting for this type.
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002498 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002499 llvm::Value *V =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002500 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
John McCalla738c252011-03-09 04:27:21 +00002501 if (isPromoted)
2502 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002503 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002504 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002505 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002506 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002507 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002508 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002509
John McCallf26e73d2016-03-11 04:30:43 +00002510 case ABIArgInfo::CoerceAndExpand: {
2511 // Reconstruct into a temporary.
2512 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2513 ArgVals.push_back(ParamValue::forIndirect(alloca));
2514
2515 auto coercionType = ArgI.getCoerceAndExpandType();
2516 alloca = Builder.CreateElementBitCast(alloca, coercionType);
John McCallf26e73d2016-03-11 04:30:43 +00002517
2518 unsigned argIndex = FirstIRArg;
2519 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2520 llvm::Type *eltType = coercionType->getElementType(i);
2521 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2522 continue;
2523
James Y Knight751fe282019-02-09 22:22:28 +00002524 auto eltAddr = Builder.CreateStructGEP(alloca, i);
John McCallf26e73d2016-03-11 04:30:43 +00002525 auto elt = FnArgs[argIndex++];
2526 Builder.CreateStore(elt, eltAddr);
2527 }
2528 assert(argIndex == FirstIRArg + NumIRArgs);
2529 break;
2530 }
2531
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002532 case ABIArgInfo::Expand: {
2533 // If this structure was expanded into multiple arguments then
2534 // we need to create a temporary and reconstruct it from the
2535 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002536 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2537 LValue LV = MakeAddrLValue(Alloca, Ty);
2538 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002539
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002540 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2541 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2542 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2543 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2544 auto AI = FnArgs[FirstIRArg + i];
2545 AI->setName(Arg->getName() + "." + Twine(i));
2546 }
2547 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002548 }
2549
2550 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002551 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002552 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002553 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002554 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002555 } else {
2556 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002557 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002558 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002559 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002560 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002561 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002562
Reid Kleckner739756c2013-12-04 19:23:12 +00002563 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2564 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002565 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002566 } else {
2567 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002568 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002569 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002570}
2571
John McCallffa2c1a2012-01-29 07:46:59 +00002572static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2573 while (insn->use_empty()) {
2574 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2575 if (!bitcast) return;
2576
2577 // This is "safe" because we would have used a ConstantExpr otherwise.
2578 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2579 bitcast->eraseFromParent();
2580 }
2581}
2582
John McCall31168b02011-06-15 23:02:42 +00002583/// Try to emit a fused autorelease of a return result.
2584static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2585 llvm::Value *result) {
2586 // We must be immediately followed the cast.
2587 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002588 if (BB->empty()) return nullptr;
2589 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002590
Chris Lattner2192fe52011-07-18 04:24:23 +00002591 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002592
2593 // result is in a BasicBlock and is therefore an Instruction.
2594 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2595
Justin Bogner882f8612016-08-18 21:46:54 +00002596 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002597
2598 // Look for:
2599 // %generator = bitcast %type1* %generator2 to %type2*
2600 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2601 // We would have emitted this as a constant if the operand weren't
2602 // an Instruction.
2603 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2604
2605 // Require the generator to be immediately followed by the cast.
2606 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002607 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002608
Justin Bogner882f8612016-08-18 21:46:54 +00002609 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002610 }
2611
2612 // Look for:
2613 // %generator = call i8* @objc_retain(i8* %originalResult)
2614 // or
2615 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2616 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002617 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002618
2619 bool doRetainAutorelease;
2620
John McCallb04ecb72015-10-21 18:06:43 +00002621 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002622 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002623 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002624 .objc_retainAutoreleasedReturnValue) {
2625 doRetainAutorelease = false;
2626
John McCallcfa4e9b2012-09-07 23:30:50 +00002627 // If we emitted an assembly marker for this call (and the
2628 // ARCEntrypoints field should have been set if so), go looking
2629 // for that call. If we can't find it, we can't do this
2630 // optimization. But it should always be the immediately previous
2631 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002632 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002633 llvm::Instruction *prev = call->getPrevNode();
2634 assert(prev);
2635 if (isa<llvm::BitCastInst>(prev)) {
2636 prev = prev->getPrevNode();
2637 assert(prev);
2638 }
2639 assert(isa<llvm::CallInst>(prev));
2640 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002641 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002642 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002643 }
John McCall31168b02011-06-15 23:02:42 +00002644 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002645 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002646 }
2647
2648 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002649 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002650
2651 // Keep killing bitcasts, for sanity. Note that we no longer care
2652 // about precise ordering as long as there's exactly one use.
2653 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2654 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002655 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002656 result = bitcast->getOperand(0);
2657 }
2658
2659 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002660 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002661 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002662
2663 // Do the fused retain/autorelease if we were asked to.
2664 if (doRetainAutorelease)
2665 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2666
2667 // Cast back to the result type.
2668 return CGF.Builder.CreateBitCast(result, resultType);
2669}
2670
John McCallffa2c1a2012-01-29 07:46:59 +00002671/// If this is a +1 of the value of an immutable 'self', remove it.
2672static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2673 llvm::Value *result) {
2674 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002675 const ObjCMethodDecl *method =
2676 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002677 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002678 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002679 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002680
2681 // Look for a retain call.
2682 llvm::CallInst *retainCall =
2683 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2684 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002685 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002686 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002687
2688 // Look for an ordinary load of 'self'.
2689 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2690 llvm::LoadInst *load =
2691 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
Fangrui Song6907ce22018-07-30 19:24:48 +00002692 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002693 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002694 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002695
2696 // Okay! Burn it all down. This relies for correctness on the
2697 // assumption that the retain is emitted as part of the return and
2698 // that thereafter everything is used "linearly".
2699 llvm::Type *resultType = result->getType();
2700 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2701 assert(retainCall->use_empty());
2702 retainCall->eraseFromParent();
2703 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2704
2705 return CGF.Builder.CreateBitCast(load, resultType);
2706}
2707
John McCall31168b02011-06-15 23:02:42 +00002708/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002709///
2710/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002711static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2712 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002713 // If we're returning 'self', kill the initial retain. This is a
2714 // heuristic attempt to "encourage correctness" in the really unfortunate
2715 // case where we have a return of self during a dealloc and we desperately
2716 // need to avoid the possible autorelease.
2717 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2718 return self;
2719
John McCall31168b02011-06-15 23:02:42 +00002720 // At -O0, try to emit a fused retain/autorelease.
2721 if (CGF.shouldUseFusedARCCalls())
2722 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2723 return fused;
2724
2725 return CGF.EmitARCAutoreleaseReturnValue(result);
2726}
2727
John McCall6e1c0122012-01-29 02:35:02 +00002728/// Heuristically search for a dominating store to the return-value slot.
2729static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002730 // Check if a User is a store which pointerOperand is the ReturnValue.
2731 // We are looking for stores to the ReturnValue, not for stores of the
2732 // ReturnValue to some other location.
2733 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2734 auto *SI = dyn_cast<llvm::StoreInst>(U);
2735 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2736 return nullptr;
2737 // These aren't actually possible for non-coerced returns, and we
2738 // only care about non-coerced returns on this code path.
2739 assert(!SI->isAtomic() && !SI->isVolatile());
2740 return SI;
2741 };
John McCall6e1c0122012-01-29 02:35:02 +00002742 // If there are multiple uses of the return-value slot, just check
2743 // for something immediately preceding the IP. Sometimes this can
2744 // happen with how we generate implicit-returns; it can also happen
2745 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002746 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002747 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002748 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002749 llvm::Instruction *I = &IP->back();
2750
2751 // Skip lifetime markers
2752 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2753 IE = IP->rend();
2754 II != IE; ++II) {
2755 if (llvm::IntrinsicInst *Intrinsic =
2756 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2757 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2758 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2759 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002760 if (II == IE)
2761 break;
2762 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2763 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002764 }
2765 }
2766 I = &*II;
2767 break;
2768 }
2769
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002770 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002771 }
2772
2773 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002774 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002775 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002776
John McCall6e1c0122012-01-29 02:35:02 +00002777 // Now do a first-and-dirty dominance check: just walk up the
2778 // single-predecessors chain from the current insertion point.
2779 llvm::BasicBlock *StoreBB = store->getParent();
2780 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2781 while (IP != StoreBB) {
2782 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002783 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002784 }
2785
2786 // Okay, the store's basic block dominates the insertion point; we
2787 // can do our thing.
2788 return store;
2789}
2790
Adrian Prantl3be10542013-05-02 17:30:20 +00002791void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002792 bool EmitRetDbgLoc,
2793 SourceLocation EndLoc) {
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00002794 if (FI.isNoReturn()) {
2795 // Noreturn functions don't return.
2796 EmitUnreachable(EndLoc);
2797 return;
2798 }
2799
Hans Wennborgd71907d2014-09-04 22:16:33 +00002800 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2801 // Naked functions don't have epilogues.
2802 Builder.CreateUnreachable();
2803 return;
2804 }
2805
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002806 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002807 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002808 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002809 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002810 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002811
Dan Gohman481e40c2010-07-20 20:13:52 +00002812 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002813 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002814 QualType RetTy = FI.getReturnType();
2815 const ABIArgInfo &RetAI = FI.getReturnInfo();
2816
2817 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002818 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002819 // Aggregrates get evaluated directly into the destination. Sometimes we
2820 // need to return the sret value in a register, though.
2821 assert(hasAggregateEvaluationKind(RetTy));
2822 if (RetAI.getInAllocaSRet()) {
2823 llvm::Function::arg_iterator EI = CurFn->arg_end();
2824 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002825 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002826 llvm::Value *SRet = Builder.CreateStructGEP(
2827 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002828 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002829 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002830 break;
2831
Daniel Dunbar03816342010-08-21 02:24:36 +00002832 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002833 auto AI = CurFn->arg_begin();
2834 if (RetAI.isSRetAfterThis())
2835 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002836 switch (getEvaluationKind(RetTy)) {
2837 case TEK_Complex: {
2838 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002839 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002840 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002841 /*isInit*/ true);
2842 break;
2843 }
2844 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002845 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002846 break;
2847 case TEK_Scalar:
2848 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002849 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002850 /*isInit*/ true);
2851 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002852 }
2853 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002854 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002855
2856 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002857 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002858 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2859 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002860 // The internal return value temp always will have pointer-to-return-type
2861 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002862
John McCall6e1c0122012-01-29 02:35:02 +00002863 // If there is a dominating store to ReturnValue, we can elide
2864 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002865 if (llvm::StoreInst *SI =
2866 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002867 // Reuse the debug location from the store unless there is
2868 // cleanup code to be emitted between the store and return
2869 // instruction.
2870 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002871 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002872 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002873 RV = SI->getValueOperand();
2874 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002875
John McCall6e1c0122012-01-29 02:35:02 +00002876 // Otherwise, we have to do a simple load.
2877 } else {
2878 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002879 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002880 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002881 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002882 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002883
John McCall7f416cc2015-09-08 08:05:57 +00002884 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002885 }
John McCall31168b02011-06-15 23:02:42 +00002886
2887 // In ARC, end functions that return a retainable type with a call
2888 // to objc_autoreleaseReturnValue.
2889 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002890#ifndef NDEBUG
2891 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2892 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2893 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2894 // CurCodeDecl or BlockInfo.
2895 QualType RT;
2896
2897 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2898 RT = FD->getReturnType();
2899 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2900 RT = MD->getReturnType();
2901 else if (isa<BlockDecl>(CurCodeDecl))
2902 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2903 else
2904 llvm_unreachable("Unexpected function/method type");
2905
David Blaikiebbafb8a2012-03-11 07:00:24 +00002906 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002907 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002908 RT->isObjCRetainableType());
2909#endif
John McCall31168b02011-06-15 23:02:42 +00002910 RV = emitAutoreleaseOfResult(*this, RV);
2911 }
2912
Chris Lattner726b3d02010-06-26 23:13:19 +00002913 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002914
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002915 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002916 break;
2917
John McCallf26e73d2016-03-11 04:30:43 +00002918 case ABIArgInfo::CoerceAndExpand: {
2919 auto coercionType = RetAI.getCoerceAndExpandType();
John McCallf26e73d2016-03-11 04:30:43 +00002920
2921 // Load all of the coerced elements out into results.
2922 llvm::SmallVector<llvm::Value*, 4> results;
2923 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2924 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2925 auto coercedEltType = coercionType->getElementType(i);
2926 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2927 continue;
2928
James Y Knight751fe282019-02-09 22:22:28 +00002929 auto eltAddr = Builder.CreateStructGEP(addr, i);
John McCallf26e73d2016-03-11 04:30:43 +00002930 auto elt = Builder.CreateLoad(eltAddr);
2931 results.push_back(elt);
2932 }
2933
2934 // If we have one result, it's the single direct result type.
2935 if (results.size() == 1) {
2936 RV = results[0];
2937
2938 // Otherwise, we need to make a first-class aggregate.
2939 } else {
2940 // Construct a return type that lacks padding elements.
2941 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2942
2943 RV = llvm::UndefValue::get(returnType);
2944 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2945 RV = Builder.CreateInsertValue(RV, results[i], i);
2946 }
2947 }
2948 break;
2949 }
2950
Chris Lattner726b3d02010-06-26 23:13:19 +00002951 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002952 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002953 }
2954
Alexey Samsonovde443c52014-08-13 00:26:40 +00002955 llvm::Instruction *Ret;
2956 if (RV) {
Vedant Kumarc34d3432017-06-23 21:32:38 +00002957 EmitReturnValueCheck(RV);
Alexey Samsonovde443c52014-08-13 00:26:40 +00002958 Ret = Builder.CreateRet(RV);
2959 } else {
2960 Ret = Builder.CreateRetVoid();
2961 }
2962
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002963 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002964 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002965}
2966
Vedant Kumarc34d3432017-06-23 21:32:38 +00002967void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002968 // A current decl may not be available when emitting vtable thunks.
2969 if (!CurCodeDecl)
2970 return;
2971
2972 ReturnsNonNullAttr *RetNNAttr = nullptr;
2973 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
2974 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
2975
2976 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
2977 return;
2978
2979 // Prefer the returns_nonnull attribute if it's present.
2980 SourceLocation AttrLoc;
2981 SanitizerMask CheckKind;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00002982 SanitizerHandler Handler;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002983 if (RetNNAttr) {
2984 assert(!requiresReturnValueNullabilityCheck() &&
2985 "Cannot check nullability and the nonnull attribute");
2986 AttrLoc = RetNNAttr->getLocation();
2987 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00002988 Handler = SanitizerHandler::NonnullReturn;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002989 } else {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002990 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
2991 if (auto *TSI = DD->getTypeSourceInfo())
2992 if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
2993 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
2994 CheckKind = SanitizerKind::NullabilityReturn;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00002995 Handler = SanitizerHandler::NullabilityReturn;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002996 }
2997
2998 SanitizerScope SanScope(this);
2999
Vedant Kumarc34d3432017-06-23 21:32:38 +00003000 // Make sure the "return" source location is valid. If we're checking a
3001 // nullability annotation, make sure the preconditions for the check are met.
3002 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3003 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3004 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3005 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003006 if (requiresReturnValueNullabilityCheck())
Vedant Kumarc34d3432017-06-23 21:32:38 +00003007 CanNullCheck =
3008 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3009 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3010 EmitBlock(Check);
3011
3012 // Now do the null check.
3013 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3014 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3015 llvm::Value *DynamicData[] = {SLocPtr};
3016 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3017
3018 EmitBlock(NoCheck);
3019
3020#ifndef NDEBUG
3021 // The return location should not be used after the check has been emitted.
3022 ReturnLocation = Address::invalid();
3023#endif
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003024}
3025
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003026static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3027 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3028 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3029}
3030
John McCall7f416cc2015-09-08 08:05:57 +00003031static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3032 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003033 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3034 // placeholders.
3035 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
Peter Collingbourneb367c562016-11-28 22:30:21 +00003036 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3037 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00003038
3039 // FIXME: When we generate this IR in one pass, we shouldn't need
3040 // this win32-specific alignment hack.
3041 CharUnits Align = CharUnits::fromQuantity(4);
Peter Collingbourneb367c562016-11-28 22:30:21 +00003042 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
John McCall7f416cc2015-09-08 08:05:57 +00003043
3044 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003045 Ty.getQualifiers(),
3046 AggValueSlot::IsNotDestructed,
3047 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003048 AggValueSlot::IsNotAliased,
3049 AggValueSlot::DoesNotOverlap);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003050}
3051
John McCall32ea9692011-03-11 20:59:21 +00003052void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003053 const VarDecl *param,
3054 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00003055 // StartFunction converted the ABI-lowered parameter(s) into a
3056 // local alloca. We need to turn that into an r-value suitable
3057 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00003058 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00003059
John McCall32ea9692011-03-11 20:59:21 +00003060 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003061
Reid Kleckner25b56022018-12-12 23:46:06 +00003062 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3063 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3064 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003065
John McCall811b2912016-11-18 01:08:24 +00003066 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3067 // but the argument needs to be the original pointer.
3068 if (type->isReferenceType()) {
3069 args.add(RValue::get(Builder.CreateLoad(local)), type);
3070
3071 // In ARC, move out of consumed arguments so that the release cleanup
3072 // entered by StartFunction doesn't cause an over-release. This isn't
3073 // optimal -O0 code generation, but it should get cleaned up when
3074 // optimization is enabled. This also assumes that delegate calls are
3075 // performed exactly once for a set of arguments, but that should be safe.
3076 } else if (getLangOpts().ObjCAutoRefCount &&
3077 param->hasAttr<NSConsumedAttr>() &&
3078 type->isObjCRetainableType()) {
3079 llvm::Value *ptr = Builder.CreateLoad(local);
3080 auto null =
3081 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3082 Builder.CreateStore(null, local);
3083 args.add(RValue::get(ptr), type);
3084
Richard Smithd62d4982016-06-14 01:13:21 +00003085 // For the most part, we just need to load the alloca, except that
3086 // aggregate r-values are actually pointers to temporaries.
John McCall811b2912016-11-18 01:08:24 +00003087 } else {
Richard Smithd62d4982016-06-14 01:13:21 +00003088 args.add(convertTempToRValue(local, type, loc), type);
John McCall811b2912016-11-18 01:08:24 +00003089 }
Akira Hatanakaccda3d22018-04-27 06:57:00 +00003090
3091 // Deactivate the cleanup for the callee-destructed param that was pushed.
3092 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
Akira Hatanaka85282972018-05-15 21:00:30 +00003093 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3094 type.isDestructedType()) {
Akira Hatanakaccda3d22018-04-27 06:57:00 +00003095 EHScopeStack::stable_iterator cleanup =
3096 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3097 assert(cleanup.isValid() &&
3098 "cleanup for callee-destructed param not recorded");
3099 // This unreachable is a temporary marker which will be removed later.
3100 llvm::Instruction *isActive = Builder.CreateUnreachable();
3101 args.addArgCleanupDeactivation(cleanup, isActive);
3102 }
John McCall23f66262010-05-26 22:34:26 +00003103}
3104
John McCall31168b02011-06-15 23:02:42 +00003105static bool isProvablyNull(llvm::Value *addr) {
3106 return isa<llvm::ConstantPointerNull>(addr);
3107}
3108
John McCall31168b02011-06-15 23:02:42 +00003109/// Emit the actual writing-back of a writeback.
3110static void emitWriteback(CodeGenFunction &CGF,
3111 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00003112 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00003113 Address srcAddr = srcLV.getAddress();
3114 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00003115 "shouldn't have writeback for provably null argument");
3116
Craig Topper8a13c412014-05-21 05:09:00 +00003117 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003118
3119 // If the argument wasn't provably non-null, we need to null check
3120 // before doing the store.
Nuno Lopes9211cee2017-09-09 18:25:36 +00003121 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3122 CGF.CGM.getDataLayout());
John McCall31168b02011-06-15 23:02:42 +00003123 if (!provablyNonNull) {
3124 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3125 contBB = CGF.createBasicBlock("icr.done");
3126
John McCall7f416cc2015-09-08 08:05:57 +00003127 llvm::Value *isNull =
3128 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003129 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3130 CGF.EmitBlock(writebackBB);
3131 }
3132
3133 // Load the value to writeback.
3134 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3135
3136 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00003137 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3138 "icr.writeback-cast");
Fangrui Song6907ce22018-07-30 19:24:48 +00003139
John McCall31168b02011-06-15 23:02:42 +00003140 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00003141
3142 // If we have a "to use" value, it's something we need to emit a use
3143 // of. This has to be carefully threaded in: if it's done after the
3144 // release it's potentially undefined behavior (and the optimizer
3145 // will ignore it), and if it happens before the retain then the
3146 // optimizer could move the release there.
3147 if (writeback.ToUse) {
3148 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3149
3150 // Retain the new value. No need to block-copy here: the block's
3151 // being passed up the stack.
3152 value = CGF.EmitARCRetainNonBlock(value);
3153
3154 // Emit the intrinsic use here.
3155 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3156
3157 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00003158 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00003159
3160 // Put the new value in place (primitively).
3161 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3162
3163 // Release the old value.
3164 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3165
3166 // Otherwise, we can just do a normal lvalue store.
3167 } else {
3168 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3169 }
John McCall31168b02011-06-15 23:02:42 +00003170
3171 // Jump to the continuation block.
3172 if (!provablyNonNull)
3173 CGF.EmitBlock(contBB);
3174}
3175
3176static void emitWritebacks(CodeGenFunction &CGF,
3177 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00003178 for (const auto &I : args.writebacks())
3179 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00003180}
3181
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003182static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3183 const CallArgList &CallArgs) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003184 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3185 CallArgs.getCleanupsToDeactivate();
3186 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00003187 for (const auto &I : llvm::reverse(Cleanups)) {
3188 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3189 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003190 }
3191}
3192
John McCalleff18842013-03-23 02:35:54 +00003193static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3194 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3195 if (uop->getOpcode() == UO_AddrOf)
3196 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003197 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003198}
3199
John McCall31168b02011-06-15 23:02:42 +00003200/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003201/// we are passing the address of an __autoreleased temporary; it
3202/// might be copy-initialized with the current value of the given
3203/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003204static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3205 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003206 LValue srcLV;
3207
3208 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003209 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003210 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3211 srcLV = CGF.EmitLValue(lvExpr);
3212
3213 // Otherwise, just emit it as a scalar.
3214 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003215 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003216
3217 QualType srcAddrType =
3218 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003219 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003220 }
John McCall7f416cc2015-09-08 08:05:57 +00003221 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003222
3223 // The dest and src types don't necessarily match in LLVM terms
3224 // because of the crazy ObjC compatibility rules.
3225
Chris Lattner2192fe52011-07-18 04:24:23 +00003226 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003227 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3228
3229 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003230 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003231 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3232 CRE->getType());
3233 return;
3234 }
3235
John McCall31168b02011-06-15 23:02:42 +00003236 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003237 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3238 CGF.getPointerAlign(),
3239 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003240 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3241 // and that cleanup will be conditional if we can't prove that the l-value
3242 // isn't null, so we need to register a dominating point so that the cleanups
3243 // system will make valid IR.
3244 CodeGenFunction::ConditionalEvaluation condEval(CGF);
Fangrui Song6907ce22018-07-30 19:24:48 +00003245
John McCall31168b02011-06-15 23:02:42 +00003246 // Zero-initialize it if we're not doing a copy-initialization.
3247 bool shouldCopy = CRE->shouldCopy();
3248 if (!shouldCopy) {
3249 llvm::Value *null =
3250 llvm::ConstantPointerNull::get(
3251 cast<llvm::PointerType>(destType->getElementType()));
3252 CGF.Builder.CreateStore(null, temp);
3253 }
Craig Topper8a13c412014-05-21 05:09:00 +00003254
3255 llvm::BasicBlock *contBB = nullptr;
3256 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003257
3258 // If the address is *not* known to be non-null, we need to switch.
3259 llvm::Value *finalArgument;
3260
Nuno Lopes9211cee2017-09-09 18:25:36 +00003261 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3262 CGF.CGM.getDataLayout());
John McCall31168b02011-06-15 23:02:42 +00003263 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003264 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003265 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003266 llvm::Value *isNull =
3267 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003268
Fangrui Song6907ce22018-07-30 19:24:48 +00003269 finalArgument = CGF.Builder.CreateSelect(isNull,
John McCall31168b02011-06-15 23:02:42 +00003270 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003271 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003272
3273 // If we need to copy, then the load has to be conditional, which
3274 // means we need control flow.
3275 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003276 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003277 contBB = CGF.createBasicBlock("icr.cont");
3278 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3279 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3280 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003281 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003282 }
3283 }
3284
Craig Topper8a13c412014-05-21 05:09:00 +00003285 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003286
John McCall31168b02011-06-15 23:02:42 +00003287 // Perform a copy if necessary.
3288 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003289 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003290 assert(srcRV.isScalar());
3291
3292 llvm::Value *src = srcRV.getScalarVal();
3293 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3294 "icr.cast");
3295
3296 // Use an ordinary store, not a store-to-lvalue.
3297 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003298
3299 // If optimization is enabled, and the value was held in a
3300 // __strong variable, we need to tell the optimizer that this
3301 // value has to stay alive until we're doing the store back.
3302 // This is because the temporary is effectively unretained,
3303 // and so otherwise we can violate the high-level semantics.
3304 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3305 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3306 valueToUse = src;
3307 }
John McCall31168b02011-06-15 23:02:42 +00003308 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003309
John McCall31168b02011-06-15 23:02:42 +00003310 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003311 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003312 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003313 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003314
3315 // Make a phi for the value to intrinsically use.
3316 if (valueToUse) {
3317 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3318 "icr.to-use");
3319 phiToUse->addIncoming(valueToUse, copyBB);
3320 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3321 originBB);
3322 valueToUse = phiToUse;
3323 }
3324
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003325 condEval.end(CGF);
3326 }
John McCall31168b02011-06-15 23:02:42 +00003327
John McCalleff18842013-03-23 02:35:54 +00003328 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003329 args.add(RValue::get(finalArgument), CRE->getType());
3330}
3331
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003332void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003333 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003334
3335 // Save the stack.
3336 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003337 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003338}
3339
Nico Weber8cdb3f92015-08-25 18:43:32 +00003340void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3341 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003342 // Restore the stack after the call.
James Y Knight8799cae2019-02-03 21:53:49 +00003343 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003344 CGF.Builder.CreateCall(F, StackBase);
3345 }
3346}
3347
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003348void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3349 SourceLocation ArgLoc,
Vedant Kumared00ea02017-03-06 05:28:22 +00003350 AbstractCallee AC,
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003351 unsigned ParmNum) {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003352 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3353 SanOpts.has(SanitizerKind::NullabilityArg)))
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003354 return;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003355
3356 // The param decl may be missing in a variadic function.
Vedant Kumared00ea02017-03-06 05:28:22 +00003357 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003358 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003359
Fangrui Song6907ce22018-07-30 19:24:48 +00003360 // Prefer the nonnull attribute if it's present.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003361 const NonNullAttr *NNAttr = nullptr;
3362 if (SanOpts.has(SanitizerKind::NonnullAttribute))
3363 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3364
3365 bool CanCheckNullability = false;
3366 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3367 auto Nullability = PVD->getType()->getNullability(getContext());
3368 CanCheckNullability = Nullability &&
3369 *Nullability == NullabilityKind::NonNull &&
3370 PVD->getTypeSourceInfo();
3371 }
3372
3373 if (!NNAttr && !CanCheckNullability)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003374 return;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003375
3376 SourceLocation AttrLoc;
3377 SanitizerMask CheckKind;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003378 SanitizerHandler Handler;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003379 if (NNAttr) {
3380 AttrLoc = NNAttr->getLocation();
3381 CheckKind = SanitizerKind::NonnullAttribute;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003382 Handler = SanitizerHandler::NonnullArg;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003383 } else {
3384 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3385 CheckKind = SanitizerKind::NullabilityArg;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003386 Handler = SanitizerHandler::NullabilityArg;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003387 }
3388
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003389 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003390 assert(RV.isScalar());
3391 llvm::Value *V = RV.getScalarVal();
3392 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003393 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003394 llvm::Constant *StaticData[] = {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003395 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003396 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003397 };
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003398 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003399}
3400
David Blaikief05779e2015-07-21 18:37:18 +00003401void CodeGenFunction::EmitCallArgs(
3402 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3403 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Vedant Kumared00ea02017-03-06 05:28:22 +00003404 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003405 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003406
Reid Kleckner739756c2013-12-04 19:23:12 +00003407 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003408 // because arguments are destroyed left to right in the callee. As a special
3409 // case, there are certain language constructs that require left-to-right
3410 // evaluation, and in those cases we consider the evaluation order requirement
3411 // to trump the "destruction order is reverse construction order" guarantee.
3412 bool LeftToRight =
3413 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3414 ? Order == EvaluationOrder::ForceLeftToRight
3415 : Order != EvaluationOrder::ForceRightToLeft;
3416
George Burgess IV0d6592a2017-02-23 05:59:56 +00003417 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3418 RValue EmittedArg) {
Vedant Kumared00ea02017-03-06 05:28:22 +00003419 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
George Burgess IV0d6592a2017-02-23 05:59:56 +00003420 return;
Vedant Kumared00ea02017-03-06 05:28:22 +00003421 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
George Burgess IV0d6592a2017-02-23 05:59:56 +00003422 if (PS == nullptr)
3423 return;
3424
3425 const auto &Context = getContext();
3426 auto SizeTy = Context.getSizeType();
3427 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3428 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
3429 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
Erik Pilkington9c3b5882019-01-30 20:34:53 +00003430 EmittedArg.getScalarVal(),
Erik Pilkington02d5fb12019-03-19 20:44:18 +00003431 PS->isDynamic());
George Burgess IV0d6592a2017-02-23 05:59:56 +00003432 Args.add(RValue::get(V), SizeTy);
3433 // If we're emitting args in reverse, be sure to do so with
3434 // pass_object_size, as well.
3435 if (!LeftToRight)
3436 std::swap(Args.back(), *(&Args.back() - 1));
3437 };
3438
Richard Smitha560ccf2016-09-29 21:30:12 +00003439 // Insert a stack save if we're going to need any inalloca args.
3440 bool HasInAllocaArgs = false;
3441 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003442 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3443 I != E && !HasInAllocaArgs; ++I)
3444 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3445 if (HasInAllocaArgs) {
3446 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3447 Args.allocateArgumentMemory(*this);
3448 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003449 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003450
Richard Smitha560ccf2016-09-29 21:30:12 +00003451 // Evaluate each argument in the appropriate order.
3452 size_t CallArgsStart = Args.size();
3453 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3454 unsigned Idx = LeftToRight ? I : E - I - 1;
3455 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
George Burgess IV0d6592a2017-02-23 05:59:56 +00003456 unsigned InitialArgSize = Args.size();
Akira Hatanaka46dd7dbc2017-06-28 00:42:48 +00003457 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
3458 // the argument and parameter match or the objc method is parameterized.
3459 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
3460 getContext().hasSameUnqualifiedType((*Arg)->getType(),
3461 ArgTypes[Idx]) ||
3462 (isa<ObjCMethodDecl>(AC.getDecl()) &&
3463 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
3464 "Argument and parameter types don't match");
Richard Smitha560ccf2016-09-29 21:30:12 +00003465 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
George Burgess IV0d6592a2017-02-23 05:59:56 +00003466 // In particular, we depend on it being the last arg in Args, and the
3467 // objectsize bits depend on there only being one arg if !LeftToRight.
3468 assert(InitialArgSize + 1 == Args.size() &&
3469 "The code below depends on only adding one arg per EmitCallArg");
3470 (void)InitialArgSize;
Yaxun Liu5b330e82018-03-15 15:25:19 +00003471 // Since pointer argument are never emitted as LValue, it is safe to emit
3472 // non-null argument check for r-value only.
3473 if (!Args.back().hasLValue()) {
3474 RValue RVArg = Args.back().getKnownRValue();
3475 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3476 ParamsToSkip + Idx);
3477 // @llvm.objectsize should never have side-effects and shouldn't need
3478 // destruction/cleanups, so we can safely "emit" it after its arg,
3479 // regardless of right-to-leftness
3480 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3481 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003482 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003483
Richard Smitha560ccf2016-09-29 21:30:12 +00003484 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003485 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3486 // IR function.
3487 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003488 }
3489}
3490
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003491namespace {
3492
David Blaikie7e70d682015-08-18 22:40:54 +00003493struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003494 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003495 : Addr(Addr), Ty(Ty) {}
3496
John McCall7f416cc2015-09-08 08:05:57 +00003497 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003498 QualType Ty;
3499
Craig Topper4f12f102014-03-12 06:41:41 +00003500 void Emit(CodeGenFunction &CGF, Flags flags) override {
Akira Hatanaka7275da02018-02-28 07:15:55 +00003501 QualType::DestructionKind DtorKind = Ty.isDestructedType();
3502 if (DtorKind == QualType::DK_cxx_destructor) {
3503 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3504 assert(!Dtor->isTrivial());
3505 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3506 /*Delegating=*/false, Addr);
3507 } else {
3508 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
3509 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003510 }
3511};
3512
David Blaikie38b25912015-02-09 19:13:51 +00003513struct DisableDebugLocationUpdates {
3514 CodeGenFunction &CGF;
3515 bool disabledDebugInfo;
3516 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3517 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3518 CGF.disableDebugInfo();
3519 }
3520 ~DisableDebugLocationUpdates() {
3521 if (disabledDebugInfo)
3522 CGF.enableDebugInfo();
3523 }
3524};
3525
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003526} // end anonymous namespace
3527
Yaxun Liu5b330e82018-03-15 15:25:19 +00003528RValue CallArg::getRValue(CodeGenFunction &CGF) const {
3529 if (!HasLV)
3530 return RV;
3531 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
Richard Smithe78fac52018-04-05 20:52:58 +00003532 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
3533 LV.isVolatile());
Yaxun Liu5b330e82018-03-15 15:25:19 +00003534 IsUsed = true;
3535 return RValue::getAggregate(Copy.getAddress());
3536}
3537
3538void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
3539 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
3540 if (!HasLV && RV.isScalar())
3541 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*init=*/true);
3542 else if (!HasLV && RV.isComplex())
3543 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
3544 else {
3545 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
3546 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
Richard Smithe78fac52018-04-05 20:52:58 +00003547 // We assume that call args are never copied into subobjects.
3548 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
Yaxun Liu5b330e82018-03-15 15:25:19 +00003549 HasLV ? LV.isVolatileQualified()
3550 : RV.isVolatileQualified());
3551 }
3552 IsUsed = true;
3553}
3554
John McCall32ea9692011-03-11 20:59:21 +00003555void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3556 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003557 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003558 if (const ObjCIndirectCopyRestoreExpr *CRE
3559 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003560 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003561 return emitWritebackArg(*this, args, CRE);
3562 }
3563
John McCall0a76c0c2011-08-26 18:42:59 +00003564 assert(type->isReferenceType() == E->isGLValue() &&
3565 "reference binding to unmaterialized r-value!");
3566
John McCall17054bd62011-08-26 21:08:13 +00003567 if (E->isGLValue()) {
3568 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003569 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003570 }
Mike Stump11289f42009-09-09 15:08:12 +00003571
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003572 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3573
3574 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3575 // However, we still have to push an EH-only cleanup in case we unwind before
3576 // we make it to the call.
Akira Hatanaka85282972018-05-15 21:00:30 +00003577 if (HasAggregateEvalKind &&
3578 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Reid Klecknerac640602014-05-01 03:07:18 +00003579 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003580 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003581 AggValueSlot Slot;
3582 if (args.isUsingInAlloca())
3583 Slot = createPlaceholderSlot(*this, type);
3584 else
3585 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003586
Akira Hatanaka4ce0e5a2018-04-18 23:33:15 +00003587 bool DestroyedInCallee = true, NeedsEHCleanup = true;
3588 if (const auto *RD = type->getAsCXXRecordDecl())
3589 DestroyedInCallee = RD->hasNonTrivialDestructor();
3590 else
3591 NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
3592
3593 if (DestroyedInCallee)
3594 Slot.setExternallyDestructed();
Reid Klecknere39ee212014-05-03 00:33:28 +00003595
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003596 EmitAggExpr(E, Slot);
3597 RValue RV = Slot.asRValue();
3598 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003599
Akira Hatanaka4ce0e5a2018-04-18 23:33:15 +00003600 if (DestroyedInCallee && NeedsEHCleanup) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003601 // Create a no-op GEP between the placeholder and the cleanup so we can
3602 // RAUW it successfully. It also serves as a marker of the first
3603 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003604 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3605 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003606 // This unreachable is a temporary marker which will be removed later.
3607 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3608 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003609 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003610 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003611 }
3612
3613 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003614 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3615 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3616 assert(L.isSimple());
Yaxun Liu5b330e82018-03-15 15:25:19 +00003617 args.addUncopiedAggregate(L, type);
Eli Friedmandf968192011-05-26 00:10:27 +00003618 return;
3619 }
3620
John McCall32ea9692011-03-11 20:59:21 +00003621 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003622}
3623
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003624QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3625 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3626 // implicitly widens null pointer constants that are arguments to varargs
3627 // functions to pointer-sized ints.
3628 if (!getTarget().getTriple().isOSWindows())
3629 return Arg->getType();
3630
3631 if (Arg->getType()->isIntegerType() &&
3632 getContext().getTypeSize(Arg->getType()) <
3633 getContext().getTargetInfo().getPointerWidth(0) &&
3634 Arg->isNullPointerConstant(getContext(),
3635 Expr::NPC_ValueDependentIsNotNull)) {
3636 return getContext().getIntPtrType();
3637 }
3638
3639 return Arg->getType();
3640}
3641
Dan Gohman515a60d2012-02-16 00:57:37 +00003642// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3643// optimizer it can aggressively ignore unwind edges.
3644void
3645CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3646 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3647 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3648 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3649 CGM.getNoObjCARCExceptionsMetadata());
3650}
3651
John McCall882987f2013-02-28 19:01:20 +00003652/// Emits a call to the given no-arguments nounwind runtime function.
3653llvm::CallInst *
James Y Knight9871db02019-02-05 16:42:33 +00003654CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
John McCall882987f2013-02-28 19:01:20 +00003655 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003656 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003657}
3658
3659/// Emits a call to the given nounwind runtime function.
3660llvm::CallInst *
James Y Knight9871db02019-02-05 16:42:33 +00003661CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
3662 ArrayRef<llvm::Value *> args,
John McCall882987f2013-02-28 19:01:20 +00003663 const llvm::Twine &name) {
3664 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3665 call->setDoesNotThrow();
3666 return call;
3667}
3668
3669/// Emits a simple call (never an invoke) to the given no-arguments
3670/// runtime function.
James Y Knight9871db02019-02-05 16:42:33 +00003671llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
3672 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003673 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003674}
3675
David Majnemer0b17d442015-12-15 21:27:59 +00003676// Calls which may throw must have operand bundles indicating which funclet
3677// they are nested within.
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003678SmallVector<llvm::OperandBundleDef, 1>
3679CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
3680 SmallVector<llvm::OperandBundleDef, 1> BundleList;
Sanjay Patel846b63b2016-01-18 22:15:33 +00003681 // There is no need for a funclet operand bundle if we aren't inside a
3682 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003683 if (!CurrentFuncletPad)
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003684 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003685
3686 // Skip intrinsics which cannot throw.
3687 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3688 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003689 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003690
3691 BundleList.emplace_back("funclet", CurrentFuncletPad);
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003692 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003693}
3694
David Majnemer971d31b2016-02-24 17:02:45 +00003695/// Emits a simple call (never an invoke) to the given runtime function.
James Y Knight9871db02019-02-05 16:42:33 +00003696llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
3697 ArrayRef<llvm::Value *> args,
3698 const llvm::Twine &name) {
3699 llvm::CallInst *call = Builder.CreateCall(
3700 callee, args, getBundlesForFunclet(callee.getCallee()), name);
David Majnemer971d31b2016-02-24 17:02:45 +00003701 call->setCallingConv(getRuntimeCC());
3702 return call;
3703}
3704
John McCall882987f2013-02-28 19:01:20 +00003705/// Emits a call or invoke to the given noreturn runtime function.
James Y Knight9871db02019-02-05 16:42:33 +00003706void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
3707 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003708 SmallVector<llvm::OperandBundleDef, 1> BundleList =
James Y Knight9871db02019-02-05 16:42:33 +00003709 getBundlesForFunclet(callee.getCallee());
David Majnemer0b17d442015-12-15 21:27:59 +00003710
John McCall882987f2013-02-28 19:01:20 +00003711 if (getInvokeDest()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003712 llvm::InvokeInst *invoke =
John McCall882987f2013-02-28 19:01:20 +00003713 Builder.CreateInvoke(callee,
3714 getUnreachableBlock(),
3715 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003716 args,
3717 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003718 invoke->setDoesNotReturn();
3719 invoke->setCallingConv(getRuntimeCC());
3720 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003721 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003722 call->setDoesNotReturn();
3723 call->setCallingConv(getRuntimeCC());
3724 Builder.CreateUnreachable();
3725 }
3726}
3727
Sanjay Patel846b63b2016-01-18 22:15:33 +00003728/// Emits a call or invoke instruction to the given nullary runtime function.
James Y Knight9871db02019-02-05 16:42:33 +00003729llvm::CallBase *
3730CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3731 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003732 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003733}
3734
3735/// Emits a call or invoke instruction to the given runtime function.
James Y Knight9871db02019-02-05 16:42:33 +00003736llvm::CallBase *
3737CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3738 ArrayRef<llvm::Value *> args,
3739 const Twine &name) {
James Y Knight3933add2019-01-30 02:54:28 +00003740 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
3741 call->setCallingConv(getRuntimeCC());
3742 return call;
John McCall882987f2013-02-28 19:01:20 +00003743}
3744
John McCallbd309292010-07-06 01:34:17 +00003745/// Emits a call or invoke instruction to the given function, depending
3746/// on the current state of the EH stack.
James Y Knight9871db02019-02-05 16:42:33 +00003747llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
James Y Knight3933add2019-01-30 02:54:28 +00003748 ArrayRef<llvm::Value *> Args,
3749 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003750 llvm::BasicBlock *InvokeDest = getInvokeDest();
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003751 SmallVector<llvm::OperandBundleDef, 1> BundleList =
James Y Knight9871db02019-02-05 16:42:33 +00003752 getBundlesForFunclet(Callee.getCallee());
John McCallbd309292010-07-06 01:34:17 +00003753
James Y Knight3933add2019-01-30 02:54:28 +00003754 llvm::CallBase *Inst;
Dan Gohman515a60d2012-02-16 00:57:37 +00003755 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003756 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003757 else {
3758 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003759 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3760 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003761 EmitBlock(ContBB);
3762 }
3763
3764 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3765 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003766 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003767 AddObjCARCExceptionMetadata(Inst);
3768
James Y Knight3933add2019-01-30 02:54:28 +00003769 return Inst;
John McCallbd309292010-07-06 01:34:17 +00003770}
3771
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003772void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3773 llvm::Value *New) {
3774 DeferredReplacements.push_back(std::make_pair(Old, New));
3775}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003776
Daniel Dunbard931a872009-02-02 22:03:45 +00003777RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003778 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003779 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003780 const CallArgList &CallArgs,
James Y Knight3933add2019-01-30 02:54:28 +00003781 llvm::CallBase **callOrInvoke,
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00003782 SourceLocation Loc) {
Mike Stump18bb9282009-05-16 07:57:57 +00003783 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003784
Peter Collingbourneea211002018-02-05 23:09:13 +00003785 assert(Callee.isOrdinary() || Callee.isVirtual());
John McCallb92ab1a2016-10-26 23:46:34 +00003786
Daniel Dunbar613855c2008-09-09 23:27:19 +00003787 // Handle struct-return functions by passing a pointer to the
3788 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003789 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003790 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003791
James Y Knightcfe8cd72019-02-07 01:15:41 +00003792 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00003793
Amy Huang0d0334f2019-04-12 20:25:30 +00003794 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
3795
James Y Knightb92d2902019-02-05 16:05:50 +00003796#ifndef NDEBUG
3797 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
3798 // For an inalloca varargs function, we don't expect CallInfo to match the
3799 // function pointer's type, because the inalloca struct a will have extra
3800 // fields in it for the varargs parameters. Code later in this function
3801 // bitcasts the function pointer to the type derived from CallInfo.
3802 //
3803 // In other cases, we assert that the types match up (until pointers stop
3804 // having pointee types).
James Y Knightcfe8cd72019-02-07 01:15:41 +00003805 llvm::Type *TypeFromVal;
3806 if (Callee.isVirtual())
3807 TypeFromVal = Callee.getVirtualFunctionType();
3808 else
3809 TypeFromVal =
3810 Callee.getFunctionPointer()->getType()->getPointerElementType();
3811 assert(IRFuncTy == TypeFromVal);
James Y Knightb92d2902019-02-05 16:05:50 +00003812 }
3813#endif
3814
John McCallb92ab1a2016-10-26 23:46:34 +00003815 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003816
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003817 // If we're using inalloca, insert the allocation after the stack save.
3818 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003819 Address ArgMemory = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003820 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Matt Arsenault502ad602017-04-10 22:28:02 +00003821 const llvm::DataLayout &DL = CGM.getDataLayout();
Reid Kleckner9df1d972014-04-10 01:40:15 +00003822 llvm::Instruction *IP = CallArgs.getStackBase();
3823 llvm::AllocaInst *AI;
3824 if (IP) {
3825 IP = IP->getNextNode();
Matt Arsenault502ad602017-04-10 22:28:02 +00003826 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
3827 "argmem", IP);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003828 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003829 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003830 }
John McCall7f416cc2015-09-08 08:05:57 +00003831 auto Align = CallInfo.getArgStructAlignment();
3832 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003833 AI->setUsedWithInAlloca(true);
3834 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003835 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003836 }
3837
Alexey Samsonov153004f2014-09-29 22:08:00 +00003838 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003839 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3840
Chris Lattner4ca97c32009-06-13 00:26:38 +00003841 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003842 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003843 Address SRetPtr = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003844 Address SRetAlloca = Address::invalid();
George Burgess IV003be7c2018-03-08 05:32:30 +00003845 llvm::Value *UnusedReturnSizePtr = nullptr;
John McCallf26e73d2016-03-11 04:30:43 +00003846 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003847 if (!ReturnValue.isNull()) {
3848 SRetPtr = ReturnValue.getValue();
3849 } else {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003850 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003851 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3852 uint64_t size =
3853 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003854 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003855 }
3856 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003857 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003858 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003859 } else if (RetAI.isInAlloca()) {
James Y Knight751fe282019-02-09 22:22:28 +00003860 Address Addr =
3861 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00003862 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003863 }
Anders Carlsson17490832009-12-24 20:40:36 +00003864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
John McCall12f23522016-04-04 18:33:08 +00003866 Address swiftErrorTemp = Address::invalid();
3867 Address swiftErrorArg = Address::invalid();
3868
John McCallb92ab1a2016-10-26 23:46:34 +00003869 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003870 assert(CallInfo.arg_size() == CallArgs.size() &&
3871 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003872 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003873 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003874 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003875 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003876 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003877
Rafael Espindolafad28de2012-10-24 01:59:00 +00003878 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003879 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3880 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3881 llvm::UndefValue::get(ArgInfo.getPaddingType());
3882
3883 unsigned FirstIRArg, NumIRArgs;
3884 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003885
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003886 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003887 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003888 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003889 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003890 if (I->isAggregate()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003891 // Replace the placeholder with the appropriate argument slot GEP.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003892 Address Addr = I->hasLValue()
3893 ? I->getKnownLValue().getAddress()
3894 : I->getKnownRValue().getAggregateAddress();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003895 llvm::Instruction *Placeholder =
Yaxun Liu5b330e82018-03-15 15:25:19 +00003896 cast<llvm::Instruction>(Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003897 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3898 Builder.SetInsertPoint(Placeholder);
James Y Knight751fe282019-02-09 22:22:28 +00003899 Addr =
3900 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003901 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003902 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003903 } else {
3904 // Store the RValue into the argument struct.
James Y Knight751fe282019-02-09 22:22:28 +00003905 Address Addr =
3906 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00003907 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003908 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3909 // There are some cases where a trivial bitcast is not avoidable. The
3910 // definition of a type later in a translation unit may change it's type
3911 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003912 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003913 Addr = Builder.CreateBitCast(Addr, MemType);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003914 I->copyInto(*this, Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003915 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003916 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003917 }
3918
Daniel Dunbar03816342010-08-21 02:24:36 +00003919 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003920 assert(NumIRArgs == 1);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003921 if (!I->isAggregate()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00003922 // Make a temporary alloca to pass the argument.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +00003923 Address Addr = CreateMemTempWithoutCast(
3924 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
John McCall7f416cc2015-09-08 08:05:57 +00003925 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003926
Yaxun Liu5b330e82018-03-15 15:25:19 +00003927 I->copyInto(*this, Addr);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003928 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003929 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003930 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003931 // 1. If the argument is not byval, and we are required to copy the
3932 // source. (This case doesn't occur on any common architecture.)
3933 // 2. If the argument is byval, RV is not sufficiently aligned, and
3934 // we cannot force it to be sufficiently aligned.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003935 // 3. If the argument is byval, but RV is not located in default
3936 // or alloca address space.
3937 Address Addr = I->hasLValue()
3938 ? I->getKnownLValue().getAddress()
3939 : I->getKnownRValue().getAggregateAddress();
3940 llvm::Value *V = Addr.getPointer();
John McCall7f416cc2015-09-08 08:05:57 +00003941 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003942 const llvm::DataLayout *TD = &CGM.getDataLayout();
Yaxun Liu5b330e82018-03-15 15:25:19 +00003943
3944 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
3945 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
3946 TD->getAllocaAddrSpace()) &&
3947 "indirect argument must be in alloca address space");
3948
3949 bool NeedCopy = false;
3950
3951 if (Addr.getAlignment() < Align &&
3952 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) <
3953 Align.getQuantity()) {
3954 NeedCopy = true;
3955 } else if (I->hasLValue()) {
3956 auto LV = I->getKnownLValue();
3957 auto AS = LV.getAddressSpace();
Andrew Savonichev1bf1a152018-12-10 12:03:00 +00003958
Yaxun Liu5b330e82018-03-15 15:25:19 +00003959 if ((!ArgInfo.getIndirectByVal() &&
3960 (LV.getAlignment() >=
Andrew Savonichev1bf1a152018-12-10 12:03:00 +00003961 getContext().getTypeAlignInChars(I->Ty)))) {
3962 NeedCopy = true;
3963 }
3964 if (!getLangOpts().OpenCL) {
3965 if ((ArgInfo.getIndirectByVal() &&
3966 (AS != LangAS::Default &&
3967 AS != CGM.getASTAllocaAddressSpace()))) {
3968 NeedCopy = true;
3969 }
3970 }
3971 // For OpenCL even if RV is located in default or alloca address space
3972 // we don't want to perform address space cast for it.
3973 else if ((ArgInfo.getIndirectByVal() &&
3974 Addr.getType()->getAddressSpace() != IRFuncTy->
3975 getParamType(FirstIRArg)->getPointerAddressSpace())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00003976 NeedCopy = true;
3977 }
3978 }
Andrew Savonichev1bf1a152018-12-10 12:03:00 +00003979
Yaxun Liu5b330e82018-03-15 15:25:19 +00003980 if (NeedCopy) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003981 // Create an aligned temporary, and copy to it.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +00003982 Address AI = CreateMemTempWithoutCast(
3983 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
John McCall7f416cc2015-09-08 08:05:57 +00003984 IRCallArgs[FirstIRArg] = AI.getPointer();
Yaxun Liu5b330e82018-03-15 15:25:19 +00003985 I->copyInto(*this, AI);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003986 } else {
3987 // Skip the extra memcpy call.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003988 auto *T = V->getType()->getPointerElementType()->getPointerTo(
3989 CGM.getDataLayout().getAllocaAddrSpace());
3990 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
3991 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
3992 true);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003993 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003994 }
3995 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003996 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003997
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003998 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003999 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00004000 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004001
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004002 case ABIArgInfo::Extend:
4003 case ABIArgInfo::Direct: {
4004 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00004005 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
4006 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004007 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00004008 llvm::Value *V;
Yaxun Liu5b330e82018-03-15 15:25:19 +00004009 if (!I->isAggregate())
4010 V = I->getKnownRValue().getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004011 else
Yaxun Liu5b330e82018-03-15 15:25:19 +00004012 V = Builder.CreateLoad(
4013 I->hasLValue() ? I->getKnownLValue().getAddress()
4014 : I->getKnownRValue().getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004015
John McCall12f23522016-04-04 18:33:08 +00004016 // Implement swifterror by copying into a new swifterror argument.
4017 // We'll write back in the normal path out of the call.
4018 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
4019 == ParameterABI::SwiftErrorResult) {
4020 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
4021
4022 QualType pointeeTy = I->Ty->getPointeeType();
4023 swiftErrorArg =
4024 Address(V, getContext().getTypeAlignInChars(pointeeTy));
4025
4026 swiftErrorTemp =
4027 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4028 V = swiftErrorTemp.getPointer();
4029 cast<llvm::AllocaInst>(V)->setSwiftError(true);
4030
4031 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4032 Builder.CreateStore(errorValue, swiftErrorTemp);
4033 }
4034
Reid Kleckner79b0fd72014-10-10 00:05:45 +00004035 // We might have to widen integers, but we should never truncate.
4036 if (ArgInfo.getCoerceToType() != V->getType() &&
4037 V->getType()->isIntegerTy())
4038 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
4039
Chris Lattner3ce86682011-07-12 04:53:39 +00004040 // If the argument doesn't match, perform a bitcast to coerce it. This
4041 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004042 if (FirstIRArg < IRFuncTy->getNumParams() &&
4043 V->getType() != IRFuncTy->getParamType(FirstIRArg))
4044 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00004045
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004046 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004047 break;
4048 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00004049
Daniel Dunbar2f219b02009-02-03 19:12:28 +00004050 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00004051 Address Src = Address::invalid();
Yaxun Liu5b330e82018-03-15 15:25:19 +00004052 if (!I->isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00004053 Src = CreateMemTemp(I->Ty, "coerce");
Yaxun Liu5b330e82018-03-15 15:25:19 +00004054 I->copyInto(*this, Src);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00004055 } else {
Yaxun Liu5b330e82018-03-15 15:25:19 +00004056 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
4057 : I->getKnownRValue().getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00004058 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004059
Chris Lattner8a2f3c72010-07-30 04:02:24 +00004060 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004061 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004062
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004063 // Fast-isel and the optimizer generally like scalar values better than
4064 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00004065 llvm::StructType *STy =
4066 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004067 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00004068 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00004069 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4070 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
4071
4072 // If the source type is smaller than the destination type of the
4073 // coerce-to logic, copy the source value into a temp alloca the size
4074 // of the destination type to allow loading all of it. The bits past
4075 // the source value are left undef.
4076 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00004077 Address TempAlloca
4078 = CreateTempAlloca(STy, Src.getAlignment(),
4079 Src.getName() + ".coerce");
4080 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
4081 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00004082 } else {
Matt Arsenault7a124f32017-08-01 20:36:57 +00004083 Src = Builder.CreateBitCast(Src,
4084 STy->getPointerTo(Src.getAddressSpace()));
Chandler Carrutha6399a52012-10-10 11:29:08 +00004085 }
4086
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004087 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00004088 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
James Y Knight751fe282019-02-09 22:22:28 +00004089 Address EltPtr = Builder.CreateStructGEP(Src, i);
John McCall7f416cc2015-09-08 08:05:57 +00004090 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004091 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00004092 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00004093 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00004094 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004095 assert(NumIRArgs == 1);
4096 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00004097 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00004098 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004099
Daniel Dunbar2f219b02009-02-03 19:12:28 +00004100 break;
4101 }
4102
John McCallf26e73d2016-03-11 04:30:43 +00004103 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00004104 auto coercionType = ArgInfo.getCoerceAndExpandType();
4105 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4106
John McCall12f23522016-04-04 18:33:08 +00004107 llvm::Value *tempSize = nullptr;
4108 Address addr = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004109 Address AllocaAddr = Address::invalid();
Yaxun Liu5b330e82018-03-15 15:25:19 +00004110 if (I->isAggregate()) {
4111 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
4112 : I->getKnownRValue().getAggregateAddress();
4113
John McCall12f23522016-04-04 18:33:08 +00004114 } else {
Yaxun Liu5b330e82018-03-15 15:25:19 +00004115 RValue RV = I->getKnownRValue();
John McCall12f23522016-04-04 18:33:08 +00004116 assert(RV.isScalar()); // complex should always just be direct
4117
4118 llvm::Type *scalarType = RV.getScalarVal()->getType();
4119 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
4120 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
4121
John McCall12f23522016-04-04 18:33:08 +00004122 // Materialize to a temporary.
4123 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004124 CharUnits::fromQuantity(std::max(
4125 layout->getAlignment(), scalarAlign)),
4126 "tmp",
4127 /*ArraySize=*/nullptr, &AllocaAddr);
4128 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
John McCall12f23522016-04-04 18:33:08 +00004129
4130 Builder.CreateStore(RV.getScalarVal(), addr);
4131 }
4132
John McCallf26e73d2016-03-11 04:30:43 +00004133 addr = Builder.CreateElementBitCast(addr, coercionType);
4134
4135 unsigned IRArgPos = FirstIRArg;
4136 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4137 llvm::Type *eltType = coercionType->getElementType(i);
4138 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
James Y Knight751fe282019-02-09 22:22:28 +00004139 Address eltAddr = Builder.CreateStructGEP(addr, i);
John McCallf26e73d2016-03-11 04:30:43 +00004140 llvm::Value *elt = Builder.CreateLoad(eltAddr);
4141 IRCallArgs[IRArgPos++] = elt;
4142 }
4143 assert(IRArgPos == FirstIRArg + NumIRArgs);
4144
John McCall12f23522016-04-04 18:33:08 +00004145 if (tempSize) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004146 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
John McCall12f23522016-04-04 18:33:08 +00004147 }
4148
John McCallf26e73d2016-03-11 04:30:43 +00004149 break;
4150 }
4151
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00004152 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004153 unsigned IRArgPos = FirstIRArg;
Yaxun Liu5b330e82018-03-15 15:25:19 +00004154 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004155 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00004156 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004157 }
4158 }
Mike Stump11289f42009-09-09 15:08:12 +00004159
John McCall9831b842018-02-06 18:52:44 +00004160 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
4161 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
John McCallb92ab1a2016-10-26 23:46:34 +00004162
4163 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00004164 if (ArgMemory.isValid()) {
4165 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00004166 if (CallInfo.isVariadic()) {
4167 // When passing non-POD arguments by value to variadic functions, we will
4168 // end up with a variadic prototype and an inalloca call site. In such
4169 // cases, we can't do any parameter mismatch checks. Give up and bitcast
4170 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00004171 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
James Y Knightcfe8cd72019-02-07 01:15:41 +00004172 CalleePtr =
4173 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
Reid Klecknerafba553e2014-07-08 02:24:27 +00004174 } else {
4175 llvm::Type *LastParamTy =
4176 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
4177 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004178#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00004179 // Assert that these structs have equivalent element types.
4180 llvm::StructType *FullTy = CallInfo.getArgStruct();
4181 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
4182 cast<llvm::PointerType>(LastParamTy)->getElementType());
4183 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
4184 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
4185 DE = DeclaredTy->element_end(),
4186 FI = FullTy->element_begin();
4187 DI != DE; ++DI, ++FI)
4188 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004189#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00004190 Arg = Builder.CreateBitCast(Arg, LastParamTy);
4191 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004192 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004193 assert(IRFunctionArgs.hasInallocaArg());
4194 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004195 }
4196
John McCallb92ab1a2016-10-26 23:46:34 +00004197 // 2. Prepare the function pointer.
4198
4199 // If the callee is a bitcast of a non-variadic function to have a
4200 // variadic function pointer type, check to see if we can remove the
4201 // bitcast. This comes up with unprototyped functions.
4202 //
4203 // This makes the IR nicer, but more importantly it ensures that we
4204 // can inline the function at -O0 if it is marked always_inline.
James Y Knightcfe8cd72019-02-07 01:15:41 +00004205 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
4206 llvm::Value *Ptr) -> llvm::Function * {
John McCallb92ab1a2016-10-26 23:46:34 +00004207 if (!CalleeFT->isVarArg())
James Y Knightcfe8cd72019-02-07 01:15:41 +00004208 return nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +00004209
James Y Knightcfe8cd72019-02-07 01:15:41 +00004210 // Get underlying value if it's a bitcast
4211 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
4212 if (CE->getOpcode() == llvm::Instruction::BitCast)
4213 Ptr = CE->getOperand(0);
4214 }
John McCallb92ab1a2016-10-26 23:46:34 +00004215
James Y Knightcfe8cd72019-02-07 01:15:41 +00004216 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
John McCallb92ab1a2016-10-26 23:46:34 +00004217 if (!OrigFn)
James Y Knightcfe8cd72019-02-07 01:15:41 +00004218 return nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +00004219
4220 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
4221
4222 // If the original type is variadic, or if any of the component types
4223 // disagree, we cannot remove the cast.
4224 if (OrigFT->isVarArg() ||
4225 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4226 OrigFT->getReturnType() != CalleeFT->getReturnType())
James Y Knightcfe8cd72019-02-07 01:15:41 +00004227 return nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +00004228
4229 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4230 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
James Y Knightcfe8cd72019-02-07 01:15:41 +00004231 return nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +00004232
4233 return OrigFn;
4234 };
James Y Knightcfe8cd72019-02-07 01:15:41 +00004235
4236 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
4237 CalleePtr = OrigFn;
4238 IRFuncTy = OrigFn->getFunctionType();
4239 }
John McCallb92ab1a2016-10-26 23:46:34 +00004240
4241 // 3. Perform the actual call.
4242
4243 // Deactivate any cleanups that we're supposed to do immediately before
4244 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00004245 if (!CallArgs.getCleanupsToDeactivate().empty())
4246 deactivateArgCleanupsBeforeCall(*this, CallArgs);
4247
John McCallb92ab1a2016-10-26 23:46:34 +00004248 // Assert that the arguments we computed match up. The IR verifier
4249 // will catch this, but this is a common enough source of problems
4250 // during IRGen changes that it's way better for debugging to catch
4251 // it ourselves here.
4252#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004253 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
4254 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4255 // Inalloca argument can have different type.
4256 if (IRFunctionArgs.hasInallocaArg() &&
4257 i == IRFunctionArgs.getInallocaArgNo())
4258 continue;
4259 if (i < IRFuncTy->getNumParams())
4260 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
4261 }
John McCallb92ab1a2016-10-26 23:46:34 +00004262#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004263
Craig Topper3113ec32018-10-24 17:42:17 +00004264 // Update the largest vector width if any arguments have vector types.
4265 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4266 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
4267 LargestVectorWidth = std::max(LargestVectorWidth,
4268 VT->getPrimitiveSizeInBits());
4269 }
4270
John McCallb92ab1a2016-10-26 23:46:34 +00004271 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004272 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00004273 llvm::AttributeList Attrs;
John McCallb92ab1a2016-10-26 23:46:34 +00004274 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
Reid Klecknercdd26792017-04-18 23:50:03 +00004275 Callee.getAbstractInfo(), Attrs, CallingConv,
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00004276 /*AttrOnCallSite=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004277
John McCallb92ab1a2016-10-26 23:46:34 +00004278 // Apply some call-site-specific attributes.
4279 // TODO: work this into building the attribute set.
4280
4281 // Apply always_inline to all calls within flatten functions.
4282 // FIXME: should this really take priority over __try, below?
4283 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
Amy Huang0d0334f2019-04-12 20:25:30 +00004284 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
John McCallb92ab1a2016-10-26 23:46:34 +00004285 Attrs =
Reid Klecknerde864822017-03-21 16:57:30 +00004286 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
John McCallb92ab1a2016-10-26 23:46:34 +00004287 llvm::Attribute::AlwaysInline);
4288 }
4289
4290 // Disable inlining inside SEH __try blocks.
4291 if (isSEHTryScope()) {
4292 Attrs =
Reid Klecknerde864822017-03-21 16:57:30 +00004293 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
John McCallb92ab1a2016-10-26 23:46:34 +00004294 llvm::Attribute::NoInline);
4295 }
4296
4297 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004298 bool CannotThrow;
4299 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00004300 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00004301 CannotThrow = false;
4302 } else if (isCleanupPadScope() &&
4303 EHPersonality::get(*this).isMSVCXXPersonality()) {
4304 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00004305 // exception is thrown during a cleanup outside of a try/catch.
4306 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004307 CannotThrow = true;
4308 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00004309 // Otherwise, nounwind call sites will never throw.
Reid Klecknerde864822017-03-21 16:57:30 +00004310 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
David Majnemer4e52d6f2015-12-12 05:39:21 +00004311 llvm::Attribute::NoUnwind);
4312 }
George Burgess IV003be7c2018-03-08 05:32:30 +00004313
4314 // If we made a temporary, be sure to clean up after ourselves. Note that we
4315 // can't depend on being inside of an ExprWithCleanups, so we need to manually
4316 // pop this cleanup later on. Being eager about this is OK, since this
4317 // temporary is 'invisible' outside of the callee.
4318 if (UnusedReturnSizePtr)
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004319 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
George Burgess IV003be7c2018-03-08 05:32:30 +00004320 UnusedReturnSizePtr);
4321
David Majnemer4e52d6f2015-12-12 05:39:21 +00004322 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00004323
Reid Klecknerb75a3f02018-02-09 00:16:41 +00004324 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4325 getBundlesForFunclet(CalleePtr);
David Majnemer0b17d442015-12-15 21:27:59 +00004326
John McCallb92ab1a2016-10-26 23:46:34 +00004327 // Emit the actual call/invoke instruction.
James Y Knight3933add2019-01-30 02:54:28 +00004328 llvm::CallBase *CI;
John McCallbd309292010-07-06 01:34:17 +00004329 if (!InvokeDest) {
James Y Knightcfe8cd72019-02-07 01:15:41 +00004330 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004331 } else {
4332 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
James Y Knightcfe8cd72019-02-07 01:15:41 +00004333 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004334 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004335 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004336 }
Chris Lattnere70a0072010-06-29 16:40:28 +00004337 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004338 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004339
John McCallb92ab1a2016-10-26 23:46:34 +00004340 // Apply the attributes and calling convention.
James Y Knight3933add2019-01-30 02:54:28 +00004341 CI->setAttributes(Attrs);
4342 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004343
John McCallb92ab1a2016-10-26 23:46:34 +00004344 // Apply various metadata.
4345
4346 if (!CI->getType()->isVoidTy())
4347 CI->setName("call");
4348
Craig Topper3113ec32018-10-24 17:42:17 +00004349 // Update largest vector width from the return type.
4350 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
4351 LargestVectorWidth = std::max(LargestVectorWidth,
4352 VT->getPrimitiveSizeInBits());
4353
Adam Nemet1e217bc2016-03-28 22:18:53 +00004354 // Insert instrumentation or attach profile metadata at indirect call sites.
4355 // For more details, see the comment before the definition of
4356 // IPVK_IndirectCallTarget in InstrProfData.inc.
James Y Knight3933add2019-01-30 02:54:28 +00004357 if (!CI->getCalledFunction())
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004358 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004359 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004360
Dan Gohman515a60d2012-02-16 00:57:37 +00004361 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4362 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004363 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004364 AddObjCARCExceptionMetadata(CI);
4365
4366 // Suppress tail calls if requested.
4367 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
John McCallb92ab1a2016-10-26 23:46:34 +00004368 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4369 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4370 }
4371
Amy Huang0d0334f2019-04-12 20:25:30 +00004372 // Add metadata for calls to MSAllocator functions
4373 // FIXME: Get the type that the return value is cast to.
4374 if (getDebugInfo() && TargetDecl &&
4375 TargetDecl->hasAttr<MSAllocatorAttr>())
4376 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
4377
John McCallb92ab1a2016-10-26 23:46:34 +00004378 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004379
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004380 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004381 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004382 // unreachable code.
James Y Knight3933add2019-01-30 02:54:28 +00004383 if (CI->doesNotReturn()) {
George Burgess IV003be7c2018-03-08 05:32:30 +00004384 if (UnusedReturnSizePtr)
4385 PopCleanupBlock();
Leny Kholodov6aab1112015-06-08 10:23:49 +00004386
Julian Lettnerb62e9dc2019-01-24 18:04:21 +00004387 // Strip away the noreturn attribute to better diagnose unreachable UB.
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00004388 if (SanOpts.has(SanitizerKind::Unreachable)) {
Julian Lettnerf82d8922019-02-02 02:05:16 +00004389 // Also remove from function since CallBase::hasFnAttr additionally checks
4390 // attributes of the called function.
James Y Knight3933add2019-01-30 02:54:28 +00004391 if (auto *F = CI->getCalledFunction())
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00004392 F->removeFnAttr(llvm::Attribute::NoReturn);
James Y Knight3933add2019-01-30 02:54:28 +00004393 CI->removeAttribute(llvm::AttributeList::FunctionIndex,
4394 llvm::Attribute::NoReturn);
Julian Lettnerb6c06dc2019-02-01 02:51:00 +00004395
4396 // Avoid incompatibility with ASan which relies on the `noreturn`
4397 // attribute to insert handler calls.
Julian Lettner98b9f5b2019-02-04 23:37:50 +00004398 if (SanOpts.hasOneOf(SanitizerKind::Address |
4399 SanitizerKind::KernelAddress)) {
Julian Lettnerb6c06dc2019-02-01 02:51:00 +00004400 SanitizerScope SanScope(this);
4401 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
4402 Builder.SetInsertPoint(CI);
4403 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004404 llvm::FunctionCallee Fn =
4405 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
Julian Lettnerb6c06dc2019-02-01 02:51:00 +00004406 EmitNounwindRuntimeCall(Fn);
4407 }
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00004408 }
4409
4410 EmitUnreachable(Loc);
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004411 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004412
Mike Stump18bb9282009-05-16 07:57:57 +00004413 // FIXME: For now, emit a dummy basic block because expr emitters in
4414 // generally are not ready to handle emitting expressions at unreachable
4415 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004416 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004417
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004418 // Return a reasonable RValue.
4419 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004420 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004421
John McCall12f23522016-04-04 18:33:08 +00004422 // Perform the swifterror writeback.
4423 if (swiftErrorTemp.isValid()) {
4424 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4425 Builder.CreateStore(errorResult, swiftErrorArg);
4426 }
4427
John McCallb92ab1a2016-10-26 23:46:34 +00004428 // Emit any call-associated writebacks immediately. Arguably this
4429 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004430 if (CallArgs.hasWritebacks())
4431 emitWritebacks(*this, CallArgs);
4432
Nico Weber8cdb3f92015-08-25 18:43:32 +00004433 // The stack cleanup for inalloca arguments has to run out of the normal
4434 // lexical order, so deactivate it and run it manually here.
4435 CallArgs.freeArgumentMemory(*this);
4436
John McCallb92ab1a2016-10-26 23:46:34 +00004437 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004438 RValue Ret = [&] {
4439 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004440 case ABIArgInfo::CoerceAndExpand: {
4441 auto coercionType = RetAI.getCoerceAndExpandType();
John McCallf26e73d2016-03-11 04:30:43 +00004442
4443 Address addr = SRetPtr;
4444 addr = Builder.CreateElementBitCast(addr, coercionType);
4445
John McCall12f23522016-04-04 18:33:08 +00004446 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4447 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4448
John McCallf26e73d2016-03-11 04:30:43 +00004449 unsigned unpaddedIndex = 0;
4450 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4451 llvm::Type *eltType = coercionType->getElementType(i);
4452 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
James Y Knight751fe282019-02-09 22:22:28 +00004453 Address eltAddr = Builder.CreateStructGEP(addr, i);
John McCall12f23522016-04-04 18:33:08 +00004454 llvm::Value *elt = CI;
4455 if (requiresExtract)
4456 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4457 else
4458 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004459 Builder.CreateStore(elt, eltAddr);
4460 }
John McCall12f23522016-04-04 18:33:08 +00004461 // FALLTHROUGH
Galina Kistanova0872d6c2017-06-03 06:30:46 +00004462 LLVM_FALLTHROUGH;
John McCall12f23522016-04-04 18:33:08 +00004463 }
4464
4465 case ABIArgInfo::InAlloca:
4466 case ABIArgInfo::Indirect: {
4467 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
George Burgess IV003be7c2018-03-08 05:32:30 +00004468 if (UnusedReturnSizePtr)
4469 PopCleanupBlock();
John McCall12f23522016-04-04 18:33:08 +00004470 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004471 }
4472
Hal Finkelee90a222014-09-26 05:04:30 +00004473 case ABIArgInfo::Ignore:
4474 // If we are ignoring an argument that had a result, make sure to
4475 // construct the appropriate return value for our caller.
4476 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004477
Hal Finkelee90a222014-09-26 05:04:30 +00004478 case ABIArgInfo::Extend:
4479 case ABIArgInfo::Direct: {
4480 llvm::Type *RetIRTy = ConvertType(RetTy);
4481 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4482 switch (getEvaluationKind(RetTy)) {
4483 case TEK_Complex: {
4484 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4485 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4486 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004487 }
Hal Finkelee90a222014-09-26 05:04:30 +00004488 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004489 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004490 bool DestIsVolatile = ReturnValue.isVolatile();
4491
John McCall7f416cc2015-09-08 08:05:57 +00004492 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004493 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4494 DestIsVolatile = false;
4495 }
John McCall7f416cc2015-09-08 08:05:57 +00004496 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004497 return RValue::getAggregate(DestPtr);
4498 }
4499 case TEK_Scalar: {
4500 // If the argument doesn't match, perform a bitcast to coerce it. This
4501 // can happen due to trivial type mismatches.
4502 llvm::Value *V = CI;
4503 if (V->getType() != RetIRTy)
4504 V = Builder.CreateBitCast(V, RetIRTy);
4505 return RValue::get(V);
4506 }
4507 }
4508 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004509 }
Hal Finkelee90a222014-09-26 05:04:30 +00004510
John McCall7f416cc2015-09-08 08:05:57 +00004511 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004512 bool DestIsVolatile = ReturnValue.isVolatile();
4513
John McCall7f416cc2015-09-08 08:05:57 +00004514 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004515 DestPtr = CreateMemTemp(RetTy, "coerce");
4516 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004517 }
Hal Finkelee90a222014-09-26 05:04:30 +00004518
4519 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004520 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4521 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004522
4523 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004524 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004525
Hal Finkelee90a222014-09-26 05:04:30 +00004526 case ABIArgInfo::Expand:
4527 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004528 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004529
Hal Finkelee90a222014-09-26 05:04:30 +00004530 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4531 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004532
John McCallb92ab1a2016-10-26 23:46:34 +00004533 // Emit the assume_aligned check on the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004534 if (Ret.isScalar() && TargetDecl) {
4535 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4536 llvm::Value *OffsetValue = nullptr;
4537 if (const auto *Offset = AA->getOffset())
4538 OffsetValue = EmitScalarExpr(Offset);
4539
4540 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4541 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00004542 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
4543 AlignmentCI->getZExtValue(), OffsetValue);
Erich Keane623efd82017-03-30 21:48:55 +00004544 } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
Roman Lebedevbd1c0872019-01-15 09:44:25 +00004545 llvm::Value *AlignmentVal = CallArgs[AA->getParamIndex().getLLVMIndex()]
4546 .getRValue(*this)
4547 .getScalarVal();
4548 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
4549 AlignmentVal);
Hal Finkelee90a222014-09-26 05:04:30 +00004550 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004551 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004552
Hal Finkelee90a222014-09-26 05:04:30 +00004553 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004554}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004555
John McCall9831b842018-02-06 18:52:44 +00004556CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
4557 if (isVirtual()) {
4558 const CallExpr *CE = getVirtualCallExpr();
4559 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
James Y Knightcfe8cd72019-02-07 01:15:41 +00004560 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004561 CE ? CE->getBeginLoc() : SourceLocation());
John McCall9831b842018-02-06 18:52:44 +00004562 }
4563
4564 return *this;
4565}
4566
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004567/* VarArg handling */
4568
Charles Davisc7d5c942015-09-17 20:55:33 +00004569Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4570 VAListAddr = VE->isMicrosoftABI()
4571 ? EmitMSVAListRef(VE->getSubExpr())
4572 : EmitVAListRef(VE->getSubExpr());
4573 QualType Ty = VE->getType();
4574 if (VE->isMicrosoftABI())
4575 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004576 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004577}