Bug Summary

File:tools/clang/lib/CodeGen/CGCall.cpp
Warning:line 3580, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGCall.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp

1//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2//
3// 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
6//
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"
15#include "ABIInfo.h"
16#include "CGBlocks.h"
17#include "CGCXXABI.h"
18#include "CGCleanup.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "TargetInfo.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/Basic/CodeGenOptions.h"
26#include "clang/Basic/TargetBuiltins.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/CodeGen/CGFunctionInfo.h"
29#include "clang/CodeGen/SwiftCallingConv.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/Analysis/ValueTracking.h"
33#include "llvm/IR/Attributes.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/Intrinsics.h"
39using namespace clang;
40using namespace CodeGen;
41
42/***/
43
44unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
45 switch (CC) {
46 default: return llvm::CallingConv::C;
47 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
48 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
49 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
50 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
51 case CC_Win64: return llvm::CallingConv::Win64;
52 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
53 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
54 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
55 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
56 // TODO: Add support for __pascal to LLVM.
57 case CC_X86Pascal: return llvm::CallingConv::C;
58 // TODO: Add support for __vectorcall to LLVM.
59 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
60 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
61 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
62 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
63 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
64 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
65 case CC_Swift: return llvm::CallingConv::Swift;
66 }
67}
68
69/// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
70/// 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
81 if (MD)
82 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
83 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
84}
85
86/// Returns the canonical formal type of the given C++ method.
87static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
88 return MD->getType()->getCanonicalTypeUnqualified()
89 .getAs<FunctionProtoType>();
90}
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.
96static CanQualType GetReturnType(QualType RetTy) {
97 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
98}
99
100/// Arrange the argument and result information for a value of the given
101/// unprototyped freestanding function type.
102const CGFunctionInfo &
103CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
104 // When translating an unprototyped function type, always use a
105 // variadic type.
106 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
107 /*instanceMethod=*/false,
108 /*chainCall=*/false, None,
109 FTNP->getExtInfo(), {}, RequiredArgs(0));
110}
111
112static void addExtParameterInfosForCall(
113 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
114 const FunctionProtoType *proto,
115 unsigned prefixArgs,
116 unsigned totalArgs) {
117 assert(proto->hasExtParameterInfos())((proto->hasExtParameterInfos()) ? static_cast<void>
(0) : __assert_fail ("proto->hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 117, __PRETTY_FUNCTION__))
;
118 assert(paramInfos.size() <= prefixArgs)((paramInfos.size() <= prefixArgs) ? static_cast<void>
(0) : __assert_fail ("paramInfos.size() <= prefixArgs", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 118, __PRETTY_FUNCTION__))
;
119 assert(proto->getNumParams() + prefixArgs <= totalArgs)((proto->getNumParams() + prefixArgs <= totalArgs) ? static_cast
<void> (0) : __assert_fail ("proto->getNumParams() + prefixArgs <= totalArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 119, __PRETTY_FUNCTION__))
;
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 &&((paramInfos.size() <= totalArgs && "Did we forget to insert pass_object_size args?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 135, __PRETTY_FUNCTION__))
135 "Did we forget to insert pass_object_size args?")((paramInfos.size() <= totalArgs && "Did we forget to insert pass_object_size args?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 135, __PRETTY_FUNCTION__))
;
136 // Add default infos for the variadic and/or suffix arguments.
137 paramInfos.resize(totalArgs);
138}
139
140/// Adds the formal parameters in FPT to the given prefix. If any parameter in
141/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
142static void appendParameterTypes(const CodeGenTypes &CGT,
143 SmallVectorImpl<CanQualType> &prefix,
144 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
145 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() &&((paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 149, __PRETTY_FUNCTION__))
149 "We have paramInfos, but the prototype doesn't?")((paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 149, __PRETTY_FUNCTION__))
;
150 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
151 return;
152 }
153
154 unsigned PrefixSize = prefix.size();
155 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
156 // 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
160 auto ExtInfos = FPT->getExtParameterInfos();
161 assert(ExtInfos.size() == FPT->getNumParams())((ExtInfos.size() == FPT->getNumParams()) ? static_cast<
void> (0) : __assert_fail ("ExtInfos.size() == FPT->getNumParams()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 161, __PRETTY_FUNCTION__))
;
162 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
163 prefix.push_back(FPT->getParamType(I));
164 if (ExtInfos[I].hasPassObjectSize())
165 prefix.push_back(CGT.getContext().getSizeType());
166 }
167
168 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
169 prefix.size());
170}
171
172/// Arrange the LLVM function layout for a value of the given function
173/// type, on top of any implicit parameters already stored.
174static const CGFunctionInfo &
175arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
176 SmallVectorImpl<CanQualType> &prefix,
177 CanQual<FunctionProtoType> FTP) {
178 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
179 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
180 // FIXME: Kill copy.
181 appendParameterTypes(CGT, prefix, paramInfos, FTP);
182 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
183
184 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
185 /*chainCall=*/false, prefix,
186 FTP->getExtInfo(), paramInfos,
187 Required);
188}
189
190/// Arrange the argument and result information for a value of the
191/// given freestanding function type.
192const CGFunctionInfo &
193CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
194 SmallVector<CanQualType, 16> argTypes;
195 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
196 FTP);
197}
198
199static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
200 // Set the appropriate calling convention for the Function.
201 if (D->hasAttr<StdCallAttr>())
202 return CC_X86StdCall;
203
204 if (D->hasAttr<FastCallAttr>())
205 return CC_X86FastCall;
206
207 if (D->hasAttr<RegCallAttr>())
208 return CC_X86RegCall;
209
210 if (D->hasAttr<ThisCallAttr>())
211 return CC_X86ThisCall;
212
213 if (D->hasAttr<VectorCallAttr>())
214 return CC_X86VectorCall;
215
216 if (D->hasAttr<PascalAttr>())
217 return CC_X86Pascal;
218
219 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
220 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
221
222 if (D->hasAttr<AArch64VectorPcsAttr>())
223 return CC_AArch64VectorCall;
224
225 if (D->hasAttr<IntelOclBiccAttr>())
226 return CC_IntelOclBicc;
227
228 if (D->hasAttr<MSABIAttr>())
229 return IsWindows ? CC_C : CC_Win64;
230
231 if (D->hasAttr<SysVABIAttr>())
232 return IsWindows ? CC_X86_64SysV : CC_C;
233
234 if (D->hasAttr<PreserveMostAttr>())
235 return CC_PreserveMost;
236
237 if (D->hasAttr<PreserveAllAttr>())
238 return CC_PreserveAll;
239
240 return CC_C;
241}
242
243/// Arrange the argument and result information for a call to an
244/// unknown C++ non-static member function of the given abstract type.
245/// (A null RD means we don't have any meaningful "this" argument type,
246/// so fall back to a generic pointer type).
247/// The member function must be an ordinary function, i.e. not a
248/// constructor or destructor.
249const CGFunctionInfo &
250CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
251 const FunctionProtoType *FTP,
252 const CXXMethodDecl *MD) {
253 SmallVector<CanQualType, 16> argTypes;
254
255 // Add the 'this' pointer.
256 argTypes.push_back(DeriveThisType(RD, MD));
257
258 return ::arrangeLLVMFunctionInfo(
259 *this, true, argTypes,
260 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
261}
262
263/// 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
273/// 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) {
279 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!")((!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(MD) && \"wrong method for constructors!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 279, __PRETTY_FUNCTION__))
;
280 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!")((!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXDestructorDecl>(MD) && \"wrong method for destructors!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 280, __PRETTY_FUNCTION__))
;
281
282 CanQualType FT = GetFormalType(MD).getAs<Type>();
283 setCUDAKernelCallingConvention(FT, CGM, MD);
284 auto prototype = FT.getAs<FunctionProtoType>();
285
286 if (MD->isInstance()) {
287 // The abstract case is perfectly fine.
288 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
289 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
290 }
291
292 return arrangeFreeFunctionType(prototype);
293}
294
295bool 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();
302}
303
304const CGFunctionInfo &
305CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
306 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
307
308 SmallVector<CanQualType, 16> argTypes;
309 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
310 argTypes.push_back(DeriveThisType(MD->getParent(), MD));
311
312 bool PassParams = true;
313
314 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
315 // 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())
318 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
319 }
320
321 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
322
323 // Add the formal parameters.
324 if (PassParams)
325 appendParameterTypes(*this, argTypes, paramInfos, FTP);
326
327 CGCXXABI::AddedStructorArgs AddedArgs =
328 TheCXXABI.buildStructorSignature(GD, argTypes);
329 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 }
338
339 RequiredArgs required =
340 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
341 : RequiredArgs::All);
342
343 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
344 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
345 ? argTypes.front()
346 : TheCXXABI.hasMostDerivedReturn(GD)
347 ? CGM.getContext().VoidPtrTy
348 : Context.VoidTy;
349 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
350 /*chainCall=*/false, argTypes, extInfo,
351 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
370static 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;
378}
379
380/// Arrange a call to a C++ method, passing the given arguments.
381///
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.
388const CGFunctionInfo &
389CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
390 const CXXConstructorDecl *D,
391 CXXCtorType CtorKind,
392 unsigned ExtraPrefixArgs,
393 unsigned ExtraSuffixArgs,
394 bool PassProtoArgs) {
395 // FIXME: Kill copy.
396 SmallVector<CanQualType, 16> ArgTypes;
397 for (const auto &Arg : args)
398 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
399
400 // +1 for implicit this, which should always be args[0].
401 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
402
403 CanQual<FunctionProtoType> FPT = GetFormalType(D);
404 RequiredArgs Required = PassProtoArgs
405 ? RequiredArgs::forPrototypePlus(
406 FPT, TotalPrefixArgs + ExtraSuffixArgs)
407 : RequiredArgs::All;
408
409 GlobalDecl GD(D, CtorKind);
410 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
411 ? ArgTypes.front()
412 : TheCXXABI.hasMostDerivedReturn(GD)
413 ? CGM.getContext().VoidPtrTy
414 : Context.VoidTy;
415
416 FunctionType::ExtInfo Info = FPT->getExtInfo();
417 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 }
425 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
426 /*chainCall=*/false, ArgTypes, Info,
427 ParamInfos, Required);
428}
429
430/// Arrange the argument and result information for the declaration or
431/// definition of the given function.
432const CGFunctionInfo &
433CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
434 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
435 if (MD->isInstance())
436 return arrangeCXXMethodDeclaration(MD);
437
438 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
439
440 assert(isa<FunctionType>(FTy))((isa<FunctionType>(FTy)) ? static_cast<void> (0)
: __assert_fail ("isa<FunctionType>(FTy)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 440, __PRETTY_FUNCTION__))
;
441 setCUDAKernelCallingConvention(FTy, CGM, FD);
442
443 // When declaring a function without a prototype, always use a
444 // non-variadic type.
445 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
446 return arrangeLLVMFunctionInfo(
447 noProto->getReturnType(), /*instanceMethod=*/false,
448 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
449 }
450
451 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
452}
453
454/// 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;
473 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
474 argTys.push_back(Context.getCanonicalParamType(receiverType));
475 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
476 // FIXME: Kill copy?
477 for (const auto *I : MD->parameters()) {
478 argTys.push_back(Context.getCanonicalParamType(I->getType()));
479 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
480 I->hasAttr<NoEscapeAttr>());
481 extParamInfos.push_back(extParamInfo);
482 }
483
484 FunctionType::ExtInfo einfo;
485 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
486 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
487
488 if (getContext().getLangOpts().ObjCAutoRefCount &&
489 MD->hasAttr<NSReturnsRetainedAttr>())
490 einfo = einfo.withProducesResult(true);
491
492 RequiredArgs required =
493 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
494
495 return arrangeLLVMFunctionInfo(
496 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
497 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
498}
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);
509}
510
511const CGFunctionInfo &
512CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
513 // FIXME: Do we need to handle ObjCMethodDecl?
514 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
515
516 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
517 isa<CXXDestructorDecl>(GD.getDecl()))
518 return arrangeCXXStructorDeclaration(GD);
519
520 return arrangeFunctionDeclaration(FD);
521}
522
523/// 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 &
529CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
530 assert(MD->isVirtual() && "only methods have thunks")((MD->isVirtual() && "only methods have thunks") ?
static_cast<void> (0) : __assert_fail ("MD->isVirtual() && \"only methods have thunks\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 530, __PRETTY_FUNCTION__))
;
531 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
532 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
533 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
534 /*chainCall=*/false, ArgTys,
535 FTP->getExtInfo(), {}, RequiredArgs(1));
536}
537
538const CGFunctionInfo &
539CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
540 CXXCtorType CT) {
541 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure)((CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure) ? static_cast
<void> (0) : __assert_fail ("CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 541, __PRETTY_FUNCTION__))
;
542
543 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
544 SmallVector<CanQualType, 2> ArgTys;
545 const CXXRecordDecl *RD = CD->getParent();
546 ArgTys.push_back(DeriveThisType(RD, CD));
547 if (CT == Ctor_CopyingClosure)
548 ArgTys.push_back(*FTP->param_type_begin());
549 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,
555 FunctionType::ExtInfo(CC), {},
556 RequiredArgs::All);
557}
558
559/// 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,
563 CodeGenModule &CGM,
564 const CallArgList &args,
565 const FunctionType *fnType,
566 unsigned numExtraRequiredArgs,
567 bool chainCall) {
568 assert(args.size() >= numExtraRequiredArgs)((args.size() >= numExtraRequiredArgs) ? static_cast<void
> (0) : __assert_fail ("args.size() >= numExtraRequiredArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 568, __PRETTY_FUNCTION__))
;
569
570 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
571
572 // 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())
579 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
580
581 if (proto->hasExtParameterInfos())
582 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
583 args.size());
584
585 // 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.
589 } else if (CGM.getTargetCodeGenInfo()
590 .isNoProtoCallVariadic(args,
591 cast<FunctionNoProtoType>(fnType))) {
592 required = RequiredArgs(args.size());
593 }
594
595 // 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,
601 argTypes, fnType->getExtInfo(), paramInfos,
602 required);
603}
604
605/// 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 &
610CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
611 const FunctionType *fnType,
612 bool chainCall) {
613 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
614 chainCall ? 1 : 0, chainCall);
615}
616
617/// A block function is essentially a free function with an
618/// extra implicit argument.
619const CGFunctionInfo &
620CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
621 const FunctionType *fnType) {
622 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
623 /*chainCall=*/false);
624}
625
626const CGFunctionInfo &
627CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
628 const FunctionArgList &params) {
629 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
630 auto argTypes = getArgTypesForDeclaration(Context, params);
631
632 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
633 /*instanceMethod*/ false, /*chainCall*/ false,
634 argTypes, proto->getExtInfo(), paramInfos,
635 RequiredArgs::forPrototypePlus(proto, 1));
636}
637
638const CGFunctionInfo &
639CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
640 const CallArgList &args) {
641 // FIXME: Kill copy.
642 SmallVector<CanQualType, 16> argTypes;
643 for (const auto &Arg : args)
644 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
645 return arrangeLLVMFunctionInfo(
646 GetReturnType(resultType), /*instanceMethod=*/false,
647 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
648 /*paramInfos=*/ {}, RequiredArgs::All);
649}
650
651const 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
669/// Arrange a call to a C++ method, passing the given arguments.
670///
671/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
672/// does not count `this`.
673const CGFunctionInfo &
674CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
675 const FunctionProtoType *proto,
676 RequiredArgs required,
677 unsigned numPrefixArgs) {
678 assert(numPrefixArgs + 1 <= args.size() &&((numPrefixArgs + 1 <= args.size() && "Emitting a call with less args than the required prefix?"
) ? static_cast<void> (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 679, __PRETTY_FUNCTION__))
679 "Emitting a call with less args than the required prefix?")((numPrefixArgs + 1 <= args.size() && "Emitting a call with less args than the required prefix?"
) ? static_cast<void> (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 679, __PRETTY_FUNCTION__))
;
680 // Add one to account for `this`. It's a bit awkward here, but we don't count
681 // `this` in similar places elsewhere.
682 auto paramInfos =
683 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
684
685 // FIXME: Kill copy.
686 auto argTypes = getArgTypesForCall(Context, args);
687
688 FunctionType::ExtInfo info = proto->getExtInfo();
689 return arrangeLLVMFunctionInfo(
690 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
691 /*chainCall=*/false, argTypes, info, paramInfos, required);
692}
693
694const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
695 return arrangeLLVMFunctionInfo(
696 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
697 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())((signature.arg_size() <= args.size()) ? static_cast<void
> (0) : __assert_fail ("signature.arg_size() <= args.size()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 703, __PRETTY_FUNCTION__))
;
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())((signature.getRequiredArgs().allowsOptionalArgs()) ? static_cast
<void> (0) : __assert_fail ("signature.getRequiredArgs().allowsOptionalArgs()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 716, __PRETTY_FUNCTION__))
;
717 return arrangeLLVMFunctionInfo(signature.getReturnType(),
718 signature.isInstanceMethod(),
719 signature.isChainCall(),
720 argTypes,
721 signature.getExtInfo(),
722 paramInfos,
723 signature.getRequiredArgs());
724}
725
726namespace clang {
727namespace CodeGen {
728void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
729}
730}
731
732/// 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 &
736CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
737 bool instanceMethod,
738 bool chainCall,
739 ArrayRef<CanQualType> argTypes,
740 FunctionType::ExtInfo info,
741 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
742 RequiredArgs required) {
743 assert(llvm::all_of(argTypes,((llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam
(); })) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 744, __PRETTY_FUNCTION__))
744 [](CanQualType T) { return T.isCanonicalAsParam(); }))((llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam
(); })) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 744, __PRETTY_FUNCTION__))
;
745
746 // Lookup or create unique function info.
747 llvm::FoldingSetNodeID ID;
748 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
749 required, resultType, argTypes);
750
751 void *insertPos = nullptr;
752 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
753 if (FI)
754 return *FI;
755
756 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
757
758 // Construct the function info. We co-allocate the ArgInfos.
759 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
760 paramInfos, resultType, argTypes, required);
761 FunctionInfos.InsertNode(FI, insertPos);
762
763 bool inserted = FunctionsBeingProcessed.insert(FI).second;
764 (void)inserted;
765 assert(inserted && "Recursively being processed?")((inserted && "Recursively being processed?") ? static_cast
<void> (0) : __assert_fail ("inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 765, __PRETTY_FUNCTION__))
;
766
767 // Compute ABI information.
768 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) {
773 swiftcall::computeABIInfo(CGM, *FI);
774 } else {
775 getABIInfo().computeInfo(*FI);
776 }
777
778 // 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.
781 ABIArgInfo &retInfo = FI->getReturnInfo();
782 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
783 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
784
785 for (auto &I : FI->arguments())
786 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
787 I.info.setCoerceToType(ConvertType(I.type));
788
789 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
790 assert(erased && "Not in set?")((erased && "Not in set?") ? static_cast<void> (
0) : __assert_fail ("erased && \"Not in set?\"", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 790, __PRETTY_FUNCTION__))
;
791
792 return *FI;
793}
794
795CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
796 bool instanceMethod,
797 bool chainCall,
798 const FunctionType::ExtInfo &info,
799 ArrayRef<ExtParameterInfo> paramInfos,
800 CanQualType resultType,
801 ArrayRef<CanQualType> argTypes,
802 RequiredArgs required) {
803 assert(paramInfos.empty() || paramInfos.size() == argTypes.size())((paramInfos.empty() || paramInfos.size() == argTypes.size())
? static_cast<void> (0) : __assert_fail ("paramInfos.empty() || paramInfos.size() == argTypes.size()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 803, __PRETTY_FUNCTION__))
;
804 assert(!required.allowsOptionalArgs() ||((!required.allowsOptionalArgs() || required.getNumRequiredArgs
() <= argTypes.size()) ? static_cast<void> (0) : __assert_fail
("!required.allowsOptionalArgs() || required.getNumRequiredArgs() <= argTypes.size()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 805, __PRETTY_FUNCTION__))
805 required.getNumRequiredArgs() <= argTypes.size())((!required.allowsOptionalArgs() || required.getNumRequiredArgs
() <= argTypes.size()) ? static_cast<void> (0) : __assert_fail
("!required.allowsOptionalArgs() || required.getNumRequiredArgs() <= argTypes.size()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 805, __PRETTY_FUNCTION__))
;
806
807 void *buffer =
808 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
809 argTypes.size() + 1, paramInfos.size()));
810
811 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
812 FI->CallingConvention = llvmCC;
813 FI->EffectiveCallingConvention = llvmCC;
814 FI->ASTCallingConvention = info.getCC();
815 FI->InstanceMethod = instanceMethod;
816 FI->ChainCall = chainCall;
817 FI->NoReturn = info.getNoReturn();
818 FI->ReturnsRetained = info.getProducesResult();
819 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
820 FI->NoCfCheck = info.getNoCfCheck();
821 FI->Required = required;
822 FI->HasRegParm = info.getHasRegParm();
823 FI->RegParm = info.getRegParm();
824 FI->ArgStruct = nullptr;
825 FI->ArgStructAlign = 0;
826 FI->NumArgs = argTypes.size();
827 FI->HasExtParameterInfos = !paramInfos.empty();
828 FI->getArgsBuffer()[0].type = resultType;
829 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
830 FI->getArgsBuffer()[i + 1].type = argTypes[i];
831 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
832 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
833 return FI;
834}
835
836/***/
837
838namespace {
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) {}
858 virtual ~TypeExpansion() {}
859};
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 {
873 SmallVector<const CXXBaseSpecifier *, 1> Bases;
874
875 SmallVector<const FieldDecl *, 1> Fields;
876
877 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
878 SmallVector<const FieldDecl *, 1> &&Fields)
879 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
880 Fields(std::move(Fields)) {}
881 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 std::make_unique<ConstantArrayExpansion>(
907 AT->getElementType(), AT->getSize().getZExtValue());
908 }
909 if (const RecordType *RT = Ty->getAs<RecordType>()) {
910 SmallVector<const CXXBaseSpecifier *, 1> Bases;
911 SmallVector<const FieldDecl *, 1> Fields;
912 const RecordDecl *RD = RT->getDecl();
913 assert(!RD->hasFlexibleArrayMember() &&((!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."
) ? static_cast<void> (0) : __assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 914, __PRETTY_FUNCTION__))
914 "Cannot expand structure with flexible array.")((!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."
) ? static_cast<void> (0) : __assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 914, __PRETTY_FUNCTION__))
;
915 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.
918 const FieldDecl *LargestFD = nullptr;
919 CharUnits UnionSize = CharUnits::Zero();
920
921 for (const auto *FD : RD->fields()) {
922 if (FD->isZeroLengthBitField(Context))
923 continue;
924 assert(!FD->isBitField() &&((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 925, __PRETTY_FUNCTION__))
925 "Cannot expand structure with bit-field members.")((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 925, __PRETTY_FUNCTION__))
;
926 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
927 if (UnionSize < FieldSize) {
928 UnionSize = FieldSize;
929 LargestFD = FD;
930 }
931 }
932 if (LargestFD)
933 Fields.push_back(LargestFD);
934 } else {
935 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
936 assert(!CXXRD->isDynamicClass() &&((!CXXRD->isDynamicClass() && "cannot expand vtable pointers in dynamic classes"
) ? static_cast<void> (0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 937, __PRETTY_FUNCTION__))
937 "cannot expand vtable pointers in dynamic classes")((!CXXRD->isDynamicClass() && "cannot expand vtable pointers in dynamic classes"
) ? static_cast<void> (0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 937, __PRETTY_FUNCTION__))
;
938 for (const CXXBaseSpecifier &BS : CXXRD->bases())
939 Bases.push_back(&BS);
940 }
941
942 for (const auto *FD : RD->fields()) {
943 if (FD->isZeroLengthBitField(Context))
944 continue;
945 assert(!FD->isBitField() &&((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 946, __PRETTY_FUNCTION__))
946 "Cannot expand structure with bit-field members.")((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 946, __PRETTY_FUNCTION__))
;
947 Fields.push_back(FD);
948 }
949 }
950 return std::make_unique<RecordExpansion>(std::move(Bases),
951 std::move(Fields));
952 }
953 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
954 return std::make_unique<ComplexExpansion>(CT->getElementType());
955 }
956 return std::make_unique<NoExpansion>();
957}
958
959static 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;
966 for (auto BS : RExp->Bases)
967 Res += getExpansionSize(BS->getType(), Context);
968 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()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 974, __PRETTY_FUNCTION__))
;
975 return 1;
976}
977
978void
979CodeGenTypes::getExpandedTypes(QualType Ty,
980 SmallVectorImpl<llvm::Type *>::iterator &TI) {
981 auto Exp = getTypeExpansion(Ty, Context);
982 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
983 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
984 getExpandedTypes(CAExp->EltTy, TI);
985 }
986 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
987 for (auto BS : RExp->Bases)
988 getExpandedTypes(BS->getType(), TI);
989 for (auto FD : RExp->Fields)
990 getExpandedTypes(FD->getType(), TI);
991 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
992 llvm::Type *EltTy = ConvertType(CExp->EltTy);
993 *TI++ = EltTy;
994 *TI++ = EltTy;
995 } else {
996 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 996, __PRETTY_FUNCTION__))
;
997 *TI++ = ConvertType(Ty);
998 }
999}
1000
1001static 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
1016void CodeGenFunction::ExpandTypeFromArgs(
1017 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
1018 assert(LV.isSimple() &&((LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1019, __PRETTY_FUNCTION__))
1019 "Unexpected non-simple lvalue during struct expansion.")((LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1019, __PRETTY_FUNCTION__))
;
1020
1021 auto Exp = getTypeExpansion(Ty, getContext());
1022 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1023 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
1024 [&](Address EltAddr) {
1025 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1026 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1027 });
1028 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1029 Address This = LV.getAddress();
1030 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1031 // Perform a single step derived-to-base conversion.
1032 Address Base =
1033 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 }
1040 for (auto FD : RExp->Fields) {
1041 // FIXME: What are the right qualifiers here?
1042 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1043 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1044 }
1045 } else if (isa<ComplexExpansion>(Exp.get())) {
1046 auto realValue = *AI++;
1047 auto imagValue = *AI++;
1048 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1049 } else {
1050 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1050, __PRETTY_FUNCTION__))
;
1051 EmitStoreThroughLValue(RValue::get(*AI++), LV);
1052 }
1053}
1054
1055void CodeGenFunction::ExpandTypeToArgs(
1056 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1057 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1058 auto Exp = getTypeExpansion(Ty, getContext());
1059 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1060 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 });
1070 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1071 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1072 : Arg.getKnownRValue().getAggregateAddress();
1073 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1074 // Perform a single step derived-to-base conversion.
1075 Address Base =
1076 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1077 /*NullCheckValue=*/false, SourceLocation());
1078 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1079
1080 // Recurse onto bases.
1081 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1082 IRCallArgPos);
1083 }
1084
1085 LValue LV = MakeAddrLValue(This, Ty);
1086 for (auto FD : RExp->Fields) {
1087 CallArg FldArg =
1088 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1089 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1090 IRCallArgPos);
1091 }
1092 } else if (isa<ComplexExpansion>(Exp.get())) {
1093 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1094 IRCallArgs[IRCallArgPos++] = CV.first;
1095 IRCallArgs[IRCallArgPos++] = CV.second;
1096 } else {
1097 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1097, __PRETTY_FUNCTION__))
;
1098 auto RV = Arg.getKnownRValue();
1099 assert(RV.isScalar() &&((RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1100, __PRETTY_FUNCTION__))
1100 "Unexpected non-scalar rvalue during struct expansion.")((RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1100, __PRETTY_FUNCTION__))
;
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 }
1110}
1111
1112/// 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
1122/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1123/// 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.
1126static Address
1127EnterStructPointerForCoercedAccess(Address SrcPtr,
1128 llvm::StructType *SrcSTy,
1129 uint64_t DstSize, CodeGenFunction &CGF) {
1130 // We can't dive into a zero-element struct.
1131 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1132
1133 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1134
1135 // If the first elt is at least as large as what we're looking for, or if the
1136 // 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.
1139 uint64_t FirstEltSize =
1140 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1141 if (FirstEltSize < DstSize &&
1142 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1143 return SrcPtr;
1144
1145 // GEP into the first element.
1146 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1147
1148 // If the first element is a struct, recurse.
1149 llvm::Type *SrcTy = SrcPtr.getElementType();
1150 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1151 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1152
1153 return SrcPtr;
1154}
1155
1156/// 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.
1159///
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.
1163static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1164 llvm::Type *Ty,
1165 CodeGenFunction &CGF) {
1166 if (Val->getType() == Ty)
1167 return Val;
1168
1169 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");
1173
1174 // Convert the pointer to an integer so we can play with its width.
1175 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1176 }
1177
1178 llvm::Type *DestIntTy = Ty;
1179 if (isa<llvm::PointerType>(DestIntTy))
1180 DestIntTy = CGF.IntPtrTy;
1181
1182 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.
1187 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1188 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1189
1190 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 }
1202
1203 if (isa<llvm::PointerType>(Ty))
1204 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1205 return Val;
1206}
1207
1208
1209
1210/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1211/// a pointer to an object of type \arg Ty, known to be aligned to
1212/// \arg SrcAlign bytes.
1213///
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.
1217static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1218 CodeGenFunction &CGF) {
1219 llvm::Type *SrcTy = Src.getElementType();
1220
1221 // If SrcTy and Ty are the same, just do a load.
1222 if (SrcTy == Ty)
1223 return CGF.Builder.CreateLoad(Src);
1224
1225 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1226
1227 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1228 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1229 SrcTy = Src.getType()->getElementType();
1230 }
1231
1232 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1233
1234 // 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))) {
1238 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1239 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1240 }
1241
1242 // If load is legal, just bitcast the src pointer.
1243 if (SrcSize >= DstSize) {
1244 // 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.
1247 //
1248 // FIXME: Assert that we aren't truncating non-padding bits when have access
1249 // to that information.
1250 Src = CGF.Builder.CreateBitCast(Src,
1251 Ty->getPointerTo(Src.getAddressSpace()));
1252 return CGF.Builder.CreateLoad(Src);
1253 }
1254
1255 // Otherwise do coercion through memory. This is stupid, but simple.
1256 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1257 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
1258 Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty);
1259 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1260 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
1261 false);
1262 return CGF.Builder.CreateLoad(Tmp);
1263}
1264
1265// 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,
1270 Address Dest, bool DestIsVolatile) {
1271 // Prefer scalar stores to first-class aggregate stores.
1272 if (llvm::StructType *STy =
1273 dyn_cast<llvm::StructType>(Val->getType())) {
1274 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1275 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i);
1276 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
1277 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1278 }
1279 } else {
1280 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
1281 }
1282}
1283
1284/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1285/// where the source and destination may have different types. The
1286/// destination is known to be aligned to \arg DstAlign bytes.
1287///
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,
1291 Address Dst,
1292 bool DstIsVolatile,
1293 CodeGenFunction &CGF) {
1294 llvm::Type *SrcTy = Src->getType();
1295 llvm::Type *DstTy = Dst.getType()->getElementType();
1296 if (SrcTy == DstTy) {
1297 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1298 return;
1299 }
1300
1301 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1302
1303 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1304 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1305 DstTy = Dst.getType()->getElementType();
1306 }
1307
1308 // 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);
1313 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1314 return;
1315 }
1316
1317 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1318
1319 // If store is legal, just bitcast the src pointer.
1320 if (SrcSize <= DstSize) {
1321 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1322 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
1323 } else {
1324 // Otherwise do coercion through memory. This is stupid, but
1325 // simple.
1326
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.
1333 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1334 CGF.Builder.CreateStore(Src, Tmp);
1335 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
1336 Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty);
1337 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1338 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1339 false);
1340 }
1341}
1342
1343static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1344 const ABIArgInfo &info) {
1345 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
1354namespace {
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())((hasInallocaArg()) ? static_cast<void> (0) : __assert_fail
("hasInallocaArg()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1389, __PRETTY_FUNCTION__))
;
1390 return InallocaArgNo;
1391 }
1392
1393 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1394 unsigned getSRetArgNo() const {
1395 assert(hasSRetArg())((hasSRetArg()) ? static_cast<void> (0) : __assert_fail
("hasSRetArg()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1395, __PRETTY_FUNCTION__))
;
1396 return SRetArgNo;
1397 }
1398
1399 unsigned totalIRArgs() const { return TotalIRArgs; }
1400
1401 bool hasPaddingArg(unsigned ArgNo) const {
1402 assert(ArgNo < ArgInfo.size())((ArgNo < ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1402, __PRETTY_FUNCTION__))
;
1403 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1404 }
1405 unsigned getPaddingArgNo(unsigned ArgNo) const {
1406 assert(hasPaddingArg(ArgNo))((hasPaddingArg(ArgNo)) ? static_cast<void> (0) : __assert_fail
("hasPaddingArg(ArgNo)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1406, __PRETTY_FUNCTION__))
;
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())((ArgNo < ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1413, __PRETTY_FUNCTION__))
;
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())((I != FI.arg_end()) ? static_cast<void> (0) : __assert_fail
("I != FI.arg_end()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1439, __PRETTY_FUNCTION__))
;
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;
1468 case ABIArgInfo::CoerceAndExpand:
1469 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1470 break;
1471 case ABIArgInfo::Expand:
1472 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1473 break;
1474 }
1475
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())((ArgNo == ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo == ArgInfo.size()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1486, __PRETTY_FUNCTION__))
;
1487
1488 if (FI.usesInAlloca())
1489 InallocaArgNo = IRArgNo++;
1490
1491 TotalIRArgs = IRArgNo;
1492}
1493} // namespace
1494
1495/***/
1496
1497bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1498 const auto &RI = FI.getReturnInfo();
1499 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1500}
1501
1502bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1503 return ReturnTypeUsesSRet(FI) &&
1504 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1505}
1506
1507bool 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:
1513 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1514 case BuiltinType::Double:
1515 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1516 case BuiltinType::LongDouble:
1517 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1518 }
1519 }
1520
1521 return false;
1522}
1523
1524bool 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)
1528 return getTarget().useObjCFP2RetForComplexLongDouble();
1529 }
1530 }
1531
1532 return false;
1533}
1534
1535llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1536 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1537 return GetFunctionType(FI);
1538}
1539
1540llvm::FunctionType *
1541CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1542
1543 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1544 (void)Inserted;
1545 assert(Inserted && "Recursively being processed?")((Inserted && "Recursively being processed?") ? static_cast
<void> (0) : __assert_fail ("Inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1545, __PRETTY_FUNCTION__))
;
1546
1547 llvm::Type *resultType = nullptr;
1548 const ABIArgInfo &retAI = FI.getReturnInfo();
1549 switch (retAI.getKind()) {
1550 case ABIArgInfo::Expand:
1551 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1551)
;
1552
1553 case ABIArgInfo::Extend:
1554 case ABIArgInfo::Direct:
1555 resultType = retAI.getCoerceToType();
1556 break;
1557
1558 case ABIArgInfo::InAlloca:
1559 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 }
1568 break;
1569
1570 case ABIArgInfo::Indirect:
1571 case ABIArgInfo::Ignore:
1572 resultType = llvm::Type::getVoidTy(getLLVMContext());
1573 break;
1574
1575 case ABIArgInfo::CoerceAndExpand:
1576 resultType = retAI.getUnpaddedCoerceAndExpandType();
1577 break;
1578 }
1579
1580 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)((ArgStruct) ? static_cast<void> (0) : __assert_fail ("ArgStruct"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1595, __PRETTY_FUNCTION__))
;
1596 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1597 }
1598
1599 // Add in all of the required arguments.
1600 unsigned ArgNo = 0;
1601 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1602 ie = it + FI.getNumRequiredArgs();
1603 for (; it != ie; ++it, ++ArgNo) {
1604 const ABIArgInfo &ArgInfo = it->info;
1605
1606 // Insert a padding type to ensure proper alignment.
1607 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1608 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1609 ArgInfo.getPaddingType();
1610
1611 unsigned FirstIRArg, NumIRArgs;
1612 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1613
1614 switch (ArgInfo.getKind()) {
1615 case ABIArgInfo::Ignore:
1616 case ABIArgInfo::InAlloca:
1617 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1617, __PRETTY_FUNCTION__))
;
1618 break;
1619
1620 case ABIArgInfo::Indirect: {
1621 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1621, __PRETTY_FUNCTION__))
;
1622 // indirect arguments are always on the stack, which is alloca addr space.
1623 llvm::Type *LTy = ConvertTypeForMem(it->type);
1624 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1625 CGM.getDataLayout().getAllocaAddrSpace());
1626 break;
1627 }
1628
1629 case ABIArgInfo::Extend:
1630 case ABIArgInfo::Direct: {
1631 // 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.
1633 llvm::Type *argType = ArgInfo.getCoerceToType();
1634 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1635 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1636 assert(NumIRArgs == st->getNumElements())((NumIRArgs == st->getNumElements()) ? static_cast<void
> (0) : __assert_fail ("NumIRArgs == st->getNumElements()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1636, __PRETTY_FUNCTION__))
;
1637 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1638 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1639 } else {
1640 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 ArgTypes[FirstIRArg] = argType;
1642 }
1643 break;
1644 }
1645
1646 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)((ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs) ?
static_cast<void> (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1651, __PRETTY_FUNCTION__))
;
1652 break;
1653 }
1654
1655 case ABIArgInfo::Expand:
1656 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1657 getExpandedTypes(it->type, ArgTypesIter);
1658 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs)((ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs) ?
static_cast<void> (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1658, __PRETTY_FUNCTION__))
;
1659 break;
1660 }
1661 }
1662
1663 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1664 assert(Erased && "Not in set?")((Erased && "Not in set?") ? static_cast<void> (
0) : __assert_fail ("Erased && \"Not in set?\"", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665
1666 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1667}
1668
1669llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1670 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1671 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1672
1673 if (!isFuncTypeConvertible(FPT))
1674 return llvm::StructType::get(getLLVMContext());
1675
1676 return GetFunctionType(GD);
1677}
1678
1679static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1680 llvm::AttrBuilder &FuncAttrs,
1681 const FunctionProtoType *FPT) {
1682 if (!FPT)
1683 return;
1684
1685 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1686 FPT->isNothrow())
1687 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1688}
1689
1690void 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);
1703 if (CodeGenOpts.IndirectTlsSegRefs)
1704 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1705 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 StringRef FpKind;
1717 switch (CodeGenOpts.getFramePointer()) {
1718 case CodeGenOptions::FramePointerKind::None:
1719 FpKind = "none";
1720 break;
1721 case CodeGenOptions::FramePointerKind::NonLeaf:
1722 FpKind = "non-leaf";
1723 break;
1724 case CodeGenOptions::FramePointerKind::All:
1725 FpKind = "all";
1726 break;
1727 }
1728 FuncAttrs.addAttribute("frame-pointer", FpKind);
1729
1730 FuncAttrs.addAttribute("less-precise-fpmad",
1731 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1732
1733 if (CodeGenOpts.NullPointerIsValid)
1734 FuncAttrs.addAttribute("null-pointer-is-valid", "true");
1735 if (!CodeGenOpts.FPDenormalMode.empty())
1736 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1737
1738 FuncAttrs.addAttribute("no-trapping-math",
1739 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1740
1741 // Strict (compliant) code is the default, so only add this attribute to
1742 // indicate that we are trying to workaround a problem case.
1743 if (!CodeGenOpts.StrictFloatCastOverflow)
1744 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
1745
1746 // TODO: Are these all needed?
1747 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1748 FuncAttrs.addAttribute("no-infs-fp-math",
1749 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1750 FuncAttrs.addAttribute("no-nans-fp-math",
1751 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1752 FuncAttrs.addAttribute("unsafe-fp-math",
1753 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1754 FuncAttrs.addAttribute("use-soft-float",
1755 llvm::toStringRef(CodeGenOpts.SoftFloat));
1756 FuncAttrs.addAttribute("stack-protector-buffer-size",
1757 llvm::utostr(CodeGenOpts.SSPBufferSize));
1758 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1759 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1760 FuncAttrs.addAttribute(
1761 "correctly-rounded-divide-sqrt-fp-math",
1762 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1763
1764 if (getLangOpts().OpenCL)
1765 FuncAttrs.addAttribute("denorms-are-zero",
1766 llvm::toStringRef(CodeGenOpts.FlushDenorm));
1767
1768 // TODO: Reciprocal estimate codegen options should apply to instructions?
1769 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1770 if (!Recips.empty())
1771 FuncAttrs.addAttribute("reciprocal-estimates",
1772 llvm::join(Recips, ","));
1773
1774 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1775 CodeGenOpts.PreferVectorWidth != "none")
1776 FuncAttrs.addAttribute("prefer-vector-width",
1777 CodeGenOpts.PreferVectorWidth);
1778
1779 if (CodeGenOpts.StackRealignment)
1780 FuncAttrs.addAttribute("stackrealign");
1781 if (CodeGenOpts.Backchain)
1782 FuncAttrs.addAttribute("backchain");
1783
1784 if (CodeGenOpts.SpeculativeLoadHardening)
1785 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1786 }
1787
1788 if (getLangOpts().assumeFunctionsAreConvergent()) {
1789 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1790 // convergent (meaning, they may call an intrinsically convergent op, such
1791 // as __syncthreads() / barrier(), and so can't have certain optimizations
1792 // applied around them). LLVM will remove this attribute where it safely
1793 // can.
1794 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1795 }
1796
1797 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1798 // Exceptions aren't supported in CUDA device code.
1799 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1800
1801 // Respect -fcuda-flush-denormals-to-zero.
1802 if (CodeGenOpts.FlushDenorm)
1803 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1804 }
1805
1806 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1807 StringRef Var, Value;
1808 std::tie(Var, Value) = Attr.split('=');
1809 FuncAttrs.addAttribute(Var, Value);
1810 }
1811}
1812
1813void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1814 llvm::AttrBuilder FuncAttrs;
1815 ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(),
1816 /* AttrOnCallSite = */ false, FuncAttrs);
1817 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1818}
1819
1820void CodeGenModule::ConstructAttributeList(
1821 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1822 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
1823 llvm::AttrBuilder FuncAttrs;
1824 llvm::AttrBuilder RetAttrs;
1825
1826 CallingConv = FI.getEffectiveCallingConvention();
1827 if (FI.isNoReturn())
1828 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1829
1830 // If we have information about the function prototype, we can learn
1831 // attributes from there.
1832 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1833 CalleeInfo.getCalleeFunctionProtoType());
1834
1835 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
1836
1837 bool HasOptnone = false;
1838 // FIXME: handle sseregparm someday...
1839 if (TargetDecl) {
1840 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1841 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1842 if (TargetDecl->hasAttr<NoThrowAttr>())
1843 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1844 if (TargetDecl->hasAttr<NoReturnAttr>())
1845 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1846 if (TargetDecl->hasAttr<ColdAttr>())
1847 FuncAttrs.addAttribute(llvm::Attribute::Cold);
1848 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1849 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1850 if (TargetDecl->hasAttr<ConvergentAttr>())
1851 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1852
1853 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1854 AddAttributesFromFunctionProtoType(
1855 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
1856 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1857 // These attributes are not inherited by overloads.
1858 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1859 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
1860 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1861 }
1862
1863 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
1864 if (TargetDecl->hasAttr<ConstAttr>()) {
1865 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1866 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1867 } else if (TargetDecl->hasAttr<PureAttr>()) {
1868 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1869 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1870 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1871 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1872 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1873 }
1874 if (TargetDecl->hasAttr<RestrictAttr>())
1875 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1876 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
1877 !CodeGenOpts.NullPointerIsValid)
1878 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1879 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1880 FuncAttrs.addAttribute("no_caller_saved_registers");
1881 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
1882 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
1883
1884 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
1885 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1886 Optional<unsigned> NumElemsParam;
1887 if (AllocSize->getNumElemsParam().isValid())
1888 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
1889 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
1890 NumElemsParam);
1891 }
1892 }
1893
1894 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
1895
1896 // This must run after constructing the default function attribute list
1897 // to ensure that the speculative load hardening attribute is removed
1898 // in the case where the -mspeculative-load-hardening flag was passed.
1899 if (TargetDecl) {
1900 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
1901 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
1902 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
1903 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1904 }
1905
1906 if (CodeGenOpts.EnableSegmentedStacks &&
1907 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1908 FuncAttrs.addAttribute("split-stack");
1909
1910 // Add NonLazyBind attribute to function declarations when -fno-plt
1911 // is used.
1912 if (TargetDecl && CodeGenOpts.NoPLT) {
1913 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1914 if (!Fn->isDefined() && !AttrOnCallSite) {
1915 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
1916 }
1917 }
1918 }
1919
1920 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
1921 if (getLangOpts().OpenCLVersion <= 120) {
1922 // OpenCL v1.2 Work groups are always uniform
1923 FuncAttrs.addAttribute("uniform-work-group-size", "true");
1924 } else {
1925 // OpenCL v2.0 Work groups may be whether uniform or not.
1926 // '-cl-uniform-work-group-size' compile option gets a hint
1927 // to the compiler that the global work-size be a multiple of
1928 // the work-group size specified to clEnqueueNDRangeKernel
1929 // (i.e. work groups are uniform).
1930 FuncAttrs.addAttribute("uniform-work-group-size",
1931 llvm::toStringRef(CodeGenOpts.UniformWGSize));
1932 }
1933 }
1934
1935 if (!AttrOnCallSite) {
1936 bool DisableTailCalls = false;
1937
1938 if (CodeGenOpts.DisableTailCalls)
1939 DisableTailCalls = true;
1940 else if (TargetDecl) {
1941 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1942 TargetDecl->hasAttr<AnyX86InterruptAttr>())
1943 DisableTailCalls = true;
1944 else if (CodeGenOpts.NoEscapingBlockTailCalls) {
1945 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
1946 if (!BD->doesNotEscape())
1947 DisableTailCalls = true;
1948 }
1949 }
1950
1951 FuncAttrs.addAttribute("disable-tail-calls",
1952 llvm::toStringRef(DisableTailCalls));
1953 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
1954 }
1955
1956 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
1957
1958 QualType RetTy = FI.getReturnType();
1959 const ABIArgInfo &RetAI = FI.getReturnInfo();
1960 switch (RetAI.getKind()) {
1961 case ABIArgInfo::Extend:
1962 if (RetAI.isSignExt())
1963 RetAttrs.addAttribute(llvm::Attribute::SExt);
1964 else
1965 RetAttrs.addAttribute(llvm::Attribute::ZExt);
1966 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1967 case ABIArgInfo::Direct:
1968 if (RetAI.getInReg())
1969 RetAttrs.addAttribute(llvm::Attribute::InReg);
1970 break;
1971 case ABIArgInfo::Ignore:
1972 break;
1973
1974 case ABIArgInfo::InAlloca:
1975 case ABIArgInfo::Indirect: {
1976 // inalloca and sret disable readnone and readonly
1977 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1978 .removeAttribute(llvm::Attribute::ReadNone);
1979 break;
1980 }
1981
1982 case ABIArgInfo::CoerceAndExpand:
1983 break;
1984
1985 case ABIArgInfo::Expand:
1986 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 1986)
;
1987 }
1988
1989 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1990 QualType PTy = RefTy->getPointeeType();
1991 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1992 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1993 .getQuantity());
1994 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
1995 !CodeGenOpts.NullPointerIsValid)
1996 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1997 }
1998
1999 bool hasUsedSRet = false;
2000 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2001
2002 // Attach attributes to sret.
2003 if (IRFunctionArgs.hasSRetArg()) {
2004 llvm::AttrBuilder SRETAttrs;
2005 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
2006 hasUsedSRet = true;
2007 if (RetAI.getInReg())
2008 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2009 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2010 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2011 }
2012
2013 // Attach attributes to inalloca argument.
2014 if (IRFunctionArgs.hasInallocaArg()) {
2015 llvm::AttrBuilder Attrs;
2016 Attrs.addAttribute(llvm::Attribute::InAlloca);
2017 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2018 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2019 }
2020
2021 unsigned ArgNo = 0;
2022 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2023 E = FI.arg_end();
2024 I != E; ++I, ++ArgNo) {
2025 QualType ParamType = I->type;
2026 const ABIArgInfo &AI = I->info;
2027 llvm::AttrBuilder Attrs;
2028
2029 // Add attribute for padding argument, if necessary.
2030 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2031 if (AI.getPaddingInReg()) {
2032 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2033 llvm::AttributeSet::get(
2034 getLLVMContext(),
2035 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2036 }
2037 }
2038
2039 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2040 // have the corresponding parameter variable. It doesn't make
2041 // sense to do it here because parameters are so messed up.
2042 switch (AI.getKind()) {
2043 case ABIArgInfo::Extend:
2044 if (AI.isSignExt())
2045 Attrs.addAttribute(llvm::Attribute::SExt);
2046 else
2047 Attrs.addAttribute(llvm::Attribute::ZExt);
2048 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2049 case ABIArgInfo::Direct:
2050 if (ArgNo == 0 && FI.isChainCall())
2051 Attrs.addAttribute(llvm::Attribute::Nest);
2052 else if (AI.getInReg())
2053 Attrs.addAttribute(llvm::Attribute::InReg);
2054 break;
2055
2056 case ABIArgInfo::Indirect: {
2057 if (AI.getInReg())
2058 Attrs.addAttribute(llvm::Attribute::InReg);
2059
2060 if (AI.getIndirectByVal())
2061 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2062
2063 CharUnits Align = AI.getIndirectAlign();
2064
2065 // In a byval argument, it is important that the required
2066 // alignment of the type is honored, as LLVM might be creating a
2067 // *new* stack object, and needs to know what alignment to give
2068 // it. (Sometimes it can deduce a sensible alignment on its own,
2069 // but not if clang decides it must emit a packed struct, or the
2070 // user specifies increased alignment requirements.)
2071 //
2072 // This is different from indirect *not* byval, where the object
2073 // exists already, and the align attribute is purely
2074 // informative.
2075 assert(!Align.isZero())((!Align.isZero()) ? static_cast<void> (0) : __assert_fail
("!Align.isZero()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2075, __PRETTY_FUNCTION__))
;
2076
2077 // For now, only add this when we have a byval argument.
2078 // TODO: be less lazy about updating test cases.
2079 if (AI.getIndirectByVal())
2080 Attrs.addAlignmentAttr(Align.getQuantity());
2081
2082 // byval disables readnone and readonly.
2083 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2084 .removeAttribute(llvm::Attribute::ReadNone);
2085 break;
2086 }
2087 case ABIArgInfo::Ignore:
2088 case ABIArgInfo::Expand:
2089 case ABIArgInfo::CoerceAndExpand:
2090 break;
2091
2092 case ABIArgInfo::InAlloca:
2093 // inalloca disables readnone and readonly.
2094 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2095 .removeAttribute(llvm::Attribute::ReadNone);
2096 continue;
2097 }
2098
2099 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2100 QualType PTy = RefTy->getPointeeType();
2101 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2102 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2103 .getQuantity());
2104 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
2105 !CodeGenOpts.NullPointerIsValid)
2106 Attrs.addAttribute(llvm::Attribute::NonNull);
2107 }
2108
2109 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2110 case ParameterABI::Ordinary:
2111 break;
2112
2113 case ParameterABI::SwiftIndirectResult: {
2114 // Add 'sret' if we haven't already used it for something, but
2115 // only if the result is void.
2116 if (!hasUsedSRet && RetTy->isVoidType()) {
2117 Attrs.addAttribute(llvm::Attribute::StructRet);
2118 hasUsedSRet = true;
2119 }
2120
2121 // Add 'noalias' in either case.
2122 Attrs.addAttribute(llvm::Attribute::NoAlias);
2123
2124 // Add 'dereferenceable' and 'alignment'.
2125 auto PTy = ParamType->getPointeeType();
2126 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2127 auto info = getContext().getTypeInfoInChars(PTy);
2128 Attrs.addDereferenceableAttr(info.first.getQuantity());
2129 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2130 info.second.getQuantity()));
2131 }
2132 break;
2133 }
2134
2135 case ParameterABI::SwiftErrorResult:
2136 Attrs.addAttribute(llvm::Attribute::SwiftError);
2137 break;
2138
2139 case ParameterABI::SwiftContext:
2140 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2141 break;
2142 }
2143
2144 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2145 Attrs.addAttribute(llvm::Attribute::NoCapture);
2146
2147 if (Attrs.hasAttributes()) {
2148 unsigned FirstIRArg, NumIRArgs;
2149 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2150 for (unsigned i = 0; i < NumIRArgs; i++)
2151 ArgAttrs[FirstIRArg + i] =
2152 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2153 }
2154 }
2155 assert(ArgNo == FI.arg_size())((ArgNo == FI.arg_size()) ? static_cast<void> (0) : __assert_fail
("ArgNo == FI.arg_size()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2155, __PRETTY_FUNCTION__))
;
2156
2157 AttrList = llvm::AttributeList::get(
2158 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2159 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2160}
2161
2162/// An argument came in as a promoted argument; demote it back to its
2163/// declared type.
2164static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2165 const VarDecl *var,
2166 llvm::Value *value) {
2167 llvm::Type *varType = CGF.ConvertType(var->getType());
2168
2169 // This can happen with promotions that actually don't change the
2170 // underlying type, like the enum promotions.
2171 if (value->getType() == varType) return value;
2172
2173 assert((varType->isIntegerTy() || varType->isFloatingPointTy())(((varType->isIntegerTy() || varType->isFloatingPointTy
()) && "unexpected promotion type") ? static_cast<
void> (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2174, __PRETTY_FUNCTION__))
2174 && "unexpected promotion type")(((varType->isIntegerTy() || varType->isFloatingPointTy
()) && "unexpected promotion type") ? static_cast<
void> (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2174, __PRETTY_FUNCTION__))
;
2175
2176 if (isa<llvm::IntegerType>(varType))
2177 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2178
2179 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2180}
2181
2182/// Returns the attribute (either parameter attribute, or function
2183/// attribute), which declares argument ArgNo to be non-null.
2184static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2185 QualType ArgType, unsigned ArgNo) {
2186 // FIXME: __attribute__((nonnull)) can also be applied to:
2187 // - references to pointers, where the pointee is known to be
2188 // nonnull (apparently a Clang extension)
2189 // - transparent unions containing pointers
2190 // In the former case, LLVM IR cannot represent the constraint. In
2191 // the latter case, we have no guarantee that the transparent union
2192 // is in fact passed as a pointer.
2193 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2194 return nullptr;
2195 // First, check attribute on parameter itself.
2196 if (PVD) {
2197 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2198 return ParmNNAttr;
2199 }
2200 // Check function attributes.
2201 if (!FD)
2202 return nullptr;
2203 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2204 if (NNAttr->isNonNull(ArgNo))
2205 return NNAttr;
2206 }
2207 return nullptr;
2208}
2209
2210namespace {
2211 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2212 Address Temp;
2213 Address Arg;
2214 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2215 void Emit(CodeGenFunction &CGF, Flags flags) override {
2216 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2217 CGF.Builder.CreateStore(errorValue, Arg);
2218 }
2219 };
2220}
2221
2222void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2223 llvm::Function *Fn,
2224 const FunctionArgList &Args) {
2225 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2226 // Naked functions don't have prologues.
2227 return;
2228
2229 // If this is an implicit-return-zero function, go ahead and
2230 // initialize the return value. TODO: it might be nice to have
2231 // a more general mechanism for this that didn't require synthesized
2232 // return statements.
2233 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2234 if (FD->hasImplicitReturnZero()) {
2235 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2236 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2237 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2238 Builder.CreateStore(Zero, ReturnValue);
2239 }
2240 }
2241
2242 // FIXME: We no longer need the types from FunctionArgList; lift up and
2243 // simplify.
2244
2245 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2246 // Flattened function arguments.
2247 SmallVector<llvm::Value *, 16> FnArgs;
2248 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2249 for (auto &Arg : Fn->args()) {
2250 FnArgs.push_back(&Arg);
2251 }
2252 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs())((FnArgs.size() == IRFunctionArgs.totalIRArgs()) ? static_cast
<void> (0) : __assert_fail ("FnArgs.size() == IRFunctionArgs.totalIRArgs()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2252, __PRETTY_FUNCTION__))
;
2253
2254 // If we're using inalloca, all the memory arguments are GEPs off of the last
2255 // parameter, which is a pointer to the complete memory area.
2256 Address ArgStruct = Address::invalid();
2257 if (IRFunctionArgs.hasInallocaArg()) {
2258 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2259 FI.getArgStructAlignment());
2260
2261 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo())((ArgStruct.getType() == FI.getArgStruct()->getPointerTo()
) ? static_cast<void> (0) : __assert_fail ("ArgStruct.getType() == FI.getArgStruct()->getPointerTo()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2261, __PRETTY_FUNCTION__))
;
2262 }
2263
2264 // Name the struct return parameter.
2265 if (IRFunctionArgs.hasSRetArg()) {
2266 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
2267 AI->setName("agg.result");
2268 AI->addAttr(llvm::Attribute::NoAlias);
2269 }
2270
2271 // Track if we received the parameter as a pointer (indirect, byval, or
2272 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2273 // into a local alloca for us.
2274 SmallVector<ParamValue, 16> ArgVals;
2275 ArgVals.reserve(Args.size());
2276
2277 // Create a pointer value for every parameter declaration. This usually
2278 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2279 // any cleanups or do anything that might unwind. We do that separately, so
2280 // we can push the cleanups in the correct order for the ABI.
2281 assert(FI.arg_size() == Args.size() &&((FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2282, __PRETTY_FUNCTION__))
2282 "Mismatch between function signature & arguments.")((FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2282, __PRETTY_FUNCTION__))
;
2283 unsigned ArgNo = 0;
2284 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2285 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2286 i != e; ++i, ++info_it, ++ArgNo) {
2287 const VarDecl *Arg = *i;
2288 const ABIArgInfo &ArgI = info_it->info;
2289
2290 bool isPromoted =
2291 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2292 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2293 // the parameter is promoted. In this case we convert to
2294 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2295 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2296 assert(hasScalarEvaluationKind(Ty) ==((hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->
getType())) ? static_cast<void> (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2297, __PRETTY_FUNCTION__))
2297 hasScalarEvaluationKind(Arg->getType()))((hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->
getType())) ? static_cast<void> (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2297, __PRETTY_FUNCTION__))
;
2298
2299 unsigned FirstIRArg, NumIRArgs;
2300 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2301
2302 switch (ArgI.getKind()) {
2303 case ABIArgInfo::InAlloca: {
2304 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2304, __PRETTY_FUNCTION__))
;
2305 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2306 Address V =
2307 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2308 ArgVals.push_back(ParamValue::forIndirect(V));
2309 break;
2310 }
2311
2312 case ABIArgInfo::Indirect: {
2313 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2313, __PRETTY_FUNCTION__))
;
2314 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
2315
2316 if (!hasScalarEvaluationKind(Ty)) {
2317 // Aggregates and complex variables are accessed by reference. All we
2318 // need to do is realign the value, if requested.
2319 Address V = ParamAddr;
2320 if (ArgI.getIndirectRealign()) {
2321 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2322
2323 // Copy from the incoming argument pointer to the temporary with the
2324 // appropriate alignment.
2325 //
2326 // FIXME: We should have a common utility for generating an aggregate
2327 // copy.
2328 CharUnits Size = getContext().getTypeSizeInChars(Ty);
2329 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2330 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2331 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2332 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
2333 V = AlignedTemp;
2334 }
2335 ArgVals.push_back(ParamValue::forIndirect(V));
2336 } else {
2337 // Load scalar value from indirect argument.
2338 llvm::Value *V =
2339 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2340
2341 if (isPromoted)
2342 V = emitArgumentDemotion(*this, Arg, V);
2343 ArgVals.push_back(ParamValue::forDirect(V));
2344 }
2345 break;
2346 }
2347
2348 case ABIArgInfo::Extend:
2349 case ABIArgInfo::Direct: {
2350
2351 // If we have the trivial case, handle it with no muss and fuss.
2352 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2353 ArgI.getCoerceToType() == ConvertType(Ty) &&
2354 ArgI.getDirectOffset() == 0) {
2355 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2355, __PRETTY_FUNCTION__))
;
2356 llvm::Value *V = FnArgs[FirstIRArg];
2357 auto AI = cast<llvm::Argument>(V);
2358
2359 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2360 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2361 PVD->getFunctionScopeIndex()) &&
2362 !CGM.getCodeGenOpts().NullPointerIsValid)
2363 AI->addAttr(llvm::Attribute::NonNull);
2364
2365 QualType OTy = PVD->getOriginalType();
2366 if (const auto *ArrTy =
2367 getContext().getAsConstantArrayType(OTy)) {
2368 // A C99 array parameter declaration with the static keyword also
2369 // indicates dereferenceability, and if the size is constant we can
2370 // use the dereferenceable attribute (which requires the size in
2371 // bytes).
2372 if (ArrTy->getSizeModifier() == ArrayType::Static) {
2373 QualType ETy = ArrTy->getElementType();
2374 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2375 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2376 ArrSize) {
2377 llvm::AttrBuilder Attrs;
2378 Attrs.addDereferenceableAttr(
2379 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2380 AI->addAttrs(Attrs);
2381 } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
2382 !CGM.getCodeGenOpts().NullPointerIsValid) {
2383 AI->addAttr(llvm::Attribute::NonNull);
2384 }
2385 }
2386 } else if (const auto *ArrTy =
2387 getContext().getAsVariableArrayType(OTy)) {
2388 // For C99 VLAs with the static keyword, we don't know the size so
2389 // we can't use the dereferenceable attribute, but in addrspace(0)
2390 // we know that it must be nonnull.
2391 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2392 !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
2393 !CGM.getCodeGenOpts().NullPointerIsValid)
2394 AI->addAttr(llvm::Attribute::NonNull);
2395 }
2396
2397 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2398 if (!AVAttr)
2399 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2400 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2401 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2402 // If alignment-assumption sanitizer is enabled, we do *not* add
2403 // alignment attribute here, but emit normal alignment assumption,
2404 // so the UBSAN check could function.
2405 llvm::Value *AlignmentValue =
2406 EmitScalarExpr(AVAttr->getAlignment());
2407 llvm::ConstantInt *AlignmentCI =
2408 cast<llvm::ConstantInt>(AlignmentValue);
2409 unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
2410 +llvm::Value::MaximumAlignment);
2411 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2412 }
2413 }
2414
2415 if (Arg->getType().isRestrictQualified())
2416 AI->addAttr(llvm::Attribute::NoAlias);
2417
2418 // LLVM expects swifterror parameters to be used in very restricted
2419 // ways. Copy the value into a less-restricted temporary.
2420 if (FI.getExtParameterInfo(ArgNo).getABI()
2421 == ParameterABI::SwiftErrorResult) {
2422 QualType pointeeTy = Ty->getPointeeType();
2423 assert(pointeeTy->isPointerType())((pointeeTy->isPointerType()) ? static_cast<void> (0
) : __assert_fail ("pointeeTy->isPointerType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2423, __PRETTY_FUNCTION__))
;
2424 Address temp =
2425 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2426 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2427 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2428 Builder.CreateStore(incomingErrorValue, temp);
2429 V = temp.getPointer();
2430
2431 // Push a cleanup to copy the value back at the end of the function.
2432 // The convention does not guarantee that the value will be written
2433 // back if the function exits with an unwind exception.
2434 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2435 }
2436
2437 // Ensure the argument is the correct type.
2438 if (V->getType() != ArgI.getCoerceToType())
2439 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2440
2441 if (isPromoted)
2442 V = emitArgumentDemotion(*this, Arg, V);
2443
2444 // Because of merging of function types from multiple decls it is
2445 // possible for the type of an argument to not match the corresponding
2446 // type in the function type. Since we are codegening the callee
2447 // in here, add a cast to the argument type.
2448 llvm::Type *LTy = ConvertType(Arg->getType());
2449 if (V->getType() != LTy)
2450 V = Builder.CreateBitCast(V, LTy);
2451
2452 ArgVals.push_back(ParamValue::forDirect(V));
2453 break;
2454 }
2455
2456 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2457 Arg->getName());
2458
2459 // Pointer to store into.
2460 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2461
2462 // Fast-isel and the optimizer generally like scalar values better than
2463 // FCAs, so we flatten them if this is safe to do for this argument.
2464 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2465 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2466 STy->getNumElements() > 1) {
2467 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2468 llvm::Type *DstTy = Ptr.getElementType();
2469 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2470
2471 Address AddrToStoreInto = Address::invalid();
2472 if (SrcSize <= DstSize) {
2473 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
2474 } else {
2475 AddrToStoreInto =
2476 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2477 }
2478
2479 assert(STy->getNumElements() == NumIRArgs)((STy->getNumElements() == NumIRArgs) ? static_cast<void
> (0) : __assert_fail ("STy->getNumElements() == NumIRArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2479, __PRETTY_FUNCTION__))
;
2480 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2481 auto AI = FnArgs[FirstIRArg + i];
2482 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2483 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
2484 Builder.CreateStore(AI, EltPtr);
2485 }
2486
2487 if (SrcSize > DstSize) {
2488 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2489 }
2490
2491 } else {
2492 // Simple case, just do a coerced store of the argument into the alloca.
2493 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2493, __PRETTY_FUNCTION__))
;
2494 auto AI = FnArgs[FirstIRArg];
2495 AI->setName(Arg->getName() + ".coerce");
2496 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
2497 }
2498
2499 // Match to what EmitParmDecl is expecting for this type.
2500 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
2501 llvm::Value *V =
2502 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
2503 if (isPromoted)
2504 V = emitArgumentDemotion(*this, Arg, V);
2505 ArgVals.push_back(ParamValue::forDirect(V));
2506 } else {
2507 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2508 }
2509 break;
2510 }
2511
2512 case ABIArgInfo::CoerceAndExpand: {
2513 // Reconstruct into a temporary.
2514 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2515 ArgVals.push_back(ParamValue::forIndirect(alloca));
2516
2517 auto coercionType = ArgI.getCoerceAndExpandType();
2518 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2519
2520 unsigned argIndex = FirstIRArg;
2521 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2522 llvm::Type *eltType = coercionType->getElementType(i);
2523 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2524 continue;
2525
2526 auto eltAddr = Builder.CreateStructGEP(alloca, i);
2527 auto elt = FnArgs[argIndex++];
2528 Builder.CreateStore(elt, eltAddr);
2529 }
2530 assert(argIndex == FirstIRArg + NumIRArgs)((argIndex == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("argIndex == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2530, __PRETTY_FUNCTION__))
;
2531 break;
2532 }
2533
2534 case ABIArgInfo::Expand: {
2535 // If this structure was expanded into multiple arguments then
2536 // we need to create a temporary and reconstruct it from the
2537 // arguments.
2538 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2539 LValue LV = MakeAddrLValue(Alloca, Ty);
2540 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2541
2542 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2543 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2544 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs)((FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs) ? static_cast
<void> (0) : __assert_fail ("FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2544, __PRETTY_FUNCTION__))
;
2545 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2546 auto AI = FnArgs[FirstIRArg + i];
2547 AI->setName(Arg->getName() + "." + Twine(i));
2548 }
2549 break;
2550 }
2551
2552 case ABIArgInfo::Ignore:
2553 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2553, __PRETTY_FUNCTION__))
;
2554 // Initialize the local variable appropriately.
2555 if (!hasScalarEvaluationKind(Ty)) {
2556 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
2557 } else {
2558 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2559 ArgVals.push_back(ParamValue::forDirect(U));
2560 }
2561 break;
2562 }
2563 }
2564
2565 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2566 for (int I = Args.size() - 1; I >= 0; --I)
2567 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2568 } else {
2569 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2570 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2571 }
2572}
2573
2574static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2575 while (insn->use_empty()) {
2576 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2577 if (!bitcast) return;
2578
2579 // This is "safe" because we would have used a ConstantExpr otherwise.
2580 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2581 bitcast->eraseFromParent();
2582 }
2583}
2584
2585/// Try to emit a fused autorelease of a return result.
2586static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2587 llvm::Value *result) {
2588 // We must be immediately followed the cast.
2589 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
2590 if (BB->empty()) return nullptr;
2591 if (&BB->back() != result) return nullptr;
2592
2593 llvm::Type *resultType = result->getType();
2594
2595 // result is in a BasicBlock and is therefore an Instruction.
2596 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2597
2598 SmallVector<llvm::Instruction *, 4> InstsToKill;
2599
2600 // Look for:
2601 // %generator = bitcast %type1* %generator2 to %type2*
2602 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2603 // We would have emitted this as a constant if the operand weren't
2604 // an Instruction.
2605 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2606
2607 // Require the generator to be immediately followed by the cast.
2608 if (generator->getNextNode() != bitcast)
2609 return nullptr;
2610
2611 InstsToKill.push_back(bitcast);
2612 }
2613
2614 // Look for:
2615 // %generator = call i8* @objc_retain(i8* %originalResult)
2616 // or
2617 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2618 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
2619 if (!call) return nullptr;
2620
2621 bool doRetainAutorelease;
2622
2623 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
2624 doRetainAutorelease = true;
2625 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
2626 .objc_retainAutoreleasedReturnValue) {
2627 doRetainAutorelease = false;
2628
2629 // If we emitted an assembly marker for this call (and the
2630 // ARCEntrypoints field should have been set if so), go looking
2631 // for that call. If we can't find it, we can't do this
2632 // optimization. But it should always be the immediately previous
2633 // instruction, unless we needed bitcasts around the call.
2634 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
2635 llvm::Instruction *prev = call->getPrevNode();
2636 assert(prev)((prev) ? static_cast<void> (0) : __assert_fail ("prev"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2636, __PRETTY_FUNCTION__))
;
2637 if (isa<llvm::BitCastInst>(prev)) {
2638 prev = prev->getPrevNode();
2639 assert(prev)((prev) ? static_cast<void> (0) : __assert_fail ("prev"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2639, __PRETTY_FUNCTION__))
;
2640 }
2641 assert(isa<llvm::CallInst>(prev))((isa<llvm::CallInst>(prev)) ? static_cast<void> (
0) : __assert_fail ("isa<llvm::CallInst>(prev)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2641, __PRETTY_FUNCTION__))
;
2642 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==((cast<llvm::CallInst>(prev)->getCalledValue() == CGF
.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? static_cast<void> (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2643, __PRETTY_FUNCTION__))
2643 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker)((cast<llvm::CallInst>(prev)->getCalledValue() == CGF
.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? static_cast<void> (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2643, __PRETTY_FUNCTION__))
;
2644 InstsToKill.push_back(prev);
2645 }
2646 } else {
2647 return nullptr;
2648 }
2649
2650 result = call->getArgOperand(0);
2651 InstsToKill.push_back(call);
2652
2653 // Keep killing bitcasts, for sanity. Note that we no longer care
2654 // about precise ordering as long as there's exactly one use.
2655 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2656 if (!bitcast->hasOneUse()) break;
2657 InstsToKill.push_back(bitcast);
2658 result = bitcast->getOperand(0);
2659 }
2660
2661 // Delete all the unnecessary instructions, from latest to earliest.
2662 for (auto *I : InstsToKill)
2663 I->eraseFromParent();
2664
2665 // Do the fused retain/autorelease if we were asked to.
2666 if (doRetainAutorelease)
2667 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2668
2669 // Cast back to the result type.
2670 return CGF.Builder.CreateBitCast(result, resultType);
2671}
2672
2673/// If this is a +1 of the value of an immutable 'self', remove it.
2674static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2675 llvm::Value *result) {
2676 // This is only applicable to a method with an immutable 'self'.
2677 const ObjCMethodDecl *method =
2678 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
2679 if (!method) return nullptr;
2680 const VarDecl *self = method->getSelfDecl();
2681 if (!self->getType().isConstQualified()) return nullptr;
2682
2683 // Look for a retain call.
2684 llvm::CallInst *retainCall =
2685 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2686 if (!retainCall ||
2687 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
2688 return nullptr;
2689
2690 // Look for an ordinary load of 'self'.
2691 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2692 llvm::LoadInst *load =
2693 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2694 if (!load || load->isAtomic() || load->isVolatile() ||
2695 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
2696 return nullptr;
2697
2698 // Okay! Burn it all down. This relies for correctness on the
2699 // assumption that the retain is emitted as part of the return and
2700 // that thereafter everything is used "linearly".
2701 llvm::Type *resultType = result->getType();
2702 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2703 assert(retainCall->use_empty())((retainCall->use_empty()) ? static_cast<void> (0) :
__assert_fail ("retainCall->use_empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2703, __PRETTY_FUNCTION__))
;
2704 retainCall->eraseFromParent();
2705 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2706
2707 return CGF.Builder.CreateBitCast(load, resultType);
2708}
2709
2710/// Emit an ARC autorelease of the result of a function.
2711///
2712/// \return the value to actually return from the function
2713static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2714 llvm::Value *result) {
2715 // If we're returning 'self', kill the initial retain. This is a
2716 // heuristic attempt to "encourage correctness" in the really unfortunate
2717 // case where we have a return of self during a dealloc and we desperately
2718 // need to avoid the possible autorelease.
2719 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2720 return self;
2721
2722 // At -O0, try to emit a fused retain/autorelease.
2723 if (CGF.shouldUseFusedARCCalls())
2724 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2725 return fused;
2726
2727 return CGF.EmitARCAutoreleaseReturnValue(result);
2728}
2729
2730/// Heuristically search for a dominating store to the return-value slot.
2731static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2732 // Check if a User is a store which pointerOperand is the ReturnValue.
2733 // We are looking for stores to the ReturnValue, not for stores of the
2734 // ReturnValue to some other location.
2735 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2736 auto *SI = dyn_cast<llvm::StoreInst>(U);
2737 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2738 return nullptr;
2739 // These aren't actually possible for non-coerced returns, and we
2740 // only care about non-coerced returns on this code path.
2741 assert(!SI->isAtomic() && !SI->isVolatile())((!SI->isAtomic() && !SI->isVolatile()) ? static_cast
<void> (0) : __assert_fail ("!SI->isAtomic() && !SI->isVolatile()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2741, __PRETTY_FUNCTION__))
;
2742 return SI;
2743 };
2744 // If there are multiple uses of the return-value slot, just check
2745 // for something immediately preceding the IP. Sometimes this can
2746 // happen with how we generate implicit-returns; it can also happen
2747 // with noreturn cleanups.
2748 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
2749 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2750 if (IP->empty()) return nullptr;
2751 llvm::Instruction *I = &IP->back();
2752
2753 // Skip lifetime markers
2754 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2755 IE = IP->rend();
2756 II != IE; ++II) {
2757 if (llvm::IntrinsicInst *Intrinsic =
2758 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2759 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2760 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2761 ++II;
2762 if (II == IE)
2763 break;
2764 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2765 continue;
2766 }
2767 }
2768 I = &*II;
2769 break;
2770 }
2771
2772 return GetStoreIfValid(I);
2773 }
2774
2775 llvm::StoreInst *store =
2776 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
2777 if (!store) return nullptr;
2778
2779 // Now do a first-and-dirty dominance check: just walk up the
2780 // single-predecessors chain from the current insertion point.
2781 llvm::BasicBlock *StoreBB = store->getParent();
2782 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2783 while (IP != StoreBB) {
2784 if (!(IP = IP->getSinglePredecessor()))
2785 return nullptr;
2786 }
2787
2788 // Okay, the store's basic block dominates the insertion point; we
2789 // can do our thing.
2790 return store;
2791}
2792
2793void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
2794 bool EmitRetDbgLoc,
2795 SourceLocation EndLoc) {
2796 if (FI.isNoReturn()) {
2797 // Noreturn functions don't return.
2798 EmitUnreachable(EndLoc);
2799 return;
2800 }
2801
2802 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2803 // Naked functions don't have epilogues.
2804 Builder.CreateUnreachable();
2805 return;
2806 }
2807
2808 // Functions with no result always return void.
2809 if (!ReturnValue.isValid()) {
2810 Builder.CreateRetVoid();
2811 return;
2812 }
2813
2814 llvm::DebugLoc RetDbgLoc;
2815 llvm::Value *RV = nullptr;
2816 QualType RetTy = FI.getReturnType();
2817 const ABIArgInfo &RetAI = FI.getReturnInfo();
2818
2819 switch (RetAI.getKind()) {
2820 case ABIArgInfo::InAlloca:
2821 // Aggregrates get evaluated directly into the destination. Sometimes we
2822 // need to return the sret value in a register, though.
2823 assert(hasAggregateEvaluationKind(RetTy))((hasAggregateEvaluationKind(RetTy)) ? static_cast<void>
(0) : __assert_fail ("hasAggregateEvaluationKind(RetTy)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2823, __PRETTY_FUNCTION__))
;
2824 if (RetAI.getInAllocaSRet()) {
2825 llvm::Function::arg_iterator EI = CurFn->arg_end();
2826 --EI;
2827 llvm::Value *ArgStruct = &*EI;
2828 llvm::Value *SRet = Builder.CreateStructGEP(
2829 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
2830 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
2831 }
2832 break;
2833
2834 case ABIArgInfo::Indirect: {
2835 auto AI = CurFn->arg_begin();
2836 if (RetAI.isSRetAfterThis())
2837 ++AI;
2838 switch (getEvaluationKind(RetTy)) {
2839 case TEK_Complex: {
2840 ComplexPairTy RT =
2841 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
2842 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
2843 /*isInit*/ true);
2844 break;
2845 }
2846 case TEK_Aggregate:
2847 // Do nothing; aggregrates get evaluated directly into the destination.
2848 break;
2849 case TEK_Scalar:
2850 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
2851 MakeNaturalAlignAddrLValue(&*AI, RetTy),
2852 /*isInit*/ true);
2853 break;
2854 }
2855 break;
2856 }
2857
2858 case ABIArgInfo::Extend:
2859 case ABIArgInfo::Direct:
2860 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2861 RetAI.getDirectOffset() == 0) {
2862 // The internal return value temp always will have pointer-to-return-type
2863 // type, just do a load.
2864
2865 // If there is a dominating store to ReturnValue, we can elide
2866 // the load, zap the store, and usually zap the alloca.
2867 if (llvm::StoreInst *SI =
2868 findDominatingStoreToReturnValue(*this)) {
2869 // Reuse the debug location from the store unless there is
2870 // cleanup code to be emitted between the store and return
2871 // instruction.
2872 if (EmitRetDbgLoc && !AutoreleaseResult)
2873 RetDbgLoc = SI->getDebugLoc();
2874 // Get the stored value and nuke the now-dead store.
2875 RV = SI->getValueOperand();
2876 SI->eraseFromParent();
2877
2878 // Otherwise, we have to do a simple load.
2879 } else {
2880 RV = Builder.CreateLoad(ReturnValue);
2881 }
2882 } else {
2883 // If the value is offset in memory, apply the offset now.
2884 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
2885
2886 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
2887 }
2888
2889 // In ARC, end functions that return a retainable type with a call
2890 // to objc_autoreleaseReturnValue.
2891 if (AutoreleaseResult) {
2892#ifndef NDEBUG
2893 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2894 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2895 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2896 // CurCodeDecl or BlockInfo.
2897 QualType RT;
2898
2899 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2900 RT = FD->getReturnType();
2901 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2902 RT = MD->getReturnType();
2903 else if (isa<BlockDecl>(CurCodeDecl))
2904 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2905 else
2906 llvm_unreachable("Unexpected function/method type")::llvm::llvm_unreachable_internal("Unexpected function/method type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2906)
;
2907
2908 assert(getLangOpts().ObjCAutoRefCount &&((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __PRETTY_FUNCTION__))
2909 !FI.isReturnsRetained() &&((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __PRETTY_FUNCTION__))
2910 RT->isObjCRetainableType())((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __PRETTY_FUNCTION__))
;
2911#endif
2912 RV = emitAutoreleaseOfResult(*this, RV);
2913 }
2914
2915 break;
2916
2917 case ABIArgInfo::Ignore:
2918 break;
2919
2920 case ABIArgInfo::CoerceAndExpand: {
2921 auto coercionType = RetAI.getCoerceAndExpandType();
2922
2923 // Load all of the coerced elements out into results.
2924 llvm::SmallVector<llvm::Value*, 4> results;
2925 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2926 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2927 auto coercedEltType = coercionType->getElementType(i);
2928 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2929 continue;
2930
2931 auto eltAddr = Builder.CreateStructGEP(addr, i);
2932 auto elt = Builder.CreateLoad(eltAddr);
2933 results.push_back(elt);
2934 }
2935
2936 // If we have one result, it's the single direct result type.
2937 if (results.size() == 1) {
2938 RV = results[0];
2939
2940 // Otherwise, we need to make a first-class aggregate.
2941 } else {
2942 // Construct a return type that lacks padding elements.
2943 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2944
2945 RV = llvm::UndefValue::get(returnType);
2946 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2947 RV = Builder.CreateInsertValue(RV, results[i], i);
2948 }
2949 }
2950 break;
2951 }
2952
2953 case ABIArgInfo::Expand:
2954 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2954)
;
2955 }
2956
2957 llvm::Instruction *Ret;
2958 if (RV) {
2959 EmitReturnValueCheck(RV);
2960 Ret = Builder.CreateRet(RV);
2961 } else {
2962 Ret = Builder.CreateRetVoid();
2963 }
2964
2965 if (RetDbgLoc)
2966 Ret->setDebugLoc(std::move(RetDbgLoc));
2967}
2968
2969void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
2970 // A current decl may not be available when emitting vtable thunks.
2971 if (!CurCodeDecl)
2972 return;
2973
2974 ReturnsNonNullAttr *RetNNAttr = nullptr;
2975 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
2976 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
2977
2978 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
2979 return;
2980
2981 // Prefer the returns_nonnull attribute if it's present.
2982 SourceLocation AttrLoc;
2983 SanitizerMask CheckKind;
2984 SanitizerHandler Handler;
2985 if (RetNNAttr) {
2986 assert(!requiresReturnValueNullabilityCheck() &&((!requiresReturnValueNullabilityCheck() && "Cannot check nullability and the nonnull attribute"
) ? static_cast<void> (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2987, __PRETTY_FUNCTION__))
2987 "Cannot check nullability and the nonnull attribute")((!requiresReturnValueNullabilityCheck() && "Cannot check nullability and the nonnull attribute"
) ? static_cast<void> (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 2987, __PRETTY_FUNCTION__))
;
2988 AttrLoc = RetNNAttr->getLocation();
2989 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
2990 Handler = SanitizerHandler::NonnullReturn;
2991 } else {
2992 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
2993 if (auto *TSI = DD->getTypeSourceInfo())
2994 if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
2995 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
2996 CheckKind = SanitizerKind::NullabilityReturn;
2997 Handler = SanitizerHandler::NullabilityReturn;
2998 }
2999
3000 SanitizerScope SanScope(this);
3001
3002 // Make sure the "return" source location is valid. If we're checking a
3003 // nullability annotation, make sure the preconditions for the check are met.
3004 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3005 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3006 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3007 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3008 if (requiresReturnValueNullabilityCheck())
3009 CanNullCheck =
3010 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3011 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3012 EmitBlock(Check);
3013
3014 // Now do the null check.
3015 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3016 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3017 llvm::Value *DynamicData[] = {SLocPtr};
3018 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3019
3020 EmitBlock(NoCheck);
3021
3022#ifndef NDEBUG
3023 // The return location should not be used after the check has been emitted.
3024 ReturnLocation = Address::invalid();
3025#endif
3026}
3027
3028static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3029 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3030 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3031}
3032
3033static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3034 QualType Ty) {
3035 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3036 // placeholders.
3037 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3038 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3039 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
3040
3041 // FIXME: When we generate this IR in one pass, we shouldn't need
3042 // this win32-specific alignment hack.
3043 CharUnits Align = CharUnits::fromQuantity(4);
3044 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3045
3046 return AggValueSlot::forAddr(Address(Placeholder, Align),
3047 Ty.getQualifiers(),
3048 AggValueSlot::IsNotDestructed,
3049 AggValueSlot::DoesNotNeedGCBarriers,
3050 AggValueSlot::IsNotAliased,
3051 AggValueSlot::DoesNotOverlap);
3052}
3053
3054void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3055 const VarDecl *param,
3056 SourceLocation loc) {
3057 // StartFunction converted the ABI-lowered parameter(s) into a
3058 // local alloca. We need to turn that into an r-value suitable
3059 // for EmitCall.
3060 Address local = GetAddrOfLocalVar(param);
3061
3062 QualType type = param->getType();
3063
3064 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3065 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3066 }
3067
3068 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3069 // but the argument needs to be the original pointer.
3070 if (type->isReferenceType()) {
3071 args.add(RValue::get(Builder.CreateLoad(local)), type);
3072
3073 // In ARC, move out of consumed arguments so that the release cleanup
3074 // entered by StartFunction doesn't cause an over-release. This isn't
3075 // optimal -O0 code generation, but it should get cleaned up when
3076 // optimization is enabled. This also assumes that delegate calls are
3077 // performed exactly once for a set of arguments, but that should be safe.
3078 } else if (getLangOpts().ObjCAutoRefCount &&
3079 param->hasAttr<NSConsumedAttr>() &&
3080 type->isObjCRetainableType()) {
3081 llvm::Value *ptr = Builder.CreateLoad(local);
3082 auto null =
3083 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3084 Builder.CreateStore(null, local);
3085 args.add(RValue::get(ptr), type);
3086
3087 // For the most part, we just need to load the alloca, except that
3088 // aggregate r-values are actually pointers to temporaries.
3089 } else {
3090 args.add(convertTempToRValue(local, type, loc), type);
3091 }
3092
3093 // Deactivate the cleanup for the callee-destructed param that was pushed.
3094 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
3095 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3096 param->needsDestruction(getContext())) {
3097 EHScopeStack::stable_iterator cleanup =
3098 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3099 assert(cleanup.isValid() &&((cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? static_cast<void> (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3100, __PRETTY_FUNCTION__))
3100 "cleanup for callee-destructed param not recorded")((cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? static_cast<void> (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3100, __PRETTY_FUNCTION__))
;
3101 // This unreachable is a temporary marker which will be removed later.
3102 llvm::Instruction *isActive = Builder.CreateUnreachable();
3103 args.addArgCleanupDeactivation(cleanup, isActive);
3104 }
3105}
3106
3107static bool isProvablyNull(llvm::Value *addr) {
3108 return isa<llvm::ConstantPointerNull>(addr);
3109}
3110
3111/// Emit the actual writing-back of a writeback.
3112static void emitWriteback(CodeGenFunction &CGF,
3113 const CallArgList::Writeback &writeback) {
3114 const LValue &srcLV = writeback.Source;
3115 Address srcAddr = srcLV.getAddress();
3116 assert(!isProvablyNull(srcAddr.getPointer()) &&((!isProvablyNull(srcAddr.getPointer()) && "shouldn't have writeback for provably null argument"
) ? static_cast<void> (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3117, __PRETTY_FUNCTION__))
3117 "shouldn't have writeback for provably null argument")((!isProvablyNull(srcAddr.getPointer()) && "shouldn't have writeback for provably null argument"
) ? static_cast<void> (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118
3119 llvm::BasicBlock *contBB = nullptr;
3120
3121 // If the argument wasn't provably non-null, we need to null check
3122 // before doing the store.
3123 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3124 CGF.CGM.getDataLayout());
3125 if (!provablyNonNull) {
3126 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3127 contBB = CGF.createBasicBlock("icr.done");
3128
3129 llvm::Value *isNull =
3130 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3131 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3132 CGF.EmitBlock(writebackBB);
3133 }
3134
3135 // Load the value to writeback.
3136 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3137
3138 // Cast it back, in case we're writing an id to a Foo* or something.
3139 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3140 "icr.writeback-cast");
3141
3142 // Perform the writeback.
3143
3144 // If we have a "to use" value, it's something we need to emit a use
3145 // of. This has to be carefully threaded in: if it's done after the
3146 // release it's potentially undefined behavior (and the optimizer
3147 // will ignore it), and if it happens before the retain then the
3148 // optimizer could move the release there.
3149 if (writeback.ToUse) {
3150 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong)((srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) ? static_cast
<void> (0) : __assert_fail ("srcLV.getObjCLifetime() == Qualifiers::OCL_Strong"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3150, __PRETTY_FUNCTION__))
;
3151
3152 // Retain the new value. No need to block-copy here: the block's
3153 // being passed up the stack.
3154 value = CGF.EmitARCRetainNonBlock(value);
3155
3156 // Emit the intrinsic use here.
3157 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3158
3159 // Load the old value (primitively).
3160 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3161
3162 // Put the new value in place (primitively).
3163 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3164
3165 // Release the old value.
3166 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3167
3168 // Otherwise, we can just do a normal lvalue store.
3169 } else {
3170 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3171 }
3172
3173 // Jump to the continuation block.
3174 if (!provablyNonNull)
3175 CGF.EmitBlock(contBB);
3176}
3177
3178static void emitWritebacks(CodeGenFunction &CGF,
3179 const CallArgList &args) {
3180 for (const auto &I : args.writebacks())
3181 emitWriteback(CGF, I);
3182}
3183
3184static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3185 const CallArgList &CallArgs) {
3186 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3187 CallArgs.getCleanupsToDeactivate();
3188 // Iterate in reverse to increase the likelihood of popping the cleanup.
3189 for (const auto &I : llvm::reverse(Cleanups)) {
3190 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3191 I.IsActiveIP->eraseFromParent();
3192 }
3193}
3194
3195static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3196 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3197 if (uop->getOpcode() == UO_AddrOf)
3198 return uop->getSubExpr();
3199 return nullptr;
3200}
3201
3202/// Emit an argument that's being passed call-by-writeback. That is,
3203/// we are passing the address of an __autoreleased temporary; it
3204/// might be copy-initialized with the current value of the given
3205/// address, but it will definitely be copied out of after the call.
3206static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3207 const ObjCIndirectCopyRestoreExpr *CRE) {
3208 LValue srcLV;
3209
3210 // Make an optimistic effort to emit the address as an l-value.
3211 // This can fail if the argument expression is more complicated.
3212 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3213 srcLV = CGF.EmitLValue(lvExpr);
3214
3215 // Otherwise, just emit it as a scalar.
3216 } else {
3217 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3218
3219 QualType srcAddrType =
3220 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3221 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3222 }
3223 Address srcAddr = srcLV.getAddress();
3224
3225 // The dest and src types don't necessarily match in LLVM terms
3226 // because of the crazy ObjC compatibility rules.
3227
3228 llvm::PointerType *destType =
3229 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3230
3231 // If the address is a constant null, just pass the appropriate null.
3232 if (isProvablyNull(srcAddr.getPointer())) {
3233 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3234 CRE->getType());
3235 return;
3236 }
3237
3238 // Create the temporary.
3239 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3240 CGF.getPointerAlign(),
3241 "icr.temp");
3242 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3243 // and that cleanup will be conditional if we can't prove that the l-value
3244 // isn't null, so we need to register a dominating point so that the cleanups
3245 // system will make valid IR.
3246 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3247
3248 // Zero-initialize it if we're not doing a copy-initialization.
3249 bool shouldCopy = CRE->shouldCopy();
3250 if (!shouldCopy) {
3251 llvm::Value *null =
3252 llvm::ConstantPointerNull::get(
3253 cast<llvm::PointerType>(destType->getElementType()));
3254 CGF.Builder.CreateStore(null, temp);
3255 }
3256
3257 llvm::BasicBlock *contBB = nullptr;
3258 llvm::BasicBlock *originBB = nullptr;
3259
3260 // If the address is *not* known to be non-null, we need to switch.
3261 llvm::Value *finalArgument;
3262
3263 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3264 CGF.CGM.getDataLayout());
3265 if (provablyNonNull) {
3266 finalArgument = temp.getPointer();
3267 } else {
3268 llvm::Value *isNull =
3269 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3270
3271 finalArgument = CGF.Builder.CreateSelect(isNull,
3272 llvm::ConstantPointerNull::get(destType),
3273 temp.getPointer(), "icr.argument");
3274
3275 // If we need to copy, then the load has to be conditional, which
3276 // means we need control flow.
3277 if (shouldCopy) {
3278 originBB = CGF.Builder.GetInsertBlock();
3279 contBB = CGF.createBasicBlock("icr.cont");
3280 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3281 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3282 CGF.EmitBlock(copyBB);
3283 condEval.begin(CGF);
3284 }
3285 }
3286
3287 llvm::Value *valueToUse = nullptr;
3288
3289 // Perform a copy if necessary.
3290 if (shouldCopy) {
3291 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
3292 assert(srcRV.isScalar())((srcRV.isScalar()) ? static_cast<void> (0) : __assert_fail
("srcRV.isScalar()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3292, __PRETTY_FUNCTION__))
;
3293
3294 llvm::Value *src = srcRV.getScalarVal();
3295 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3296 "icr.cast");
3297
3298 // Use an ordinary store, not a store-to-lvalue.
3299 CGF.Builder.CreateStore(src, temp);
3300
3301 // If optimization is enabled, and the value was held in a
3302 // __strong variable, we need to tell the optimizer that this
3303 // value has to stay alive until we're doing the store back.
3304 // This is because the temporary is effectively unretained,
3305 // and so otherwise we can violate the high-level semantics.
3306 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3307 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3308 valueToUse = src;
3309 }
3310 }
3311
3312 // Finish the control flow if we needed it.
3313 if (shouldCopy && !provablyNonNull) {
3314 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
3315 CGF.EmitBlock(contBB);
3316
3317 // Make a phi for the value to intrinsically use.
3318 if (valueToUse) {
3319 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3320 "icr.to-use");
3321 phiToUse->addIncoming(valueToUse, copyBB);
3322 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3323 originBB);
3324 valueToUse = phiToUse;
3325 }
3326
3327 condEval.end(CGF);
3328 }
3329
3330 args.addWriteback(srcLV, temp, valueToUse);
3331 args.add(RValue::get(finalArgument), CRE->getType());
3332}
3333
3334void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3335 assert(!StackBase)((!StackBase) ? static_cast<void> (0) : __assert_fail (
"!StackBase", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3335, __PRETTY_FUNCTION__))
;
3336
3337 // Save the stack.
3338 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
3339 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
3340}
3341
3342void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3343 if (StackBase) {
3344 // Restore the stack after the call.
3345 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
3346 CGF.Builder.CreateCall(F, StackBase);
3347 }
3348}
3349
3350void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3351 SourceLocation ArgLoc,
3352 AbstractCallee AC,
3353 unsigned ParmNum) {
3354 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3355 SanOpts.has(SanitizerKind::NullabilityArg)))
3356 return;
3357
3358 // The param decl may be missing in a variadic function.
3359 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
3360 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3361
3362 // Prefer the nonnull attribute if it's present.
3363 const NonNullAttr *NNAttr = nullptr;
3364 if (SanOpts.has(SanitizerKind::NonnullAttribute))
3365 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3366
3367 bool CanCheckNullability = false;
3368 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3369 auto Nullability = PVD->getType()->getNullability(getContext());
3370 CanCheckNullability = Nullability &&
3371 *Nullability == NullabilityKind::NonNull &&
3372 PVD->getTypeSourceInfo();
3373 }
3374
3375 if (!NNAttr && !CanCheckNullability)
3376 return;
3377
3378 SourceLocation AttrLoc;
3379 SanitizerMask CheckKind;
3380 SanitizerHandler Handler;
3381 if (NNAttr) {
3382 AttrLoc = NNAttr->getLocation();
3383 CheckKind = SanitizerKind::NonnullAttribute;
3384 Handler = SanitizerHandler::NonnullArg;
3385 } else {
3386 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3387 CheckKind = SanitizerKind::NullabilityArg;
3388 Handler = SanitizerHandler::NullabilityArg;
3389 }
3390
3391 SanitizerScope SanScope(this);
3392 assert(RV.isScalar())((RV.isScalar()) ? static_cast<void> (0) : __assert_fail
("RV.isScalar()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3392, __PRETTY_FUNCTION__))
;
3393 llvm::Value *V = RV.getScalarVal();
3394 llvm::Value *Cond =
3395 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
3396 llvm::Constant *StaticData[] = {
3397 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
3398 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
3399 };
3400 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
3401}
3402
3403void CodeGenFunction::EmitCallArgs(
3404 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3405 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3406 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
3407 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()))(((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())
) ? static_cast<void> (0) : __assert_fail ("(int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3407, __PRETTY_FUNCTION__))
;
1
Assuming the condition is true
2
'?' condition is true
3408
3409 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3410 // because arguments are destroyed left to right in the callee. As a special
3411 // case, there are certain language constructs that require left-to-right
3412 // evaluation, and in those cases we consider the evaluation order requirement
3413 // to trump the "destruction order is reverse construction order" guarantee.
3414 bool LeftToRight =
3415 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3
'?' condition is true
3416 ? Order == EvaluationOrder::ForceLeftToRight
4
Assuming 'Order' is not equal to ForceLeftToRight
3417 : Order != EvaluationOrder::ForceRightToLeft;
3418
3419 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3420 RValue EmittedArg) {
3421 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
3422 return;
3423 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3424 if (PS == nullptr)
3425 return;
3426
3427 const auto &Context = getContext();
3428 auto SizeTy = Context.getSizeType();
3429 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3430 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?")((EmittedArg.getScalarVal() && "We emitted nothing for the arg?"
) ? static_cast<void> (0) : __assert_fail ("EmittedArg.getScalarVal() && \"We emitted nothing for the arg?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3430, __PRETTY_FUNCTION__))
;
3431 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3432 EmittedArg.getScalarVal(),
3433 PS->isDynamic());
3434 Args.add(RValue::get(V), SizeTy);
3435 // If we're emitting args in reverse, be sure to do so with
3436 // pass_object_size, as well.
3437 if (!LeftToRight)
3438 std::swap(Args.back(), *(&Args.back() - 1));
3439 };
3440
3441 // Insert a stack save if we're going to need any inalloca args.
3442 bool HasInAllocaArgs = false;
3443 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
5
Taking true branch
3444 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3445 I != E && !HasInAllocaArgs; ++I)
6
Assuming 'I' is equal to 'E'
3446 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3447 if (HasInAllocaArgs
6.1
'HasInAllocaArgs' is false
6.1
'HasInAllocaArgs' is false
6.1
'HasInAllocaArgs' is false
) {
7
Taking false branch
3448 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)((getTarget().getTriple().getArch() == llvm::Triple::x86) ? static_cast
<void> (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3448, __PRETTY_FUNCTION__))
;
3449 Args.allocateArgumentMemory(*this);
3450 }
3451 }
3452
3453 // Evaluate each argument in the appropriate order.
3454 size_t CallArgsStart = Args.size();
3455 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
8
Assuming 'I' is not equal to 'E'
9
Loop condition is true. Entering loop body
3456 unsigned Idx = LeftToRight
9.1
'LeftToRight' is false
9.1
'LeftToRight' is false
9.1
'LeftToRight' is false
? I : E - I - 1;
10
'?' condition is false
3457 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3458 unsigned InitialArgSize = Args.size();
3459 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
3460 // the argument and parameter match or the objc method is parameterized.
3461 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
11
Assuming the object is not a 'ObjCIndirectCopyRestoreExpr'
12
'?' condition is true
3462 getContext().hasSameUnqualifiedType((*Arg)->getType(),(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
3463 ArgTypes[Idx]) ||(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
3464 (isa<ObjCMethodDecl>(AC.getDecl()) &&(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
3465 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
3466 "Argument and parameter types don't match")(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3466, __PRETTY_FUNCTION__))
;
3467 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
13
Calling 'CodeGenFunction::EmitCallArg'
3468 // In particular, we depend on it being the last arg in Args, and the
3469 // objectsize bits depend on there only being one arg if !LeftToRight.
3470 assert(InitialArgSize + 1 == Args.size() &&((InitialArgSize + 1 == Args.size() && "The code below depends on only adding one arg per EmitCallArg"
) ? static_cast<void> (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3471, __PRETTY_FUNCTION__))
3471 "The code below depends on only adding one arg per EmitCallArg")((InitialArgSize + 1 == Args.size() && "The code below depends on only adding one arg per EmitCallArg"
) ? static_cast<void> (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3471, __PRETTY_FUNCTION__))
;
3472 (void)InitialArgSize;
3473 // Since pointer argument are never emitted as LValue, it is safe to emit
3474 // non-null argument check for r-value only.
3475 if (!Args.back().hasLValue()) {
3476 RValue RVArg = Args.back().getKnownRValue();
3477 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3478 ParamsToSkip + Idx);
3479 // @llvm.objectsize should never have side-effects and shouldn't need
3480 // destruction/cleanups, so we can safely "emit" it after its arg,
3481 // regardless of right-to-leftness
3482 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3483 }
3484 }
3485
3486 if (!LeftToRight) {
3487 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3488 // IR function.
3489 std::reverse(Args.begin() + CallArgsStart, Args.end());
3490 }
3491}
3492
3493namespace {
3494
3495struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
3496 DestroyUnpassedArg(Address Addr, QualType Ty)
3497 : Addr(Addr), Ty(Ty) {}
3498
3499 Address Addr;
3500 QualType Ty;
3501
3502 void Emit(CodeGenFunction &CGF, Flags flags) override {
3503 QualType::DestructionKind DtorKind = Ty.isDestructedType();
3504 if (DtorKind == QualType::DK_cxx_destructor) {
3505 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3506 assert(!Dtor->isTrivial())((!Dtor->isTrivial()) ? static_cast<void> (0) : __assert_fail
("!Dtor->isTrivial()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3506, __PRETTY_FUNCTION__))
;
3507 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3508 /*Delegating=*/false, Addr, Ty);
3509 } else {
3510 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
3511 }
3512 }
3513};
3514
3515struct DisableDebugLocationUpdates {
3516 CodeGenFunction &CGF;
3517 bool disabledDebugInfo;
3518 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3519 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3520 CGF.disableDebugInfo();
3521 }
3522 ~DisableDebugLocationUpdates() {
3523 if (disabledDebugInfo)
3524 CGF.enableDebugInfo();
3525 }
3526};
3527
3528} // end anonymous namespace
3529
3530RValue CallArg::getRValue(CodeGenFunction &CGF) const {
3531 if (!HasLV)
3532 return RV;
3533 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
3534 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
3535 LV.isVolatile());
3536 IsUsed = true;
3537 return RValue::getAggregate(Copy.getAddress());
3538}
3539
3540void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
3541 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
3542 if (!HasLV && RV.isScalar())
3543 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
3544 else if (!HasLV && RV.isComplex())
3545 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
3546 else {
3547 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
3548 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
3549 // We assume that call args are never copied into subobjects.
3550 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
3551 HasLV ? LV.isVolatileQualified()
3552 : RV.isVolatileQualified());
3553 }
3554 IsUsed = true;
3555}
3556
3557void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3558 QualType type) {
3559 DisableDebugLocationUpdates Dis(*this, E);
3560 if (const ObjCIndirectCopyRestoreExpr *CRE
14.1
'CRE' is null
14.1
'CRE' is null
14.1
'CRE' is null
15
Taking false branch
3561 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
14
Assuming 'E' is not a 'ObjCIndirectCopyRestoreExpr'
3562 assert(getLangOpts().ObjCAutoRefCount)((getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3562, __PRETTY_FUNCTION__))
; 3563 return emitWritebackArg(*this, args, CRE); 3564 } 3565 3566 assert(type->isReferenceType() == E->isGLValue() &&((type->isReferenceType() == E->isGLValue() && "reference binding to unmaterialized r-value!"
) ? static_cast<void> (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3567, __PRETTY_FUNCTION__))
16
'?' condition is true
3567 "reference binding to unmaterialized r-value!")((type->isReferenceType() == E->isGLValue() && "reference binding to unmaterialized r-value!"
) ? static_cast<void> (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3567, __PRETTY_FUNCTION__))
; 3568 3569 if (E->isGLValue()) {
17
Calling 'Expr::isGLValue'
19
Returning from 'Expr::isGLValue'
20
Taking false branch
3570 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3570, __PRETTY_FUNCTION__))
; 3571 return args.add(EmitReferenceBindingToExpr(E), type); 3572 } 3573 3574 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
21
Calling 'CodeGenFunction::hasAggregateEvaluationKind'
24
Returning from 'CodeGenFunction::hasAggregateEvaluationKind'
3575 3576 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 3577 // However, we still have to push an EH-only cleanup in case we unwind before 3578 // we make it to the call. 3579 if (HasAggregateEvalKind
24.1
'HasAggregateEvalKind' is true
24.1
'HasAggregateEvalKind' is true
24.1
'HasAggregateEvalKind' is true
&& 3580 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
25
Assuming the object is not a 'RecordType'
26
Called C++ object pointer is null
3581 // If we're using inalloca, use the argument memory. Otherwise, use a 3582 // temporary. 3583 AggValueSlot Slot; 3584 if (args.isUsingInAlloca()) 3585 Slot = createPlaceholderSlot(*this, type); 3586 else 3587 Slot = CreateAggTemp(type, "agg.tmp"); 3588 3589 bool DestroyedInCallee = true, NeedsEHCleanup = true; 3590 if (const auto *RD = type->getAsCXXRecordDecl()) 3591 DestroyedInCallee = RD->hasNonTrivialDestructor(); 3592 else 3593 NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); 3594 3595 if (DestroyedInCallee) 3596 Slot.setExternallyDestructed(); 3597 3598 EmitAggExpr(E, Slot); 3599 RValue RV = Slot.asRValue(); 3600 args.add(RV, type); 3601 3602 if (DestroyedInCallee && NeedsEHCleanup) { 3603 // Create a no-op GEP between the placeholder and the cleanup so we can 3604 // RAUW it successfully. It also serves as a marker of the first 3605 // instruction where the cleanup is active. 3606 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 3607 type); 3608 // This unreachable is a temporary marker which will be removed later. 3609 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 3610 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 3611 } 3612 return; 3613 } 3614 3615 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3616 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3617 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3618 assert(L.isSimple())((L.isSimple()) ? static_cast<void> (0) : __assert_fail
("L.isSimple()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3618, __PRETTY_FUNCTION__))
; 3619 args.addUncopiedAggregate(L, type); 3620 return; 3621 } 3622 3623 args.add(EmitAnyExprToTemp(E), type); 3624} 3625 3626QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3627 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3628 // implicitly widens null pointer constants that are arguments to varargs 3629 // functions to pointer-sized ints. 3630 if (!getTarget().getTriple().isOSWindows()) 3631 return Arg->getType(); 3632 3633 if (Arg->getType()->isIntegerType() && 3634 getContext().getTypeSize(Arg->getType()) < 3635 getContext().getTargetInfo().getPointerWidth(0) && 3636 Arg->isNullPointerConstant(getContext(), 3637 Expr::NPC_ValueDependentIsNotNull)) { 3638 return getContext().getIntPtrType(); 3639 } 3640 3641 return Arg->getType(); 3642} 3643 3644// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3645// optimizer it can aggressively ignore unwind edges. 3646void 3647CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3648 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3649 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3650 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3651 CGM.getNoObjCARCExceptionsMetadata()); 3652} 3653 3654/// Emits a call to the given no-arguments nounwind runtime function. 3655llvm::CallInst * 3656CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3657 const llvm::Twine &name) { 3658 return EmitNounwindRuntimeCall(callee, None, name); 3659} 3660 3661/// Emits a call to the given nounwind runtime function. 3662llvm::CallInst * 3663CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3664 ArrayRef<llvm::Value *> args, 3665 const llvm::Twine &name) { 3666 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3667 call->setDoesNotThrow(); 3668 return call; 3669} 3670 3671/// Emits a simple call (never an invoke) to the given no-arguments 3672/// runtime function. 3673llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3674 const llvm::Twine &name) { 3675 return EmitRuntimeCall(callee, None, name); 3676} 3677 3678// Calls which may throw must have operand bundles indicating which funclet 3679// they are nested within. 3680SmallVector<llvm::OperandBundleDef, 1> 3681CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) { 3682 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3683 // There is no need for a funclet operand bundle if we aren't inside a 3684 // funclet. 3685 if (!CurrentFuncletPad) 3686 return BundleList; 3687 3688 // Skip intrinsics which cannot throw. 3689 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 3690 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 3691 return BundleList; 3692 3693 BundleList.emplace_back("funclet", CurrentFuncletPad); 3694 return BundleList; 3695} 3696 3697/// Emits a simple call (never an invoke) to the given runtime function. 3698llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3699 ArrayRef<llvm::Value *> args, 3700 const llvm::Twine &name) { 3701 llvm::CallInst *call = Builder.CreateCall( 3702 callee, args, getBundlesForFunclet(callee.getCallee()), name); 3703 call->setCallingConv(getRuntimeCC()); 3704 return call; 3705} 3706 3707/// Emits a call or invoke to the given noreturn runtime function. 3708void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke( 3709 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) { 3710 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3711 getBundlesForFunclet(callee.getCallee()); 3712 3713 if (getInvokeDest()) { 3714 llvm::InvokeInst *invoke = 3715 Builder.CreateInvoke(callee, 3716 getUnreachableBlock(), 3717 getInvokeDest(), 3718 args, 3719 BundleList); 3720 invoke->setDoesNotReturn(); 3721 invoke->setCallingConv(getRuntimeCC()); 3722 } else { 3723 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 3724 call->setDoesNotReturn(); 3725 call->setCallingConv(getRuntimeCC()); 3726 Builder.CreateUnreachable(); 3727 } 3728} 3729 3730/// Emits a call or invoke instruction to the given nullary runtime function. 3731llvm::CallBase * 3732CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3733 const Twine &name) { 3734 return EmitRuntimeCallOrInvoke(callee, None, name); 3735} 3736 3737/// Emits a call or invoke instruction to the given runtime function. 3738llvm::CallBase * 3739CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3740 ArrayRef<llvm::Value *> args, 3741 const Twine &name) { 3742 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name); 3743 call->setCallingConv(getRuntimeCC()); 3744 return call; 3745} 3746 3747/// Emits a call or invoke instruction to the given function, depending 3748/// on the current state of the EH stack. 3749llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee, 3750 ArrayRef<llvm::Value *> Args, 3751 const Twine &Name) { 3752 llvm::BasicBlock *InvokeDest = getInvokeDest(); 3753 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3754 getBundlesForFunclet(Callee.getCallee()); 3755 3756 llvm::CallBase *Inst; 3757 if (!InvokeDest) 3758 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 3759 else { 3760 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 3761 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 3762 Name); 3763 EmitBlock(ContBB); 3764 } 3765 3766 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3767 // optimizer it can aggressively ignore unwind edges. 3768 if (CGM.getLangOpts().ObjCAutoRefCount) 3769 AddObjCARCExceptionMetadata(Inst); 3770 3771 return Inst; 3772} 3773 3774void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 3775 llvm::Value *New) { 3776 DeferredReplacements.push_back(std::make_pair(Old, New)); 3777} 3778 3779RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 3780 const CGCallee &Callee, 3781 ReturnValueSlot ReturnValue, 3782 const CallArgList &CallArgs, 3783 llvm::CallBase **callOrInvoke, 3784 SourceLocation Loc) { 3785 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 3786 3787 assert(Callee.isOrdinary() || Callee.isVirtual())((Callee.isOrdinary() || Callee.isVirtual()) ? static_cast<
void> (0) : __assert_fail ("Callee.isOrdinary() || Callee.isVirtual()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3787, __PRETTY_FUNCTION__))
; 3788 3789 // Handle struct-return functions by passing a pointer to the 3790 // location that we would like to return into. 3791 QualType RetTy = CallInfo.getReturnType(); 3792 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 3793 3794 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo); 3795 3796 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl(); 3797 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 3798 // We can only guarantee that a function is called from the correct 3799 // context/function based on the appropriate target attributes, 3800 // so only check in the case where we have both always_inline and target 3801 // since otherwise we could be making a conditional call after a check for 3802 // the proper cpu features (and it won't cause code generation issues due to 3803 // function based code generation). 3804 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 3805 TargetDecl->hasAttr<TargetAttr>()) 3806 checkTargetFeatures(Loc, FD); 3807 3808#ifndef NDEBUG 3809 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) { 3810 // For an inalloca varargs function, we don't expect CallInfo to match the 3811 // function pointer's type, because the inalloca struct a will have extra 3812 // fields in it for the varargs parameters. Code later in this function 3813 // bitcasts the function pointer to the type derived from CallInfo. 3814 // 3815 // In other cases, we assert that the types match up (until pointers stop 3816 // having pointee types). 3817 llvm::Type *TypeFromVal; 3818 if (Callee.isVirtual()) 3819 TypeFromVal = Callee.getVirtualFunctionType(); 3820 else 3821 TypeFromVal = 3822 Callee.getFunctionPointer()->getType()->getPointerElementType(); 3823 assert(IRFuncTy == TypeFromVal)((IRFuncTy == TypeFromVal) ? static_cast<void> (0) : __assert_fail
("IRFuncTy == TypeFromVal", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3823, __PRETTY_FUNCTION__))
; 3824 } 3825#endif 3826 3827 // 1. Set up the arguments. 3828 3829 // If we're using inalloca, insert the allocation after the stack save. 3830 // FIXME: Do this earlier rather than hacking it in here! 3831 Address ArgMemory = Address::invalid(); 3832 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 3833 const llvm::DataLayout &DL = CGM.getDataLayout(); 3834 llvm::Instruction *IP = CallArgs.getStackBase(); 3835 llvm::AllocaInst *AI; 3836 if (IP) { 3837 IP = IP->getNextNode(); 3838 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), 3839 "argmem", IP); 3840 } else { 3841 AI = CreateTempAlloca(ArgStruct, "argmem"); 3842 } 3843 auto Align = CallInfo.getArgStructAlignment(); 3844 AI->setAlignment(llvm::MaybeAlign(Align.getQuantity())); 3845 AI->setUsedWithInAlloca(true); 3846 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca())((AI->isUsedWithInAlloca() && !AI->isStaticAlloca
()) ? static_cast<void> (0) : __assert_fail ("AI->isUsedWithInAlloca() && !AI->isStaticAlloca()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3846, __PRETTY_FUNCTION__))
; 3847 ArgMemory = Address(AI, Align); 3848 } 3849 3850 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 3851 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 3852 3853 // If the call returns a temporary with struct return, create a temporary 3854 // alloca to hold the result, unless one is given to us. 3855 Address SRetPtr = Address::invalid(); 3856 Address SRetAlloca = Address::invalid(); 3857 llvm::Value *UnusedReturnSizePtr = nullptr; 3858 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 3859 if (!ReturnValue.isNull()) { 3860 SRetPtr = ReturnValue.getValue(); 3861 } else { 3862 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca); 3863 if (HaveInsertPoint() && ReturnValue.isUnused()) { 3864 uint64_t size = 3865 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 3866 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer()); 3867 } 3868 } 3869 if (IRFunctionArgs.hasSRetArg()) { 3870 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 3871 } else if (RetAI.isInAlloca()) { 3872 Address Addr = 3873 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex()); 3874 Builder.CreateStore(SRetPtr.getPointer(), Addr); 3875 } 3876 } 3877 3878 Address swiftErrorTemp = Address::invalid(); 3879 Address swiftErrorArg = Address::invalid(); 3880 3881 // Translate all of the arguments as necessary to match the IR lowering. 3882 assert(CallInfo.arg_size() == CallArgs.size() &&((CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3883, __PRETTY_FUNCTION__))
3883 "Mismatch between function signature & arguments.")((CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3883, __PRETTY_FUNCTION__))
; 3884 unsigned ArgNo = 0; 3885 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 3886 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 3887 I != E; ++I, ++info_it, ++ArgNo) { 3888 const ABIArgInfo &ArgInfo = info_it->info; 3889 3890 // Insert a padding argument to ensure proper alignment. 3891 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 3892 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 3893 llvm::UndefValue::get(ArgInfo.getPaddingType()); 3894 3895 unsigned FirstIRArg, NumIRArgs; 3896 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 3897 3898 switch (ArgInfo.getKind()) { 3899 case ABIArgInfo::InAlloca: { 3900 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3900, __PRETTY_FUNCTION__))
; 3901 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)((getTarget().getTriple().getArch() == llvm::Triple::x86) ? static_cast
<void> (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3901, __PRETTY_FUNCTION__))
; 3902 if (I->isAggregate()) { 3903 // Replace the placeholder with the appropriate argument slot GEP. 3904 Address Addr = I->hasLValue() 3905 ? I->getKnownLValue().getAddress() 3906 : I->getKnownRValue().getAggregateAddress(); 3907 llvm::Instruction *Placeholder = 3908 cast<llvm::Instruction>(Addr.getPointer()); 3909 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 3910 Builder.SetInsertPoint(Placeholder); 3911 Addr = 3912 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 3913 Builder.restoreIP(IP); 3914 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 3915 } else { 3916 // Store the RValue into the argument struct. 3917 Address Addr = 3918 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 3919 unsigned AS = Addr.getType()->getPointerAddressSpace(); 3920 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 3921 // There are some cases where a trivial bitcast is not avoidable. The 3922 // definition of a type later in a translation unit may change it's type 3923 // from {}* to (%struct.foo*)*. 3924 if (Addr.getType() != MemType) 3925 Addr = Builder.CreateBitCast(Addr, MemType); 3926 I->copyInto(*this, Addr); 3927 } 3928 break; 3929 } 3930 3931 case ABIArgInfo::Indirect: { 3932 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3932, __PRETTY_FUNCTION__))
; 3933 if (!I->isAggregate()) { 3934 // Make a temporary alloca to pass the argument. 3935 Address Addr = CreateMemTempWithoutCast( 3936 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp"); 3937 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3938 3939 I->copyInto(*this, Addr); 3940 } else { 3941 // We want to avoid creating an unnecessary temporary+copy here; 3942 // however, we need one in three cases: 3943 // 1. If the argument is not byval, and we are required to copy the 3944 // source. (This case doesn't occur on any common architecture.) 3945 // 2. If the argument is byval, RV is not sufficiently aligned, and 3946 // we cannot force it to be sufficiently aligned. 3947 // 3. If the argument is byval, but RV is not located in default 3948 // or alloca address space. 3949 Address Addr = I->hasLValue() 3950 ? I->getKnownLValue().getAddress() 3951 : I->getKnownRValue().getAggregateAddress(); 3952 llvm::Value *V = Addr.getPointer(); 3953 CharUnits Align = ArgInfo.getIndirectAlign(); 3954 const llvm::DataLayout *TD = &CGM.getDataLayout(); 3955 3956 assert((FirstIRArg >= IRFuncTy->getNumParams() ||(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3959, __PRETTY_FUNCTION__))
3957 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3959, __PRETTY_FUNCTION__))
3958 TD->getAllocaAddrSpace()) &&(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3959, __PRETTY_FUNCTION__))
3959 "indirect argument must be in alloca address space")(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 3959, __PRETTY_FUNCTION__))
; 3960 3961 bool NeedCopy = false; 3962 3963 if (Addr.getAlignment() < Align && 3964 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) < 3965 Align.getQuantity()) { 3966 NeedCopy = true; 3967 } else if (I->hasLValue()) { 3968 auto LV = I->getKnownLValue(); 3969 auto AS = LV.getAddressSpace(); 3970 3971 if ((!ArgInfo.getIndirectByVal() && 3972 (LV.getAlignment() >= 3973 getContext().getTypeAlignInChars(I->Ty)))) { 3974 NeedCopy = true; 3975 } 3976 if (!getLangOpts().OpenCL) { 3977 if ((ArgInfo.getIndirectByVal() && 3978 (AS != LangAS::Default && 3979 AS != CGM.getASTAllocaAddressSpace()))) { 3980 NeedCopy = true; 3981 } 3982 } 3983 // For OpenCL even if RV is located in default or alloca address space 3984 // we don't want to perform address space cast for it. 3985 else if ((ArgInfo.getIndirectByVal() && 3986 Addr.getType()->getAddressSpace() != IRFuncTy-> 3987 getParamType(FirstIRArg)->getPointerAddressSpace())) { 3988 NeedCopy = true; 3989 } 3990 } 3991 3992 if (NeedCopy) { 3993 // Create an aligned temporary, and copy to it. 3994 Address AI = CreateMemTempWithoutCast( 3995 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp"); 3996 IRCallArgs[FirstIRArg] = AI.getPointer(); 3997 I->copyInto(*this, AI); 3998 } else { 3999 // Skip the extra memcpy call. 4000 auto *T = V->getType()->getPointerElementType()->getPointerTo( 4001 CGM.getDataLayout().getAllocaAddrSpace()); 4002 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast( 4003 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T, 4004 true); 4005 } 4006 } 4007 break; 4008 } 4009 4010 case ABIArgInfo::Ignore: 4011 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4011, __PRETTY_FUNCTION__))
; 4012 break; 4013 4014 case ABIArgInfo::Extend: 4015 case ABIArgInfo::Direct: { 4016 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 4017 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 4018 ArgInfo.getDirectOffset() == 0) { 4019 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4019, __PRETTY_FUNCTION__))
; 4020 llvm::Value *V; 4021 if (!I->isAggregate()) 4022 V = I->getKnownRValue().getScalarVal(); 4023 else 4024 V = Builder.CreateLoad( 4025 I->hasLValue() ? I->getKnownLValue().getAddress() 4026 : I->getKnownRValue().getAggregateAddress()); 4027 4028 // Implement swifterror by copying into a new swifterror argument. 4029 // We'll write back in the normal path out of the call. 4030 if (CallInfo.getExtParameterInfo(ArgNo).getABI() 4031 == ParameterABI::SwiftErrorResult) { 4032 assert(!swiftErrorTemp.isValid() && "multiple swifterror args")((!swiftErrorTemp.isValid() && "multiple swifterror args"
) ? static_cast<void> (0) : __assert_fail ("!swiftErrorTemp.isValid() && \"multiple swifterror args\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4032, __PRETTY_FUNCTION__))
; 4033 4034 QualType pointeeTy = I->Ty->getPointeeType(); 4035 swiftErrorArg = 4036 Address(V, getContext().getTypeAlignInChars(pointeeTy)); 4037 4038 swiftErrorTemp = 4039 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 4040 V = swiftErrorTemp.getPointer(); 4041 cast<llvm::AllocaInst>(V)->setSwiftError(true); 4042 4043 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg); 4044 Builder.CreateStore(errorValue, swiftErrorTemp); 4045 } 4046 4047 // We might have to widen integers, but we should never truncate. 4048 if (ArgInfo.getCoerceToType() != V->getType() && 4049 V->getType()->isIntegerTy()) 4050 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 4051 4052 // If the argument doesn't match, perform a bitcast to coerce it. This 4053 // can happen due to trivial type mismatches. 4054 if (FirstIRArg < IRFuncTy->getNumParams() && 4055 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 4056 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 4057 4058 IRCallArgs[FirstIRArg] = V; 4059 break; 4060 } 4061 4062 // FIXME: Avoid the conversion through memory if possible. 4063 Address Src = Address::invalid(); 4064 if (!I->isAggregate()) { 4065 Src = CreateMemTemp(I->Ty, "coerce"); 4066 I->copyInto(*this, Src); 4067 } else { 4068 Src = I->hasLValue() ? I->getKnownLValue().getAddress() 4069 : I->getKnownRValue().getAggregateAddress(); 4070 } 4071 4072 // If the value is offset in memory, apply the offset now. 4073 Src = emitAddressAtOffset(*this, Src, ArgInfo); 4074 4075 // Fast-isel and the optimizer generally like scalar values better than 4076 // FCAs, so we flatten them if this is safe to do for this argument. 4077 llvm::StructType *STy = 4078 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 4079 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 4080 llvm::Type *SrcTy = Src.getType()->getElementType(); 4081 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4082 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 4083 4084 // If the source type is smaller than the destination type of the 4085 // coerce-to logic, copy the source value into a temp alloca the size 4086 // of the destination type to allow loading all of it. The bits past 4087 // the source value are left undef. 4088 if (SrcSize < DstSize) { 4089 Address TempAlloca 4090 = CreateTempAlloca(STy, Src.getAlignment(), 4091 Src.getName() + ".coerce"); 4092 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 4093 Src = TempAlloca; 4094 } else { 4095 Src = Builder.CreateBitCast(Src, 4096 STy->getPointerTo(Src.getAddressSpace())); 4097 } 4098 4099 assert(NumIRArgs == STy->getNumElements())((NumIRArgs == STy->getNumElements()) ? static_cast<void
> (0) : __assert_fail ("NumIRArgs == STy->getNumElements()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4099, __PRETTY_FUNCTION__))
; 4100 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 4101 Address EltPtr = Builder.CreateStructGEP(Src, i); 4102 llvm::Value *LI = Builder.CreateLoad(EltPtr); 4103 IRCallArgs[FirstIRArg + i] = LI; 4104 } 4105 } else { 4106 // In the simple case, just pass the coerced loaded value. 4107 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4107, __PRETTY_FUNCTION__))
; 4108 IRCallArgs[FirstIRArg] = 4109 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 4110 } 4111 4112 break; 4113 } 4114 4115 case ABIArgInfo::CoerceAndExpand: { 4116 auto coercionType = ArgInfo.getCoerceAndExpandType(); 4117 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 4118 4119 llvm::Value *tempSize = nullptr; 4120 Address addr = Address::invalid(); 4121 Address AllocaAddr = Address::invalid(); 4122 if (I->isAggregate()) { 4123 addr = I->hasLValue() ? I->getKnownLValue().getAddress() 4124 : I->getKnownRValue().getAggregateAddress(); 4125 4126 } else { 4127 RValue RV = I->getKnownRValue(); 4128 assert(RV.isScalar())((RV.isScalar()) ? static_cast<void> (0) : __assert_fail
("RV.isScalar()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4128, __PRETTY_FUNCTION__))
; // complex should always just be direct 4129 4130 llvm::Type *scalarType = RV.getScalarVal()->getType(); 4131 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); 4132 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); 4133 4134 // Materialize to a temporary. 4135 addr = CreateTempAlloca( 4136 RV.getScalarVal()->getType(), 4137 CharUnits::fromQuantity(std::max( 4138 (unsigned)layout->getAlignment().value(), scalarAlign)), 4139 "tmp", 4140 /*ArraySize=*/nullptr, &AllocaAddr); 4141 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer()); 4142 4143 Builder.CreateStore(RV.getScalarVal(), addr); 4144 } 4145 4146 addr = Builder.CreateElementBitCast(addr, coercionType); 4147 4148 unsigned IRArgPos = FirstIRArg; 4149 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4150 llvm::Type *eltType = coercionType->getElementType(i); 4151 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4152 Address eltAddr = Builder.CreateStructGEP(addr, i); 4153 llvm::Value *elt = Builder.CreateLoad(eltAddr); 4154 IRCallArgs[IRArgPos++] = elt; 4155 } 4156 assert(IRArgPos == FirstIRArg + NumIRArgs)((IRArgPos == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4156, __PRETTY_FUNCTION__))
; 4157 4158 if (tempSize) { 4159 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer()); 4160 } 4161 4162 break; 4163 } 4164 4165 case ABIArgInfo::Expand: 4166 unsigned IRArgPos = FirstIRArg; 4167 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos); 4168 assert(IRArgPos == FirstIRArg + NumIRArgs)((IRArgPos == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4168, __PRETTY_FUNCTION__))
; 4169 break; 4170 } 4171 } 4172 4173 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this); 4174 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer(); 4175 4176 // If we're using inalloca, set up that argument. 4177 if (ArgMemory.isValid()) { 4178 llvm::Value *Arg = ArgMemory.getPointer(); 4179 if (CallInfo.isVariadic()) { 4180 // When passing non-POD arguments by value to variadic functions, we will 4181 // end up with a variadic prototype and an inalloca call site. In such 4182 // cases, we can't do any parameter mismatch checks. Give up and bitcast 4183 // the callee. 4184 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace(); 4185 CalleePtr = 4186 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS)); 4187 } else { 4188 llvm::Type *LastParamTy = 4189 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 4190 if (Arg->getType() != LastParamTy) { 4191#ifndef NDEBUG 4192 // Assert that these structs have equivalent element types. 4193 llvm::StructType *FullTy = CallInfo.getArgStruct(); 4194 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 4195 cast<llvm::PointerType>(LastParamTy)->getElementType()); 4196 assert(DeclaredTy->getNumElements() == FullTy->getNumElements())((DeclaredTy->getNumElements() == FullTy->getNumElements
()) ? static_cast<void> (0) : __assert_fail ("DeclaredTy->getNumElements() == FullTy->getNumElements()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4196, __PRETTY_FUNCTION__))
; 4197 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 4198 DE = DeclaredTy->element_end(), 4199 FI = FullTy->element_begin(); 4200 DI != DE; ++DI, ++FI) 4201 assert(*DI == *FI)((*DI == *FI) ? static_cast<void> (0) : __assert_fail (
"*DI == *FI", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4201, __PRETTY_FUNCTION__))
; 4202#endif 4203 Arg = Builder.CreateBitCast(Arg, LastParamTy); 4204 } 4205 } 4206 assert(IRFunctionArgs.hasInallocaArg())((IRFunctionArgs.hasInallocaArg()) ? static_cast<void> (
0) : __assert_fail ("IRFunctionArgs.hasInallocaArg()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4206, __PRETTY_FUNCTION__))
; 4207 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 4208 } 4209 4210 // 2. Prepare the function pointer. 4211 4212 // If the callee is a bitcast of a non-variadic function to have a 4213 // variadic function pointer type, check to see if we can remove the 4214 // bitcast. This comes up with unprototyped functions. 4215 // 4216 // This makes the IR nicer, but more importantly it ensures that we 4217 // can inline the function at -O0 if it is marked always_inline. 4218 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT, 4219 llvm::Value *Ptr) -> llvm::Function * { 4220 if (!CalleeFT->isVarArg()) 4221 return nullptr; 4222 4223 // Get underlying value if it's a bitcast 4224 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) { 4225 if (CE->getOpcode() == llvm::Instruction::BitCast) 4226 Ptr = CE->getOperand(0); 4227 } 4228 4229 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr); 4230 if (!OrigFn) 4231 return nullptr; 4232 4233 llvm::FunctionType *OrigFT = OrigFn->getFunctionType(); 4234 4235 // If the original type is variadic, or if any of the component types 4236 // disagree, we cannot remove the cast. 4237 if (OrigFT->isVarArg() || 4238 OrigFT->getNumParams() != CalleeFT->getNumParams() || 4239 OrigFT->getReturnType() != CalleeFT->getReturnType()) 4240 return nullptr; 4241 4242 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i) 4243 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i)) 4244 return nullptr; 4245 4246 return OrigFn; 4247 }; 4248 4249 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) { 4250 CalleePtr = OrigFn; 4251 IRFuncTy = OrigFn->getFunctionType(); 4252 } 4253 4254 // 3. Perform the actual call. 4255 4256 // Deactivate any cleanups that we're supposed to do immediately before 4257 // the call. 4258 if (!CallArgs.getCleanupsToDeactivate().empty()) 4259 deactivateArgCleanupsBeforeCall(*this, CallArgs); 4260 4261 // Assert that the arguments we computed match up. The IR verifier 4262 // will catch this, but this is a common enough source of problems 4263 // during IRGen changes that it's way better for debugging to catch 4264 // it ourselves here. 4265#ifndef NDEBUG 4266 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg())((IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy
->isVarArg()) ? static_cast<void> (0) : __assert_fail
("IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4266, __PRETTY_FUNCTION__))
; 4267 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4268 // Inalloca argument can have different type. 4269 if (IRFunctionArgs.hasInallocaArg() && 4270 i == IRFunctionArgs.getInallocaArgNo()) 4271 continue; 4272 if (i < IRFuncTy->getNumParams()) 4273 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i))((IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)
) ? static_cast<void> (0) : __assert_fail ("IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4273, __PRETTY_FUNCTION__))
; 4274 } 4275#endif 4276 4277 // Update the largest vector width if any arguments have vector types. 4278 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4279 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType())) 4280 LargestVectorWidth = std::max(LargestVectorWidth, 4281 VT->getPrimitiveSizeInBits()); 4282 } 4283 4284 // Compute the calling convention and attributes. 4285 unsigned CallingConv; 4286 llvm::AttributeList Attrs; 4287 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo, 4288 Callee.getAbstractInfo(), Attrs, CallingConv, 4289 /*AttrOnCallSite=*/true); 4290 4291 // Apply some call-site-specific attributes. 4292 // TODO: work this into building the attribute set. 4293 4294 // Apply always_inline to all calls within flatten functions. 4295 // FIXME: should this really take priority over __try, below? 4296 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 4297 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) { 4298 Attrs = 4299 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4300 llvm::Attribute::AlwaysInline); 4301 } 4302 4303 // Disable inlining inside SEH __try blocks. 4304 if (isSEHTryScope()) { 4305 Attrs = 4306 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4307 llvm::Attribute::NoInline); 4308 } 4309 4310 // Decide whether to use a call or an invoke. 4311 bool CannotThrow; 4312 if (currentFunctionUsesSEHTry()) { 4313 // SEH cares about asynchronous exceptions, so everything can "throw." 4314 CannotThrow = false; 4315 } else if (isCleanupPadScope() && 4316 EHPersonality::get(*this).isMSVCXXPersonality()) { 4317 // The MSVC++ personality will implicitly terminate the program if an 4318 // exception is thrown during a cleanup outside of a try/catch. 4319 // We don't need to model anything in IR to get this behavior. 4320 CannotThrow = true; 4321 } else { 4322 // Otherwise, nounwind call sites will never throw. 4323 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex, 4324 llvm::Attribute::NoUnwind); 4325 } 4326 4327 // If we made a temporary, be sure to clean up after ourselves. Note that we 4328 // can't depend on being inside of an ExprWithCleanups, so we need to manually 4329 // pop this cleanup later on. Being eager about this is OK, since this 4330 // temporary is 'invisible' outside of the callee. 4331 if (UnusedReturnSizePtr) 4332 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca, 4333 UnusedReturnSizePtr); 4334 4335 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 4336 4337 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4338 getBundlesForFunclet(CalleePtr); 4339 4340 // Emit the actual call/invoke instruction. 4341 llvm::CallBase *CI; 4342 if (!InvokeDest) { 4343 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList); 4344 } else { 4345 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 4346 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs, 4347 BundleList); 4348 EmitBlock(Cont); 4349 } 4350 if (callOrInvoke) 4351 *callOrInvoke = CI; 4352 4353 // Apply the attributes and calling convention. 4354 CI->setAttributes(Attrs); 4355 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 4356 4357 // Apply various metadata. 4358 4359 if (!CI->getType()->isVoidTy()) 4360 CI->setName("call"); 4361 4362 // Update largest vector width from the return type. 4363 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType())) 4364 LargestVectorWidth = std::max(LargestVectorWidth, 4365 VT->getPrimitiveSizeInBits()); 4366 4367 // Insert instrumentation or attach profile metadata at indirect call sites. 4368 // For more details, see the comment before the definition of 4369 // IPVK_IndirectCallTarget in InstrProfData.inc. 4370 if (!CI->getCalledFunction()) 4371 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 4372 CI, CalleePtr); 4373 4374 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4375 // optimizer it can aggressively ignore unwind edges. 4376 if (CGM.getLangOpts().ObjCAutoRefCount) 4377 AddObjCARCExceptionMetadata(CI); 4378 4379 // Suppress tail calls if requested. 4380 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 4381 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 4382 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 4383 } 4384 4385 // Add metadata for calls to MSAllocator functions 4386 if (getDebugInfo() && TargetDecl && 4387 TargetDecl->hasAttr<MSAllocatorAttr>()) 4388 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc); 4389 4390 // 4. Finish the call. 4391 4392 // If the call doesn't return, finish the basic block and clear the 4393 // insertion point; this allows the rest of IRGen to discard 4394 // unreachable code. 4395 if (CI->doesNotReturn()) { 4396 if (UnusedReturnSizePtr) 4397 PopCleanupBlock(); 4398 4399 // Strip away the noreturn attribute to better diagnose unreachable UB. 4400 if (SanOpts.has(SanitizerKind::Unreachable)) { 4401 // Also remove from function since CallBase::hasFnAttr additionally checks 4402 // attributes of the called function. 4403 if (auto *F = CI->getCalledFunction()) 4404 F->removeFnAttr(llvm::Attribute::NoReturn); 4405 CI->removeAttribute(llvm::AttributeList::FunctionIndex, 4406 llvm::Attribute::NoReturn); 4407 4408 // Avoid incompatibility with ASan which relies on the `noreturn` 4409 // attribute to insert handler calls. 4410 if (SanOpts.hasOneOf(SanitizerKind::Address | 4411 SanitizerKind::KernelAddress)) { 4412 SanitizerScope SanScope(this); 4413 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder); 4414 Builder.SetInsertPoint(CI); 4415 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 4416 llvm::FunctionCallee Fn = 4417 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return"); 4418 EmitNounwindRuntimeCall(Fn); 4419 } 4420 } 4421 4422 EmitUnreachable(Loc); 4423 Builder.ClearInsertionPoint(); 4424 4425 // FIXME: For now, emit a dummy basic block because expr emitters in 4426 // generally are not ready to handle emitting expressions at unreachable 4427 // points. 4428 EnsureInsertPoint(); 4429 4430 // Return a reasonable RValue. 4431 return GetUndefRValue(RetTy); 4432 } 4433 4434 // Perform the swifterror writeback. 4435 if (swiftErrorTemp.isValid()) { 4436 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp); 4437 Builder.CreateStore(errorResult, swiftErrorArg); 4438 } 4439 4440 // Emit any call-associated writebacks immediately. Arguably this 4441 // should happen after any return-value munging. 4442 if (CallArgs.hasWritebacks()) 4443 emitWritebacks(*this, CallArgs); 4444 4445 // The stack cleanup for inalloca arguments has to run out of the normal 4446 // lexical order, so deactivate it and run it manually here. 4447 CallArgs.freeArgumentMemory(*this); 4448 4449 // Extract the return value. 4450 RValue Ret = [&] { 4451 switch (RetAI.getKind()) { 4452 case ABIArgInfo::CoerceAndExpand: { 4453 auto coercionType = RetAI.getCoerceAndExpandType(); 4454 4455 Address addr = SRetPtr; 4456 addr = Builder.CreateElementBitCast(addr, coercionType); 4457 4458 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType())((CI->getType() == RetAI.getUnpaddedCoerceAndExpandType())
? static_cast<void> (0) : __assert_fail ("CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4458, __PRETTY_FUNCTION__))
; 4459 bool requiresExtract = isa<llvm::StructType>(CI->getType()); 4460 4461 unsigned unpaddedIndex = 0; 4462 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4463 llvm::Type *eltType = coercionType->getElementType(i); 4464 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4465 Address eltAddr = Builder.CreateStructGEP(addr, i); 4466 llvm::Value *elt = CI; 4467 if (requiresExtract) 4468 elt = Builder.CreateExtractValue(elt, unpaddedIndex++); 4469 else 4470 assert(unpaddedIndex == 0)((unpaddedIndex == 0) ? static_cast<void> (0) : __assert_fail
("unpaddedIndex == 0", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4470, __PRETTY_FUNCTION__))
; 4471 Builder.CreateStore(elt, eltAddr); 4472 } 4473 // FALLTHROUGH 4474 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 4475 } 4476 4477 case ABIArgInfo::InAlloca: 4478 case ABIArgInfo::Indirect: { 4479 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 4480 if (UnusedReturnSizePtr) 4481 PopCleanupBlock(); 4482 return ret; 4483 } 4484 4485 case ABIArgInfo::Ignore: 4486 // If we are ignoring an argument that had a result, make sure to 4487 // construct the appropriate return value for our caller. 4488 return GetUndefRValue(RetTy); 4489 4490 case ABIArgInfo::Extend: 4491 case ABIArgInfo::Direct: { 4492 llvm::Type *RetIRTy = ConvertType(RetTy); 4493 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 4494 switch (getEvaluationKind(RetTy)) { 4495 case TEK_Complex: { 4496 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 4497 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 4498 return RValue::getComplex(std::make_pair(Real, Imag)); 4499 } 4500 case TEK_Aggregate: { 4501 Address DestPtr = ReturnValue.getValue(); 4502 bool DestIsVolatile = ReturnValue.isVolatile(); 4503 4504 if (!DestPtr.isValid()) { 4505 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 4506 DestIsVolatile = false; 4507 } 4508 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 4509 return RValue::getAggregate(DestPtr); 4510 } 4511 case TEK_Scalar: { 4512 // If the argument doesn't match, perform a bitcast to coerce it. This 4513 // can happen due to trivial type mismatches. 4514 llvm::Value *V = CI; 4515 if (V->getType() != RetIRTy) 4516 V = Builder.CreateBitCast(V, RetIRTy); 4517 return RValue::get(V); 4518 } 4519 } 4520 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4520)
; 4521 } 4522 4523 Address DestPtr = ReturnValue.getValue(); 4524 bool DestIsVolatile = ReturnValue.isVolatile(); 4525 4526 if (!DestPtr.isValid()) { 4527 DestPtr = CreateMemTemp(RetTy, "coerce"); 4528 DestIsVolatile = false; 4529 } 4530 4531 // If the value is offset in memory, apply the offset now. 4532 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 4533 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 4534 4535 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 4536 } 4537 4538 case ABIArgInfo::Expand: 4539 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4539)
; 4540 } 4541 4542 llvm_unreachable("Unhandled ABIArgInfo::Kind")::llvm::llvm_unreachable_internal("Unhandled ABIArgInfo::Kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGCall.cpp"
, 4542)
; 4543 } (); 4544 4545 // Emit the assume_aligned check on the return value. 4546 if (Ret.isScalar() && TargetDecl) { 4547 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) { 4548 llvm::Value *OffsetValue = nullptr; 4549 if (const auto *Offset = AA->getOffset()) 4550 OffsetValue = EmitScalarExpr(Offset); 4551 4552 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment()); 4553 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment); 4554 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(), 4555 AlignmentCI->getZExtValue(), OffsetValue); 4556 } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) { 4557 llvm::Value *AlignmentVal = CallArgs[AA->getParamIndex().getLLVMIndex()] 4558 .getRValue(*this) 4559 .getScalarVal(); 4560 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(), 4561 AlignmentVal); 4562 } 4563 } 4564 4565 return Ret; 4566} 4567 4568CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const { 4569 if (isVirtual()) { 4570 const CallExpr *CE = getVirtualCallExpr(); 4571 return CGF.CGM.getCXXABI().getVirtualFunctionPointer( 4572 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(), 4573 CE ? CE->getBeginLoc() : SourceLocation()); 4574 } 4575 4576 return *this; 4577} 4578 4579/* VarArg handling */ 4580 4581Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 4582 VAListAddr = VE->isMicrosoftABI() 4583 ? EmitMSVAListRef(VE->getSubExpr()) 4584 : EmitVAListRef(VE->getSubExpr()); 4585 QualType Ty = VE->getType(); 4586 if (VE->isMicrosoftABI()) 4587 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 4588 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 4589}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h

1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Expr interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_EXPR_H
14#define LLVM_CLANG_AST_EXPR_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTVector.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/OperationKinds.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/TemplateBase.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/FixedPoint.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SyncScope.h"
28#include "clang/Basic/TypeTraits.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/iterator.h"
32#include "llvm/ADT/iterator_range.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/Support/AtomicOrdering.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/TrailingObjects.h"
38
39namespace clang {
40 class APValue;
41 class ASTContext;
42 class BlockDecl;
43 class CXXBaseSpecifier;
44 class CXXMemberCallExpr;
45 class CXXOperatorCallExpr;
46 class CastExpr;
47 class Decl;
48 class IdentifierInfo;
49 class MaterializeTemporaryExpr;
50 class NamedDecl;
51 class ObjCPropertyRefExpr;
52 class OpaqueValueExpr;
53 class ParmVarDecl;
54 class StringLiteral;
55 class TargetInfo;
56 class ValueDecl;
57
58/// A simple array of base specifiers.
59typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
60
61/// An adjustment to be made to the temporary created when emitting a
62/// reference binding, which accesses a particular subobject of that temporary.
63struct SubobjectAdjustment {
64 enum {
65 DerivedToBaseAdjustment,
66 FieldAdjustment,
67 MemberPointerAdjustment
68 } Kind;
69
70 struct DTB {
71 const CastExpr *BasePath;
72 const CXXRecordDecl *DerivedClass;
73 };
74
75 struct P {
76 const MemberPointerType *MPT;
77 Expr *RHS;
78 };
79
80 union {
81 struct DTB DerivedToBase;
82 FieldDecl *Field;
83 struct P Ptr;
84 };
85
86 SubobjectAdjustment(const CastExpr *BasePath,
87 const CXXRecordDecl *DerivedClass)
88 : Kind(DerivedToBaseAdjustment) {
89 DerivedToBase.BasePath = BasePath;
90 DerivedToBase.DerivedClass = DerivedClass;
91 }
92
93 SubobjectAdjustment(FieldDecl *Field)
94 : Kind(FieldAdjustment) {
95 this->Field = Field;
96 }
97
98 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
99 : Kind(MemberPointerAdjustment) {
100 this->Ptr.MPT = MPT;
101 this->Ptr.RHS = RHS;
102 }
103};
104
105/// This represents one expression. Note that Expr's are subclasses of Stmt.
106/// This allows an expression to be transparently used any place a Stmt is
107/// required.
108class Expr : public ValueStmt {
109 QualType TR;
110
111public:
112 Expr() = delete;
113 Expr(const Expr&) = delete;
114 Expr(Expr &&) = delete;
115 Expr &operator=(const Expr&) = delete;
116 Expr &operator=(Expr&&) = delete;
117
118protected:
119 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
120 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
121 : ValueStmt(SC)
122 {
123 ExprBits.TypeDependent = TD;
124 ExprBits.ValueDependent = VD;
125 ExprBits.InstantiationDependent = ID;
126 ExprBits.ValueKind = VK;
127 ExprBits.ObjectKind = OK;
128 assert(ExprBits.ObjectKind == OK && "truncated kind")((ExprBits.ObjectKind == OK && "truncated kind") ? static_cast
<void> (0) : __assert_fail ("ExprBits.ObjectKind == OK && \"truncated kind\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 128, __PRETTY_FUNCTION__))
;
129 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
130 setType(T);
131 }
132
133 /// Construct an empty expression.
134 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
135
136public:
137 QualType getType() const { return TR; }
138 void setType(QualType t) {
139 // In C++, the type of an expression is always adjusted so that it
140 // will not have reference type (C++ [expr]p6). Use
141 // QualType::getNonReferenceType() to retrieve the non-reference
142 // type. Additionally, inspect Expr::isLvalue to determine whether
143 // an expression that is adjusted in this manner should be
144 // considered an lvalue.
145 assert((t.isNull() || !t->isReferenceType()) &&(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type"
) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 146, __PRETTY_FUNCTION__))
146 "Expressions can't have reference type")(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type"
) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 146, __PRETTY_FUNCTION__))
;
147
148 TR = t;
149 }
150
151 /// isValueDependent - Determines whether this expression is
152 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
153 /// array bound of "Chars" in the following example is
154 /// value-dependent.
155 /// @code
156 /// template<int Size, char (&Chars)[Size]> struct meta_string;
157 /// @endcode
158 bool isValueDependent() const { return ExprBits.ValueDependent; }
159
160 /// Set whether this expression is value-dependent or not.
161 void setValueDependent(bool VD) {
162 ExprBits.ValueDependent = VD;
163 }
164
165 /// isTypeDependent - Determines whether this expression is
166 /// type-dependent (C++ [temp.dep.expr]), which means that its type
167 /// could change from one template instantiation to the next. For
168 /// example, the expressions "x" and "x + y" are type-dependent in
169 /// the following code, but "y" is not type-dependent:
170 /// @code
171 /// template<typename T>
172 /// void add(T x, int y) {
173 /// x + y;
174 /// }
175 /// @endcode
176 bool isTypeDependent() const { return ExprBits.TypeDependent; }
177
178 /// Set whether this expression is type-dependent or not.
179 void setTypeDependent(bool TD) {
180 ExprBits.TypeDependent = TD;
181 }
182
183 /// Whether this expression is instantiation-dependent, meaning that
184 /// it depends in some way on a template parameter, even if neither its type
185 /// nor (constant) value can change due to the template instantiation.
186 ///
187 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
188 /// instantiation-dependent (since it involves a template parameter \c T), but
189 /// is neither type- nor value-dependent, since the type of the inner
190 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
191 /// \c sizeof is known.
192 ///
193 /// \code
194 /// template<typename T>
195 /// void f(T x, T y) {
196 /// sizeof(sizeof(T() + T());
197 /// }
198 /// \endcode
199 ///
200 bool isInstantiationDependent() const {
201 return ExprBits.InstantiationDependent;
202 }
203
204 /// Set whether this expression is instantiation-dependent or not.
205 void setInstantiationDependent(bool ID) {
206 ExprBits.InstantiationDependent = ID;
207 }
208
209 /// Whether this expression contains an unexpanded parameter
210 /// pack (for C++11 variadic templates).
211 ///
212 /// Given the following function template:
213 ///
214 /// \code
215 /// template<typename F, typename ...Types>
216 /// void forward(const F &f, Types &&...args) {
217 /// f(static_cast<Types&&>(args)...);
218 /// }
219 /// \endcode
220 ///
221 /// The expressions \c args and \c static_cast<Types&&>(args) both
222 /// contain parameter packs.
223 bool containsUnexpandedParameterPack() const {
224 return ExprBits.ContainsUnexpandedParameterPack;
225 }
226
227 /// Set the bit that describes whether this expression
228 /// contains an unexpanded parameter pack.
229 void setContainsUnexpandedParameterPack(bool PP = true) {
230 ExprBits.ContainsUnexpandedParameterPack = PP;
231 }
232
233 /// getExprLoc - Return the preferred location for the arrow when diagnosing
234 /// a problem with a generic expression.
235 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__));
236
237 /// isUnusedResultAWarning - Return true if this immediate expression should
238 /// be warned about if the result is unused. If so, fill in expr, location,
239 /// and ranges with expr to warn on and source locations/ranges appropriate
240 /// for a warning.
241 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
242 SourceRange &R1, SourceRange &R2,
243 ASTContext &Ctx) const;
244
245 /// isLValue - True if this expression is an "l-value" according to
246 /// the rules of the current language. C and C++ give somewhat
247 /// different rules for this concept, but in general, the result of
248 /// an l-value expression identifies a specific object whereas the
249 /// result of an r-value expression is a value detached from any
250 /// specific storage.
251 ///
252 /// C++11 divides the concept of "r-value" into pure r-values
253 /// ("pr-values") and so-called expiring values ("x-values"), which
254 /// identify specific objects that can be safely cannibalized for
255 /// their resources. This is an unfortunate abuse of terminology on
256 /// the part of the C++ committee. In Clang, when we say "r-value",
257 /// we generally mean a pr-value.
258 bool isLValue() const { return getValueKind() == VK_LValue; }
259 bool isRValue() const { return getValueKind() == VK_RValue; }
260 bool isXValue() const { return getValueKind() == VK_XValue; }
261 bool isGLValue() const { return getValueKind() != VK_RValue; }
18
Returning zero, which participates in a condition later
262
263 enum LValueClassification {
264 LV_Valid,
265 LV_NotObjectType,
266 LV_IncompleteVoidType,
267 LV_DuplicateVectorComponents,
268 LV_InvalidExpression,
269 LV_InvalidMessageExpression,
270 LV_MemberFunction,
271 LV_SubObjCPropertySetting,
272 LV_ClassTemporary,
273 LV_ArrayTemporary
274 };
275 /// Reasons why an expression might not be an l-value.
276 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
277
278 enum isModifiableLvalueResult {
279 MLV_Valid,
280 MLV_NotObjectType,
281 MLV_IncompleteVoidType,
282 MLV_DuplicateVectorComponents,
283 MLV_InvalidExpression,
284 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
285 MLV_IncompleteType,
286 MLV_ConstQualified,
287 MLV_ConstQualifiedField,
288 MLV_ConstAddrSpace,
289 MLV_ArrayType,
290 MLV_NoSetterProperty,
291 MLV_MemberFunction,
292 MLV_SubObjCPropertySetting,
293 MLV_InvalidMessageExpression,
294 MLV_ClassTemporary,
295 MLV_ArrayTemporary
296 };
297 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
298 /// does not have an incomplete type, does not have a const-qualified type,
299 /// and if it is a structure or union, does not have any member (including,
300 /// recursively, any member or element of all contained aggregates or unions)
301 /// with a const-qualified type.
302 ///
303 /// \param Loc [in,out] - A source location which *may* be filled
304 /// in with the location of the expression making this a
305 /// non-modifiable lvalue, if specified.
306 isModifiableLvalueResult
307 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
308
309 /// The return type of classify(). Represents the C++11 expression
310 /// taxonomy.
311 class Classification {
312 public:
313 /// The various classification results. Most of these mean prvalue.
314 enum Kinds {
315 CL_LValue,
316 CL_XValue,
317 CL_Function, // Functions cannot be lvalues in C.
318 CL_Void, // Void cannot be an lvalue in C.
319 CL_AddressableVoid, // Void expression whose address can be taken in C.
320 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
321 CL_MemberFunction, // An expression referring to a member function
322 CL_SubObjCPropertySetting,
323 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
324 CL_ArrayTemporary, // A temporary of array type.
325 CL_ObjCMessageRValue, // ObjC message is an rvalue
326 CL_PRValue // A prvalue for any other reason, of any other type
327 };
328 /// The results of modification testing.
329 enum ModifiableType {
330 CM_Untested, // testModifiable was false.
331 CM_Modifiable,
332 CM_RValue, // Not modifiable because it's an rvalue
333 CM_Function, // Not modifiable because it's a function; C++ only
334 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
335 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
336 CM_ConstQualified,
337 CM_ConstQualifiedField,
338 CM_ConstAddrSpace,
339 CM_ArrayType,
340 CM_IncompleteType
341 };
342
343 private:
344 friend class Expr;
345
346 unsigned short Kind;
347 unsigned short Modifiable;
348
349 explicit Classification(Kinds k, ModifiableType m)
350 : Kind(k), Modifiable(m)
351 {}
352
353 public:
354 Classification() {}
355
356 Kinds getKind() const { return static_cast<Kinds>(Kind); }
357 ModifiableType getModifiable() const {
358 assert(Modifiable != CM_Untested && "Did not test for modifiability.")((Modifiable != CM_Untested && "Did not test for modifiability."
) ? static_cast<void> (0) : __assert_fail ("Modifiable != CM_Untested && \"Did not test for modifiability.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 358, __PRETTY_FUNCTION__))
;
359 return static_cast<ModifiableType>(Modifiable);
360 }
361 bool isLValue() const { return Kind == CL_LValue; }
362 bool isXValue() const { return Kind == CL_XValue; }
363 bool isGLValue() const { return Kind <= CL_XValue; }
364 bool isPRValue() const { return Kind >= CL_Function; }
365 bool isRValue() const { return Kind >= CL_XValue; }
366 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
367
368 /// Create a simple, modifiably lvalue
369 static Classification makeSimpleLValue() {
370 return Classification(CL_LValue, CM_Modifiable);
371 }
372
373 };
374 /// Classify - Classify this expression according to the C++11
375 /// expression taxonomy.
376 ///
377 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
378 /// old lvalue vs rvalue. This function determines the type of expression this
379 /// is. There are three expression types:
380 /// - lvalues are classical lvalues as in C++03.
381 /// - prvalues are equivalent to rvalues in C++03.
382 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
383 /// function returning an rvalue reference.
384 /// lvalues and xvalues are collectively referred to as glvalues, while
385 /// prvalues and xvalues together form rvalues.
386 Classification Classify(ASTContext &Ctx) const {
387 return ClassifyImpl(Ctx, nullptr);
388 }
389
390 /// ClassifyModifiable - Classify this expression according to the
391 /// C++11 expression taxonomy, and see if it is valid on the left side
392 /// of an assignment.
393 ///
394 /// This function extends classify in that it also tests whether the
395 /// expression is modifiable (C99 6.3.2.1p1).
396 /// \param Loc A source location that might be filled with a relevant location
397 /// if the expression is not modifiable.
398 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
399 return ClassifyImpl(Ctx, &Loc);
400 }
401
402 /// getValueKindForType - Given a formal return or parameter type,
403 /// give its value kind.
404 static ExprValueKind getValueKindForType(QualType T) {
405 if (const ReferenceType *RT = T->getAs<ReferenceType>())
406 return (isa<LValueReferenceType>(RT)
407 ? VK_LValue
408 : (RT->getPointeeType()->isFunctionType()
409 ? VK_LValue : VK_XValue));
410 return VK_RValue;
411 }
412
413 /// getValueKind - The value kind that this expression produces.
414 ExprValueKind getValueKind() const {
415 return static_cast<ExprValueKind>(ExprBits.ValueKind);
416 }
417
418 /// getObjectKind - The object kind that this expression produces.
419 /// Object kinds are meaningful only for expressions that yield an
420 /// l-value or x-value.
421 ExprObjectKind getObjectKind() const {
422 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
423 }
424
425 bool isOrdinaryOrBitFieldObject() const {
426 ExprObjectKind OK = getObjectKind();
427 return (OK == OK_Ordinary || OK == OK_BitField);
428 }
429
430 /// setValueKind - Set the value kind produced by this expression.
431 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
432
433 /// setObjectKind - Set the object kind produced by this expression.
434 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
435
436private:
437 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
438
439public:
440
441 /// Returns true if this expression is a gl-value that
442 /// potentially refers to a bit-field.
443 ///
444 /// In C++, whether a gl-value refers to a bitfield is essentially
445 /// an aspect of the value-kind type system.
446 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
447
448 /// If this expression refers to a bit-field, retrieve the
449 /// declaration of that bit-field.
450 ///
451 /// Note that this returns a non-null pointer in subtly different
452 /// places than refersToBitField returns true. In particular, this can
453 /// return a non-null pointer even for r-values loaded from
454 /// bit-fields, but it will return null for a conditional bit-field.
455 FieldDecl *getSourceBitField();
456
457 const FieldDecl *getSourceBitField() const {
458 return const_cast<Expr*>(this)->getSourceBitField();
459 }
460
461 Decl *getReferencedDeclOfCallee();
462 const Decl *getReferencedDeclOfCallee() const {
463 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
464 }
465
466 /// If this expression is an l-value for an Objective C
467 /// property, find the underlying property reference expression.
468 const ObjCPropertyRefExpr *getObjCProperty() const;
469
470 /// Check if this expression is the ObjC 'self' implicit parameter.
471 bool isObjCSelfExpr() const;
472
473 /// Returns whether this expression refers to a vector element.
474 bool refersToVectorElement() const;
475
476 /// Returns whether this expression refers to a global register
477 /// variable.
478 bool refersToGlobalRegisterVar() const;
479
480 /// Returns whether this expression has a placeholder type.
481 bool hasPlaceholderType() const {
482 return getType()->isPlaceholderType();
483 }
484
485 /// Returns whether this expression has a specific placeholder type.
486 bool hasPlaceholderType(BuiltinType::Kind K) const {
487 assert(BuiltinType::isPlaceholderTypeKind(K))((BuiltinType::isPlaceholderTypeKind(K)) ? static_cast<void
> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind(K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 487, __PRETTY_FUNCTION__))
;
488 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
489 return BT->getKind() == K;
490 return false;
491 }
492
493 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
494 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
495 /// but also int expressions which are produced by things like comparisons in
496 /// C.
497 bool isKnownToHaveBooleanValue() const;
498
499 /// isIntegerConstantExpr - Return true if this expression is a valid integer
500 /// constant expression, and, if so, return its value in Result. If not a
501 /// valid i-c-e, return false and fill in Loc (if specified) with the location
502 /// of the invalid expression.
503 ///
504 /// Note: This does not perform the implicit conversions required by C++11
505 /// [expr.const]p5.
506 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
507 SourceLocation *Loc = nullptr,
508 bool isEvaluated = true) const;
509 bool isIntegerConstantExpr(const ASTContext &Ctx,
510 SourceLocation *Loc = nullptr) const;
511
512 /// isCXX98IntegralConstantExpr - Return true if this expression is an
513 /// integral constant expression in C++98. Can only be used in C++.
514 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
515
516 /// isCXX11ConstantExpr - Return true if this expression is a constant
517 /// expression in C++11. Can only be used in C++.
518 ///
519 /// Note: This does not perform the implicit conversions required by C++11
520 /// [expr.const]p5.
521 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
522 SourceLocation *Loc = nullptr) const;
523
524 /// isPotentialConstantExpr - Return true if this function's definition
525 /// might be usable in a constant expression in C++11, if it were marked
526 /// constexpr. Return false if the function can never produce a constant
527 /// expression, along with diagnostics describing why not.
528 static bool isPotentialConstantExpr(const FunctionDecl *FD,
529 SmallVectorImpl<
530 PartialDiagnosticAt> &Diags);
531
532 /// isPotentialConstantExprUnevaluted - Return true if this expression might
533 /// be usable in a constant expression in C++11 in an unevaluated context, if
534 /// it were in function FD marked constexpr. Return false if the function can
535 /// never produce a constant expression, along with diagnostics describing
536 /// why not.
537 static bool isPotentialConstantExprUnevaluated(Expr *E,
538 const FunctionDecl *FD,
539 SmallVectorImpl<
540 PartialDiagnosticAt> &Diags);
541
542 /// isConstantInitializer - Returns true if this expression can be emitted to
543 /// IR as a constant, and thus can be used as a constant initializer in C.
544 /// If this expression is not constant and Culprit is non-null,
545 /// it is used to store the address of first non constant expr.
546 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
547 const Expr **Culprit = nullptr) const;
548
549 /// EvalStatus is a struct with detailed info about an evaluation in progress.
550 struct EvalStatus {
551 /// Whether the evaluated expression has side effects.
552 /// For example, (f() && 0) can be folded, but it still has side effects.
553 bool HasSideEffects;
554
555 /// Whether the evaluation hit undefined behavior.
556 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
557 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
558 bool HasUndefinedBehavior;
559
560 /// Diag - If this is non-null, it will be filled in with a stack of notes
561 /// indicating why evaluation failed (or why it failed to produce a constant
562 /// expression).
563 /// If the expression is unfoldable, the notes will indicate why it's not
564 /// foldable. If the expression is foldable, but not a constant expression,
565 /// the notes will describes why it isn't a constant expression. If the
566 /// expression *is* a constant expression, no notes will be produced.
567 SmallVectorImpl<PartialDiagnosticAt> *Diag;
568
569 EvalStatus()
570 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
571
572 // hasSideEffects - Return true if the evaluated expression has
573 // side effects.
574 bool hasSideEffects() const {
575 return HasSideEffects;
576 }
577 };
578
579 /// EvalResult is a struct with detailed info about an evaluated expression.
580 struct EvalResult : EvalStatus {
581 /// Val - This is the value the expression can be folded to.
582 APValue Val;
583
584 // isGlobalLValue - Return true if the evaluated lvalue expression
585 // is global.
586 bool isGlobalLValue() const;
587 };
588
589 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
590 /// an rvalue using any crazy technique (that has nothing to do with language
591 /// standards) that we want to, even if the expression has side-effects. If
592 /// this function returns true, it returns the folded constant in Result. If
593 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
594 /// applied.
595 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
596 bool InConstantContext = false) const;
597
598 /// EvaluateAsBooleanCondition - Return true if this is a constant
599 /// which we can fold and convert to a boolean condition using
600 /// any crazy technique that we want to, even if the expression has
601 /// side-effects.
602 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
603 bool InConstantContext = false) const;
604
605 enum SideEffectsKind {
606 SE_NoSideEffects, ///< Strictly evaluate the expression.
607 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
608 ///< arbitrary unmodeled side effects.
609 SE_AllowSideEffects ///< Allow any unmodeled side effect.
610 };
611
612 /// EvaluateAsInt - Return true if this is a constant which we can fold and
613 /// convert to an integer, using any crazy technique that we want to.
614 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
615 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
616 bool InConstantContext = false) const;
617
618 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
619 /// convert to a floating point value, using any crazy technique that we
620 /// want to.
621 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
622 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
623 bool InConstantContext = false) const;
624
625 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
626 /// convert to a fixed point value.
627 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
628 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
629 bool InConstantContext = false) const;
630
631 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
632 /// constant folded without side-effects, but discard the result.
633 bool isEvaluatable(const ASTContext &Ctx,
634 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
635
636 /// HasSideEffects - This routine returns true for all those expressions
637 /// which have any effect other than producing a value. Example is a function
638 /// call, volatile variable read, or throwing an exception. If
639 /// IncludePossibleEffects is false, this call treats certain expressions with
640 /// potential side effects (such as function call-like expressions,
641 /// instantiation-dependent expressions, or invocations from a macro) as not
642 /// having side effects.
643 bool HasSideEffects(const ASTContext &Ctx,
644 bool IncludePossibleEffects = true) const;
645
646 /// Determine whether this expression involves a call to any function
647 /// that is not trivial.
648 bool hasNonTrivialCall(const ASTContext &Ctx) const;
649
650 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
651 /// integer. This must be called on an expression that constant folds to an
652 /// integer.
653 llvm::APSInt EvaluateKnownConstInt(
654 const ASTContext &Ctx,
655 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
656
657 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
658 const ASTContext &Ctx,
659 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
660
661 void EvaluateForOverflow(const ASTContext &Ctx) const;
662
663 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
664 /// lvalue with link time known address, with no side-effects.
665 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
666 bool InConstantContext = false) const;
667
668 /// EvaluateAsInitializer - Evaluate an expression as if it were the
669 /// initializer of the given declaration. Returns true if the initializer
670 /// can be folded to a constant, and produces any relevant notes. In C++11,
671 /// notes will be produced if the expression is not a constant expression.
672 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
673 const VarDecl *VD,
674 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
675
676 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
677 /// of a call to the given function with the given arguments, inside an
678 /// unevaluated context. Returns true if the expression could be folded to a
679 /// constant.
680 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
681 const FunctionDecl *Callee,
682 ArrayRef<const Expr*> Args,
683 const Expr *This = nullptr) const;
684
685 /// Indicates how the constant expression will be used.
686 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
687
688 /// Evaluate an expression that is required to be a constant expression.
689 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
690 const ASTContext &Ctx) const;
691
692 /// If the current Expr is a pointer, this will try to statically
693 /// determine the number of bytes available where the pointer is pointing.
694 /// Returns true if all of the above holds and we were able to figure out the
695 /// size, false otherwise.
696 ///
697 /// \param Type - How to evaluate the size of the Expr, as defined by the
698 /// "type" parameter of __builtin_object_size
699 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
700 unsigned Type) const;
701
702 /// Enumeration used to describe the kind of Null pointer constant
703 /// returned from \c isNullPointerConstant().
704 enum NullPointerConstantKind {
705 /// Expression is not a Null pointer constant.
706 NPCK_NotNull = 0,
707
708 /// Expression is a Null pointer constant built from a zero integer
709 /// expression that is not a simple, possibly parenthesized, zero literal.
710 /// C++ Core Issue 903 will classify these expressions as "not pointers"
711 /// once it is adopted.
712 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
713 NPCK_ZeroExpression,
714
715 /// Expression is a Null pointer constant built from a literal zero.
716 NPCK_ZeroLiteral,
717
718 /// Expression is a C++11 nullptr.
719 NPCK_CXX11_nullptr,
720
721 /// Expression is a GNU-style __null constant.
722 NPCK_GNUNull
723 };
724
725 /// Enumeration used to describe how \c isNullPointerConstant()
726 /// should cope with value-dependent expressions.
727 enum NullPointerConstantValueDependence {
728 /// Specifies that the expression should never be value-dependent.
729 NPC_NeverValueDependent = 0,
730
731 /// Specifies that a value-dependent expression of integral or
732 /// dependent type should be considered a null pointer constant.
733 NPC_ValueDependentIsNull,
734
735 /// Specifies that a value-dependent expression should be considered
736 /// to never be a null pointer constant.
737 NPC_ValueDependentIsNotNull
738 };
739
740 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
741 /// a Null pointer constant. The return value can further distinguish the
742 /// kind of NULL pointer constant that was detected.
743 NullPointerConstantKind isNullPointerConstant(
744 ASTContext &Ctx,
745 NullPointerConstantValueDependence NPC) const;
746
747 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
748 /// write barrier.
749 bool isOBJCGCCandidate(ASTContext &Ctx) const;
750
751 /// Returns true if this expression is a bound member function.
752 bool isBoundMemberFunction(ASTContext &Ctx) const;
753
754 /// Given an expression of bound-member type, find the type
755 /// of the member. Returns null if this is an *overloaded* bound
756 /// member expression.
757 static QualType findBoundMemberType(const Expr *expr);
758
759 /// Skip past any implicit casts which might surround this expression until
760 /// reaching a fixed point. Skips:
761 /// * ImplicitCastExpr
762 /// * FullExpr
763 Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__));
764 const Expr *IgnoreImpCasts() const {
765 return const_cast<Expr *>(this)->IgnoreImpCasts();
766 }
767
768 /// Skip past any casts which might surround this expression until reaching
769 /// a fixed point. Skips:
770 /// * CastExpr
771 /// * FullExpr
772 /// * MaterializeTemporaryExpr
773 /// * SubstNonTypeTemplateParmExpr
774 Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__));
775 const Expr *IgnoreCasts() const {
776 return const_cast<Expr *>(this)->IgnoreCasts();
777 }
778
779 /// Skip past any implicit AST nodes which might surround this expression
780 /// until reaching a fixed point. Skips:
781 /// * What IgnoreImpCasts() skips
782 /// * MaterializeTemporaryExpr
783 /// * CXXBindTemporaryExpr
784 Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__));
785 const Expr *IgnoreImplicit() const {
786 return const_cast<Expr *>(this)->IgnoreImplicit();
787 }
788
789 /// Skip past any parentheses which might surround this expression until
790 /// reaching a fixed point. Skips:
791 /// * ParenExpr
792 /// * UnaryOperator if `UO_Extension`
793 /// * GenericSelectionExpr if `!isResultDependent()`
794 /// * ChooseExpr if `!isConditionDependent()`
795 /// * ConstantExpr
796 Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__));
797 const Expr *IgnoreParens() const {
798 return const_cast<Expr *>(this)->IgnoreParens();
799 }
800
801 /// Skip past any parentheses and implicit casts which might surround this
802 /// expression until reaching a fixed point.
803 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
804 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
805 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
806 /// * What IgnoreParens() skips
807 /// * What IgnoreImpCasts() skips
808 /// * MaterializeTemporaryExpr
809 /// * SubstNonTypeTemplateParmExpr
810 Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__));
811 const Expr *IgnoreParenImpCasts() const {
812 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
813 }
814
815 /// Skip past any parentheses and casts which might surround this expression
816 /// until reaching a fixed point. Skips:
817 /// * What IgnoreParens() skips
818 /// * What IgnoreCasts() skips
819 Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__));
820 const Expr *IgnoreParenCasts() const {
821 return const_cast<Expr *>(this)->IgnoreParenCasts();
822 }
823
824 /// Skip conversion operators. If this Expr is a call to a conversion
825 /// operator, return the argument.
826 Expr *IgnoreConversionOperator() LLVM_READONLY__attribute__((__pure__));
827 const Expr *IgnoreConversionOperator() const {
828 return const_cast<Expr *>(this)->IgnoreConversionOperator();
829 }
830
831 /// Skip past any parentheses and lvalue casts which might surround this
832 /// expression until reaching a fixed point. Skips:
833 /// * What IgnoreParens() skips
834 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
835 /// casts are skipped
836 /// FIXME: This is intended purely as a temporary workaround for code
837 /// that hasn't yet been rewritten to do the right thing about those
838 /// casts, and may disappear along with the last internal use.
839 Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__));
840 const Expr *IgnoreParenLValueCasts() const {
841 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
842 }
843
844 /// Skip past any parenthese and casts which do not change the value
845 /// (including ptr->int casts of the same size) until reaching a fixed point.
846 /// Skips:
847 /// * What IgnoreParens() skips
848 /// * CastExpr which do not change the value
849 /// * SubstNonTypeTemplateParmExpr
850 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__));
851 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
852 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
853 }
854
855 /// Skip past any parentheses and derived-to-base casts until reaching a
856 /// fixed point. Skips:
857 /// * What IgnoreParens() skips
858 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
859 /// CK_UncheckedDerivedToBase and CK_NoOp)
860 Expr *ignoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__));
861 const Expr *ignoreParenBaseCasts() const {
862 return const_cast<Expr *>(this)->ignoreParenBaseCasts();
863 }
864
865 /// Determine whether this expression is a default function argument.
866 ///
867 /// Default arguments are implicitly generated in the abstract syntax tree
868 /// by semantic analysis for function calls, object constructions, etc. in
869 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
870 /// this routine also looks through any implicit casts to determine whether
871 /// the expression is a default argument.
872 bool isDefaultArgument() const;
873
874 /// Determine whether the result of this expression is a
875 /// temporary object of the given class type.
876 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
877
878 /// Whether this expression is an implicit reference to 'this' in C++.
879 bool isImplicitCXXThis() const;
880
881 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
882
883 /// For an expression of class type or pointer to class type,
884 /// return the most derived class decl the expression is known to refer to.
885 ///
886 /// If this expression is a cast, this method looks through it to find the
887 /// most derived decl that can be inferred from the expression.
888 /// This is valid because derived-to-base conversions have undefined
889 /// behavior if the object isn't dynamically of the derived type.
890 const CXXRecordDecl *getBestDynamicClassType() const;
891
892 /// Get the inner expression that determines the best dynamic class.
893 /// If this is a prvalue, we guarantee that it is of the most-derived type
894 /// for the object itself.
895 const Expr *getBestDynamicClassTypeExpr() const;
896
897 /// Walk outwards from an expression we want to bind a reference to and
898 /// find the expression whose lifetime needs to be extended. Record
899 /// the LHSs of comma expressions and adjustments needed along the path.
900 const Expr *skipRValueSubobjectAdjustments(
901 SmallVectorImpl<const Expr *> &CommaLHS,
902 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
903 const Expr *skipRValueSubobjectAdjustments() const {
904 SmallVector<const Expr *, 8> CommaLHSs;
905 SmallVector<SubobjectAdjustment, 8> Adjustments;
906 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
907 }
908
909 /// Checks that the two Expr's will refer to the same value as a comparison
910 /// operand. The caller must ensure that the values referenced by the Expr's
911 /// are not modified between E1 and E2 or the result my be invalid.
912 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
913
914 static bool classof(const Stmt *T) {
915 return T->getStmtClass() >= firstExprConstant &&
916 T->getStmtClass() <= lastExprConstant;
917 }
918};
919
920//===----------------------------------------------------------------------===//
921// Wrapper Expressions.
922//===----------------------------------------------------------------------===//
923
924/// FullExpr - Represents a "full-expression" node.
925class FullExpr : public Expr {
926protected:
927 Stmt *SubExpr;
928
929 FullExpr(StmtClass SC, Expr *subexpr)
930 : Expr(SC, subexpr->getType(),
931 subexpr->getValueKind(), subexpr->getObjectKind(),
932 subexpr->isTypeDependent(), subexpr->isValueDependent(),
933 subexpr->isInstantiationDependent(),
934 subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {}
935 FullExpr(StmtClass SC, EmptyShell Empty)
936 : Expr(SC, Empty) {}
937public:
938 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
939 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
940
941 /// As with any mutator of the AST, be very careful when modifying an
942 /// existing AST to preserve its invariants.
943 void setSubExpr(Expr *E) { SubExpr = E; }
944
945 static bool classof(const Stmt *T) {
946 return T->getStmtClass() >= firstFullExprConstant &&
947 T->getStmtClass() <= lastFullExprConstant;
948 }
949};
950
951/// ConstantExpr - An expression that occurs in a constant context and
952/// optionally the result of evaluating the expression.
953class ConstantExpr final
954 : public FullExpr,
955 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
956 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
957 "this class assumes llvm::APInt::WordType is uint64_t for "
958 "trail-allocated storage");
959
960public:
961 /// Describes the kind of result that can be trail-allocated.
962 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
963
964private:
965 size_t numTrailingObjects(OverloadToken<APValue>) const {
966 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
967 }
968 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
969 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
970 }
971
972 void DefaultInit(ResultStorageKind StorageKind);
973 uint64_t &Int64Result() {
974 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 975, __PRETTY_FUNCTION__))
975 "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 975, __PRETTY_FUNCTION__))
;
976 return *getTrailingObjects<uint64_t>();
977 }
978 const uint64_t &Int64Result() const {
979 return const_cast<ConstantExpr *>(this)->Int64Result();
980 }
981 APValue &APValueResult() {
982 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 983, __PRETTY_FUNCTION__))
983 "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 983, __PRETTY_FUNCTION__))
;
984 return *getTrailingObjects<APValue>();
985 }
986 const APValue &APValueResult() const {
987 return const_cast<ConstantExpr *>(this)->APValueResult();
988 }
989
990 ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind);
991 ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty);
992
993public:
994 friend TrailingObjects;
995 friend class ASTStmtReader;
996 friend class ASTStmtWriter;
997 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
998 const APValue &Result);
999 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1000 ResultStorageKind Storage = RSK_None);
1001 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1002 ResultStorageKind StorageKind,
1003 EmptyShell Empty);
1004
1005 static ResultStorageKind getStorageKind(const APValue &Value);
1006 static ResultStorageKind getStorageKind(const Type *T,
1007 const ASTContext &Context);
1008
1009 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1010 return SubExpr->getBeginLoc();
1011 }
1012 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1013 return SubExpr->getEndLoc();
1014 }
1015
1016 static bool classof(const Stmt *T) {
1017 return T->getStmtClass() == ConstantExprClass;
1018 }
1019
1020 void SetResult(APValue Value, const ASTContext &Context) {
1021 MoveIntoResult(Value, Context);
1022 }
1023 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1024
1025 APValue::ValueKind getResultAPValueKind() const {
1026 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1027 }
1028 ResultStorageKind getResultStorageKind() const {
1029 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1030 }
1031 APValue getAPValueResult() const;
1032 const APValue &getResultAsAPValue() const { return APValueResult(); }
1033 llvm::APSInt getResultAsAPSInt() const;
1034 // Iterators
1035 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1036 const_child_range children() const {
1037 return const_child_range(&SubExpr, &SubExpr + 1);
1038 }
1039};
1040
1041//===----------------------------------------------------------------------===//
1042// Primary Expressions.
1043//===----------------------------------------------------------------------===//
1044
1045/// OpaqueValueExpr - An expression referring to an opaque object of a
1046/// fixed type and value class. These don't correspond to concrete
1047/// syntax; instead they're used to express operations (usually copy
1048/// operations) on values whose source is generally obvious from
1049/// context.
1050class OpaqueValueExpr : public Expr {
1051 friend class ASTStmtReader;
1052 Expr *SourceExpr;
1053
1054public:
1055 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1056 ExprObjectKind OK = OK_Ordinary,
1057 Expr *SourceExpr = nullptr)
1058 : Expr(OpaqueValueExprClass, T, VK, OK,
1059 T->isDependentType() ||
1060 (SourceExpr && SourceExpr->isTypeDependent()),
1061 T->isDependentType() ||
1062 (SourceExpr && SourceExpr->isValueDependent()),
1063 T->isInstantiationDependentType() ||
1064 (SourceExpr && SourceExpr->isInstantiationDependent()),
1065 false),
1066 SourceExpr(SourceExpr) {
1067 setIsUnique(false);
1068 OpaqueValueExprBits.Loc = Loc;
1069 }
1070
1071 /// Given an expression which invokes a copy constructor --- i.e. a
1072 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1073 /// find the OpaqueValueExpr that's the source of the construction.
1074 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1075
1076 explicit OpaqueValueExpr(EmptyShell Empty)
1077 : Expr(OpaqueValueExprClass, Empty) {}
1078
1079 /// Retrieve the location of this expression.
1080 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1081
1082 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1083 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1084 }
1085 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1086 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1087 }
1088 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
1089 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1090 }
1091
1092 child_range children() {
1093 return child_range(child_iterator(), child_iterator());
1094 }
1095
1096 const_child_range children() const {
1097 return const_child_range(const_child_iterator(), const_child_iterator());
1098 }
1099
1100 /// The source expression of an opaque value expression is the
1101 /// expression which originally generated the value. This is
1102 /// provided as a convenience for analyses that don't wish to
1103 /// precisely model the execution behavior of the program.
1104 ///
1105 /// The source expression is typically set when building the
1106 /// expression which binds the opaque value expression in the first
1107 /// place.
1108 Expr *getSourceExpr() const { return SourceExpr; }
1109
1110 void setIsUnique(bool V) {
1111 assert((!V || SourceExpr) &&(((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1112, __PRETTY_FUNCTION__))
1112 "unique OVEs are expected to have source expressions")(((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1112, __PRETTY_FUNCTION__))
;
1113 OpaqueValueExprBits.IsUnique = V;
1114 }
1115
1116 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1117
1118 static bool classof(const Stmt *T) {
1119 return T->getStmtClass() == OpaqueValueExprClass;
1120 }
1121};
1122
1123/// A reference to a declared variable, function, enum, etc.
1124/// [C99 6.5.1p2]
1125///
1126/// This encodes all the information about how a declaration is referenced
1127/// within an expression.
1128///
1129/// There are several optional constructs attached to DeclRefExprs only when
1130/// they apply in order to conserve memory. These are laid out past the end of
1131/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1132///
1133/// DeclRefExprBits.HasQualifier:
1134/// Specifies when this declaration reference expression has a C++
1135/// nested-name-specifier.
1136/// DeclRefExprBits.HasFoundDecl:
1137/// Specifies when this declaration reference expression has a record of
1138/// a NamedDecl (different from the referenced ValueDecl) which was found
1139/// during name lookup and/or overload resolution.
1140/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1141/// Specifies when this declaration reference expression has an explicit
1142/// C++ template keyword and/or template argument list.
1143/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1144/// Specifies when this declaration reference expression (validly)
1145/// refers to an enclosed local or a captured variable.
1146class DeclRefExpr final
1147 : public Expr,
1148 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1149 NamedDecl *, ASTTemplateKWAndArgsInfo,
1150 TemplateArgumentLoc> {
1151 friend class ASTStmtReader;
1152 friend class ASTStmtWriter;
1153 friend TrailingObjects;
1154
1155 /// The declaration that we are referencing.
1156 ValueDecl *D;
1157
1158 /// Provides source/type location info for the declaration name
1159 /// embedded in D.
1160 DeclarationNameLoc DNLoc;
1161
1162 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1163 return hasQualifier();
1164 }
1165
1166 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1167 return hasFoundDecl();
1168 }
1169
1170 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1171 return hasTemplateKWAndArgsInfo();
1172 }
1173
1174 /// Test whether there is a distinct FoundDecl attached to the end of
1175 /// this DRE.
1176 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1177
1178 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1179 SourceLocation TemplateKWLoc, ValueDecl *D,
1180 bool RefersToEnlosingVariableOrCapture,
1181 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1182 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1183 ExprValueKind VK, NonOdrUseReason NOUR);
1184
1185 /// Construct an empty declaration reference expression.
1186 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1187
1188 /// Computes the type- and value-dependence flags for this
1189 /// declaration reference expression.
1190 void computeDependence(const ASTContext &Ctx);
1191
1192public:
1193 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1194 bool RefersToEnclosingVariableOrCapture, QualType T,
1195 ExprValueKind VK, SourceLocation L,
1196 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1197 NonOdrUseReason NOUR = NOUR_None);
1198
1199 static DeclRefExpr *
1200 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1201 SourceLocation TemplateKWLoc, ValueDecl *D,
1202 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1203 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1204 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1205 NonOdrUseReason NOUR = NOUR_None);
1206
1207 static DeclRefExpr *
1208 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1209 SourceLocation TemplateKWLoc, ValueDecl *D,
1210 bool RefersToEnclosingVariableOrCapture,
1211 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1212 NamedDecl *FoundD = nullptr,
1213 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1214 NonOdrUseReason NOUR = NOUR_None);
1215
1216 /// Construct an empty declaration reference expression.
1217 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1218 bool HasFoundDecl,
1219 bool HasTemplateKWAndArgsInfo,
1220 unsigned NumTemplateArgs);
1221
1222 ValueDecl *getDecl() { return D; }
1223 const ValueDecl *getDecl() const { return D; }
1224 void setDecl(ValueDecl *NewD) { D = NewD; }
1225
1226 DeclarationNameInfo getNameInfo() const {
1227 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1228 }
1229
1230 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1231 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1232 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1233 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1234
1235 /// Determine whether this declaration reference was preceded by a
1236 /// C++ nested-name-specifier, e.g., \c N::foo.
1237 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1238
1239 /// If the name was qualified, retrieves the nested-name-specifier
1240 /// that precedes the name, with source-location information.
1241 NestedNameSpecifierLoc getQualifierLoc() const {
1242 if (!hasQualifier())
1243 return NestedNameSpecifierLoc();
1244 return *getTrailingObjects<NestedNameSpecifierLoc>();
1245 }
1246
1247 /// If the name was qualified, retrieves the nested-name-specifier
1248 /// that precedes the name. Otherwise, returns NULL.
1249 NestedNameSpecifier *getQualifier() const {
1250 return getQualifierLoc().getNestedNameSpecifier();
1251 }
1252
1253 /// Get the NamedDecl through which this reference occurred.
1254 ///
1255 /// This Decl may be different from the ValueDecl actually referred to in the
1256 /// presence of using declarations, etc. It always returns non-NULL, and may
1257 /// simple return the ValueDecl when appropriate.
1258
1259 NamedDecl *getFoundDecl() {
1260 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1261 }
1262
1263 /// Get the NamedDecl through which this reference occurred.
1264 /// See non-const variant.
1265 const NamedDecl *getFoundDecl() const {
1266 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1267 }
1268
1269 bool hasTemplateKWAndArgsInfo() const {
1270 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1271 }
1272
1273 /// Retrieve the location of the template keyword preceding
1274 /// this name, if any.
1275 SourceLocation getTemplateKeywordLoc() const {
1276 if (!hasTemplateKWAndArgsInfo())
1277 return SourceLocation();
1278 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1279 }
1280
1281 /// Retrieve the location of the left angle bracket starting the
1282 /// explicit template argument list following the name, if any.
1283 SourceLocation getLAngleLoc() const {
1284 if (!hasTemplateKWAndArgsInfo())
1285 return SourceLocation();
1286 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1287 }
1288
1289 /// Retrieve the location of the right angle bracket ending the
1290 /// explicit template argument list following the name, if any.
1291 SourceLocation getRAngleLoc() const {
1292 if (!hasTemplateKWAndArgsInfo())
1293 return SourceLocation();
1294 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1295 }
1296
1297 /// Determines whether the name in this declaration reference
1298 /// was preceded by the template keyword.
1299 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1300
1301 /// Determines whether this declaration reference was followed by an
1302 /// explicit template argument list.
1303 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1304
1305 /// Copies the template arguments (if present) into the given
1306 /// structure.
1307 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1308 if (hasExplicitTemplateArgs())
1309 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1310 getTrailingObjects<TemplateArgumentLoc>(), List);
1311 }
1312
1313 /// Retrieve the template arguments provided as part of this
1314 /// template-id.
1315 const TemplateArgumentLoc *getTemplateArgs() const {
1316 if (!hasExplicitTemplateArgs())
1317 return nullptr;
1318 return getTrailingObjects<TemplateArgumentLoc>();
1319 }
1320
1321 /// Retrieve the number of template arguments provided as part of this
1322 /// template-id.
1323 unsigned getNumTemplateArgs() const {
1324 if (!hasExplicitTemplateArgs())
1325 return 0;
1326 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1327 }
1328
1329 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1330 return {getTemplateArgs(), getNumTemplateArgs()};
1331 }
1332
1333 /// Returns true if this expression refers to a function that
1334 /// was resolved from an overloaded set having size greater than 1.
1335 bool hadMultipleCandidates() const {
1336 return DeclRefExprBits.HadMultipleCandidates;
1337 }
1338 /// Sets the flag telling whether this expression refers to
1339 /// a function that was resolved from an overloaded set having size
1340 /// greater than 1.
1341 void setHadMultipleCandidates(bool V = true) {
1342 DeclRefExprBits.HadMultipleCandidates = V;
1343 }
1344
1345 /// Is this expression a non-odr-use reference, and if so, why?
1346 NonOdrUseReason isNonOdrUse() const {
1347 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1348 }
1349
1350 /// Does this DeclRefExpr refer to an enclosing local or a captured
1351 /// variable?
1352 bool refersToEnclosingVariableOrCapture() const {
1353 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1354 }
1355
1356 static bool classof(const Stmt *T) {
1357 return T->getStmtClass() == DeclRefExprClass;
1358 }
1359
1360 // Iterators
1361 child_range children() {
1362 return child_range(child_iterator(), child_iterator());
1363 }
1364
1365 const_child_range children() const {
1366 return const_child_range(const_child_iterator(), const_child_iterator());
1367 }
1368};
1369
1370/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1371/// leaking memory.
1372///
1373/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1374/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1375/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1376/// the APFloat/APInt values will never get freed. APNumericStorage uses
1377/// ASTContext's allocator for memory allocation.
1378class APNumericStorage {
1379 union {
1380 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1381 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1382 };
1383 unsigned BitWidth;
1384
1385 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1386
1387 APNumericStorage(const APNumericStorage &) = delete;
1388 void operator=(const APNumericStorage &) = delete;
1389
1390protected:
1391 APNumericStorage() : VAL(0), BitWidth(0) { }
1392
1393 llvm::APInt getIntValue() const {
1394 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1395 if (NumWords > 1)
1396 return llvm::APInt(BitWidth, NumWords, pVal);
1397 else
1398 return llvm::APInt(BitWidth, VAL);
1399 }
1400 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1401};
1402
1403class APIntStorage : private APNumericStorage {
1404public:
1405 llvm::APInt getValue() const { return getIntValue(); }
1406 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1407 setIntValue(C, Val);
1408 }
1409};
1410
1411class APFloatStorage : private APNumericStorage {
1412public:
1413 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1414 return llvm::APFloat(Semantics, getIntValue());
1415 }
1416 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1417 setIntValue(C, Val.bitcastToAPInt());
1418 }
1419};
1420
1421class IntegerLiteral : public Expr, public APIntStorage {
1422 SourceLocation Loc;
1423
1424 /// Construct an empty integer literal.
1425 explicit IntegerLiteral(EmptyShell Empty)
1426 : Expr(IntegerLiteralClass, Empty) { }
1427
1428public:
1429 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1430 // or UnsignedLongLongTy
1431 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1432 SourceLocation l);
1433
1434 /// Returns a new integer literal with value 'V' and type 'type'.
1435 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1436 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1437 /// \param V - the value that the returned integer literal contains.
1438 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1439 QualType type, SourceLocation l);
1440 /// Returns a new empty integer literal.
1441 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1442
1443 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1444 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1445
1446 /// Retrieve the location of the literal.
1447 SourceLocation getLocation() const { return Loc; }
1448
1449 void setLocation(SourceLocation Location) { Loc = Location; }
1450
1451 static bool classof(const Stmt *T) {
1452 return T->getStmtClass() == IntegerLiteralClass;
1453 }
1454
1455 // Iterators
1456 child_range children() {
1457 return child_range(child_iterator(), child_iterator());
1458 }
1459 const_child_range children() const {
1460 return const_child_range(const_child_iterator(), const_child_iterator());
1461 }
1462};
1463
1464class FixedPointLiteral : public Expr, public APIntStorage {
1465 SourceLocation Loc;
1466 unsigned Scale;
1467
1468 /// \brief Construct an empty integer literal.
1469 explicit FixedPointLiteral(EmptyShell Empty)
1470 : Expr(FixedPointLiteralClass, Empty) {}
1471
1472 public:
1473 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1474 SourceLocation l, unsigned Scale);
1475
1476 // Store the int as is without any bit shifting.
1477 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1478 const llvm::APInt &V,
1479 QualType type, SourceLocation l,
1480 unsigned Scale);
1481
1482 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1483 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1484
1485 /// \brief Retrieve the location of the literal.
1486 SourceLocation getLocation() const { return Loc; }
1487
1488 void setLocation(SourceLocation Location) { Loc = Location; }
1489
1490 static bool classof(const Stmt *T) {
1491 return T->getStmtClass() == FixedPointLiteralClass;
1492 }
1493
1494 std::string getValueAsString(unsigned Radix) const;
1495
1496 // Iterators
1497 child_range children() {
1498 return child_range(child_iterator(), child_iterator());
1499 }
1500 const_child_range children() const {
1501 return const_child_range(const_child_iterator(), const_child_iterator());
1502 }
1503};
1504
1505class CharacterLiteral : public Expr {
1506public:
1507 enum CharacterKind {
1508 Ascii,
1509 Wide,
1510 UTF8,
1511 UTF16,
1512 UTF32
1513 };
1514
1515private:
1516 unsigned Value;
1517 SourceLocation Loc;
1518public:
1519 // type should be IntTy
1520 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1521 SourceLocation l)
1522 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1523 false, false),
1524 Value(value), Loc(l) {
1525 CharacterLiteralBits.Kind = kind;
1526 }
1527
1528 /// Construct an empty character literal.
1529 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1530
1531 SourceLocation getLocation() const { return Loc; }
1532 CharacterKind getKind() const {
1533 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1534 }
1535
1536 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1537 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1538
1539 unsigned getValue() const { return Value; }
1540
1541 void setLocation(SourceLocation Location) { Loc = Location; }
1542 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1543 void setValue(unsigned Val) { Value = Val; }
1544
1545 static bool classof(const Stmt *T) {
1546 return T->getStmtClass() == CharacterLiteralClass;
1547 }
1548
1549 // Iterators
1550 child_range children() {
1551 return child_range(child_iterator(), child_iterator());
1552 }
1553 const_child_range children() const {
1554 return const_child_range(const_child_iterator(), const_child_iterator());
1555 }
1556};
1557
1558class FloatingLiteral : public Expr, private APFloatStorage {
1559 SourceLocation Loc;
1560
1561 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1562 QualType Type, SourceLocation L);
1563
1564 /// Construct an empty floating-point literal.
1565 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1566
1567public:
1568 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1569 bool isexact, QualType Type, SourceLocation L);
1570 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1571
1572 llvm::APFloat getValue() const {
1573 return APFloatStorage::getValue(getSemantics());
1574 }
1575 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1576 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")((&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"
) ? static_cast<void> (0) : __assert_fail ("&getSemantics() == &Val.getSemantics() && \"Inconsistent semantics\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1576, __PRETTY_FUNCTION__))
;
1577 APFloatStorage::setValue(C, Val);
1578 }
1579
1580 /// Get a raw enumeration value representing the floating-point semantics of
1581 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1582 llvm::APFloatBase::Semantics getRawSemantics() const {
1583 return static_cast<llvm::APFloatBase::Semantics>(
1584 FloatingLiteralBits.Semantics);
1585 }
1586
1587 /// Set the raw enumeration value representing the floating-point semantics of
1588 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1589 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1590 FloatingLiteralBits.Semantics = Sem;
1591 }
1592
1593 /// Return the APFloat semantics this literal uses.
1594 const llvm::fltSemantics &getSemantics() const {
1595 return llvm::APFloatBase::EnumToSemantics(
1596 static_cast<llvm::APFloatBase::Semantics>(
1597 FloatingLiteralBits.Semantics));
1598 }
1599
1600 /// Set the APFloat semantics this literal uses.
1601 void setSemantics(const llvm::fltSemantics &Sem) {
1602 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1603 }
1604
1605 bool isExact() const { return FloatingLiteralBits.IsExact; }
1606 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1607
1608 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1609 /// double. Note that this may cause loss of precision, but is useful for
1610 /// debugging dumps, etc.
1611 double getValueAsApproximateDouble() const;
1612
1613 SourceLocation getLocation() const { return Loc; }
1614 void setLocation(SourceLocation L) { Loc = L; }
1615
1616 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1617 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1618
1619 static bool classof(const Stmt *T) {
1620 return T->getStmtClass() == FloatingLiteralClass;
1621 }
1622
1623 // Iterators
1624 child_range children() {
1625 return child_range(child_iterator(), child_iterator());
1626 }
1627 const_child_range children() const {
1628 return const_child_range(const_child_iterator(), const_child_iterator());
1629 }
1630};
1631
1632/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1633/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1634/// IntegerLiteral classes. Instances of this class always have a Complex type
1635/// whose element type matches the subexpression.
1636///
1637class ImaginaryLiteral : public Expr {
1638 Stmt *Val;
1639public:
1640 ImaginaryLiteral(Expr *val, QualType Ty)
1641 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1642 false, false),
1643 Val(val) {}
1644
1645 /// Build an empty imaginary literal.
1646 explicit ImaginaryLiteral(EmptyShell Empty)
1647 : Expr(ImaginaryLiteralClass, Empty) { }
1648
1649 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1650 Expr *getSubExpr() { return cast<Expr>(Val); }
1651 void setSubExpr(Expr *E) { Val = E; }
1652
1653 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1654 return Val->getBeginLoc();
1655 }
1656 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Val->getEndLoc(); }
1657
1658 static bool classof(const Stmt *T) {
1659 return T->getStmtClass() == ImaginaryLiteralClass;
1660 }
1661
1662 // Iterators
1663 child_range children() { return child_range(&Val, &Val+1); }
1664 const_child_range children() const {
1665 return const_child_range(&Val, &Val + 1);
1666 }
1667};
1668
1669/// StringLiteral - This represents a string literal expression, e.g. "foo"
1670/// or L"bar" (wide strings). The actual string data can be obtained with
1671/// getBytes() and is NOT null-terminated. The length of the string data is
1672/// determined by calling getByteLength().
1673///
1674/// The C type for a string is always a ConstantArrayType. In C++, the char
1675/// type is const qualified, in C it is not.
1676///
1677/// Note that strings in C can be formed by concatenation of multiple string
1678/// literal pptokens in translation phase #6. This keeps track of the locations
1679/// of each of these pieces.
1680///
1681/// Strings in C can also be truncated and extended by assigning into arrays,
1682/// e.g. with constructs like:
1683/// char X[2] = "foobar";
1684/// In this case, getByteLength() will return 6, but the string literal will
1685/// have type "char[2]".
1686class StringLiteral final
1687 : public Expr,
1688 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1689 char> {
1690 friend class ASTStmtReader;
1691 friend TrailingObjects;
1692
1693 /// StringLiteral is followed by several trailing objects. They are in order:
1694 ///
1695 /// * A single unsigned storing the length in characters of this string. The
1696 /// length in bytes is this length times the width of a single character.
1697 /// Always present and stored as a trailing objects because storing it in
1698 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1699 /// due to alignment requirements. If you add some data to StringLiteral,
1700 /// consider moving it inside StringLiteral.
1701 ///
1702 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1703 /// token this string is made of.
1704 ///
1705 /// * An array of getByteLength() char used to store the string data.
1706
1707public:
1708 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1709
1710private:
1711 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1712 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1713 return getNumConcatenated();
1714 }
1715
1716 unsigned numTrailingObjects(OverloadToken<char>) const {
1717 return getByteLength();
1718 }
1719
1720 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1721 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1722
1723 const uint16_t *getStrDataAsUInt16() const {
1724 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1725 }
1726
1727 const uint32_t *getStrDataAsUInt32() const {
1728 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1729 }
1730
1731 /// Build a string literal.
1732 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1733 bool Pascal, QualType Ty, const SourceLocation *Loc,
1734 unsigned NumConcatenated);
1735
1736 /// Build an empty string literal.
1737 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1738 unsigned CharByteWidth);
1739
1740 /// Map a target and string kind to the appropriate character width.
1741 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1742
1743 /// Set one of the string literal token.
1744 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1745 assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number"
) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1745, __PRETTY_FUNCTION__))
;
1746 getTrailingObjects<SourceLocation>()[TokNum] = L;
1747 }
1748
1749public:
1750 /// This is the "fully general" constructor that allows representation of
1751 /// strings formed from multiple concatenated tokens.
1752 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1753 StringKind Kind, bool Pascal, QualType Ty,
1754 const SourceLocation *Loc,
1755 unsigned NumConcatenated);
1756
1757 /// Simple constructor for string literals made from one token.
1758 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1759 StringKind Kind, bool Pascal, QualType Ty,
1760 SourceLocation Loc) {
1761 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1762 }
1763
1764 /// Construct an empty string literal.
1765 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1766 unsigned NumConcatenated, unsigned Length,
1767 unsigned CharByteWidth);
1768
1769 StringRef getString() const {
1770 assert(getCharByteWidth() == 1 &&((getCharByteWidth() == 1 && "This function is used in places that assume strings use char"
) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1771, __PRETTY_FUNCTION__))
1771 "This function is used in places that assume strings use char")((getCharByteWidth() == 1 && "This function is used in places that assume strings use char"
) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1771, __PRETTY_FUNCTION__))
;
1772 return StringRef(getStrDataAsChar(), getByteLength());
1773 }
1774
1775 /// Allow access to clients that need the byte representation, such as
1776 /// ASTWriterStmt::VisitStringLiteral().
1777 StringRef getBytes() const {
1778 // FIXME: StringRef may not be the right type to use as a result for this.
1779 return StringRef(getStrDataAsChar(), getByteLength());
1780 }
1781
1782 void outputString(raw_ostream &OS) const;
1783
1784 uint32_t getCodeUnit(size_t i) const {
1785 assert(i < getLength() && "out of bounds access")((i < getLength() && "out of bounds access") ? static_cast
<void> (0) : __assert_fail ("i < getLength() && \"out of bounds access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1785, __PRETTY_FUNCTION__))
;
1786 switch (getCharByteWidth()) {
1787 case 1:
1788 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1789 case 2:
1790 return getStrDataAsUInt16()[i];
1791 case 4:
1792 return getStrDataAsUInt32()[i];
1793 }
1794 llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1794)
;
1795 }
1796
1797 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1798 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1799 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1800
1801 StringKind getKind() const {
1802 return static_cast<StringKind>(StringLiteralBits.Kind);
1803 }
1804
1805 bool isAscii() const { return getKind() == Ascii; }
1806 bool isWide() const { return getKind() == Wide; }
1807 bool isUTF8() const { return getKind() == UTF8; }
1808 bool isUTF16() const { return getKind() == UTF16; }
1809 bool isUTF32() const { return getKind() == UTF32; }
1810 bool isPascal() const { return StringLiteralBits.IsPascal; }
1811
1812 bool containsNonAscii() const {
1813 for (auto c : getString())
1814 if (!isASCII(c))
1815 return true;
1816 return false;
1817 }
1818
1819 bool containsNonAsciiOrNull() const {
1820 for (auto c : getString())
1821 if (!isASCII(c) || !c)
1822 return true;
1823 return false;
1824 }
1825
1826 /// getNumConcatenated - Get the number of string literal tokens that were
1827 /// concatenated in translation phase #6 to form this string literal.
1828 unsigned getNumConcatenated() const {
1829 return StringLiteralBits.NumConcatenated;
1830 }
1831
1832 /// Get one of the string literal token.
1833 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1834 assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number"
) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1834, __PRETTY_FUNCTION__))
;
1835 return getTrailingObjects<SourceLocation>()[TokNum];
1836 }
1837
1838 /// getLocationOfByte - Return a source location that points to the specified
1839 /// byte of this string literal.
1840 ///
1841 /// Strings are amazingly complex. They can be formed from multiple tokens
1842 /// and can have escape sequences in them in addition to the usual trigraph
1843 /// and escaped newline business. This routine handles this complexity.
1844 ///
1845 SourceLocation
1846 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1847 const LangOptions &Features, const TargetInfo &Target,
1848 unsigned *StartToken = nullptr,
1849 unsigned *StartTokenByteOffset = nullptr) const;
1850
1851 typedef const SourceLocation *tokloc_iterator;
1852
1853 tokloc_iterator tokloc_begin() const {
1854 return getTrailingObjects<SourceLocation>();
1855 }
1856
1857 tokloc_iterator tokloc_end() const {
1858 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1859 }
1860
1861 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return *tokloc_begin(); }
1862 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return *(tokloc_end() - 1); }
1863
1864 static bool classof(const Stmt *T) {
1865 return T->getStmtClass() == StringLiteralClass;
1866 }
1867
1868 // Iterators
1869 child_range children() {
1870 return child_range(child_iterator(), child_iterator());
1871 }
1872 const_child_range children() const {
1873 return const_child_range(const_child_iterator(), const_child_iterator());
1874 }
1875};
1876
1877/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1878class PredefinedExpr final
1879 : public Expr,
1880 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1881 friend class ASTStmtReader;
1882 friend TrailingObjects;
1883
1884 // PredefinedExpr is optionally followed by a single trailing
1885 // "Stmt *" for the predefined identifier. It is present if and only if
1886 // hasFunctionName() is true and is always a "StringLiteral *".
1887
1888public:
1889 enum IdentKind {
1890 Func,
1891 Function,
1892 LFunction, // Same as Function, but as wide string.
1893 FuncDName,
1894 FuncSig,
1895 LFuncSig, // Same as FuncSig, but as as wide string
1896 PrettyFunction,
1897 /// The same as PrettyFunction, except that the
1898 /// 'virtual' keyword is omitted for virtual member functions.
1899 PrettyFunctionNoVirtual
1900 };
1901
1902private:
1903 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1904 StringLiteral *SL);
1905
1906 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1907
1908 /// True if this PredefinedExpr has storage for a function name.
1909 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1910
1911 void setFunctionName(StringLiteral *SL) {
1912 assert(hasFunctionName() &&((hasFunctionName() && "This PredefinedExpr has no storage for a function name!"
) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1913, __PRETTY_FUNCTION__))
1913 "This PredefinedExpr has no storage for a function name!")((hasFunctionName() && "This PredefinedExpr has no storage for a function name!"
) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1913, __PRETTY_FUNCTION__))
;
1914 *getTrailingObjects<Stmt *>() = SL;
1915 }
1916
1917public:
1918 /// Create a PredefinedExpr.
1919 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1920 QualType FNTy, IdentKind IK, StringLiteral *SL);
1921
1922 /// Create an empty PredefinedExpr.
1923 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1924 bool HasFunctionName);
1925
1926 IdentKind getIdentKind() const {
1927 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1928 }
1929
1930 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
1931 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
1932
1933 StringLiteral *getFunctionName() {
1934 return hasFunctionName()
1935 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1936 : nullptr;
1937 }
1938
1939 const StringLiteral *getFunctionName() const {
1940 return hasFunctionName()
1941 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1942 : nullptr;
1943 }
1944
1945 static StringRef getIdentKindName(IdentKind IK);
1946 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
1947
1948 SourceLocation getBeginLoc() const { return getLocation(); }
1949 SourceLocation getEndLoc() const { return getLocation(); }
1950
1951 static bool classof(const Stmt *T) {
1952 return T->getStmtClass() == PredefinedExprClass;
1953 }
1954
1955 // Iterators
1956 child_range children() {
1957 return child_range(getTrailingObjects<Stmt *>(),
1958 getTrailingObjects<Stmt *>() + hasFunctionName());
1959 }
1960
1961 const_child_range children() const {
1962 return const_child_range(getTrailingObjects<Stmt *>(),
1963 getTrailingObjects<Stmt *>() + hasFunctionName());
1964 }
1965};
1966
1967/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1968/// AST node is only formed if full location information is requested.
1969class ParenExpr : public Expr {
1970 SourceLocation L, R;
1971 Stmt *Val;
1972public:
1973 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1974 : Expr(ParenExprClass, val->getType(),
1975 val->getValueKind(), val->getObjectKind(),
1976 val->isTypeDependent(), val->isValueDependent(),
1977 val->isInstantiationDependent(),
1978 val->containsUnexpandedParameterPack()),
1979 L(l), R(r), Val(val) {}
1980
1981 /// Construct an empty parenthesized expression.
1982 explicit ParenExpr(EmptyShell Empty)
1983 : Expr(ParenExprClass, Empty) { }
1984
1985 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1986 Expr *getSubExpr() { return cast<Expr>(Val); }
1987 void setSubExpr(Expr *E) { Val = E; }
1988
1989 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return L; }
1990 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return R; }
1991
1992 /// Get the location of the left parentheses '('.
1993 SourceLocation getLParen() const { return L; }
1994 void setLParen(SourceLocation Loc) { L = Loc; }
1995
1996 /// Get the location of the right parentheses ')'.
1997 SourceLocation getRParen() const { return R; }
1998 void setRParen(SourceLocation Loc) { R = Loc; }
1999
2000 static bool classof(const Stmt *T) {
2001 return T->getStmtClass() == ParenExprClass;
2002 }
2003
2004 // Iterators
2005 child_range children() { return child_range(&Val, &Val+1); }
2006 const_child_range children() const {
2007 return const_child_range(&Val, &Val + 1);
2008 }
2009};
2010
2011/// UnaryOperator - This represents the unary-expression's (except sizeof and
2012/// alignof), the postinc/postdec operators from postfix-expression, and various
2013/// extensions.
2014///
2015/// Notes on various nodes:
2016///
2017/// Real/Imag - These return the real/imag part of a complex operand. If
2018/// applied to a non-complex value, the former returns its operand and the
2019/// later returns zero in the type of the operand.
2020///
2021class UnaryOperator : public Expr {
2022 Stmt *Val;
2023
2024public:
2025 typedef UnaryOperatorKind Opcode;
2026
2027 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
2028 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
2029 : Expr(UnaryOperatorClass, type, VK, OK,
2030 input->isTypeDependent() || type->isDependentType(),
2031 input->isValueDependent(),
2032 (input->isInstantiationDependent() ||
2033 type->isInstantiationDependentType()),
2034 input->containsUnexpandedParameterPack()),
2035 Val(input) {
2036 UnaryOperatorBits.Opc = opc;
2037 UnaryOperatorBits.CanOverflow = CanOverflow;
2038 UnaryOperatorBits.Loc = l;
2039 }
2040
2041 /// Build an empty unary operator.
2042 explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) {
2043 UnaryOperatorBits.Opc = UO_AddrOf;
2044 }
2045
2046 Opcode getOpcode() const {
2047 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2048 }
2049 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2050
2051 Expr *getSubExpr() const { return cast<Expr>(Val); }
2052 void setSubExpr(Expr *E) { Val = E; }
2053
2054 /// getOperatorLoc - Return the location of the operator.
2055 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2056 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2057
2058 /// Returns true if the unary operator can cause an overflow. For instance,
2059 /// signed int i = INT_MAX; i++;
2060 /// signed char c = CHAR_MAX; c++;
2061 /// Due to integer promotions, c++ is promoted to an int before the postfix
2062 /// increment, and the result is an int that cannot overflow. However, i++
2063 /// can overflow.
2064 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2065 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2066
2067 /// isPostfix - Return true if this is a postfix operation, like x++.
2068 static bool isPostfix(Opcode Op) {
2069 return Op == UO_PostInc || Op == UO_PostDec;
2070 }
2071
2072 /// isPrefix - Return true if this is a prefix operation, like --x.
2073 static bool isPrefix(Opcode Op) {
2074 return Op == UO_PreInc || Op == UO_PreDec;
2075 }
2076
2077 bool isPrefix() const { return isPrefix(getOpcode()); }
2078 bool isPostfix() const { return isPostfix(getOpcode()); }
2079
2080 static bool isIncrementOp(Opcode Op) {
2081 return Op == UO_PreInc || Op == UO_PostInc;
2082 }
2083 bool isIncrementOp() const {
2084 return isIncrementOp(getOpcode());
2085 }
2086
2087 static bool isDecrementOp(Opcode Op) {
2088 return Op == UO_PreDec || Op == UO_PostDec;
2089 }
2090 bool isDecrementOp() const {
2091 return isDecrementOp(getOpcode());
2092 }
2093
2094 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2095 bool isIncrementDecrementOp() const {
2096 return isIncrementDecrementOp(getOpcode());
2097 }
2098
2099 static bool isArithmeticOp(Opcode Op) {
2100 return Op >= UO_Plus && Op <= UO_LNot;
2101 }
2102 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2103
2104 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2105 /// corresponds to, e.g. "sizeof" or "[pre]++"
2106 static StringRef getOpcodeStr(Opcode Op);
2107
2108 /// Retrieve the unary opcode that corresponds to the given
2109 /// overloaded operator.
2110 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2111
2112 /// Retrieve the overloaded operator kind that corresponds to
2113 /// the given unary opcode.
2114 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2115
2116 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2117 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2118 }
2119 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2120 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2121 }
2122 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2123
2124 static bool classof(const Stmt *T) {
2125 return T->getStmtClass() == UnaryOperatorClass;
2126 }
2127
2128 // Iterators
2129 child_range children() { return child_range(&Val, &Val+1); }
2130 const_child_range children() const {
2131 return const_child_range(&Val, &Val + 1);
2132 }
2133};
2134
2135/// Helper class for OffsetOfExpr.
2136
2137// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2138class OffsetOfNode {
2139public:
2140 /// The kind of offsetof node we have.
2141 enum Kind {
2142 /// An index into an array.
2143 Array = 0x00,
2144 /// A field.
2145 Field = 0x01,
2146 /// A field in a dependent type, known only by its name.
2147 Identifier = 0x02,
2148 /// An implicit indirection through a C++ base class, when the
2149 /// field found is in a base class.
2150 Base = 0x03
2151 };
2152
2153private:
2154 enum { MaskBits = 2, Mask = 0x03 };
2155
2156 /// The source range that covers this part of the designator.
2157 SourceRange Range;
2158
2159 /// The data describing the designator, which comes in three
2160 /// different forms, depending on the lower two bits.
2161 /// - An unsigned index into the array of Expr*'s stored after this node
2162 /// in memory, for [constant-expression] designators.
2163 /// - A FieldDecl*, for references to a known field.
2164 /// - An IdentifierInfo*, for references to a field with a given name
2165 /// when the class type is dependent.
2166 /// - A CXXBaseSpecifier*, for references that look at a field in a
2167 /// base class.
2168 uintptr_t Data;
2169
2170public:
2171 /// Create an offsetof node that refers to an array element.
2172 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2173 SourceLocation RBracketLoc)
2174 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2175
2176 /// Create an offsetof node that refers to a field.
2177 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2178 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2179 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2180
2181 /// Create an offsetof node that refers to an identifier.
2182 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2183 SourceLocation NameLoc)
2184 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2185 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2186
2187 /// Create an offsetof node that refers into a C++ base class.
2188 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2189 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2190
2191 /// Determine what kind of offsetof node this is.
2192 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2193
2194 /// For an array element node, returns the index into the array
2195 /// of expressions.
2196 unsigned getArrayExprIndex() const {
2197 assert(getKind() == Array)((getKind() == Array) ? static_cast<void> (0) : __assert_fail
("getKind() == Array", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2197, __PRETTY_FUNCTION__))
;
2198 return Data >> 2;
2199 }
2200
2201 /// For a field offsetof node, returns the field.
2202 FieldDecl *getField() const {
2203 assert(getKind() == Field)((getKind() == Field) ? static_cast<void> (0) : __assert_fail
("getKind() == Field", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2203, __PRETTY_FUNCTION__))
;
2204 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2205 }
2206
2207 /// For a field or identifier offsetof node, returns the name of
2208 /// the field.
2209 IdentifierInfo *getFieldName() const;
2210
2211 /// For a base class node, returns the base specifier.
2212 CXXBaseSpecifier *getBase() const {
2213 assert(getKind() == Base)((getKind() == Base) ? static_cast<void> (0) : __assert_fail
("getKind() == Base", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2213, __PRETTY_FUNCTION__))
;
2214 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2215 }
2216
2217 /// Retrieve the source range that covers this offsetof node.
2218 ///
2219 /// For an array element node, the source range contains the locations of
2220 /// the square brackets. For a field or identifier node, the source range
2221 /// contains the location of the period (if there is one) and the
2222 /// identifier.
2223 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
2224 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
2225 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
2226};
2227
2228/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2229/// offsetof(record-type, member-designator). For example, given:
2230/// @code
2231/// struct S {
2232/// float f;
2233/// double d;
2234/// };
2235/// struct T {
2236/// int i;
2237/// struct S s[10];
2238/// };
2239/// @endcode
2240/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2241
2242class OffsetOfExpr final
2243 : public Expr,
2244 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2245 SourceLocation OperatorLoc, RParenLoc;
2246 // Base type;
2247 TypeSourceInfo *TSInfo;
2248 // Number of sub-components (i.e. instances of OffsetOfNode).
2249 unsigned NumComps;
2250 // Number of sub-expressions (i.e. array subscript expressions).
2251 unsigned NumExprs;
2252
2253 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2254 return NumComps;
2255 }
2256
2257 OffsetOfExpr(const ASTContext &C, QualType type,
2258 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2259 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2260 SourceLocation RParenLoc);
2261
2262 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2263 : Expr(OffsetOfExprClass, EmptyShell()),
2264 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2265
2266public:
2267
2268 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2269 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2270 ArrayRef<OffsetOfNode> comps,
2271 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2272
2273 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2274 unsigned NumComps, unsigned NumExprs);
2275
2276 /// getOperatorLoc - Return the location of the operator.
2277 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2278 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2279
2280 /// Return the location of the right parentheses.
2281 SourceLocation getRParenLoc() const { return RParenLoc; }
2282 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2283
2284 TypeSourceInfo *getTypeSourceInfo() const {
2285 return TSInfo;
2286 }
2287 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2288 TSInfo = tsi;
2289 }
2290
2291 const OffsetOfNode &getComponent(unsigned Idx) const {
2292 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2292, __PRETTY_FUNCTION__))
;
2293 return getTrailingObjects<OffsetOfNode>()[Idx];
2294 }
2295
2296 void setComponent(unsigned Idx, OffsetOfNode ON) {
2297 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2297, __PRETTY_FUNCTION__))
;
2298 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2299 }
2300
2301 unsigned getNumComponents() const {
2302 return NumComps;
2303 }
2304
2305 Expr* getIndexExpr(unsigned Idx) {
2306 assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2306, __PRETTY_FUNCTION__))
;
2307 return getTrailingObjects<Expr *>()[Idx];
2308 }
2309
2310 const Expr *getIndexExpr(unsigned Idx) const {
2311 assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2311, __PRETTY_FUNCTION__))
;
2312 return getTrailingObjects<Expr *>()[Idx];
2313 }
2314
2315 void setIndexExpr(unsigned Idx, Expr* E) {
2316 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2316, __PRETTY_FUNCTION__))
;
2317 getTrailingObjects<Expr *>()[Idx] = E;
2318 }
2319
2320 unsigned getNumExpressions() const {
2321 return NumExprs;
2322 }
2323
2324 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
2325 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2326
2327 static bool classof(const Stmt *T) {
2328 return T->getStmtClass() == OffsetOfExprClass;
2329 }
2330
2331 // Iterators
2332 child_range children() {
2333 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2334 return child_range(begin, begin + NumExprs);
2335 }
2336 const_child_range children() const {
2337 Stmt *const *begin =
2338 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2339 return const_child_range(begin, begin + NumExprs);
2340 }
2341 friend TrailingObjects;
2342};
2343
2344/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2345/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2346/// vec_step (OpenCL 1.1 6.11.12).
2347class UnaryExprOrTypeTraitExpr : public Expr {
2348 union {
2349 TypeSourceInfo *Ty;
2350 Stmt *Ex;
2351 } Argument;
2352 SourceLocation OpLoc, RParenLoc;
2353
2354public:
2355 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2356 QualType resultType, SourceLocation op,
2357 SourceLocation rp) :
2358 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2359 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2360 // Value-dependent if the argument is type-dependent.
2361 TInfo->getType()->isDependentType(),
2362 TInfo->getType()->isInstantiationDependentType(),
2363 TInfo->getType()->containsUnexpandedParameterPack()),
2364 OpLoc(op), RParenLoc(rp) {
2365 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2366 UnaryExprOrTypeTraitExprBits.IsType = true;
2367 Argument.Ty = TInfo;
2368 }
2369
2370 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2371 QualType resultType, SourceLocation op,
2372 SourceLocation rp);
2373
2374 /// Construct an empty sizeof/alignof expression.
2375 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2376 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2377
2378 UnaryExprOrTypeTrait getKind() const {
2379 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2380 }
2381 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2382
2383 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2384 QualType getArgumentType() const {
2385 return getArgumentTypeInfo()->getType();
2386 }
2387 TypeSourceInfo *getArgumentTypeInfo() const {
2388 assert(isArgumentType() && "calling getArgumentType() when arg is expr")((isArgumentType() && "calling getArgumentType() when arg is expr"
) ? static_cast<void> (0) : __assert_fail ("isArgumentType() && \"calling getArgumentType() when arg is expr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2388, __PRETTY_FUNCTION__))
;
2389 return Argument.Ty;
2390 }
2391 Expr *getArgumentExpr() {
2392 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")((!isArgumentType() && "calling getArgumentExpr() when arg is type"
) ? static_cast<void> (0) : __assert_fail ("!isArgumentType() && \"calling getArgumentExpr() when arg is type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2392, __PRETTY_FUNCTION__))
;
2393 return static_cast<Expr*>(Argument.Ex);
2394 }
2395 const Expr *getArgumentExpr() const {
2396 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2397 }
2398
2399 void setArgument(Expr *E) {
2400 Argument.Ex = E;
2401 UnaryExprOrTypeTraitExprBits.IsType = false;
2402 }
2403 void setArgument(TypeSourceInfo *TInfo) {
2404 Argument.Ty = TInfo;
2405 UnaryExprOrTypeTraitExprBits.IsType = true;
2406 }
2407
2408 /// Gets the argument type, or the type of the argument expression, whichever
2409 /// is appropriate.
2410 QualType getTypeOfArgument() const {
2411 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2412 }
2413
2414 SourceLocation getOperatorLoc() const { return OpLoc; }
2415 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2416
2417 SourceLocation getRParenLoc() const { return RParenLoc; }
2418 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2419
2420 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; }
2421 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2422
2423 static bool classof(const Stmt *T) {
2424 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2425 }
2426
2427 // Iterators
2428 child_range children();
2429 const_child_range children() const;
2430};
2431
2432//===----------------------------------------------------------------------===//
2433// Postfix Operators.
2434//===----------------------------------------------------------------------===//
2435
2436/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2437class ArraySubscriptExpr : public Expr {
2438 enum { LHS, RHS, END_EXPR };
2439 Stmt *SubExprs[END_EXPR];
2440
2441 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2442
2443public:
2444 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2445 ExprValueKind VK, ExprObjectKind OK,
2446 SourceLocation rbracketloc)
2447 : Expr(ArraySubscriptExprClass, t, VK, OK,
2448 lhs->isTypeDependent() || rhs->isTypeDependent(),
2449 lhs->isValueDependent() || rhs->isValueDependent(),
2450 (lhs->isInstantiationDependent() ||
2451 rhs->isInstantiationDependent()),
2452 (lhs->containsUnexpandedParameterPack() ||
2453 rhs->containsUnexpandedParameterPack())) {
2454 SubExprs[LHS] = lhs;
2455 SubExprs[RHS] = rhs;
2456 ArraySubscriptExprBits.RBracketLoc = rbracketloc;
2457 }
2458
2459 /// Create an empty array subscript expression.
2460 explicit ArraySubscriptExpr(EmptyShell Shell)
2461 : Expr(ArraySubscriptExprClass, Shell) { }
2462
2463 /// An array access can be written A[4] or 4[A] (both are equivalent).
2464 /// - getBase() and getIdx() always present the normalized view: A[4].
2465 /// In this case getBase() returns "A" and getIdx() returns "4".
2466 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2467 /// 4[A] getLHS() returns "4".
2468 /// Note: Because vector element access is also written A[4] we must
2469 /// predicate the format conversion in getBase and getIdx only on the
2470 /// the type of the RHS, as it is possible for the LHS to be a vector of
2471 /// integer type
2472 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2473 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2474 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2475
2476 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2477 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2478 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2479
2480 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2481 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2482
2483 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2484 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2485
2486 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2487 return getLHS()->getBeginLoc();
2488 }
2489 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2490
2491 SourceLocation getRBracketLoc() const {
2492 return ArraySubscriptExprBits.RBracketLoc;
2493 }
2494 void setRBracketLoc(SourceLocation L) {
2495 ArraySubscriptExprBits.RBracketLoc = L;
2496 }
2497
2498 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
2499 return getBase()->getExprLoc();
2500 }
2501
2502 static bool classof(const Stmt *T) {
2503 return T->getStmtClass() == ArraySubscriptExprClass;
2504 }
2505
2506 // Iterators
2507 child_range children() {
2508 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2509 }
2510 const_child_range children() const {
2511 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2512 }
2513};
2514
2515/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2516/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2517/// while its subclasses may represent alternative syntax that (semantically)
2518/// results in a function call. For example, CXXOperatorCallExpr is
2519/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2520/// "str1 + str2" to resolve to a function call.
2521class CallExpr : public Expr {
2522 enum { FN = 0, PREARGS_START = 1 };
2523
2524 /// The number of arguments in the call expression.
2525 unsigned NumArgs;
2526
2527 /// The location of the right parenthese. This has a different meaning for
2528 /// the derived classes of CallExpr.
2529 SourceLocation RParenLoc;
2530
2531 void updateDependenciesFromArg(Expr *Arg);
2532
2533 // CallExpr store some data in trailing objects. However since CallExpr
2534 // is used a base of other expression classes we cannot use
2535 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2536 // and casts.
2537 //
2538 // The trailing objects are in order:
2539 //
2540 // * A single "Stmt *" for the callee expression.
2541 //
2542 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2543 //
2544 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2545 //
2546 // Note that we store the offset in bytes from the this pointer to the start
2547 // of the trailing objects. It would be perfectly possible to compute it
2548 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2549 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2550 // compute this once and then load the offset from the bit-fields of Stmt,
2551 // instead of re-computing the offset each time the trailing objects are
2552 // accessed.
2553
2554 /// Return a pointer to the start of the trailing array of "Stmt *".
2555 Stmt **getTrailingStmts() {
2556 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2557 CallExprBits.OffsetToTrailingObjects);
2558 }
2559 Stmt *const *getTrailingStmts() const {
2560 return const_cast<CallExpr *>(this)->getTrailingStmts();
2561 }
2562
2563 /// Map a statement class to the appropriate offset in bytes from the
2564 /// this pointer to the trailing objects.
2565 static unsigned offsetToTrailingObjects(StmtClass SC);
2566
2567public:
2568 enum class ADLCallKind : bool { NotADL, UsesADL };
2569 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2570 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2571
2572protected:
2573 /// Build a call expression, assuming that appropriate storage has been
2574 /// allocated for the trailing objects.
2575 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2576 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2577 SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL);
2578
2579 /// Build an empty call expression, for deserialization.
2580 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2581 EmptyShell Empty);
2582
2583 /// Return the size in bytes needed for the trailing objects.
2584 /// Used by the derived classes to allocate the right amount of storage.
2585 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) {
2586 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *);
2587 }
2588
2589 Stmt *getPreArg(unsigned I) {
2590 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2590, __PRETTY_FUNCTION__))
;
2591 return getTrailingStmts()[PREARGS_START + I];
2592 }
2593 const Stmt *getPreArg(unsigned I) const {
2594 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2594, __PRETTY_FUNCTION__))
;
2595 return getTrailingStmts()[PREARGS_START + I];
2596 }
2597 void setPreArg(unsigned I, Stmt *PreArg) {
2598 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2598, __PRETTY_FUNCTION__))
;
2599 getTrailingStmts()[PREARGS_START + I] = PreArg;
2600 }
2601
2602 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2603
2604public:
2605 /// Create a call expression. Fn is the callee expression, Args is the
2606 /// argument array, Ty is the type of the call expression (which is *not*
2607 /// the return type in general), VK is the value kind of the call expression
2608 /// (lvalue, rvalue, ...), and RParenLoc is the location of the right
2609 /// parenthese in the call expression. MinNumArgs specifies the minimum
2610 /// number of arguments. The actual number of arguments will be the greater
2611 /// of Args.size() and MinNumArgs. This is used in a few places to allocate
2612 /// enough storage for the default arguments. UsesADL specifies whether the
2613 /// callee was found through argument-dependent lookup.
2614 ///
2615 /// Note that you can use CreateTemporary if you need a temporary call
2616 /// expression on the stack.
2617 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2618 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2619 SourceLocation RParenLoc, unsigned MinNumArgs = 0,
2620 ADLCallKind UsesADL = NotADL);
2621
2622 /// Create a temporary call expression with no arguments in the memory
2623 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2624 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2625 ///
2626 /// \code{.cpp}
2627 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2628 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2629 /// \endcode
2630 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2631 ExprValueKind VK, SourceLocation RParenLoc,
2632 ADLCallKind UsesADL = NotADL);
2633
2634 /// Create an empty call expression, for deserialization.
2635 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2636 EmptyShell Empty);
2637
2638 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2639 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2640 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2641
2642 ADLCallKind getADLCallKind() const {
2643 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2644 }
2645 void setADLCallKind(ADLCallKind V = UsesADL) {
2646 CallExprBits.UsesADL = static_cast<bool>(V);
2647 }
2648 bool usesADL() const { return getADLCallKind() == UsesADL; }
2649
2650 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2651 const Decl *getCalleeDecl() const {
2652 return getCallee()->getReferencedDeclOfCallee();
2653 }
2654
2655 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2656 FunctionDecl *getDirectCallee() {
2657 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2658 }
2659 const FunctionDecl *getDirectCallee() const {
2660 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2661 }
2662
2663 /// getNumArgs - Return the number of actual arguments to this call.
2664 unsigned getNumArgs() const { return NumArgs; }
2665
2666 /// Retrieve the call arguments.
2667 Expr **getArgs() {
2668 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2669 getNumPreArgs());
2670 }
2671 const Expr *const *getArgs() const {
2672 return reinterpret_cast<const Expr *const *>(
2673 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2674 }
2675
2676 /// getArg - Return the specified argument.
2677 Expr *getArg(unsigned Arg) {
2678 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2678, __PRETTY_FUNCTION__))
;
2679 return getArgs()[Arg];
2680 }
2681 const Expr *getArg(unsigned Arg) const {
2682 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2682, __PRETTY_FUNCTION__))
;
2683 return getArgs()[Arg];
2684 }
2685
2686 /// setArg - Set the specified argument.
2687 void setArg(unsigned Arg, Expr *ArgExpr) {
2688 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2688, __PRETTY_FUNCTION__))
;
2689 getArgs()[Arg] = ArgExpr;
2690 }
2691
2692 /// Reduce the number of arguments in this call expression. This is used for
2693 /// example during error recovery to drop extra arguments. There is no way
2694 /// to perform the opposite because: 1.) We don't track how much storage
2695 /// we have for the argument array 2.) This would potentially require growing
2696 /// the argument array, something we cannot support since the arguments are
2697 /// stored in a trailing array.
2698 void shrinkNumArgs(unsigned NewNumArgs) {
2699 assert((NewNumArgs <= getNumArgs()) &&(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!"
) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2700, __PRETTY_FUNCTION__))
2700 "shrinkNumArgs cannot increase the number of arguments!")(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!"
) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2700, __PRETTY_FUNCTION__))
;
2701 NumArgs = NewNumArgs;
2702 }
2703
2704 /// Bluntly set a new number of arguments without doing any checks whatsoever.
2705 /// Only used during construction of a CallExpr in a few places in Sema.
2706 /// FIXME: Find a way to remove it.
2707 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
2708
2709 typedef ExprIterator arg_iterator;
2710 typedef ConstExprIterator const_arg_iterator;
2711 typedef llvm::iterator_range<arg_iterator> arg_range;
2712 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2713
2714 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2715 const_arg_range arguments() const {
2716 return const_arg_range(arg_begin(), arg_end());
2717 }
2718
2719 arg_iterator arg_begin() {
2720 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2721 }
2722 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
2723
2724 const_arg_iterator arg_begin() const {
2725 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2726 }
2727 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
2728
2729 /// This method provides fast access to all the subexpressions of
2730 /// a CallExpr without going through the slower virtual child_iterator
2731 /// interface. This provides efficient reverse iteration of the
2732 /// subexpressions. This is currently used for CFG construction.
2733 ArrayRef<Stmt *> getRawSubExprs() {
2734 return llvm::makeArrayRef(getTrailingStmts(),
2735 PREARGS_START + getNumPreArgs() + getNumArgs());
2736 }
2737
2738 /// getNumCommas - Return the number of commas that must have been present in
2739 /// this function call.
2740 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
2741
2742 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2743 /// of the callee. If not, return 0.
2744 unsigned getBuiltinCallee() const;
2745
2746 /// Returns \c true if this is a call to a builtin which does not
2747 /// evaluate side-effects within its arguments.
2748 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2749
2750 /// getCallReturnType - Get the return type of the call expr. This is not
2751 /// always the type of the expr itself, if the return type is a reference
2752 /// type.
2753 QualType getCallReturnType(const ASTContext &Ctx) const;
2754
2755 /// Returns the WarnUnusedResultAttr that is either declared on the called
2756 /// function, or its return type declaration.
2757 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
2758
2759 /// Returns true if this call expression should warn on unused results.
2760 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
2761 return getUnusedResultAttr(Ctx) != nullptr;
2762 }
2763
2764 SourceLocation getRParenLoc() const { return RParenLoc; }
2765 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2766
2767 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
2768 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
2769
2770 /// Return true if this is a call to __assume() or __builtin_assume() with
2771 /// a non-value-dependent constant parameter evaluating as false.
2772 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2773
2774 bool isCallToStdMove() const {
2775 const FunctionDecl *FD = getDirectCallee();
2776 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2777 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2778 }
2779
2780 static bool classof(const Stmt *T) {
2781 return T->getStmtClass() >= firstCallExprConstant &&
2782 T->getStmtClass() <= lastCallExprConstant;
2783 }
2784
2785 // Iterators
2786 child_range children() {
2787 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
2788 getNumPreArgs() + getNumArgs());
2789 }
2790
2791 const_child_range children() const {
2792 return const_child_range(getTrailingStmts(),
2793 getTrailingStmts() + PREARGS_START +
2794 getNumPreArgs() + getNumArgs());
2795 }
2796};
2797
2798/// Extra data stored in some MemberExpr objects.
2799struct MemberExprNameQualifier {
2800 /// The nested-name-specifier that qualifies the name, including
2801 /// source-location information.
2802 NestedNameSpecifierLoc QualifierLoc;
2803
2804 /// The DeclAccessPair through which the MemberDecl was found due to
2805 /// name qualifiers.
2806 DeclAccessPair FoundDecl;
2807};
2808
2809/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2810///
2811class MemberExpr final
2812 : public Expr,
2813 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2814 ASTTemplateKWAndArgsInfo,
2815 TemplateArgumentLoc> {
2816 friend class ASTReader;
2817 friend class ASTStmtReader;
2818 friend class ASTStmtWriter;
2819 friend TrailingObjects;
2820
2821 /// Base - the expression for the base pointer or structure references. In
2822 /// X.F, this is "X".
2823 Stmt *Base;
2824
2825 /// MemberDecl - This is the decl being referenced by the field/member name.
2826 /// In X.F, this is the decl referenced by F.
2827 ValueDecl *MemberDecl;
2828
2829 /// MemberDNLoc - Provides source/type location info for the
2830 /// declaration name embedded in MemberDecl.
2831 DeclarationNameLoc MemberDNLoc;
2832
2833 /// MemberLoc - This is the location of the member name.
2834 SourceLocation MemberLoc;
2835
2836 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2837 return hasQualifierOrFoundDecl();
2838 }
2839
2840 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2841 return hasTemplateKWAndArgsInfo();
2842 }
2843
2844 bool hasQualifierOrFoundDecl() const {
2845 return MemberExprBits.HasQualifierOrFoundDecl;
2846 }
2847
2848 bool hasTemplateKWAndArgsInfo() const {
2849 return MemberExprBits.HasTemplateKWAndArgsInfo;
2850 }
2851
2852 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
2853 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
2854 QualType T, ExprValueKind VK, ExprObjectKind OK,
2855 NonOdrUseReason NOUR);
2856 MemberExpr(EmptyShell Empty)
2857 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
2858
2859public:
2860 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
2861 SourceLocation OperatorLoc,
2862 NestedNameSpecifierLoc QualifierLoc,
2863 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
2864 DeclAccessPair FoundDecl,
2865 DeclarationNameInfo MemberNameInfo,
2866 const TemplateArgumentListInfo *TemplateArgs,
2867 QualType T, ExprValueKind VK, ExprObjectKind OK,
2868 NonOdrUseReason NOUR);
2869
2870 /// Create an implicit MemberExpr, with no location, qualifier, template
2871 /// arguments, and so on. Suitable only for non-static member access.
2872 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
2873 bool IsArrow, ValueDecl *MemberDecl,
2874 QualType T, ExprValueKind VK,
2875 ExprObjectKind OK) {
2876 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
2877 SourceLocation(), MemberDecl,
2878 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
2879 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
2880 }
2881
2882 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
2883 bool HasFoundDecl,
2884 bool HasTemplateKWAndArgsInfo,
2885 unsigned NumTemplateArgs);
2886
2887 void setBase(Expr *E) { Base = E; }
2888 Expr *getBase() const { return cast<Expr>(Base); }
2889
2890 /// Retrieve the member declaration to which this expression refers.
2891 ///
2892 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2893 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2894 ValueDecl *getMemberDecl() const { return MemberDecl; }
2895 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2896
2897 /// Retrieves the declaration found by lookup.
2898 DeclAccessPair getFoundDecl() const {
2899 if (!hasQualifierOrFoundDecl())
2900 return DeclAccessPair::make(getMemberDecl(),
2901 getMemberDecl()->getAccess());
2902 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2903 }
2904
2905 /// Determines whether this member expression actually had
2906 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2907 /// x->Base::foo.
2908 bool hasQualifier() const { return getQualifier() != nullptr; }
2909
2910 /// If the member name was qualified, retrieves the
2911 /// nested-name-specifier that precedes the member name, with source-location
2912 /// information.
2913 NestedNameSpecifierLoc getQualifierLoc() const {
2914 if (!hasQualifierOrFoundDecl())
2915 return NestedNameSpecifierLoc();
2916 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2917 }
2918
2919 /// If the member name was qualified, retrieves the
2920 /// nested-name-specifier that precedes the member name. Otherwise, returns
2921 /// NULL.
2922 NestedNameSpecifier *getQualifier() const {
2923 return getQualifierLoc().getNestedNameSpecifier();
2924 }
2925
2926 /// Retrieve the location of the template keyword preceding
2927 /// the member name, if any.
2928 SourceLocation getTemplateKeywordLoc() const {
2929 if (!hasTemplateKWAndArgsInfo())
2930 return SourceLocation();
2931 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2932 }
2933
2934 /// Retrieve the location of the left angle bracket starting the
2935 /// explicit template argument list following the member name, if any.
2936 SourceLocation getLAngleLoc() const {
2937 if (!hasTemplateKWAndArgsInfo())
2938 return SourceLocation();
2939 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2940 }
2941
2942 /// Retrieve the location of the right angle bracket ending the
2943 /// explicit template argument list following the member name, if any.
2944 SourceLocation getRAngleLoc() const {
2945 if (!hasTemplateKWAndArgsInfo())
2946 return SourceLocation();
2947 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2948 }
2949
2950 /// Determines whether the member name was preceded by the template keyword.
2951 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2952
2953 /// Determines whether the member name was followed by an
2954 /// explicit template argument list.
2955 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2956
2957 /// Copies the template arguments (if present) into the given
2958 /// structure.
2959 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2960 if (hasExplicitTemplateArgs())
2961 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2962 getTrailingObjects<TemplateArgumentLoc>(), List);
2963 }
2964
2965 /// Retrieve the template arguments provided as part of this
2966 /// template-id.
2967 const TemplateArgumentLoc *getTemplateArgs() const {
2968 if (!hasExplicitTemplateArgs())
2969 return nullptr;
2970
2971 return getTrailingObjects<TemplateArgumentLoc>();
2972 }
2973
2974 /// Retrieve the number of template arguments provided as part of this
2975 /// template-id.
2976 unsigned getNumTemplateArgs() const {
2977 if (!hasExplicitTemplateArgs())
2978 return 0;
2979
2980 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2981 }
2982
2983 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2984 return {getTemplateArgs(), getNumTemplateArgs()};
2985 }
2986
2987 /// Retrieve the member declaration name info.
2988 DeclarationNameInfo getMemberNameInfo() const {
2989 return DeclarationNameInfo(MemberDecl->getDeclName(),
2990 MemberLoc, MemberDNLoc);
2991 }
2992
2993 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
2994
2995 bool isArrow() const { return MemberExprBits.IsArrow; }
2996 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
2997
2998 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2999 /// location of 'F'.
3000 SourceLocation getMemberLoc() const { return MemberLoc; }
3001 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3002
3003 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3004 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
3005
3006 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; }
3007
3008 /// Determine whether the base of this explicit is implicit.
3009 bool isImplicitAccess() const {
3010 return getBase() && getBase()->isImplicitCXXThis();
3011 }
3012
3013 /// Returns true if this member expression refers to a method that
3014 /// was resolved from an overloaded set having size greater than 1.
3015 bool hadMultipleCandidates() const {
3016 return MemberExprBits.HadMultipleCandidates;
3017 }
3018 /// Sets the flag telling whether this expression refers to
3019 /// a method that was resolved from an overloaded set having size
3020 /// greater than 1.
3021 void setHadMultipleCandidates(bool V = true) {
3022 MemberExprBits.HadMultipleCandidates = V;
3023 }
3024
3025 /// Returns true if virtual dispatch is performed.
3026 /// If the member access is fully qualified, (i.e. X::f()), virtual
3027 /// dispatching is not performed. In -fapple-kext mode qualified
3028 /// calls to virtual method will still go through the vtable.
3029 bool performsVirtualDispatch(const LangOptions &LO) const {
3030 return LO.AppleKext || !hasQualifier();
3031 }
3032
3033 /// Is this expression a non-odr-use reference, and if so, why?
3034 /// This is only meaningful if the named member is a static member.
3035 NonOdrUseReason isNonOdrUse() const {
3036 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3037 }
3038
3039 static bool classof(const Stmt *T) {
3040 return T->getStmtClass() == MemberExprClass;
3041 }
3042
3043 // Iterators
3044 child_range children() { return child_range(&Base, &Base+1); }
3045 const_child_range children() const {
3046 return const_child_range(&Base, &Base + 1);
3047 }
3048};
3049
3050/// CompoundLiteralExpr - [C99 6.5.2.5]
3051///
3052class CompoundLiteralExpr : public Expr {
3053 /// LParenLoc - If non-null, this is the location of the left paren in a
3054 /// compound literal like "(int){4}". This can be null if this is a
3055 /// synthesized compound expression.
3056 SourceLocation LParenLoc;
3057
3058 /// The type as written. This can be an incomplete array type, in
3059 /// which case the actual expression type will be different.
3060 /// The int part of the pair stores whether this expr is file scope.
3061 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3062 Stmt *Init;
3063public:
3064 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3065 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3066 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
3067 tinfo->getType()->isDependentType(),
3068 init->isValueDependent(),
3069 (init->isInstantiationDependent() ||
3070 tinfo->getType()->isInstantiationDependentType()),
3071 init->containsUnexpandedParameterPack()),
3072 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
3073
3074 /// Construct an empty compound literal.
3075 explicit CompoundLiteralExpr(EmptyShell Empty)
3076 : Expr(CompoundLiteralExprClass, Empty) { }
3077
3078 const Expr *getInitializer() const { return cast<Expr>(Init); }
3079 Expr *getInitializer() { return cast<Expr>(Init); }
3080 void setInitializer(Expr *E) { Init = E; }
3081
3082 bool isFileScope() const { return TInfoAndScope.getInt(); }
3083 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3084
3085 SourceLocation getLParenLoc() const { return LParenLoc; }
3086 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3087
3088 TypeSourceInfo *getTypeSourceInfo() const {
3089 return TInfoAndScope.getPointer();
3090 }
3091 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3092 TInfoAndScope.setPointer(tinfo);
3093 }
3094
3095 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3096 // FIXME: Init should never be null.
3097 if (!Init)
3098 return SourceLocation();
3099 if (LParenLoc.isInvalid())
3100 return Init->getBeginLoc();
3101 return LParenLoc;
3102 }
3103 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3104 // FIXME: Init should never be null.
3105 if (!Init)
3106 return SourceLocation();
3107 return Init->getEndLoc();
3108 }
3109
3110 static bool classof(const Stmt *T) {
3111 return T->getStmtClass() == CompoundLiteralExprClass;
3112 }
3113
3114 // Iterators
3115 child_range children() { return child_range(&Init, &Init+1); }
3116 const_child_range children() const {
3117 return const_child_range(&Init, &Init + 1);
3118 }
3119};
3120
3121/// CastExpr - Base class for type casts, including both implicit
3122/// casts (ImplicitCastExpr) and explicit casts that have some
3123/// representation in the source code (ExplicitCastExpr's derived
3124/// classes).
3125class CastExpr : public Expr {
3126 Stmt *Op;
3127
3128 bool CastConsistency() const;
3129
3130 const CXXBaseSpecifier * const *path_buffer() const {
3131 return const_cast<CastExpr*>(this)->path_buffer();
3132 }
3133 CXXBaseSpecifier **path_buffer();
3134
3135protected:
3136 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3137 Expr *op, unsigned BasePathSize)
3138 : Expr(SC, ty, VK, OK_Ordinary,
3139 // Cast expressions are type-dependent if the type is
3140 // dependent (C++ [temp.dep.expr]p3).
3141 ty->isDependentType(),
3142 // Cast expressions are value-dependent if the type is
3143 // dependent or if the subexpression is value-dependent.
3144 ty->isDependentType() || (op && op->isValueDependent()),
3145 (ty->isInstantiationDependentType() ||
3146 (op && op->isInstantiationDependent())),
3147 // An implicit cast expression doesn't (lexically) contain an
3148 // unexpanded pack, even if its target type does.
3149 ((SC != ImplicitCastExprClass &&
3150 ty->containsUnexpandedParameterPack()) ||
3151 (op && op->containsUnexpandedParameterPack()))),
3152 Op(op) {
3153 CastExprBits.Kind = kind;
3154 CastExprBits.PartOfExplicitCast = false;
3155 CastExprBits.BasePathSize = BasePathSize;
3156 assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3157, __PRETTY_FUNCTION__))
3157 "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3157, __PRETTY_FUNCTION__))
;
3158 assert(CastConsistency())((CastConsistency()) ? static_cast<void> (0) : __assert_fail
("CastConsistency()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3158, __PRETTY_FUNCTION__))
;
3159 }
3160
3161 /// Construct an empty cast.
3162 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
3163 : Expr(SC, Empty) {
3164 CastExprBits.PartOfExplicitCast = false;
3165 CastExprBits.BasePathSize = BasePathSize;
3166 assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3167, __PRETTY_FUNCTION__))
3167 "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3167, __PRETTY_FUNCTION__))
;
3168 }
3169
3170public:
3171 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3172 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3173
3174 static const char *getCastKindName(CastKind CK);
3175 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3176
3177 Expr *getSubExpr() { return cast<Expr>(Op); }
3178 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3179 void setSubExpr(Expr *E) { Op = E; }
3180
3181 /// Retrieve the cast subexpression as it was written in the source
3182 /// code, looking through any implicit casts or other intermediate nodes
3183 /// introduced by semantic analysis.
3184 Expr *getSubExprAsWritten();
3185 const Expr *getSubExprAsWritten() const {
3186 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3187 }
3188
3189 /// If this cast applies a user-defined conversion, retrieve the conversion
3190 /// function that it invokes.
3191 NamedDecl *getConversionFunction() const;
3192
3193 typedef CXXBaseSpecifier **path_iterator;
3194 typedef const CXXBaseSpecifier *const *path_const_iterator;
3195 bool path_empty() const { return path_size() == 0; }
3196 unsigned path_size() const { return CastExprBits.BasePathSize; }
3197 path_iterator path_begin() { return path_buffer(); }
3198 path_iterator path_end() { return path_buffer() + path_size(); }
3199 path_const_iterator path_begin() const { return path_buffer(); }
3200 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3201
3202 llvm::iterator_range<path_iterator> path() {
3203 return llvm::make_range(path_begin(), path_end());
3204 }
3205 llvm::iterator_range<path_const_iterator> path() const {
3206 return llvm::make_range(path_begin(), path_end());
3207 }
3208
3209 const FieldDecl *getTargetUnionField() const {
3210 assert(getCastKind() == CK_ToUnion)((getCastKind() == CK_ToUnion) ? static_cast<void> (0) :
__assert_fail ("getCastKind() == CK_ToUnion", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3210, __PRETTY_FUNCTION__))
;
3211 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3212 }
3213
3214 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3215 QualType opType);
3216 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3217 QualType opType);
3218
3219 static bool classof(const Stmt *T) {
3220 return T->getStmtClass() >= firstCastExprConstant &&
3221 T->getStmtClass() <= lastCastExprConstant;
3222 }
3223
3224 // Iterators
3225 child_range children() { return child_range(&Op, &Op+1); }
3226 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3227};
3228
3229/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3230/// conversions, which have no direct representation in the original
3231/// source code. For example: converting T[]->T*, void f()->void
3232/// (*f)(), float->double, short->int, etc.
3233///
3234/// In C, implicit casts always produce rvalues. However, in C++, an
3235/// implicit cast whose result is being bound to a reference will be
3236/// an lvalue or xvalue. For example:
3237///
3238/// @code
3239/// class Base { };
3240/// class Derived : public Base { };
3241/// Derived &&ref();
3242/// void f(Derived d) {
3243/// Base& b = d; // initializer is an ImplicitCastExpr
3244/// // to an lvalue of type Base
3245/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3246/// // to an xvalue of type Base
3247/// }
3248/// @endcode
3249class ImplicitCastExpr final
3250 : public CastExpr,
3251 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
3252
3253 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3254 unsigned BasePathLength, ExprValueKind VK)
3255 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { }
3256
3257 /// Construct an empty implicit cast.
3258 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
3259 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
3260
3261public:
3262 enum OnStack_t { OnStack };
3263 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3264 ExprValueKind VK)
3265 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
3266 }
3267
3268 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3269 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3270 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3271 }
3272
3273 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3274 CastKind Kind, Expr *Operand,
3275 const CXXCastPath *BasePath,
3276 ExprValueKind Cat);
3277
3278 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3279 unsigned PathSize);
3280
3281 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3282 return getSubExpr()->getBeginLoc();
3283 }
3284 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3285 return getSubExpr()->getEndLoc();
3286 }
3287
3288 static bool classof(const Stmt *T) {
3289 return T->getStmtClass() == ImplicitCastExprClass;
3290 }
3291
3292 friend TrailingObjects;
3293 friend class CastExpr;
3294};
3295
3296/// ExplicitCastExpr - An explicit cast written in the source
3297/// code.
3298///
3299/// This class is effectively an abstract class, because it provides
3300/// the basic representation of an explicitly-written cast without
3301/// specifying which kind of cast (C cast, functional cast, static
3302/// cast, etc.) was written; specific derived classes represent the
3303/// particular style of cast and its location information.
3304///
3305/// Unlike implicit casts, explicit cast nodes have two different
3306/// types: the type that was written into the source code, and the
3307/// actual type of the expression as determined by semantic
3308/// analysis. These types may differ slightly. For example, in C++ one
3309/// can cast to a reference type, which indicates that the resulting
3310/// expression will be an lvalue or xvalue. The reference type, however,
3311/// will not be used as the type of the expression.
3312class ExplicitCastExpr : public CastExpr {
3313 /// TInfo - Source type info for the (written) type
3314 /// this expression is casting to.
3315 TypeSourceInfo *TInfo;
3316
3317protected:
3318 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3319 CastKind kind, Expr *op, unsigned PathSize,
3320 TypeSourceInfo *writtenTy)
3321 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
3322
3323 /// Construct an empty explicit cast.
3324 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
3325 : CastExpr(SC, Shell, PathSize) { }
3326
3327public:
3328 /// getTypeInfoAsWritten - Returns the type source info for the type
3329 /// that this expression is casting to.
3330 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3331 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3332
3333 /// getTypeAsWritten - Returns the type that this expression is
3334 /// casting to, as written in the source code.
3335 QualType getTypeAsWritten() const { return TInfo->getType(); }
3336
3337 static bool classof(const Stmt *T) {
3338 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3339 T->getStmtClass() <= lastExplicitCastExprConstant;
3340 }
3341};
3342
3343/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3344/// cast in C++ (C++ [expr.cast]), which uses the syntax
3345/// (Type)expr. For example: @c (int)f.
3346class CStyleCastExpr final
3347 : public ExplicitCastExpr,
3348 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
3349 SourceLocation LPLoc; // the location of the left paren
3350 SourceLocation RPLoc; // the location of the right paren
3351
3352 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3353 unsigned PathSize, TypeSourceInfo *writtenTy,
3354 SourceLocation l, SourceLocation r)
3355 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3356 writtenTy), LPLoc(l), RPLoc(r) {}
3357
3358 /// Construct an empty C-style explicit cast.
3359 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3360 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3361
3362public:
3363 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3364 ExprValueKind VK, CastKind K,
3365 Expr *Op, const CXXCastPath *BasePath,
3366 TypeSourceInfo *WrittenTy, SourceLocation L,
3367 SourceLocation R);
3368
3369 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3370 unsigned PathSize);
3371
3372 SourceLocation getLParenLoc() const { return LPLoc; }
3373 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3374
3375 SourceLocation getRParenLoc() const { return RPLoc; }
3376 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3377
3378 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; }
3379 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3380 return getSubExpr()->getEndLoc();
3381 }
3382
3383 static bool classof(const Stmt *T) {
3384 return T->getStmtClass() == CStyleCastExprClass;
3385 }
3386
3387 friend TrailingObjects;
3388 friend class CastExpr;
3389};
3390
3391/// A builtin binary operation expression such as "x + y" or "x <= y".
3392///
3393/// This expression node kind describes a builtin binary operation,
3394/// such as "x + y" for integer values "x" and "y". The operands will
3395/// already have been converted to appropriate types (e.g., by
3396/// performing promotions or conversions).
3397///
3398/// In C++, where operators may be overloaded, a different kind of
3399/// expression node (CXXOperatorCallExpr) is used to express the
3400/// invocation of an overloaded operator with operator syntax. Within
3401/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3402/// used to store an expression "x + y" depends on the subexpressions
3403/// for x and y. If neither x or y is type-dependent, and the "+"
3404/// operator resolves to a built-in operation, BinaryOperator will be
3405/// used to express the computation (x and y may still be
3406/// value-dependent). If either x or y is type-dependent, or if the
3407/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3408/// be used to express the computation.
3409class BinaryOperator : public Expr {
3410 enum { LHS, RHS, END_EXPR };
3411 Stmt *SubExprs[END_EXPR];
3412
3413public:
3414 typedef BinaryOperatorKind Opcode;
3415
3416 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3417 ExprValueKind VK, ExprObjectKind OK,
3418 SourceLocation opLoc, FPOptions FPFeatures)
3419 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3420 lhs->isTypeDependent() || rhs->isTypeDependent(),
3421 lhs->isValueDependent() || rhs->isValueDependent(),
3422 (lhs->isInstantiationDependent() ||
3423 rhs->isInstantiationDependent()),
3424 (lhs->containsUnexpandedParameterPack() ||
3425 rhs->containsUnexpandedParameterPack())) {
3426 BinaryOperatorBits.Opc = opc;
3427 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3428 BinaryOperatorBits.OpLoc = opLoc;
3429 SubExprs[LHS] = lhs;
3430 SubExprs[RHS] = rhs;
3431 assert(!isCompoundAssignmentOp() &&((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3432, __PRETTY_FUNCTION__))
3432 "Use CompoundAssignOperator for compound assignments")((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3432, __PRETTY_FUNCTION__))
;
3433 }
3434
3435 /// Construct an empty binary operator.
3436 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3437 BinaryOperatorBits.Opc = BO_Comma;
3438 }
3439
3440 SourceLocation getExprLoc() const { return getOperatorLoc(); }
3441 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3442 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3443
3444 Opcode getOpcode() const {
3445 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3446 }
3447 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3448
3449 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3450 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3451 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3452 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3453
3454 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3455 return getLHS()->getBeginLoc();
3456 }
3457 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3458 return getRHS()->getEndLoc();
3459 }
3460
3461 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3462 /// corresponds to, e.g. "<<=".
3463 static StringRef getOpcodeStr(Opcode Op);
3464
3465 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3466
3467 /// Retrieve the binary opcode that corresponds to the given
3468 /// overloaded operator.
3469 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3470
3471 /// Retrieve the overloaded operator kind that corresponds to
3472 /// the given binary opcode.
3473 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3474
3475 /// predicates to categorize the respective opcodes.
3476 static bool isPtrMemOp(Opcode Opc) {
3477 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3478 }
3479 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3480
3481 static bool isMultiplicativeOp(Opcode Opc) {
3482 return Opc >= BO_Mul && Opc <= BO_Rem;
3483 }
3484 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3485 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3486 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3487 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3488 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3489
3490 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3491 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3492
3493 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3494 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3495
3496 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3497 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3498
3499 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3500 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3501
3502 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3503 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3504
3505 static Opcode negateComparisonOp(Opcode Opc) {
3506 switch (Opc) {
3507 default:
3508 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3508)
;
3509 case BO_LT: return BO_GE;
3510 case BO_GT: return BO_LE;
3511 case BO_LE: return BO_GT;
3512 case BO_GE: return BO_LT;
3513 case BO_EQ: return BO_NE;
3514 case BO_NE: return BO_EQ;
3515 }
3516 }
3517
3518 static Opcode reverseComparisonOp(Opcode Opc) {
3519 switch (Opc) {
3520 default:
3521 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3521)
;
3522 case BO_LT: return BO_GT;
3523 case BO_GT: return BO_LT;
3524 case BO_LE: return BO_GE;
3525 case BO_GE: return BO_LE;
3526 case BO_EQ:
3527 case BO_NE:
3528 return Opc;
3529 }
3530 }
3531
3532 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3533 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3534
3535 static bool isAssignmentOp(Opcode Opc) {
3536 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3537 }
3538 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3539
3540 static bool isCompoundAssignmentOp(Opcode Opc) {
3541 return Opc > BO_Assign && Opc <= BO_OrAssign;
3542 }
3543 bool isCompoundAssignmentOp() const {
3544 return isCompoundAssignmentOp(getOpcode());
3545 }
3546 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3547 assert(isCompoundAssignmentOp(Opc))((isCompoundAssignmentOp(Opc)) ? static_cast<void> (0) :
__assert_fail ("isCompoundAssignmentOp(Opc)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3547, __PRETTY_FUNCTION__))
;
3548 if (Opc >= BO_AndAssign)
3549 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3550 else
3551 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3552 }
3553
3554 static bool isShiftAssignOp(Opcode Opc) {
3555 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3556 }
3557 bool isShiftAssignOp() const {
3558 return isShiftAssignOp(getOpcode());
3559 }
3560
3561 // Return true if a binary operator using the specified opcode and operands
3562 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3563 // integer to a pointer.
3564 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3565 Expr *LHS, Expr *RHS);
3566
3567 static bool classof(const Stmt *S) {
3568 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3569 S->getStmtClass() <= lastBinaryOperatorConstant;
3570 }
3571
3572 // Iterators
3573 child_range children() {
3574 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3575 }
3576 const_child_range children() const {
3577 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3578 }
3579
3580 // Set the FP contractability status of this operator. Only meaningful for
3581 // operations on floating point types.
3582 void setFPFeatures(FPOptions F) {
3583 BinaryOperatorBits.FPFeatures = F.getInt();
3584 }
3585
3586 FPOptions getFPFeatures() const {
3587 return FPOptions(BinaryOperatorBits.FPFeatures);
3588 }
3589
3590 // Get the FP contractability status of this operator. Only meaningful for
3591 // operations on floating point types.
3592 bool isFPContractableWithinStatement() const {
3593 return getFPFeatures().allowFPContractWithinStatement();
3594 }
3595
3596 // Get the FENV_ACCESS status of this operator. Only meaningful for
3597 // operations on floating point types.
3598 bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); }
3599
3600protected:
3601 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3602 ExprValueKind VK, ExprObjectKind OK,
3603 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3604 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3605 lhs->isTypeDependent() || rhs->isTypeDependent(),
3606 lhs->isValueDependent() || rhs->isValueDependent(),
3607 (lhs->isInstantiationDependent() ||
3608 rhs->isInstantiationDependent()),
3609 (lhs->containsUnexpandedParameterPack() ||
3610 rhs->containsUnexpandedParameterPack())) {
3611 BinaryOperatorBits.Opc = opc;
3612 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3613 BinaryOperatorBits.OpLoc = opLoc;
3614 SubExprs[LHS] = lhs;
3615 SubExprs[RHS] = rhs;
3616 }
3617
3618 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
3619 BinaryOperatorBits.Opc = BO_MulAssign;
3620 }
3621};
3622
3623/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3624/// track of the type the operation is performed in. Due to the semantics of
3625/// these operators, the operands are promoted, the arithmetic performed, an
3626/// implicit conversion back to the result type done, then the assignment takes
3627/// place. This captures the intermediate type which the computation is done
3628/// in.
3629class CompoundAssignOperator : public BinaryOperator {
3630 QualType ComputationLHSType;
3631 QualType ComputationResultType;
3632public:
3633 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3634 ExprValueKind VK, ExprObjectKind OK,
3635 QualType CompLHSType, QualType CompResultType,
3636 SourceLocation OpLoc, FPOptions FPFeatures)
3637 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3638 true),
3639 ComputationLHSType(CompLHSType),
3640 ComputationResultType(CompResultType) {
3641 assert(isCompoundAssignmentOp() &&((isCompoundAssignmentOp() && "Only should be used for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3642, __PRETTY_FUNCTION__))
3642 "Only should be used for compound assignments")((isCompoundAssignmentOp() && "Only should be used for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3642, __PRETTY_FUNCTION__))
;
3643 }
3644
3645 /// Build an empty compound assignment operator expression.
3646 explicit CompoundAssignOperator(EmptyShell Empty)
3647 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3648
3649 // The two computation types are the type the LHS is converted
3650 // to for the computation and the type of the result; the two are
3651 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3652 QualType getComputationLHSType() const { return ComputationLHSType; }
3653 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3654
3655 QualType getComputationResultType() const { return ComputationResultType; }
3656 void setComputationResultType(QualType T) { ComputationResultType = T; }
3657
3658 static bool classof(const Stmt *S) {
3659 return S->getStmtClass() == CompoundAssignOperatorClass;
3660 }
3661};
3662
3663/// AbstractConditionalOperator - An abstract base class for
3664/// ConditionalOperator and BinaryConditionalOperator.
3665class AbstractConditionalOperator : public Expr {
3666 SourceLocation QuestionLoc, ColonLoc;
3667 friend class ASTStmtReader;
3668
3669protected:
3670 AbstractConditionalOperator(StmtClass SC, QualType T,
3671 ExprValueKind VK, ExprObjectKind OK,
3672 bool TD, bool VD, bool ID,
3673 bool ContainsUnexpandedParameterPack,
3674 SourceLocation qloc,
3675 SourceLocation cloc)
3676 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3677 QuestionLoc(qloc), ColonLoc(cloc) {}
3678
3679 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3680 : Expr(SC, Empty) { }
3681
3682public:
3683 // getCond - Return the expression representing the condition for
3684 // the ?: operator.
3685 Expr *getCond() const;
3686
3687 // getTrueExpr - Return the subexpression representing the value of
3688 // the expression if the condition evaluates to true.
3689 Expr *getTrueExpr() const;
3690
3691 // getFalseExpr - Return the subexpression representing the value of
3692 // the expression if the condition evaluates to false. This is
3693 // the same as getRHS.
3694 Expr *getFalseExpr() const;
3695
3696 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3697 SourceLocation getColonLoc() const { return ColonLoc; }
3698
3699 static bool classof(const Stmt *T) {
3700 return T->getStmtClass() == ConditionalOperatorClass ||
3701 T->getStmtClass() == BinaryConditionalOperatorClass;
3702 }
3703};
3704
3705/// ConditionalOperator - The ?: ternary operator. The GNU "missing
3706/// middle" extension is a BinaryConditionalOperator.
3707class ConditionalOperator : public AbstractConditionalOperator {
3708 enum { COND, LHS, RHS, END_EXPR };
3709 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3710
3711 friend class ASTStmtReader;
3712public:
3713 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3714 SourceLocation CLoc, Expr *rhs,
3715 QualType t, ExprValueKind VK, ExprObjectKind OK)
3716 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3717 // FIXME: the type of the conditional operator doesn't
3718 // depend on the type of the conditional, but the standard
3719 // seems to imply that it could. File a bug!
3720 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3721 (cond->isValueDependent() || lhs->isValueDependent() ||
3722 rhs->isValueDependent()),
3723 (cond->isInstantiationDependent() ||
3724 lhs->isInstantiationDependent() ||
3725 rhs->isInstantiationDependent()),
3726 (cond->containsUnexpandedParameterPack() ||
3727 lhs->containsUnexpandedParameterPack() ||
3728 rhs->containsUnexpandedParameterPack()),
3729 QLoc, CLoc) {
3730 SubExprs[COND] = cond;
3731 SubExprs[LHS] = lhs;
3732 SubExprs[RHS] = rhs;
3733 }
3734
3735 /// Build an empty conditional operator.
3736 explicit ConditionalOperator(EmptyShell Empty)
3737 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3738
3739 // getCond - Return the expression representing the condition for
3740 // the ?: operator.
3741 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3742
3743 // getTrueExpr - Return the subexpression representing the value of
3744 // the expression if the condition evaluates to true.
3745 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3746
3747 // getFalseExpr - Return the subexpression representing the value of
3748 // the expression if the condition evaluates to false. This is
3749 // the same as getRHS.
3750 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3751
3752 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3753 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3754
3755 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3756 return getCond()->getBeginLoc();
3757 }
3758 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3759 return getRHS()->getEndLoc();
3760 }
3761
3762 static bool classof(const Stmt *T) {
3763 return T->getStmtClass() == ConditionalOperatorClass;
3764 }
3765
3766 // Iterators
3767 child_range children() {
3768 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3769 }
3770 const_child_range children() const {
3771 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3772 }
3773};
3774
3775/// BinaryConditionalOperator - The GNU extension to the conditional
3776/// operator which allows the middle operand to be omitted.
3777///
3778/// This is a different expression kind on the assumption that almost
3779/// every client ends up needing to know that these are different.
3780class BinaryConditionalOperator : public AbstractConditionalOperator {
3781 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3782
3783 /// - the common condition/left-hand-side expression, which will be
3784 /// evaluated as the opaque value
3785 /// - the condition, expressed in terms of the opaque value
3786 /// - the left-hand-side, expressed in terms of the opaque value
3787 /// - the right-hand-side
3788 Stmt *SubExprs[NUM_SUBEXPRS];
3789 OpaqueValueExpr *OpaqueValue;
3790
3791 friend class ASTStmtReader;
3792public:
3793 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3794 Expr *cond, Expr *lhs, Expr *rhs,
3795 SourceLocation qloc, SourceLocation cloc,
3796 QualType t, ExprValueKind VK, ExprObjectKind OK)
3797 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3798 (common->isTypeDependent() || rhs->isTypeDependent()),
3799 (common->isValueDependent() || rhs->isValueDependent()),
3800 (common->isInstantiationDependent() ||
3801 rhs->isInstantiationDependent()),
3802 (common->containsUnexpandedParameterPack() ||
3803 rhs->containsUnexpandedParameterPack()),
3804 qloc, cloc),
3805 OpaqueValue(opaqueValue) {
3806 SubExprs[COMMON] = common;
3807 SubExprs[COND] = cond;
3808 SubExprs[LHS] = lhs;
3809 SubExprs[RHS] = rhs;
3810 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")((OpaqueValue->getSourceExpr() == common && "Wrong opaque value"
) ? static_cast<void> (0) : __assert_fail ("OpaqueValue->getSourceExpr() == common && \"Wrong opaque value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3810, __PRETTY_FUNCTION__))
;
3811 }
3812
3813 /// Build an empty conditional operator.
3814 explicit BinaryConditionalOperator(EmptyShell Empty)
3815 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3816
3817 /// getCommon - Return the common expression, written to the
3818 /// left of the condition. The opaque value will be bound to the
3819 /// result of this expression.
3820 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3821
3822 /// getOpaqueValue - Return the opaque value placeholder.
3823 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3824
3825 /// getCond - Return the condition expression; this is defined
3826 /// in terms of the opaque value.
3827 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3828
3829 /// getTrueExpr - Return the subexpression which will be
3830 /// evaluated if the condition evaluates to true; this is defined
3831 /// in terms of the opaque value.
3832 Expr *getTrueExpr() const {
3833 return cast<Expr>(SubExprs[LHS]);
3834 }
3835
3836 /// getFalseExpr - Return the subexpression which will be
3837 /// evaluated if the condnition evaluates to false; this is
3838 /// defined in terms of the opaque value.
3839 Expr *getFalseExpr() const {
3840 return cast<Expr>(SubExprs[RHS]);
3841 }
3842
3843 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3844 return getCommon()->getBeginLoc();
3845 }
3846 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3847 return getFalseExpr()->getEndLoc();
3848 }
3849
3850 static bool classof(const Stmt *T) {
3851 return T->getStmtClass() == BinaryConditionalOperatorClass;
3852 }
3853
3854 // Iterators
3855 child_range children() {
3856 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3857 }
3858 const_child_range children() const {
3859 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3860 }
3861};
3862
3863inline Expr *AbstractConditionalOperator::getCond() const {
3864 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3865 return co->getCond();
3866 return cast<BinaryConditionalOperator>(this)->getCond();
3867}
3868
3869inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3870 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3871 return co->getTrueExpr();
3872 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3873}
3874
3875inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3876 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3877 return co->getFalseExpr();
3878 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3879}
3880
3881/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3882class AddrLabelExpr : public Expr {
3883 SourceLocation AmpAmpLoc, LabelLoc;
3884 LabelDecl *Label;
3885public:
3886 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3887 QualType t)
3888 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3889 false),
3890 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3891
3892 /// Build an empty address of a label expression.
3893 explicit AddrLabelExpr(EmptyShell Empty)
3894 : Expr(AddrLabelExprClass, Empty) { }
3895
3896 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3897 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3898 SourceLocation getLabelLoc() const { return LabelLoc; }
3899 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3900
3901 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AmpAmpLoc; }
3902 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return LabelLoc; }
3903
3904 LabelDecl *getLabel() const { return Label; }
3905 void setLabel(LabelDecl *L) { Label = L; }
3906
3907 static bool classof(const Stmt *T) {
3908 return T->getStmtClass() == AddrLabelExprClass;
3909 }
3910
3911 // Iterators
3912 child_range children() {
3913 return child_range(child_iterator(), child_iterator());
3914 }
3915 const_child_range children() const {
3916 return const_child_range(const_child_iterator(), const_child_iterator());
3917 }
3918};
3919
3920/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3921/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3922/// takes the value of the last subexpression.
3923///
3924/// A StmtExpr is always an r-value; values "returned" out of a
3925/// StmtExpr will be copied.
3926class StmtExpr : public Expr {
3927 Stmt *SubStmt;
3928 SourceLocation LParenLoc, RParenLoc;
3929public:
3930 // FIXME: Does type-dependence need to be computed differently?
3931 // FIXME: Do we need to compute instantiation instantiation-dependence for
3932 // statements? (ugh!)
3933 StmtExpr(CompoundStmt *substmt, QualType T,
3934 SourceLocation lp, SourceLocation rp) :
3935 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3936 T->isDependentType(), false, false, false),
3937 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3938
3939 /// Build an empty statement expression.
3940 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3941
3942 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3943 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3944 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3945
3946 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; }
3947 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3948
3949 SourceLocation getLParenLoc() const { return LParenLoc; }
3950 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3951 SourceLocation getRParenLoc() const { return RParenLoc; }
3952 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3953
3954 static bool classof(const Stmt *T) {
3955 return T->getStmtClass() == StmtExprClass;
3956 }
3957
3958 // Iterators
3959 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3960 const_child_range children() const {
3961 return const_child_range(&SubStmt, &SubStmt + 1);
3962 }
3963};
3964
3965/// ShuffleVectorExpr - clang-specific builtin-in function
3966/// __builtin_shufflevector.
3967/// This AST node represents a operator that does a constant
3968/// shuffle, similar to LLVM's shufflevector instruction. It takes
3969/// two vectors and a variable number of constant indices,
3970/// and returns the appropriately shuffled vector.
3971class ShuffleVectorExpr : public Expr {
3972 SourceLocation BuiltinLoc, RParenLoc;
3973
3974 // SubExprs - the list of values passed to the __builtin_shufflevector
3975 // function. The first two are vectors, and the rest are constant
3976 // indices. The number of values in this list is always
3977 // 2+the number of indices in the vector type.
3978 Stmt **SubExprs;
3979 unsigned NumExprs;
3980
3981public:
3982 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3983 SourceLocation BLoc, SourceLocation RP);
3984
3985 /// Build an empty vector-shuffle expression.
3986 explicit ShuffleVectorExpr(EmptyShell Empty)
3987 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3988
3989 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3990 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3991
3992 SourceLocation getRParenLoc() const { return RParenLoc; }
3993 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3994
3995 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
3996 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
3997
3998 static bool classof(const Stmt *T) {
3999 return T->getStmtClass() == ShuffleVectorExprClass;
4000 }
4001
4002 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4003 /// constant expression, the actual arguments passed in, and the function
4004 /// pointers.
4005 unsigned getNumSubExprs() const { return NumExprs; }
4006
4007 /// Retrieve the array of expressions.
4008 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4009
4010 /// getExpr - Return the Expr at the specified index.
4011 Expr *getExpr(unsigned Index) {
4012 assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4012, __PRETTY_FUNCTION__))
;
4013 return cast<Expr>(SubExprs[Index]);
4014 }
4015 const Expr *getExpr(unsigned Index) const {
4016 assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4016, __PRETTY_FUNCTION__))
;
4017 return cast<Expr>(SubExprs[Index]);
4018 }
4019
4020 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4021
4022 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4023 assert((N < NumExprs - 2) && "Shuffle idx out of range!")(((N < NumExprs - 2) && "Shuffle idx out of range!"
) ? static_cast<void> (0) : __assert_fail ("(N < NumExprs - 2) && \"Shuffle idx out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4023, __PRETTY_FUNCTION__))
;
4024 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4025 }
4026
4027 // Iterators
4028 child_range children() {
4029 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4030 }
4031 const_child_range children() const {
4032 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4033 }
4034};
4035
4036/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4037/// This AST node provides support for converting a vector type to another
4038/// vector type of the same arity.
4039class ConvertVectorExpr : public Expr {
4040private:
4041 Stmt *SrcExpr;
4042 TypeSourceInfo *TInfo;
4043 SourceLocation BuiltinLoc, RParenLoc;
4044
4045 friend class ASTReader;
4046 friend class ASTStmtReader;
4047 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4048
4049public:
4050 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
4051 ExprValueKind VK, ExprObjectKind OK,
4052 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4053 : Expr(ConvertVectorExprClass, DstType, VK, OK,
4054 DstType->isDependentType(),
4055 DstType->isDependentType() || SrcExpr->isValueDependent(),
4056 (DstType->isInstantiationDependentType() ||
4057 SrcExpr->isInstantiationDependent()),
4058 (DstType->containsUnexpandedParameterPack() ||
4059 SrcExpr->containsUnexpandedParameterPack())),
4060 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4061
4062 /// getSrcExpr - Return the Expr to be converted.
4063 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4064
4065 /// getTypeSourceInfo - Return the destination type.
4066 TypeSourceInfo *getTypeSourceInfo() const {
4067 return TInfo;
4068 }
4069 void setTypeSourceInfo(TypeSourceInfo *ti) {
4070 TInfo = ti;
4071 }
4072
4073 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4074 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4075
4076 /// getRParenLoc - Return the location of final right parenthesis.
4077 SourceLocation getRParenLoc() const { return RParenLoc; }
4078
4079 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4080 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4081
4082 static bool classof(const Stmt *T) {
4083 return T->getStmtClass() == ConvertVectorExprClass;
4084 }
4085
4086 // Iterators
4087 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4088 const_child_range children() const {
4089 return const_child_range(&SrcExpr, &SrcExpr + 1);
4090 }
4091};
4092
4093/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4094/// This AST node is similar to the conditional operator (?:) in C, with
4095/// the following exceptions:
4096/// - the test expression must be a integer constant expression.
4097/// - the expression returned acts like the chosen subexpression in every
4098/// visible way: the type is the same as that of the chosen subexpression,
4099/// and all predicates (whether it's an l-value, whether it's an integer
4100/// constant expression, etc.) return the same result as for the chosen
4101/// sub-expression.
4102class ChooseExpr : public Expr {
4103 enum { COND, LHS, RHS, END_EXPR };
4104 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4105 SourceLocation BuiltinLoc, RParenLoc;
4106 bool CondIsTrue;
4107public:
4108 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
4109 QualType t, ExprValueKind VK, ExprObjectKind OK,
4110 SourceLocation RP, bool condIsTrue,
4111 bool TypeDependent, bool ValueDependent)
4112 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
4113 (cond->isInstantiationDependent() ||
4114 lhs->isInstantiationDependent() ||
4115 rhs->isInstantiationDependent()),
4116 (cond->containsUnexpandedParameterPack() ||
4117 lhs->containsUnexpandedParameterPack() ||
4118 rhs->containsUnexpandedParameterPack())),
4119 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
4120 SubExprs[COND] = cond;
4121 SubExprs[LHS] = lhs;
4122 SubExprs[RHS] = rhs;
4123 }
4124
4125 /// Build an empty __builtin_choose_expr.
4126 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4127
4128 /// isConditionTrue - Return whether the condition is true (i.e. not
4129 /// equal to zero).
4130 bool isConditionTrue() const {
4131 assert(!isConditionDependent() &&((!isConditionDependent() && "Dependent condition isn't true or false"
) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4132, __PRETTY_FUNCTION__))
4132 "Dependent condition isn't true or false")((!isConditionDependent() && "Dependent condition isn't true or false"
) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 return CondIsTrue;
4134 }
4135 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4136
4137 bool isConditionDependent() const {
4138 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4139 }
4140
4141 /// getChosenSubExpr - Return the subexpression chosen according to the
4142 /// condition.
4143 Expr *getChosenSubExpr() const {
4144 return isConditionTrue() ? getLHS() : getRHS();
4145 }
4146
4147 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4148 void setCond(Expr *E) { SubExprs[COND] = E; }
4149 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4150 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4151 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4152 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4153
4154 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4155 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4156
4157 SourceLocation getRParenLoc() const { return RParenLoc; }
4158 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4159
4160 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4161 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4162
4163 static bool classof(const Stmt *T) {
4164 return T->getStmtClass() == ChooseExprClass;
4165 }
4166
4167 // Iterators
4168 child_range children() {
4169 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4170 }
4171 const_child_range children() const {
4172 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4173 }
4174};
4175
4176/// GNUNullExpr - Implements the GNU __null extension, which is a name
4177/// for a null pointer constant that has integral type (e.g., int or
4178/// long) and is the same size and alignment as a pointer. The __null
4179/// extension is typically only used by system headers, which define
4180/// NULL as __null in C++ rather than using 0 (which is an integer
4181/// that may not match the size of a pointer).
4182class GNUNullExpr : public Expr {
4183 /// TokenLoc - The location of the __null keyword.
4184 SourceLocation TokenLoc;
4185
4186public:
4187 GNUNullExpr(QualType Ty, SourceLocation Loc)
4188 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
4189 false),
4190 TokenLoc(Loc) { }
4191
4192 /// Build an empty GNU __null expression.
4193 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4194
4195 /// getTokenLocation - The location of the __null token.
4196 SourceLocation getTokenLocation() const { return TokenLoc; }
4197 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4198
4199 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
4200 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; }
4201
4202 static bool classof(const Stmt *T) {
4203 return T->getStmtClass() == GNUNullExprClass;
4204 }
4205
4206 // Iterators
4207 child_range children() {
4208 return child_range(child_iterator(), child_iterator());
4209 }
4210 const_child_range children() const {
4211 return const_child_range(const_child_iterator(), const_child_iterator());
4212 }
4213};
4214
4215/// Represents a call to the builtin function \c __builtin_va_arg.
4216class VAArgExpr : public Expr {
4217 Stmt *Val;
4218 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4219 SourceLocation BuiltinLoc, RParenLoc;
4220public:
4221 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4222 SourceLocation RPLoc, QualType t, bool IsMS)
4223 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
4224 false, (TInfo->getType()->isInstantiationDependentType() ||
4225 e->isInstantiationDependent()),
4226 (TInfo->getType()->containsUnexpandedParameterPack() ||
4227 e->containsUnexpandedParameterPack())),
4228 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
4229
4230 /// Create an empty __builtin_va_arg expression.
4231 explicit VAArgExpr(EmptyShell Empty)
4232 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4233
4234 const Expr *getSubExpr() const { return cast<Expr>(Val); }
4235 Expr *getSubExpr() { return cast<Expr>(Val); }
4236 void setSubExpr(Expr *E) { Val = E; }
4237
4238 /// Returns whether this is really a Win64 ABI va_arg expression.
4239 bool isMicrosoftABI() const { return TInfo.getInt(); }
4240 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4241
4242 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4243 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4244
4245 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4246 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4247
4248 SourceLocation getRParenLoc() const { return RParenLoc; }
4249 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4250
4251 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
4252 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4253
4254 static bool classof(const Stmt *T) {
4255 return T->getStmtClass() == VAArgExprClass;
4256 }
4257
4258 // Iterators
4259 child_range children() { return child_range(&Val, &Val+1); }
4260 const_child_range children() const {
4261 return const_child_range(&Val, &Val + 1);
4262 }
4263};
4264
4265/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4266/// __builtin_FUNCTION(), or __builtin_FILE().
4267class SourceLocExpr final : public Expr {
4268 SourceLocation BuiltinLoc, RParenLoc;
4269 DeclContext *ParentContext;
4270
4271public:
4272 enum IdentKind { Function, File, Line, Column };
4273
4274 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
4275 SourceLocation RParenLoc, DeclContext *Context);
4276
4277 /// Build an empty call expression.
4278 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4279
4280 /// Return the result of evaluating this SourceLocExpr in the specified
4281 /// (and possibly null) default argument or initialization context.
4282 APValue EvaluateInContext(const ASTContext &Ctx,
4283 const Expr *DefaultExpr) const;
4284
4285 /// Return a string representing the name of the specific builtin function.
4286 StringRef getBuiltinStr() const;
4287
4288 IdentKind getIdentKind() const {
4289 return static_cast<IdentKind>(SourceLocExprBits.Kind);
4290 }
4291
4292 bool isStringType() const {
4293 switch (getIdentKind()) {
4294 case File:
4295 case Function:
4296 return true;
4297 case Line:
4298 case Column:
4299 return false;
4300 }
4301 llvm_unreachable("unknown source location expression kind")::llvm::llvm_unreachable_internal("unknown source location expression kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4301)
;
4302 }
4303 bool isIntType() const LLVM_READONLY__attribute__((__pure__)) { return !isStringType(); }
4304
4305 /// If the SourceLocExpr has been resolved return the subexpression
4306 /// representing the resolved value. Otherwise return null.
4307 const DeclContext *getParentContext() const { return ParentContext; }
4308 DeclContext *getParentContext() { return ParentContext; }
4309
4310 SourceLocation getLocation() const { return BuiltinLoc; }
4311 SourceLocation getBeginLoc() const { return BuiltinLoc; }
4312 SourceLocation getEndLoc() const { return RParenLoc; }
4313
4314 child_range children() {
4315 return child_range(child_iterator(), child_iterator());
4316 }
4317
4318 const_child_range children() const {
4319 return const_child_range(child_iterator(), child_iterator());
4320 }
4321
4322 static bool classof(const Stmt *T) {
4323 return T->getStmtClass() == SourceLocExprClass;
4324 }
4325
4326private:
4327 friend class ASTStmtReader;
4328};
4329
4330/// Describes an C or C++ initializer list.
4331///
4332/// InitListExpr describes an initializer list, which can be used to
4333/// initialize objects of different types, including
4334/// struct/class/union types, arrays, and vectors. For example:
4335///
4336/// @code
4337/// struct foo x = { 1, { 2, 3 } };
4338/// @endcode
4339///
4340/// Prior to semantic analysis, an initializer list will represent the
4341/// initializer list as written by the user, but will have the
4342/// placeholder type "void". This initializer list is called the
4343/// syntactic form of the initializer, and may contain C99 designated
4344/// initializers (represented as DesignatedInitExprs), initializations
4345/// of subobject members without explicit braces, and so on. Clients
4346/// interested in the original syntax of the initializer list should
4347/// use the syntactic form of the initializer list.
4348///
4349/// After semantic analysis, the initializer list will represent the
4350/// semantic form of the initializer, where the initializations of all
4351/// subobjects are made explicit with nested InitListExpr nodes and
4352/// C99 designators have been eliminated by placing the designated
4353/// initializations into the subobject they initialize. Additionally,
4354/// any "holes" in the initialization, where no initializer has been
4355/// specified for a particular subobject, will be replaced with
4356/// implicitly-generated ImplicitValueInitExpr expressions that
4357/// value-initialize the subobjects. Note, however, that the
4358/// initializer lists may still have fewer initializers than there are
4359/// elements to initialize within the object.
4360///
4361/// After semantic analysis has completed, given an initializer list,
4362/// method isSemanticForm() returns true if and only if this is the
4363/// semantic form of the initializer list (note: the same AST node
4364/// may at the same time be the syntactic form).
4365/// Given the semantic form of the initializer list, one can retrieve
4366/// the syntactic form of that initializer list (when different)
4367/// using method getSyntacticForm(); the method returns null if applied
4368/// to a initializer list which is already in syntactic form.
4369/// Similarly, given the syntactic form (i.e., an initializer list such
4370/// that isSemanticForm() returns false), one can retrieve the semantic
4371/// form using method getSemanticForm().
4372/// Since many initializer lists have the same syntactic and semantic forms,
4373/// getSyntacticForm() may return NULL, indicating that the current
4374/// semantic initializer list also serves as its syntactic form.
4375class InitListExpr : public Expr {
4376 // FIXME: Eliminate this vector in favor of ASTContext allocation
4377 typedef ASTVector<Stmt *> InitExprsTy;
4378 InitExprsTy InitExprs;
4379 SourceLocation LBraceLoc, RBraceLoc;
4380
4381 /// The alternative form of the initializer list (if it exists).
4382 /// The int part of the pair stores whether this initializer list is
4383 /// in semantic form. If not null, the pointer points to:
4384 /// - the syntactic form, if this is in semantic form;
4385 /// - the semantic form, if this is in syntactic form.
4386 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4387
4388 /// Either:
4389 /// If this initializer list initializes an array with more elements than
4390 /// there are initializers in the list, specifies an expression to be used
4391 /// for value initialization of the rest of the elements.
4392 /// Or
4393 /// If this initializer list initializes a union, specifies which
4394 /// field within the union will be initialized.
4395 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4396
4397public:
4398 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4399 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4400
4401 /// Build an empty initializer list.
4402 explicit InitListExpr(EmptyShell Empty)
4403 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4404
4405 unsigned getNumInits() const { return InitExprs.size(); }
4406
4407 /// Retrieve the set of initializers.
4408 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4409
4410 /// Retrieve the set of initializers.
4411 Expr * const *getInits() const {
4412 return reinterpret_cast<Expr * const *>(InitExprs.data());
4413 }
4414
4415 ArrayRef<Expr *> inits() {
4416 return llvm::makeArrayRef(getInits(), getNumInits());
4417 }
4418
4419 ArrayRef<Expr *> inits() const {
4420 return llvm::makeArrayRef(getInits(), getNumInits());
4421 }
4422
4423 const Expr *getInit(unsigned Init) const {
4424 assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4424, __PRETTY_FUNCTION__))
;
4425 return cast_or_null<Expr>(InitExprs[Init]);
4426 }
4427
4428 Expr *getInit(unsigned Init) {
4429 assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4429, __PRETTY_FUNCTION__))
;
4430 return cast_or_null<Expr>(InitExprs[Init]);
4431 }
4432
4433 void setInit(unsigned Init, Expr *expr) {
4434 assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4434, __PRETTY_FUNCTION__))
;
4435 InitExprs[Init] = expr;
4436
4437 if (expr) {
4438 ExprBits.TypeDependent |= expr->isTypeDependent();
4439 ExprBits.ValueDependent |= expr->isValueDependent();
4440 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
4441 ExprBits.ContainsUnexpandedParameterPack |=
4442 expr->containsUnexpandedParameterPack();
4443 }
4444 }
4445
4446 /// Reserve space for some number of initializers.
4447 void reserveInits(const ASTContext &C, unsigned NumInits);
4448
4449 /// Specify the number of initializers
4450 ///
4451 /// If there are more than @p NumInits initializers, the remaining
4452 /// initializers will be destroyed. If there are fewer than @p
4453 /// NumInits initializers, NULL expressions will be added for the
4454 /// unknown initializers.
4455 void resizeInits(const ASTContext &Context, unsigned NumInits);
4456
4457 /// Updates the initializer at index @p Init with the new
4458 /// expression @p expr, and returns the old expression at that
4459 /// location.
4460 ///
4461 /// When @p Init is out of range for this initializer list, the
4462 /// initializer list will be extended with NULL expressions to
4463 /// accommodate the new entry.
4464 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4465
4466 /// If this initializer list initializes an array with more elements
4467 /// than there are initializers in the list, specifies an expression to be
4468 /// used for value initialization of the rest of the elements.
4469 Expr *getArrayFiller() {
4470 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4471 }
4472 const Expr *getArrayFiller() const {
4473 return const_cast<InitListExpr *>(this)->getArrayFiller();
4474 }
4475 void setArrayFiller(Expr *filler);
4476
4477 /// Return true if this is an array initializer and its array "filler"
4478 /// has been set.
4479 bool hasArrayFiller() const { return getArrayFiller(); }
4480
4481 /// If this initializes a union, specifies which field in the
4482 /// union to initialize.
4483 ///
4484 /// Typically, this field is the first named field within the
4485 /// union. However, a designated initializer can specify the
4486 /// initialization of a different field within the union.
4487 FieldDecl *getInitializedFieldInUnion() {
4488 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4489 }
4490 const FieldDecl *getInitializedFieldInUnion() const {
4491 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4492 }
4493 void setInitializedFieldInUnion(FieldDecl *FD) {
4494 assert((FD == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr ||
getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!"
) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4497, __PRETTY_FUNCTION__))
4495 || getInitializedFieldInUnion() == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr ||
getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!"
) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4497, __PRETTY_FUNCTION__))
4496 || getInitializedFieldInUnion() == FD)(((FD == nullptr || getInitializedFieldInUnion() == nullptr ||
getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!"
) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4497, __PRETTY_FUNCTION__))
4497 && "Only one field of a union may be initialized at a time!")(((FD == nullptr || getInitializedFieldInUnion() == nullptr ||
getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!"
) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4497, __PRETTY_FUNCTION__))
;
4498 ArrayFillerOrUnionFieldInit = FD;
4499 }
4500
4501 // Explicit InitListExpr's originate from source code (and have valid source
4502 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4503 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4504 // valid source locations too!
4505 bool isExplicit() const {
4506 return LBraceLoc.isValid() && RBraceLoc.isValid();
4507 }
4508
4509 // Is this an initializer for an array of characters, initialized by a string
4510 // literal or an @encode?
4511 bool isStringLiteralInit() const;
4512
4513 /// Is this a transparent initializer list (that is, an InitListExpr that is
4514 /// purely syntactic, and whose semantics are that of the sole contained
4515 /// initializer)?
4516 bool isTransparent() const;
4517
4518 /// Is this the zero initializer {0} in a language which considers it
4519 /// idiomatic?
4520 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4521
4522 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4523 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4524 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4525 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4526
4527 bool isSemanticForm() const { return AltForm.getInt(); }
4528 InitListExpr *getSemanticForm() const {
4529 return isSemanticForm() ? nullptr : AltForm.getPointer();
4530 }
4531 bool isSyntacticForm() const {
4532 return !AltForm.getInt() || !AltForm.getPointer();
4533 }
4534 InitListExpr *getSyntacticForm() const {
4535 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4536 }
4537
4538 void setSyntacticForm(InitListExpr *Init) {
4539 AltForm.setPointer(Init);
4540 AltForm.setInt(true);
4541 Init->AltForm.setPointer(this);
4542 Init->AltForm.setInt(false);
4543 }
4544
4545 bool hadArrayRangeDesignator() const {
4546 return InitListExprBits.HadArrayRangeDesignator != 0;
4547 }
4548 void sawArrayRangeDesignator(bool ARD = true) {
4549 InitListExprBits.HadArrayRangeDesignator = ARD;
4550 }
4551
4552 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
4553 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
4554
4555 static bool classof(const Stmt *T) {
4556 return T->getStmtClass() == InitListExprClass;
4557 }
4558
4559 // Iterators
4560 child_range children() {
4561 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4562 return child_range(cast_away_const(CCR.begin()),
4563 cast_away_const(CCR.end()));
4564 }
4565
4566 const_child_range children() const {
4567 // FIXME: This does not include the array filler expression.
4568 if (InitExprs.empty())
4569 return const_child_range(const_child_iterator(), const_child_iterator());
4570 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4571 }
4572
4573 typedef InitExprsTy::iterator iterator;
4574 typedef InitExprsTy::const_iterator const_iterator;
4575 typedef InitExprsTy::reverse_iterator reverse_iterator;
4576 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4577
4578 iterator begin() { return InitExprs.begin(); }
4579 const_iterator begin() const { return InitExprs.begin(); }
4580 iterator end() { return InitExprs.end(); }
4581 const_iterator end() const { return InitExprs.end(); }
4582 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4583 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4584 reverse_iterator rend() { return InitExprs.rend(); }
4585 const_reverse_iterator rend() const { return InitExprs.rend(); }
4586
4587 friend class ASTStmtReader;
4588 friend class ASTStmtWriter;
4589};
4590
4591/// Represents a C99 designated initializer expression.
4592///
4593/// A designated initializer expression (C99 6.7.8) contains one or
4594/// more designators (which can be field designators, array
4595/// designators, or GNU array-range designators) followed by an
4596/// expression that initializes the field or element(s) that the
4597/// designators refer to. For example, given:
4598///
4599/// @code
4600/// struct point {
4601/// double x;
4602/// double y;
4603/// };
4604/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4605/// @endcode
4606///
4607/// The InitListExpr contains three DesignatedInitExprs, the first of
4608/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4609/// designators, one array designator for @c [2] followed by one field
4610/// designator for @c .y. The initialization expression will be 1.0.
4611class DesignatedInitExpr final
4612 : public Expr,
4613 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4614public:
4615 /// Forward declaration of the Designator class.
4616 class Designator;
4617
4618private:
4619 /// The location of the '=' or ':' prior to the actual initializer
4620 /// expression.
4621 SourceLocation EqualOrColonLoc;
4622
4623 /// Whether this designated initializer used the GNU deprecated
4624 /// syntax rather than the C99 '=' syntax.
4625 unsigned GNUSyntax : 1;
4626
4627 /// The number of designators in this initializer expression.
4628 unsigned NumDesignators : 15;
4629
4630 /// The number of subexpressions of this initializer expression,
4631 /// which contains both the initializer and any additional
4632 /// expressions used by array and array-range designators.
4633 unsigned NumSubExprs : 16;
4634
4635 /// The designators in this designated initialization
4636 /// expression.
4637 Designator *Designators;
4638
4639 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4640 llvm::ArrayRef<Designator> Designators,
4641 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4642 ArrayRef<Expr *> IndexExprs, Expr *Init);
4643
4644 explicit DesignatedInitExpr(unsigned NumSubExprs)
4645 : Expr(DesignatedInitExprClass, EmptyShell()),
4646 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4647
4648public:
4649 /// A field designator, e.g., ".x".
4650 struct FieldDesignator {
4651 /// Refers to the field that is being initialized. The low bit
4652 /// of this field determines whether this is actually a pointer
4653 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4654 /// initially constructed, a field designator will store an
4655 /// IdentifierInfo*. After semantic analysis has resolved that
4656 /// name, the field designator will instead store a FieldDecl*.
4657 uintptr_t NameOrField;
4658
4659 /// The location of the '.' in the designated initializer.
4660 unsigned DotLoc;
4661
4662 /// The location of the field name in the designated initializer.
4663 unsigned FieldLoc;
4664 };
4665
4666 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4667 struct ArrayOrRangeDesignator {
4668 /// Location of the first index expression within the designated
4669 /// initializer expression's list of subexpressions.
4670 unsigned Index;
4671 /// The location of the '[' starting the array range designator.
4672 unsigned LBracketLoc;
4673 /// The location of the ellipsis separating the start and end
4674 /// indices. Only valid for GNU array-range designators.
4675 unsigned EllipsisLoc;
4676 /// The location of the ']' terminating the array range designator.
4677 unsigned RBracketLoc;
4678 };
4679
4680 /// Represents a single C99 designator.
4681 ///
4682 /// @todo This class is infuriatingly similar to clang::Designator,
4683 /// but minor differences (storing indices vs. storing pointers)
4684 /// keep us from reusing it. Try harder, later, to rectify these
4685 /// differences.
4686 class Designator {
4687 /// The kind of designator this describes.
4688 enum {
4689 FieldDesignator,
4690 ArrayDesignator,
4691 ArrayRangeDesignator
4692 } Kind;
4693
4694 union {
4695 /// A field designator, e.g., ".x".
4696 struct FieldDesignator Field;
4697 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4698 struct ArrayOrRangeDesignator ArrayOrRange;
4699 };
4700 friend class DesignatedInitExpr;
4701
4702 public:
4703 Designator() {}
4704
4705 /// Initializes a field designator.
4706 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4707 SourceLocation FieldLoc)
4708 : Kind(FieldDesignator) {
4709 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4710 Field.DotLoc = DotLoc.getRawEncoding();
4711 Field.FieldLoc = FieldLoc.getRawEncoding();
4712 }
4713
4714 /// Initializes an array designator.
4715 Designator(unsigned Index, SourceLocation LBracketLoc,
4716 SourceLocation RBracketLoc)
4717 : Kind(ArrayDesignator) {
4718 ArrayOrRange.Index = Index;
4719 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4720 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4721 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4722 }
4723
4724 /// Initializes a GNU array-range designator.
4725 Designator(unsigned Index, SourceLocation LBracketLoc,
4726 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4727 : Kind(ArrayRangeDesignator) {
4728 ArrayOrRange.Index = Index;
4729 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4730 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4731 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4732 }
4733
4734 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4735 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4736 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4737
4738 IdentifierInfo *getFieldName() const;
4739
4740 FieldDecl *getField() const {
4741 assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4741, __PRETTY_FUNCTION__))
;
4742 if (Field.NameOrField & 0x01)
4743 return nullptr;
4744 else
4745 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4746 }
4747
4748 void setField(FieldDecl *FD) {
4749 assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4749, __PRETTY_FUNCTION__))
;
4750 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4751 }
4752
4753 SourceLocation getDotLoc() const {
4754 assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4754, __PRETTY_FUNCTION__))
;
4755 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4756 }
4757
4758 SourceLocation getFieldLoc() const {
4759 assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4759, __PRETTY_FUNCTION__))
;
4760 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4761 }
4762
4763 SourceLocation getLBracketLoc() const {
4764 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4765, __PRETTY_FUNCTION__))
4765 "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4765, __PRETTY_FUNCTION__))
;
4766 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4767 }
4768
4769 SourceLocation getRBracketLoc() const {
4770 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4771, __PRETTY_FUNCTION__))
4771 "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4771, __PRETTY_FUNCTION__))
;
4772 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4773 }
4774
4775 SourceLocation getEllipsisLoc() const {
4776 assert(Kind == ArrayRangeDesignator &&((Kind == ArrayRangeDesignator && "Only valid on an array-range designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4777, __PRETTY_FUNCTION__))
4777 "Only valid on an array-range designator")((Kind == ArrayRangeDesignator && "Only valid on an array-range designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4777, __PRETTY_FUNCTION__))
;
4778 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4779 }
4780
4781 unsigned getFirstExprIndex() const {
4782 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4783, __PRETTY_FUNCTION__))
4783 "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator") ? static_cast
<void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4783, __PRETTY_FUNCTION__))
;
4784 return ArrayOrRange.Index;
4785 }
4786
4787 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4788 if (Kind == FieldDesignator)
4789 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4790 else
4791 return getLBracketLoc();
4792 }
4793 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4794 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4795 }
4796 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
4797 return SourceRange(getBeginLoc(), getEndLoc());
4798 }
4799 };
4800
4801 static DesignatedInitExpr *Create(const ASTContext &C,
4802 llvm::ArrayRef<Designator> Designators,
4803 ArrayRef<Expr*> IndexExprs,
4804 SourceLocation EqualOrColonLoc,
4805 bool GNUSyntax, Expr *Init);
4806
4807 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4808 unsigned NumIndexExprs);
4809
4810 /// Returns the number of designators in this initializer.
4811 unsigned size() const { return NumDesignators; }
4812
4813 // Iterator access to the designators.
4814 llvm::MutableArrayRef<Designator> designators() {
4815 return {Designators, NumDesignators};
4816 }
4817
4818 llvm::ArrayRef<Designator> designators() const {
4819 return {Designators, NumDesignators};
4820 }
4821
4822 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4823 const Designator *getDesignator(unsigned Idx) const {
4824 return &designators()[Idx];
4825 }
4826
4827 void setDesignators(const ASTContext &C, const Designator *Desigs,
4828 unsigned NumDesigs);
4829
4830 Expr *getArrayIndex(const Designator &D) const;
4831 Expr *getArrayRangeStart(const Designator &D) const;
4832 Expr *getArrayRangeEnd(const Designator &D) const;
4833
4834 /// Retrieve the location of the '=' that precedes the
4835 /// initializer value itself, if present.
4836 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4837 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4838
4839 /// Whether this designated initializer should result in direct-initialization
4840 /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
4841 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
4842
4843 /// Determines whether this designated initializer used the
4844 /// deprecated GNU syntax for designated initializers.
4845 bool usesGNUSyntax() const { return GNUSyntax; }
4846 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4847
4848 /// Retrieve the initializer value.
4849 Expr *getInit() const {
4850 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4851 }
4852
4853 void setInit(Expr *init) {
4854 *child_begin() = init;
4855 }
4856
4857 /// Retrieve the total number of subexpressions in this
4858 /// designated initializer expression, including the actual
4859 /// initialized value and any expressions that occur within array
4860 /// and array-range designators.
4861 unsigned getNumSubExprs() const { return NumSubExprs; }
4862
4863 Expr *getSubExpr(unsigned Idx) const {
4864 assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ?
static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4864, __PRETTY_FUNCTION__))
;
4865 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4866 }
4867
4868 void setSubExpr(unsigned Idx, Expr *E) {
4869 assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ?
static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 4869, __PRETTY_FUNCTION__))
;
4870 getTrailingObjects<Stmt *>()[Idx] = E;
4871 }
4872
4873 /// Replaces the designator at index @p Idx with the series
4874 /// of designators in [First, Last).
4875 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4876 const Designator *First, const Designator *Last);
4877
4878 SourceRange getDesignatorsSourceRange() const;
4879
4880 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
4881 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
4882
4883 static bool classof(const Stmt *T) {
4884 return T->getStmtClass() == DesignatedInitExprClass;
4885 }
4886
4887 // Iterators
4888 child_range children() {
4889 Stmt **begin = getTrailingObjects<Stmt *>();
4890 return child_range(begin, begin + NumSubExprs);
4891 }
4892 const_child_range children() const {
4893 Stmt * const *begin = getTrailingObjects<Stmt *>();
4894 return const_child_range(begin, begin + NumSubExprs);
4895 }
4896
4897 friend TrailingObjects;
4898};
4899
4900/// Represents a place-holder for an object not to be initialized by
4901/// anything.
4902///
4903/// This only makes sense when it appears as part of an updater of a
4904/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4905/// initializes a big object, and the NoInitExpr's mark the spots within the
4906/// big object not to be overwritten by the updater.
4907///
4908/// \see DesignatedInitUpdateExpr
4909class NoInitExpr : public Expr {
4910public:
4911 explicit NoInitExpr(QualType ty)
4912 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4913 false, false, ty->isInstantiationDependentType(), false) { }
4914
4915 explicit NoInitExpr(EmptyShell Empty)
4916 : Expr(NoInitExprClass, Empty) { }
4917
4918 static bool classof(const Stmt *T) {
4919 return T->getStmtClass() == NoInitExprClass;
4920 }
4921
4922 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4923 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
4924
4925 // Iterators
4926 child_range children() {
4927 return child_range(child_iterator(), child_iterator());
4928 }
4929 const_child_range children() const {
4930 return const_child_range(const_child_iterator(), const_child_iterator());
4931 }
4932};
4933
4934// In cases like:
4935// struct Q { int a, b, c; };
4936// Q *getQ();
4937// void foo() {
4938// struct A { Q q; } a = { *getQ(), .q.b = 3 };
4939// }
4940//
4941// We will have an InitListExpr for a, with type A, and then a
4942// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4943// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4944//
4945class DesignatedInitUpdateExpr : public Expr {
4946 // BaseAndUpdaterExprs[0] is the base expression;
4947 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4948 Stmt *BaseAndUpdaterExprs[2];
4949
4950public:
4951 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4952 Expr *baseExprs, SourceLocation rBraceLoc);
4953
4954 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4955 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4956
4957 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
4958 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
4959
4960 static bool classof(const Stmt *T) {
4961 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4962 }
4963
4964 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4965 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4966
4967 InitListExpr *getUpdater() const {
4968 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4969 }
4970 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4971
4972 // Iterators
4973 // children = the base and the updater
4974 child_range children() {
4975 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4976 }
4977 const_child_range children() const {
4978 return const_child_range(&BaseAndUpdaterExprs[0],
4979 &BaseAndUpdaterExprs[0] + 2);
4980 }
4981};
4982
4983/// Represents a loop initializing the elements of an array.
4984///
4985/// The need to initialize the elements of an array occurs in a number of
4986/// contexts:
4987///
4988/// * in the implicit copy/move constructor for a class with an array member
4989/// * when a lambda-expression captures an array by value
4990/// * when a decomposition declaration decomposes an array
4991///
4992/// There are two subexpressions: a common expression (the source array)
4993/// that is evaluated once up-front, and a per-element initializer that
4994/// runs once for each array element.
4995///
4996/// Within the per-element initializer, the common expression may be referenced
4997/// via an OpaqueValueExpr, and the current index may be obtained via an
4998/// ArrayInitIndexExpr.
4999class ArrayInitLoopExpr : public Expr {
5000 Stmt *SubExprs[2];
5001
5002 explicit ArrayInitLoopExpr(EmptyShell Empty)
5003 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5004
5005public:
5006 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5007 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
5008 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
5009 T->isInstantiationDependentType(),
5010 CommonInit->containsUnexpandedParameterPack() ||
5011 ElementInit->containsUnexpandedParameterPack()),
5012 SubExprs{CommonInit, ElementInit} {}
5013
5014 /// Get the common subexpression shared by all initializations (the source
5015 /// array).
5016 OpaqueValueExpr *getCommonExpr() const {
5017 return cast<OpaqueValueExpr>(SubExprs[0]);
5018 }
5019
5020 /// Get the initializer to use for each array element.
5021 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
5022
5023 llvm::APInt getArraySize() const {
5024 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5025 ->getSize();
5026 }
5027
5028 static bool classof(const Stmt *S) {
5029 return S->getStmtClass() == ArrayInitLoopExprClass;
5030 }
5031
5032 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5033 return getCommonExpr()->getBeginLoc();
5034 }
5035 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5036 return getCommonExpr()->getEndLoc();
5037 }
5038
5039 child_range children() {
5040 return child_range(SubExprs, SubExprs + 2);
5041 }
5042 const_child_range children() const {
5043 return const_child_range(SubExprs, SubExprs + 2);
5044 }
5045
5046 friend class ASTReader;
5047 friend class ASTStmtReader;
5048 friend class ASTStmtWriter;
5049};
5050
5051/// Represents the index of the current element of an array being
5052/// initialized by an ArrayInitLoopExpr. This can only appear within the
5053/// subexpression of an ArrayInitLoopExpr.
5054class ArrayInitIndexExpr : public Expr {
5055 explicit ArrayInitIndexExpr(EmptyShell Empty)
5056 : Expr(ArrayInitIndexExprClass, Empty) {}
5057
5058public:
5059 explicit ArrayInitIndexExpr(QualType T)
5060 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
5061 false, false, false, false) {}
5062
5063 static bool classof(const Stmt *S) {
5064 return S->getStmtClass() == ArrayInitIndexExprClass;
5065 }
5066
5067 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5068 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5069
5070 child_range children() {
5071 return child_range(child_iterator(), child_iterator());
5072 }
5073 const_child_range children() const {
5074 return const_child_range(const_child_iterator(), const_child_iterator());
5075 }
5076
5077 friend class ASTReader;
5078 friend class ASTStmtReader;
5079};
5080
5081/// Represents an implicitly-generated value initialization of
5082/// an object of a given type.
5083///
5084/// Implicit value initializations occur within semantic initializer
5085/// list expressions (InitListExpr) as placeholders for subobject
5086/// initializations not explicitly specified by the user.
5087///
5088/// \see InitListExpr
5089class ImplicitValueInitExpr : public Expr {
5090public:
5091 explicit ImplicitValueInitExpr(QualType ty)
5092 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
5093 false, false, ty->isInstantiationDependentType(), false) { }
5094
5095 /// Construct an empty implicit value initialization.
5096 explicit ImplicitValueInitExpr(EmptyShell Empty)
5097 : Expr(ImplicitValueInitExprClass, Empty) { }
5098
5099 static bool classof(const Stmt *T) {
5100 return T->getStmtClass() == ImplicitValueInitExprClass;
5101 }
5102
5103 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5104 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5105
5106 // Iterators
5107 child_range children() {
5108 return child_range(child_iterator(), child_iterator());
5109 }
5110 const_child_range children() const {
5111 return const_child_range(const_child_iterator(), const_child_iterator());
5112 }
5113};
5114
5115class ParenListExpr final
5116 : public Expr,
5117 private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5118 friend class ASTStmtReader;
5119 friend TrailingObjects;
5120
5121 /// The location of the left and right parentheses.
5122 SourceLocation LParenLoc, RParenLoc;
5123
5124 /// Build a paren list.
5125 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5126 SourceLocation RParenLoc);
5127
5128 /// Build an empty paren list.
5129 ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5130
5131public:
5132 /// Create a paren list.
5133 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5134 ArrayRef<Expr *> Exprs,
5135 SourceLocation RParenLoc);
5136
5137 /// Create an empty paren list.
5138 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5139
5140 /// Return the number of expressions in this paren list.
5141 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5142
5143 Expr *getExpr(unsigned Init) {
5144 assert(Init < getNumExprs() && "Initializer access out of range!")((Init < getNumExprs() && "Initializer access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Init < getNumExprs() && \"Initializer access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5144, __PRETTY_FUNCTION__))
;
5145 return getExprs()[Init];
5146 }
5147
5148 const Expr *getExpr(unsigned Init) const {
5149 return const_cast<ParenListExpr *>(this)->getExpr(Init);
5150 }
5151
5152 Expr **getExprs() {
5153 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5154 }
5155
5156 ArrayRef<Expr *> exprs() {
5157 return llvm::makeArrayRef(getExprs(), getNumExprs());
5158 }
5159
5160 SourceLocation getLParenLoc() const { return LParenLoc; }
5161 SourceLocation getRParenLoc() const { return RParenLoc; }
5162 SourceLocation getBeginLoc() const { return getLParenLoc(); }
5163 SourceLocation getEndLoc() const { return getRParenLoc(); }
5164
5165 static bool classof(const Stmt *T) {
5166 return T->getStmtClass() == ParenListExprClass;
5167 }
5168
5169 // Iterators
5170 child_range children() {
5171 return child_range(getTrailingObjects<Stmt *>(),
5172 getTrailingObjects<Stmt *>() + getNumExprs());
5173 }
5174 const_child_range children() const {
5175 return const_child_range(getTrailingObjects<Stmt *>(),
5176 getTrailingObjects<Stmt *>() + getNumExprs());
5177 }
5178};
5179
5180/// Represents a C11 generic selection.
5181///
5182/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5183/// expression, followed by one or more generic associations. Each generic
5184/// association specifies a type name and an expression, or "default" and an
5185/// expression (in which case it is known as a default generic association).
5186/// The type and value of the generic selection are identical to those of its
5187/// result expression, which is defined as the expression in the generic
5188/// association with a type name that is compatible with the type of the
5189/// controlling expression, or the expression in the default generic association
5190/// if no types are compatible. For example:
5191///
5192/// @code
5193/// _Generic(X, double: 1, float: 2, default: 3)
5194/// @endcode
5195///
5196/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5197/// or 3 if "hello".
5198///
5199/// As an extension, generic selections are allowed in C++, where the following
5200/// additional semantics apply:
5201///
5202/// Any generic selection whose controlling expression is type-dependent or
5203/// which names a dependent type in its association list is result-dependent,
5204/// which means that the choice of result expression is dependent.
5205/// Result-dependent generic associations are both type- and value-dependent.
5206class GenericSelectionExpr final
5207 : public Expr,
5208 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5209 TypeSourceInfo *> {
5210 friend class ASTStmtReader;
5211 friend class ASTStmtWriter;
5212 friend TrailingObjects;
5213
5214 /// The number of association expressions and the index of the result
5215 /// expression in the case where the generic selection expression is not
5216 /// result-dependent. The result index is equal to ResultDependentIndex
5217 /// if and only if the generic selection expression is result-dependent.
5218 unsigned NumAssocs, ResultIndex;
5219 enum : unsigned {
5220 ResultDependentIndex = std::numeric_limits<unsigned>::max(),
5221 ControllingIndex = 0,
5222 AssocExprStartIndex = 1
5223 };
5224
5225 /// The location of the "default" and of the right parenthesis.
5226 SourceLocation DefaultLoc, RParenLoc;
5227
5228 // GenericSelectionExpr is followed by several trailing objects.
5229 // They are (in order):
5230 //
5231 // * A single Stmt * for the controlling expression.
5232 // * An array of getNumAssocs() Stmt * for the association expressions.
5233 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
5234 // association expressions.
5235 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
5236 // Add one to account for the controlling expression; the remainder
5237 // are the associated expressions.
5238 return 1 + getNumAssocs();
5239 }
5240
5241 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
5242 return getNumAssocs();
5243 }
5244
5245 template <bool Const> class AssociationIteratorTy;
5246 /// Bundle together an association expression and its TypeSourceInfo.
5247 /// The Const template parameter is for the const and non-const versions
5248 /// of AssociationTy.
5249 template <bool Const> class AssociationTy {
5250 friend class GenericSelectionExpr;
5251 template <bool OtherConst> friend class AssociationIteratorTy;
5252 using ExprPtrTy =
5253 typename std::conditional<Const, const Expr *, Expr *>::type;
5254 using TSIPtrTy = typename std::conditional<Const, const TypeSourceInfo *,
5255 TypeSourceInfo *>::type;
5256 ExprPtrTy E;
5257 TSIPtrTy TSI;
5258 bool Selected;
5259 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
5260 : E(E), TSI(TSI), Selected(Selected) {}
5261
5262 public:
5263 ExprPtrTy getAssociationExpr() const { return E; }
5264 TSIPtrTy getTypeSourceInfo() const { return TSI; }
5265 QualType getType() const { return TSI ? TSI->getType() : QualType(); }
5266 bool isSelected() const { return Selected; }
5267 AssociationTy *operator->() { return this; }
5268 const AssociationTy *operator->() const { return this; }
5269 }; // class AssociationTy
5270
5271 /// Iterator over const and non-const Association objects. The Association
5272 /// objects are created on the fly when the iterator is dereferenced.
5273 /// This abstract over how exactly the association expressions and the
5274 /// corresponding TypeSourceInfo * are stored.
5275 template <bool Const>
5276 class AssociationIteratorTy
5277 : public llvm::iterator_facade_base<
5278 AssociationIteratorTy<Const>, std::input_iterator_tag,
5279 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
5280 AssociationTy<Const>> {
5281 friend class GenericSelectionExpr;
5282 // FIXME: This iterator could conceptually be a random access iterator, and
5283 // it would be nice if we could strengthen the iterator category someday.
5284 // However this iterator does not satisfy two requirements of forward
5285 // iterators:
5286 // a) reference = T& or reference = const T&
5287 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
5288 // if *It1 and *It2 are bound to the same objects.
5289 // An alternative design approach was discussed during review;
5290 // store an Association object inside the iterator, and return a reference
5291 // to it when dereferenced. This idea was discarded beacuse of nasty
5292 // lifetime issues:
5293 // AssociationIterator It = ...;
5294 // const Association &Assoc = *It++; // Oops, Assoc is dangling.
5295 using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
5296 using StmtPtrPtrTy =
5297 typename std::conditional<Const, const Stmt *const *, Stmt **>::type;
5298 using TSIPtrPtrTy =
5299 typename std::conditional<Const, const TypeSourceInfo *const *,
5300 TypeSourceInfo **>::type;
5301 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
5302 TSIPtrPtrTy TSI; // Kept in sync with E.
5303 unsigned Offset = 0, SelectedOffset = 0;
5304 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
5305 unsigned SelectedOffset)
5306 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
5307
5308 public:
5309 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
5310 typename BaseTy::reference operator*() const {
5311 return AssociationTy<Const>(cast<Expr>(*E), *TSI,
5312 Offset == SelectedOffset);
5313 }
5314 typename BaseTy::pointer operator->() const { return **this; }
5315 using BaseTy::operator++;
5316 AssociationIteratorTy &operator++() {
5317 ++E;
5318 ++TSI;
5319 ++Offset;
5320 return *this;
5321 }
5322 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
5323 }; // class AssociationIterator
5324
5325 /// Build a non-result-dependent generic selection expression.
5326 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5327 Expr *ControllingExpr,
5328 ArrayRef<TypeSourceInfo *> AssocTypes,
5329 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5330 SourceLocation RParenLoc,
5331 bool ContainsUnexpandedParameterPack,
5332 unsigned ResultIndex);
5333
5334 /// Build a result-dependent generic selection expression.
5335 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5336 Expr *ControllingExpr,
5337 ArrayRef<TypeSourceInfo *> AssocTypes,
5338 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5339 SourceLocation RParenLoc,
5340 bool ContainsUnexpandedParameterPack);
5341
5342 /// Build an empty generic selection expression for deserialization.
5343 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
5344
5345public:
5346 /// Create a non-result-dependent generic selection expression.
5347 static GenericSelectionExpr *
5348 Create(const ASTContext &Context, SourceLocation GenericLoc,
5349 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5350 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5351 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5352 unsigned ResultIndex);
5353
5354 /// Create a result-dependent generic selection expression.
5355 static GenericSelectionExpr *
5356 Create(const ASTContext &Context, SourceLocation GenericLoc,
5357 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5358 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5359 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5360
5361 /// Create an empty generic selection expression for deserialization.
5362 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
5363 unsigned NumAssocs);
5364
5365 using Association = AssociationTy<false>;
5366 using ConstAssociation = AssociationTy<true>;
5367 using AssociationIterator = AssociationIteratorTy<false>;
5368 using ConstAssociationIterator = AssociationIteratorTy<true>;
5369 using association_range = llvm::iterator_range<AssociationIterator>;
5370 using const_association_range =
5371 llvm::iterator_range<ConstAssociationIterator>;
5372
5373 /// The number of association expressions.
5374 unsigned getNumAssocs() const { return NumAssocs; }
5375
5376 /// The zero-based index of the result expression's generic association in
5377 /// the generic selection's association list. Defined only if the
5378 /// generic selection is not result-dependent.
5379 unsigned getResultIndex() const {
5380 assert(!isResultDependent() &&((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!"
) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5381, __PRETTY_FUNCTION__))
5381 "Generic selection is result-dependent but getResultIndex called!")((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!"
) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5381, __PRETTY_FUNCTION__))
;
5382 return ResultIndex;
5383 }
5384
5385 /// Whether this generic selection is result-dependent.
5386 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
5387
5388 /// Return the controlling expression of this generic selection expression.
5389 Expr *getControllingExpr() {
5390 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5391 }
5392 const Expr *getControllingExpr() const {
5393 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5394 }
5395
5396 /// Return the result expression of this controlling expression. Defined if
5397 /// and only if the generic selection expression is not result-dependent.
5398 Expr *getResultExpr() {
5399 return cast<Expr>(
5400 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5401 }
5402 const Expr *getResultExpr() const {
5403 return cast<Expr>(
5404 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5405 }
5406
5407 ArrayRef<Expr *> getAssocExprs() const {
5408 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
5409 AssocExprStartIndex),
5410 NumAssocs};
5411 }
5412 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
5413 return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
5414 }
5415
5416 /// Return the Ith association expression with its TypeSourceInfo,
5417 /// bundled together in GenericSelectionExpr::(Const)Association.
5418 Association getAssociation(unsigned I) {
5419 assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5420, __PRETTY_FUNCTION__))
5420 "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5420, __PRETTY_FUNCTION__))
;
5421 return Association(
5422 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5423 getTrailingObjects<TypeSourceInfo *>()[I],
5424 !isResultDependent() && (getResultIndex() == I));
5425 }
5426 ConstAssociation getAssociation(unsigned I) const {
5427 assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5428, __PRETTY_FUNCTION__))
5428 "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5428, __PRETTY_FUNCTION__))
;
5429 return ConstAssociation(
5430 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5431 getTrailingObjects<TypeSourceInfo *>()[I],
5432 !isResultDependent() && (getResultIndex() == I));
5433 }
5434
5435 association_range associations() {
5436 AssociationIterator Begin(getTrailingObjects<Stmt *>() +
5437 AssocExprStartIndex,
5438 getTrailingObjects<TypeSourceInfo *>(),
5439 /*Offset=*/0, ResultIndex);
5440 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5441 /*Offset=*/NumAssocs, ResultIndex);
5442 return llvm::make_range(Begin, End);
5443 }
5444
5445 const_association_range associations() const {
5446 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
5447 AssocExprStartIndex,
5448 getTrailingObjects<TypeSourceInfo *>(),
5449 /*Offset=*/0, ResultIndex);
5450 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5451 /*Offset=*/NumAssocs, ResultIndex);
5452 return llvm::make_range(Begin, End);
5453 }
5454
5455 SourceLocation getGenericLoc() const {
5456 return GenericSelectionExprBits.GenericLoc;
5457 }
5458 SourceLocation getDefaultLoc() const { return DefaultLoc; }
5459 SourceLocation getRParenLoc() const { return RParenLoc; }
5460 SourceLocation getBeginLoc() const { return getGenericLoc(); }
5461 SourceLocation getEndLoc() const { return getRParenLoc(); }
5462
5463 static bool classof(const Stmt *T) {
5464 return T->getStmtClass() == GenericSelectionExprClass;
5465 }
5466
5467 child_range children() {
5468 return child_range(getTrailingObjects<Stmt *>(),
5469 getTrailingObjects<Stmt *>() +
5470 numTrailingObjects(OverloadToken<Stmt *>()));
5471 }
5472 const_child_range children() const {
5473 return const_child_range(getTrailingObjects<Stmt *>(),
5474 getTrailingObjects<Stmt *>() +
5475 numTrailingObjects(OverloadToken<Stmt *>()));
5476 }
5477};
5478
5479//===----------------------------------------------------------------------===//
5480// Clang Extensions
5481//===----------------------------------------------------------------------===//
5482
5483/// ExtVectorElementExpr - This represents access to specific elements of a
5484/// vector, and may occur on the left hand side or right hand side. For example
5485/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
5486///
5487/// Note that the base may have either vector or pointer to vector type, just
5488/// like a struct field reference.
5489///
5490class ExtVectorElementExpr : public Expr {
5491 Stmt *Base;
5492 IdentifierInfo *Accessor;
5493 SourceLocation AccessorLoc;
5494public:
5495 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
5496 IdentifierInfo &accessor, SourceLocation loc)
5497 : Expr(ExtVectorElementExprClass, ty, VK,
5498 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
5499 base->isTypeDependent(), base->isValueDependent(),
5500 base->isInstantiationDependent(),
5501 base->containsUnexpandedParameterPack()),
5502 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
5503
5504 /// Build an empty vector element expression.
5505 explicit ExtVectorElementExpr(EmptyShell Empty)
5506 : Expr(ExtVectorElementExprClass, Empty) { }
5507
5508 const Expr *getBase() const { return cast<Expr>(Base); }
5509 Expr *getBase() { return cast<Expr>(Base); }
5510 void setBase(Expr *E) { Base = E; }
5511
5512 IdentifierInfo &getAccessor() const { return *Accessor; }
5513 void setAccessor(IdentifierInfo *II) { Accessor = II; }
5514
5515 SourceLocation getAccessorLoc() const { return AccessorLoc; }
5516 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
5517
5518 /// getNumElements - Get the number of components being selected.
5519 unsigned getNumElements() const;
5520
5521 /// containsDuplicateElements - Return true if any element access is
5522 /// repeated.
5523 bool containsDuplicateElements() const;
5524
5525 /// getEncodedElementAccess - Encode the elements accessed into an llvm
5526 /// aggregate Constant of ConstantInt(s).
5527 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
5528
5529 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5530 return getBase()->getBeginLoc();
5531 }
5532 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return AccessorLoc; }
5533
5534 /// isArrow - Return true if the base expression is a pointer to vector,
5535 /// return false if the base expression is a vector.
5536 bool isArrow() const;
5537
5538 static bool classof(const Stmt *T) {
5539 return T->getStmtClass() == ExtVectorElementExprClass;
5540 }
5541
5542 // Iterators
5543 child_range children() { return child_range(&Base, &Base+1); }
5544 const_child_range children() const {
5545 return const_child_range(&Base, &Base + 1);
5546 }
5547};
5548
5549/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
5550/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
5551class BlockExpr : public Expr {
5552protected:
5553 BlockDecl *TheBlock;
5554public:
5555 BlockExpr(BlockDecl *BD, QualType ty)
5556 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
5557 ty->isDependentType(), ty->isDependentType(),
5558 ty->isInstantiationDependentType() || BD->isDependentContext(),
5559 false),
5560 TheBlock(BD) {}
5561
5562 /// Build an empty block expression.
5563 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
5564
5565 const BlockDecl *getBlockDecl() const { return TheBlock; }
5566 BlockDecl *getBlockDecl() { return TheBlock; }
5567 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
5568
5569 // Convenience functions for probing the underlying BlockDecl.
5570 SourceLocation getCaretLocation() const;
5571 const Stmt *getBody() const;
5572 Stmt *getBody();
5573
5574 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5575 return getCaretLocation();
5576 }
5577 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5578 return getBody()->getEndLoc();
5579 }
5580
5581 /// getFunctionType - Return the underlying function type for this block.
5582 const FunctionProtoType *getFunctionType() const;
5583
5584 static bool classof(const Stmt *T) {
5585 return T->getStmtClass() == BlockExprClass;
5586 }
5587
5588 // Iterators
5589 child_range children() {
5590 return child_range(child_iterator(), child_iterator());
5591 }
5592 const_child_range children() const {
5593 return const_child_range(const_child_iterator(), const_child_iterator());
5594 }
5595};
5596
5597/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
5598/// This AST node provides support for reinterpreting a type to another
5599/// type of the same size.
5600class AsTypeExpr : public Expr {
5601private:
5602 Stmt *SrcExpr;
5603 SourceLocation BuiltinLoc, RParenLoc;
5604
5605 friend class ASTReader;
5606 friend class ASTStmtReader;
5607 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
5608
5609public:
5610 AsTypeExpr(Expr* SrcExpr, QualType DstType,
5611 ExprValueKind VK, ExprObjectKind OK,
5612 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
5613 : Expr(AsTypeExprClass, DstType, VK, OK,
5614 DstType->isDependentType(),
5615 DstType->isDependentType() || SrcExpr->isValueDependent(),
5616 (DstType->isInstantiationDependentType() ||
5617 SrcExpr->isInstantiationDependent()),
5618 (DstType->containsUnexpandedParameterPack() ||
5619 SrcExpr->containsUnexpandedParameterPack())),
5620 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
5621
5622 /// getSrcExpr - Return the Expr to be converted.
5623 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
5624
5625 /// getBuiltinLoc - Return the location of the __builtin_astype token.
5626 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5627
5628 /// getRParenLoc - Return the location of final right parenthesis.
5629 SourceLocation getRParenLoc() const { return RParenLoc; }
5630
5631 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
5632 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
5633
5634 static bool classof(const Stmt *T) {
5635 return T->getStmtClass() == AsTypeExprClass;
5636 }
5637
5638 // Iterators
5639 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
5640 const_child_range children() const {
5641 return const_child_range(&SrcExpr, &SrcExpr + 1);
5642 }
5643};
5644
5645/// PseudoObjectExpr - An expression which accesses a pseudo-object
5646/// l-value. A pseudo-object is an abstract object, accesses to which
5647/// are translated to calls. The pseudo-object expression has a
5648/// syntactic form, which shows how the expression was actually
5649/// written in the source code, and a semantic form, which is a series
5650/// of expressions to be executed in order which detail how the
5651/// operation is actually evaluated. Optionally, one of the semantic
5652/// forms may also provide a result value for the expression.
5653///
5654/// If any of the semantic-form expressions is an OpaqueValueExpr,
5655/// that OVE is required to have a source expression, and it is bound
5656/// to the result of that source expression. Such OVEs may appear
5657/// only in subsequent semantic-form expressions and as
5658/// sub-expressions of the syntactic form.
5659///
5660/// PseudoObjectExpr should be used only when an operation can be
5661/// usefully described in terms of fairly simple rewrite rules on
5662/// objects and functions that are meant to be used by end-developers.
5663/// For example, under the Itanium ABI, dynamic casts are implemented
5664/// as a call to a runtime function called __dynamic_cast; using this
5665/// class to describe that would be inappropriate because that call is
5666/// not really part of the user-visible semantics, and instead the
5667/// cast is properly reflected in the AST and IR-generation has been
5668/// taught to generate the call as necessary. In contrast, an
5669/// Objective-C property access is semantically defined to be
5670/// equivalent to a particular message send, and this is very much
5671/// part of the user model. The name of this class encourages this
5672/// modelling design.
5673class PseudoObjectExpr final
5674 : public Expr,
5675 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
5676 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
5677 // Always at least two, because the first sub-expression is the
5678 // syntactic form.
5679
5680 // PseudoObjectExprBits.ResultIndex - The index of the
5681 // sub-expression holding the result. 0 means the result is void,
5682 // which is unambiguous because it's the index of the syntactic
5683 // form. Note that this is therefore 1 higher than the value passed
5684 // in to Create, which is an index within the semantic forms.
5685 // Note also that ASTStmtWriter assumes this encoding.
5686
5687 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
5688 const Expr * const *getSubExprsBuffer() const {
5689 return getTrailingObjects<Expr *>();
5690 }
5691
5692 PseudoObjectExpr(QualType type, ExprValueKind VK,
5693 Expr *syntactic, ArrayRef<Expr*> semantic,
5694 unsigned resultIndex);
5695
5696 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
5697
5698 unsigned getNumSubExprs() const {
5699 return PseudoObjectExprBits.NumSubExprs;
5700 }
5701
5702public:
5703 /// NoResult - A value for the result index indicating that there is
5704 /// no semantic result.
5705 enum : unsigned { NoResult = ~0U };
5706
5707 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5708 ArrayRef<Expr*> semantic,
5709 unsigned resultIndex);
5710
5711 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5712 unsigned numSemanticExprs);
5713
5714 /// Return the syntactic form of this expression, i.e. the
5715 /// expression it actually looks like. Likely to be expressed in
5716 /// terms of OpaqueValueExprs bound in the semantic form.
5717 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5718 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5719
5720 /// Return the index of the result-bearing expression into the semantics
5721 /// expressions, or PseudoObjectExpr::NoResult if there is none.
5722 unsigned getResultExprIndex() const {
5723 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
5724 return PseudoObjectExprBits.ResultIndex - 1;
5725 }
5726
5727 /// Return the result-bearing expression, or null if there is none.
5728 Expr *getResultExpr() {
5729 if (PseudoObjectExprBits.ResultIndex == 0)
5730 return nullptr;
5731 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5732 }
5733 const Expr *getResultExpr() const {
5734 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5735 }
5736
5737 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5738
5739 typedef Expr * const *semantics_iterator;
5740 typedef const Expr * const *const_semantics_iterator;
5741 semantics_iterator semantics_begin() {
5742 return getSubExprsBuffer() + 1;
5743 }
5744 const_semantics_iterator semantics_begin() const {
5745 return getSubExprsBuffer() + 1;
5746 }
5747 semantics_iterator semantics_end() {
5748 return getSubExprsBuffer() + getNumSubExprs();
5749 }
5750 const_semantics_iterator semantics_end() const {
5751 return getSubExprsBuffer() + getNumSubExprs();
5752 }
5753
5754 llvm::iterator_range<semantics_iterator> semantics() {
5755 return llvm::make_range(semantics_begin(), semantics_end());
5756 }
5757 llvm::iterator_range<const_semantics_iterator> semantics() const {
5758 return llvm::make_range(semantics_begin(), semantics_end());
5759 }
5760
5761 Expr *getSemanticExpr(unsigned index) {
5762 assert(index + 1 < getNumSubExprs())((index + 1 < getNumSubExprs()) ? static_cast<void> (
0) : __assert_fail ("index + 1 < getNumSubExprs()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5762, __PRETTY_FUNCTION__))
;
5763 return getSubExprsBuffer()[index + 1];
5764 }
5765 const Expr *getSemanticExpr(unsigned index) const {
5766 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5767 }
5768
5769 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
5770 return getSyntacticForm()->getExprLoc();
5771 }
5772
5773 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
5774 return getSyntacticForm()->getBeginLoc();
5775 }
5776 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
5777 return getSyntacticForm()->getEndLoc();
5778 }
5779
5780 child_range children() {
5781 const_child_range CCR =
5782 const_cast<const PseudoObjectExpr *>(this)->children();
5783 return child_range(cast_away_const(CCR.begin()),
5784 cast_away_const(CCR.end()));
5785 }
5786 const_child_range children() const {
5787 Stmt *const *cs = const_cast<Stmt *const *>(
5788 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5789 return const_child_range(cs, cs + getNumSubExprs());
5790 }
5791
5792 static bool classof(const Stmt *T) {
5793 return T->getStmtClass() == PseudoObjectExprClass;
5794 }
5795
5796 friend TrailingObjects;
5797 friend class ASTStmtReader;
5798};
5799
5800/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5801/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5802/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5803/// and corresponding __opencl_atomic_* for OpenCL 2.0.
5804/// All of these instructions take one primary pointer, at least one memory
5805/// order. The instructions for which getScopeModel returns non-null value
5806/// take one synch scope.
5807class AtomicExpr : public Expr {
5808public:
5809 enum AtomicOp {
5810#define BUILTIN(ID, TYPE, ATTRS)
5811#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5812#include "clang/Basic/Builtins.def"
5813 // Avoid trailing comma
5814 BI_First = 0
5815 };
5816
5817private:
5818 /// Location of sub-expressions.
5819 /// The location of Scope sub-expression is NumSubExprs - 1, which is
5820 /// not fixed, therefore is not defined in enum.
5821 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5822 Stmt *SubExprs[END_EXPR + 1];
5823 unsigned NumSubExprs;
5824 SourceLocation BuiltinLoc, RParenLoc;
5825 AtomicOp Op;
5826
5827 friend class ASTStmtReader;
5828public:
5829 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5830 AtomicOp op, SourceLocation RP);
5831
5832 /// Determine the number of arguments the specified atomic builtin
5833 /// should have.
5834 static unsigned getNumSubExprs(AtomicOp Op);
5835
5836 /// Build an empty AtomicExpr.
5837 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5838
5839 Expr *getPtr() const {
5840 return cast<Expr>(SubExprs[PTR]);
5841 }
5842 Expr *getOrder() const {
5843 return cast<Expr>(SubExprs[ORDER]);
5844 }
5845 Expr *getScope() const {
5846 assert(getScopeModel() && "No scope")((getScopeModel() && "No scope") ? static_cast<void
> (0) : __assert_fail ("getScopeModel() && \"No scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5846, __PRETTY_FUNCTION__))
;
5847 return cast<Expr>(SubExprs[NumSubExprs - 1]);
5848 }
5849 Expr *getVal1() const {
5850 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
5851 return cast<Expr>(SubExprs[ORDER]);
5852 assert(NumSubExprs > VAL1)((NumSubExprs > VAL1) ? static_cast<void> (0) : __assert_fail
("NumSubExprs > VAL1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5852, __PRETTY_FUNCTION__))
;
5853 return cast<Expr>(SubExprs[VAL1]);
5854 }
5855 Expr *getOrderFail() const {
5856 assert(NumSubExprs > ORDER_FAIL)((NumSubExprs > ORDER_FAIL) ? static_cast<void> (0) :
__assert_fail ("NumSubExprs > ORDER_FAIL", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5856, __PRETTY_FUNCTION__))
;
5857 return cast<Expr>(SubExprs[ORDER_FAIL]);
5858 }
5859 Expr *getVal2() const {
5860 if (Op == AO__atomic_exchange)
5861 return cast<Expr>(SubExprs[ORDER_FAIL]);
5862 assert(NumSubExprs > VAL2)((NumSubExprs > VAL2) ? static_cast<void> (0) : __assert_fail
("NumSubExprs > VAL2", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5862, __PRETTY_FUNCTION__))
;
5863 return cast<Expr>(SubExprs[VAL2]);
5864 }
5865 Expr *getWeak() const {
5866 assert(NumSubExprs > WEAK)((NumSubExprs > WEAK) ? static_cast<void> (0) : __assert_fail
("NumSubExprs > WEAK", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5866, __PRETTY_FUNCTION__))
;
5867 return cast<Expr>(SubExprs[WEAK]);
5868 }
5869 QualType getValueType() const;
5870
5871 AtomicOp getOp() const { return Op; }
5872 unsigned getNumSubExprs() const { return NumSubExprs; }
5873
5874 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5875 const Expr * const *getSubExprs() const {
5876 return reinterpret_cast<Expr * const *>(SubExprs);
5877 }
5878
5879 bool isVolatile() const {
5880 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5881 }
5882
5883 bool isCmpXChg() const {
5884 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5885 getOp() == AO__c11_atomic_compare_exchange_weak ||
5886 getOp() == AO__opencl_atomic_compare_exchange_strong ||
5887 getOp() == AO__opencl_atomic_compare_exchange_weak ||
5888 getOp() == AO__atomic_compare_exchange ||
5889 getOp() == AO__atomic_compare_exchange_n;
5890 }
5891
5892 bool isOpenCL() const {
5893 return getOp() >= AO__opencl_atomic_init &&
5894 getOp() <= AO__opencl_atomic_fetch_max;
5895 }
5896
5897 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5898 SourceLocation getRParenLoc() const { return RParenLoc; }
5899
5900 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; }
5901 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
5902
5903 static bool classof(const Stmt *T) {
5904 return T->getStmtClass() == AtomicExprClass;
5905 }
5906
5907 // Iterators
5908 child_range children() {
5909 return child_range(SubExprs, SubExprs+NumSubExprs);
5910 }
5911 const_child_range children() const {
5912 return const_child_range(SubExprs, SubExprs + NumSubExprs);
5913 }
5914
5915 /// Get atomic scope model for the atomic op code.
5916 /// \return empty atomic scope model if the atomic op code does not have
5917 /// scope operand.
5918 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5919 auto Kind =
5920 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
5921 ? AtomicScopeModelKind::OpenCL
5922 : AtomicScopeModelKind::None;
5923 return AtomicScopeModel::create(Kind);
5924 }
5925
5926 /// Get atomic scope model.
5927 /// \return empty atomic scope model if this atomic expression does not have
5928 /// scope operand.
5929 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5930 return getScopeModel(getOp());
5931 }
5932};
5933
5934/// TypoExpr - Internal placeholder for expressions where typo correction
5935/// still needs to be performed and/or an error diagnostic emitted.
5936class TypoExpr : public Expr {
5937public:
5938 TypoExpr(QualType T)
5939 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5940 /*isTypeDependent*/ true,
5941 /*isValueDependent*/ true,
5942 /*isInstantiationDependent*/ true,
5943 /*containsUnexpandedParameterPack*/ false) {
5944 assert(T->isDependentType() && "TypoExpr given a non-dependent type")((T->isDependentType() && "TypoExpr given a non-dependent type"
) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"TypoExpr given a non-dependent type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 5944, __PRETTY_FUNCTION__))
;
5945 }
5946
5947 child_range children() {
5948 return child_range(child_iterator(), child_iterator());
5949 }
5950 const_child_range children() const {
5951 return const_child_range(const_child_iterator(), const_child_iterator());
5952 }
5953
5954 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5955 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); }
5956
5957 static bool classof(const Stmt *T) {
5958 return T->getStmtClass() == TypoExprClass;
5959 }
5960
5961};
5962} // end namespace clang
5963
5964#endif // LLVM_CLANG_AST_EXPR_H

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h

1//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This is the internal per-function state used for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
14#define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15
16#include "CGBuilder.h"
17#include "CGDebugInfo.h"
18#include "CGLoopInfo.h"
19#include "CGValue.h"
20#include "CodeGenModule.h"
21#include "CodeGenPGO.h"
22#include "EHScopeStack.h"
23#include "VarBypassDetector.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/CurrentSourceLocExprScope.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/Type.h"
30#include "clang/Basic/ABI.h"
31#include "clang/Basic/CapturedStmt.h"
32#include "clang/Basic/CodeGenOptions.h"
33#include "clang/Basic/OpenMPKinds.h"
34#include "clang/Basic/TargetInfo.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/MapVector.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/IR/ValueHandle.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Transforms/Utils/SanitizerStats.h"
42
43namespace llvm {
44class BasicBlock;
45class LLVMContext;
46class MDNode;
47class Module;
48class SwitchInst;
49class Twine;
50class Value;
51}
52
53namespace clang {
54class ASTContext;
55class BlockDecl;
56class CXXDestructorDecl;
57class CXXForRangeStmt;
58class CXXTryStmt;
59class Decl;
60class LabelDecl;
61class EnumConstantDecl;
62class FunctionDecl;
63class FunctionProtoType;
64class LabelStmt;
65class ObjCContainerDecl;
66class ObjCInterfaceDecl;
67class ObjCIvarDecl;
68class ObjCMethodDecl;
69class ObjCImplementationDecl;
70class ObjCPropertyImplDecl;
71class TargetInfo;
72class VarDecl;
73class ObjCForCollectionStmt;
74class ObjCAtTryStmt;
75class ObjCAtThrowStmt;
76class ObjCAtSynchronizedStmt;
77class ObjCAutoreleasePoolStmt;
78
79namespace analyze_os_log {
80class OSLogBufferLayout;
81}
82
83namespace CodeGen {
84class CodeGenTypes;
85class CGCallee;
86class CGFunctionInfo;
87class CGRecordLayout;
88class CGBlockInfo;
89class CGCXXABI;
90class BlockByrefHelpers;
91class BlockByrefInfo;
92class BlockFlags;
93class BlockFieldFlags;
94class RegionCodeGenTy;
95class TargetCodeGenInfo;
96struct OMPTaskDataTy;
97struct CGCoroData;
98
99/// The kind of evaluation to perform on values of a particular
100/// type. Basically, is the code in CGExprScalar, CGExprComplex, or
101/// CGExprAgg?
102///
103/// TODO: should vectors maybe be split out into their own thing?
104enum TypeEvaluationKind {
105 TEK_Scalar,
106 TEK_Complex,
107 TEK_Aggregate
108};
109
110#define LIST_SANITIZER_CHECKSSANITIZER_CHECK(AddOverflow, add_overflow, 0) SANITIZER_CHECK
(BuiltinUnreachable, builtin_unreachable, 0) SANITIZER_CHECK(
CFICheckFail, cfi_check_fail, 0) SANITIZER_CHECK(DivremOverflow
, divrem_overflow, 0) SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss
, 0) SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0
) SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch
, 1) SANITIZER_CHECK(ImplicitConversion, implicit_conversion,
0) SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) SANITIZER_CHECK
(LoadInvalidValue, load_invalid_value, 0) SANITIZER_CHECK(MissingReturn
, missing_return, 0) SANITIZER_CHECK(MulOverflow, mul_overflow
, 0) SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) SANITIZER_CHECK
(NullabilityArg, nullability_arg, 0) SANITIZER_CHECK(NullabilityReturn
, nullability_return, 1) SANITIZER_CHECK(NonnullArg, nonnull_arg
, 0) SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) SANITIZER_CHECK
(OutOfBounds, out_of_bounds, 0) SANITIZER_CHECK(PointerOverflow
, pointer_overflow, 0) SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds
, 0) SANITIZER_CHECK(SubOverflow, sub_overflow, 0) SANITIZER_CHECK
(TypeMismatch, type_mismatch, 1) SANITIZER_CHECK(AlignmentAssumption
, alignment_assumption, 0) SANITIZER_CHECK(VLABoundNotPositive
, vla_bound_not_positive, 0)
\
111 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
112 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
113 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
114 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
115 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
116 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
117 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \
118 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
119 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
120 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
121 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
122 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
123 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
124 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
125 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
126 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
127 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
128 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
129 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
130 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
131 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
132 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
133 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
134 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
135
136enum SanitizerHandler {
137#define SANITIZER_CHECK(Enum, Name, Version) Enum,
138 LIST_SANITIZER_CHECKSSANITIZER_CHECK(AddOverflow, add_overflow, 0) SANITIZER_CHECK
(BuiltinUnreachable, builtin_unreachable, 0) SANITIZER_CHECK(
CFICheckFail, cfi_check_fail, 0) SANITIZER_CHECK(DivremOverflow
, divrem_overflow, 0) SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss
, 0) SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0
) SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch
, 1) SANITIZER_CHECK(ImplicitConversion, implicit_conversion,
0) SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) SANITIZER_CHECK
(LoadInvalidValue, load_invalid_value, 0) SANITIZER_CHECK(MissingReturn
, missing_return, 0) SANITIZER_CHECK(MulOverflow, mul_overflow
, 0) SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) SANITIZER_CHECK
(NullabilityArg, nullability_arg, 0) SANITIZER_CHECK(NullabilityReturn
, nullability_return, 1) SANITIZER_CHECK(NonnullArg, nonnull_arg
, 0) SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) SANITIZER_CHECK
(OutOfBounds, out_of_bounds, 0) SANITIZER_CHECK(PointerOverflow
, pointer_overflow, 0) SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds
, 0) SANITIZER_CHECK(SubOverflow, sub_overflow, 0) SANITIZER_CHECK
(TypeMismatch, type_mismatch, 1) SANITIZER_CHECK(AlignmentAssumption
, alignment_assumption, 0) SANITIZER_CHECK(VLABoundNotPositive
, vla_bound_not_positive, 0)
139#undef SANITIZER_CHECK
140};
141
142/// Helper class with most of the code for saving a value for a
143/// conditional expression cleanup.
144struct DominatingLLVMValue {
145 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
146
147 /// Answer whether the given value needs extra work to be saved.
148 static bool needsSaving(llvm::Value *value) {
149 // If it's not an instruction, we don't need to save.
150 if (!isa<llvm::Instruction>(value)) return false;
151
152 // If it's an instruction in the entry block, we don't need to save.
153 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
154 return (block != &block->getParent()->getEntryBlock());
155 }
156
157 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
158 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
159};
160
161/// A partial specialization of DominatingValue for llvm::Values that
162/// might be llvm::Instructions.
163template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
164 typedef T *type;
165 static type restore(CodeGenFunction &CGF, saved_type value) {
166 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
167 }
168};
169
170/// A specialization of DominatingValue for Address.
171template <> struct DominatingValue<Address> {
172 typedef Address type;
173
174 struct saved_type {
175 DominatingLLVMValue::saved_type SavedValue;
176 CharUnits Alignment;
177 };
178
179 static bool needsSaving(type value) {
180 return DominatingLLVMValue::needsSaving(value.getPointer());
181 }
182 static saved_type save(CodeGenFunction &CGF, type value) {
183 return { DominatingLLVMValue::save(CGF, value.getPointer()),
184 value.getAlignment() };
185 }
186 static type restore(CodeGenFunction &CGF, saved_type value) {
187 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
188 value.Alignment);
189 }
190};
191
192/// A specialization of DominatingValue for RValue.
193template <> struct DominatingValue<RValue> {
194 typedef RValue type;
195 class saved_type {
196 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
197 AggregateAddress, ComplexAddress };
198
199 llvm::Value *Value;
200 unsigned K : 3;
201 unsigned Align : 29;
202 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
203 : Value(v), K(k), Align(a) {}
204
205 public:
206 static bool needsSaving(RValue value);
207 static saved_type save(CodeGenFunction &CGF, RValue value);
208 RValue restore(CodeGenFunction &CGF);
209
210 // implementations in CGCleanup.cpp
211 };
212
213 static bool needsSaving(type value) {
214 return saved_type::needsSaving(value);
215 }
216 static saved_type save(CodeGenFunction &CGF, type value) {
217 return saved_type::save(CGF, value);
218 }
219 static type restore(CodeGenFunction &CGF, saved_type value) {
220 return value.restore(CGF);
221 }
222};
223
224/// CodeGenFunction - This class organizes the per-function state that is used
225/// while generating LLVM code.
226class CodeGenFunction : public CodeGenTypeCache {
227 CodeGenFunction(const CodeGenFunction &) = delete;
228 void operator=(const CodeGenFunction &) = delete;
229
230 friend class CGCXXABI;
231public:
232 /// A jump destination is an abstract label, branching to which may
233 /// require a jump out through normal cleanups.
234 struct JumpDest {
235 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
236 JumpDest(llvm::BasicBlock *Block,
237 EHScopeStack::stable_iterator Depth,
238 unsigned Index)
239 : Block(Block), ScopeDepth(Depth), Index(Index) {}
240
241 bool isValid() const { return Block != nullptr; }
242 llvm::BasicBlock *getBlock() const { return Block; }
243 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
244 unsigned getDestIndex() const { return Index; }
245
246 // This should be used cautiously.
247 void setScopeDepth(EHScopeStack::stable_iterator depth) {
248 ScopeDepth = depth;
249 }
250
251 private:
252 llvm::BasicBlock *Block;
253 EHScopeStack::stable_iterator ScopeDepth;
254 unsigned Index;
255 };
256
257 CodeGenModule &CGM; // Per-module state.
258 const TargetInfo &Target;
259
260 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
261 LoopInfoStack LoopStack;
262 CGBuilderTy Builder;
263
264 // Stores variables for which we can't generate correct lifetime markers
265 // because of jumps.
266 VarBypassDetector Bypasses;
267
268 // CodeGen lambda for loops and support for ordered clause
269 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
270 JumpDest)>
271 CodeGenLoopTy;
272 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
273 const unsigned, const bool)>
274 CodeGenOrderedTy;
275
276 // Codegen lambda for loop bounds in worksharing loop constructs
277 typedef llvm::function_ref<std::pair<LValue, LValue>(
278 CodeGenFunction &, const OMPExecutableDirective &S)>
279 CodeGenLoopBoundsTy;
280
281 // Codegen lambda for loop bounds in dispatch-based loop implementation
282 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
283 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
284 Address UB)>
285 CodeGenDispatchBoundsTy;
286
287 /// CGBuilder insert helper. This function is called after an
288 /// instruction is created using Builder.
289 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
290 llvm::BasicBlock *BB,
291 llvm::BasicBlock::iterator InsertPt) const;
292
293 /// CurFuncDecl - Holds the Decl for the current outermost
294 /// non-closure context.
295 const Decl *CurFuncDecl;
296 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
297 const Decl *CurCodeDecl;
298 const CGFunctionInfo *CurFnInfo;
299 QualType FnRetTy;
300 llvm::Function *CurFn = nullptr;
301
302 // Holds coroutine data if the current function is a coroutine. We use a
303 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
304 // in this header.
305 struct CGCoroInfo {
306 std::unique_ptr<CGCoroData> Data;
307 CGCoroInfo();
308 ~CGCoroInfo();
309 };
310 CGCoroInfo CurCoro;
311
312 bool isCoroutine() const {
313 return CurCoro.Data != nullptr;
314 }
315
316 /// CurGD - The GlobalDecl for the current function being compiled.
317 GlobalDecl CurGD;
318
319 /// PrologueCleanupDepth - The cleanup depth enclosing all the
320 /// cleanups associated with the parameters.
321 EHScopeStack::stable_iterator PrologueCleanupDepth;
322
323 /// ReturnBlock - Unified return block.
324 JumpDest ReturnBlock;
325
326 /// ReturnValue - The temporary alloca to hold the return
327 /// value. This is invalid iff the function has no return value.
328 Address ReturnValue = Address::invalid();
329
330 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
331 /// This is invalid if sret is not in use.
332 Address ReturnValuePointer = Address::invalid();
333
334 /// Return true if a label was seen in the current scope.
335 bool hasLabelBeenSeenInCurrentScope() const {
336 if (CurLexicalScope)
337 return CurLexicalScope->hasLabels();
338 return !LabelMap.empty();
339 }
340
341 /// AllocaInsertPoint - This is an instruction in the entry block before which
342 /// we prefer to insert allocas.
343 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
344
345 /// API for captured statement code generation.
346 class CGCapturedStmtInfo {
347 public:
348 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
349 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
350 explicit CGCapturedStmtInfo(const CapturedStmt &S,
351 CapturedRegionKind K = CR_Default)
352 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
353
354 RecordDecl::field_iterator Field =
355 S.getCapturedRecordDecl()->field_begin();
356 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
357 E = S.capture_end();
358 I != E; ++I, ++Field) {
359 if (I->capturesThis())
360 CXXThisFieldDecl = *Field;
361 else if (I->capturesVariable())
362 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
363 else if (I->capturesVariableByCopy())
364 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
365 }
366 }
367
368 virtual ~CGCapturedStmtInfo();
369
370 CapturedRegionKind getKind() const { return Kind; }
371
372 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
373 // Retrieve the value of the context parameter.
374 virtual llvm::Value *getContextValue() const { return ThisValue; }
375
376 /// Lookup the captured field decl for a variable.
377 virtual const FieldDecl *lookup(const VarDecl *VD) const {
378 return CaptureFields.lookup(VD->getCanonicalDecl());
379 }
380
381 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
382 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
383
384 static bool classof(const CGCapturedStmtInfo *) {
385 return true;
386 }
387
388 /// Emit the captured statement body.
389 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
390 CGF.incrementProfileCounter(S);
391 CGF.EmitStmt(S);
392 }
393
394 /// Get the name of the capture helper.
395 virtual StringRef getHelperName() const { return "__captured_stmt"; }
396
397 private:
398 /// The kind of captured statement being generated.
399 CapturedRegionKind Kind;
400
401 /// Keep the map between VarDecl and FieldDecl.
402 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
403
404 /// The base address of the captured record, passed in as the first
405 /// argument of the parallel region function.
406 llvm::Value *ThisValue;
407
408 /// Captured 'this' type.
409 FieldDecl *CXXThisFieldDecl;
410 };
411 CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
412
413 /// RAII for correct setting/restoring of CapturedStmtInfo.
414 class CGCapturedStmtRAII {
415 private:
416 CodeGenFunction &CGF;
417 CGCapturedStmtInfo *PrevCapturedStmtInfo;
418 public:
419 CGCapturedStmtRAII(CodeGenFunction &CGF,
420 CGCapturedStmtInfo *NewCapturedStmtInfo)
421 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
422 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
423 }
424 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
425 };
426
427 /// An abstract representation of regular/ObjC call/message targets.
428 class AbstractCallee {
429 /// The function declaration of the callee.
430 const Decl *CalleeDecl;
431
432 public:
433 AbstractCallee() : CalleeDecl(nullptr) {}
434 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
435 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
436 bool hasFunctionDecl() const {
437 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
438 }
439 const Decl *getDecl() const { return CalleeDecl; }
440 unsigned getNumParams() const {
441 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
442 return FD->getNumParams();
443 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
444 }
445 const ParmVarDecl *getParamDecl(unsigned I) const {
446 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
447 return FD->getParamDecl(I);
448 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
449 }
450 };
451
452 /// Sanitizers enabled for this function.
453 SanitizerSet SanOpts;
454
455 /// True if CodeGen currently emits code implementing sanitizer checks.
456 bool IsSanitizerScope = false;
457
458 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
459 class SanitizerScope {
460 CodeGenFunction *CGF;
461 public:
462 SanitizerScope(CodeGenFunction *CGF);
463 ~SanitizerScope();
464 };
465
466 /// In C++, whether we are code generating a thunk. This controls whether we
467 /// should emit cleanups.
468 bool CurFuncIsThunk = false;
469
470 /// In ARC, whether we should autorelease the return value.
471 bool AutoreleaseResult = false;
472
473 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
474 /// potentially set the return value.
475 bool SawAsmBlock = false;
476
477 const NamedDecl *CurSEHParent = nullptr;
478
479 /// True if the current function is an outlined SEH helper. This can be a
480 /// finally block or filter expression.
481 bool IsOutlinedSEHHelper = false;
482
483 /// True if CodeGen currently emits code inside presereved access index
484 /// region.
485 bool IsInPreservedAIRegion = false;
486
487 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
488 llvm::Value *BlockPointer = nullptr;
489
490 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
491 FieldDecl *LambdaThisCaptureField = nullptr;
492
493 /// A mapping from NRVO variables to the flags used to indicate
494 /// when the NRVO has been applied to this variable.
495 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
496
497 EHScopeStack EHStack;
498 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
499 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
500
501 llvm::Instruction *CurrentFuncletPad = nullptr;
502
503 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
504 llvm::Value *Addr;
505 llvm::Value *Size;
506
507 public:
508 CallLifetimeEnd(Address addr, llvm::Value *size)
509 : Addr(addr.getPointer()), Size(size) {}
510
511 void Emit(CodeGenFunction &CGF, Flags flags) override {
512 CGF.EmitLifetimeEnd(Size, Addr);
513 }
514 };
515
516 /// Header for data within LifetimeExtendedCleanupStack.
517 struct LifetimeExtendedCleanupHeader {
518 /// The size of the following cleanup object.
519 unsigned Size;
520 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
521 unsigned Kind : 31;
522 /// Whether this is a conditional cleanup.
523 unsigned IsConditional : 1;
524
525 size_t getSize() const { return Size; }
526 CleanupKind getKind() const { return (CleanupKind)Kind; }
527 bool isConditional() const { return IsConditional; }
528 };
529
530 /// i32s containing the indexes of the cleanup destinations.
531 Address NormalCleanupDest = Address::invalid();
532
533 unsigned NextCleanupDestIndex = 1;
534
535 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
536 CGBlockInfo *FirstBlockInfo = nullptr;
537
538 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
539 llvm::BasicBlock *EHResumeBlock = nullptr;
540
541 /// The exception slot. All landing pads write the current exception pointer
542 /// into this alloca.
543 llvm::Value *ExceptionSlot = nullptr;
544
545 /// The selector slot. Under the MandatoryCleanup model, all landing pads
546 /// write the current selector value into this alloca.
547 llvm::AllocaInst *EHSelectorSlot = nullptr;
548
549 /// A stack of exception code slots. Entering an __except block pushes a slot
550 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
551 /// a value from the top of the stack.
552 SmallVector<Address, 1> SEHCodeSlotStack;
553
554 /// Value returned by __exception_info intrinsic.
555 llvm::Value *SEHInfo = nullptr;
556
557 /// Emits a landing pad for the current EH stack.
558 llvm::BasicBlock *EmitLandingPad();
559
560 llvm::BasicBlock *getInvokeDestImpl();
561
562 template <class T>
563 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
564 return DominatingValue<T>::save(*this, value);
565 }
566
567public:
568 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
569 /// rethrows.
570 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
571
572 /// A class controlling the emission of a finally block.
573 class FinallyInfo {
574 /// Where the catchall's edge through the cleanup should go.
575 JumpDest RethrowDest;
576
577 /// A function to call to enter the catch.
578 llvm::FunctionCallee BeginCatchFn;
579
580 /// An i1 variable indicating whether or not the @finally is
581 /// running for an exception.
582 llvm::AllocaInst *ForEHVar;
583
584 /// An i8* variable into which the exception pointer to rethrow
585 /// has been saved.
586 llvm::AllocaInst *SavedExnVar;
587
588 public:
589 void enter(CodeGenFunction &CGF, const Stmt *Finally,
590 llvm::FunctionCallee beginCatchFn,
591 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
592 void exit(CodeGenFunction &CGF);
593 };
594
595 /// Returns true inside SEH __try blocks.
596 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
597
598 /// Returns true while emitting a cleanuppad.
599 bool isCleanupPadScope() const {
600 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
601 }
602
603 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
604 /// current full-expression. Safe against the possibility that
605 /// we're currently inside a conditionally-evaluated expression.
606 template <class T, class... As>
607 void pushFullExprCleanup(CleanupKind kind, As... A) {
608 // If we're not in a conditional branch, or if none of the
609 // arguments requires saving, then use the unconditional cleanup.
610 if (!isInConditionalBranch())
611 return EHStack.pushCleanup<T>(kind, A...);
612
613 // Stash values in a tuple so we can guarantee the order of saves.
614 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
615 SavedTuple Saved{saveValueInCond(A)...};
616
617 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
618 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
619 initFullExprCleanup();
620 }
621
622 /// Queue a cleanup to be pushed after finishing the current
623 /// full-expression.
624 template <class T, class... As>
625 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
626 if (!isInConditionalBranch())
627 return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...);
628
629 Address ActiveFlag = createCleanupActiveFlag();
630 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&((!DominatingValue<Address>::needsSaving(ActiveFlag) &&
"cleanup active flag should never need saving") ? static_cast
<void> (0) : __assert_fail ("!DominatingValue<Address>::needsSaving(ActiveFlag) && \"cleanup active flag should never need saving\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 631, __PRETTY_FUNCTION__))
631 "cleanup active flag should never need saving")((!DominatingValue<Address>::needsSaving(ActiveFlag) &&
"cleanup active flag should never need saving") ? static_cast
<void> (0) : __assert_fail ("!DominatingValue<Address>::needsSaving(ActiveFlag) && \"cleanup active flag should never need saving\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 631, __PRETTY_FUNCTION__))
;
632
633 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
634 SavedTuple Saved{saveValueInCond(A)...};
635
636 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
637 pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved);
638 }
639
640 template <class T, class... As>
641 void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag,
642 As... A) {
643 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
644 ActiveFlag.isValid()};
645
646 size_t OldSize = LifetimeExtendedCleanupStack.size();
647 LifetimeExtendedCleanupStack.resize(
648 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
649 (Header.IsConditional ? sizeof(ActiveFlag) : 0));
650
651 static_assert(sizeof(Header) % alignof(T) == 0,
652 "Cleanup will be allocated on misaligned address");
653 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
654 new (Buffer) LifetimeExtendedCleanupHeader(Header);
655 new (Buffer + sizeof(Header)) T(A...);
656 if (Header.IsConditional)
657 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
658 }
659
660 /// Set up the last cleanup that was pushed as a conditional
661 /// full-expression cleanup.
662 void initFullExprCleanup() {
663 initFullExprCleanupWithFlag(createCleanupActiveFlag());
664 }
665
666 void initFullExprCleanupWithFlag(Address ActiveFlag);
667 Address createCleanupActiveFlag();
668
669 /// PushDestructorCleanup - Push a cleanup to call the
670 /// complete-object destructor of an object of the given type at the
671 /// given address. Does nothing if T is not a C++ class type with a
672 /// non-trivial destructor.
673 void PushDestructorCleanup(QualType T, Address Addr);
674
675 /// PushDestructorCleanup - Push a cleanup to call the
676 /// complete-object variant of the given destructor on the object at
677 /// the given address.
678 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
679 Address Addr);
680
681 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
682 /// process all branch fixups.
683 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
684
685 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
686 /// The block cannot be reactivated. Pops it if it's the top of the
687 /// stack.
688 ///
689 /// \param DominatingIP - An instruction which is known to
690 /// dominate the current IP (if set) and which lies along
691 /// all paths of execution between the current IP and the
692 /// the point at which the cleanup comes into scope.
693 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
694 llvm::Instruction *DominatingIP);
695
696 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
697 /// Cannot be used to resurrect a deactivated cleanup.
698 ///
699 /// \param DominatingIP - An instruction which is known to
700 /// dominate the current IP (if set) and which lies along
701 /// all paths of execution between the current IP and the
702 /// the point at which the cleanup comes into scope.
703 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
704 llvm::Instruction *DominatingIP);
705
706 /// Enters a new scope for capturing cleanups, all of which
707 /// will be executed once the scope is exited.
708 class RunCleanupsScope {
709 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
710 size_t LifetimeExtendedCleanupStackSize;
711 bool OldDidCallStackSave;
712 protected:
713 bool PerformCleanup;
714 private:
715
716 RunCleanupsScope(const RunCleanupsScope &) = delete;
717 void operator=(const RunCleanupsScope &) = delete;
718
719 protected:
720 CodeGenFunction& CGF;
721
722 public:
723 /// Enter a new cleanup scope.
724 explicit RunCleanupsScope(CodeGenFunction &CGF)
725 : PerformCleanup(true), CGF(CGF)
726 {
727 CleanupStackDepth = CGF.EHStack.stable_begin();
728 LifetimeExtendedCleanupStackSize =
729 CGF.LifetimeExtendedCleanupStack.size();
730 OldDidCallStackSave = CGF.DidCallStackSave;
731 CGF.DidCallStackSave = false;
732 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
733 CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
734 }
735
736 /// Exit this cleanup scope, emitting any accumulated cleanups.
737 ~RunCleanupsScope() {
738 if (PerformCleanup)
739 ForceCleanup();
740 }
741
742 /// Determine whether this scope requires any cleanups.
743 bool requiresCleanups() const {
744 return CGF.EHStack.stable_begin() != CleanupStackDepth;
745 }
746
747 /// Force the emission of cleanups now, instead of waiting
748 /// until this object is destroyed.
749 /// \param ValuesToReload - A list of values that need to be available at
750 /// the insertion point after cleanup emission. If cleanup emission created
751 /// a shared cleanup block, these value pointers will be rewritten.
752 /// Otherwise, they not will be modified.
753 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
754 assert(PerformCleanup && "Already forced cleanup")((PerformCleanup && "Already forced cleanup") ? static_cast
<void> (0) : __assert_fail ("PerformCleanup && \"Already forced cleanup\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 754, __PRETTY_FUNCTION__))
;
755 CGF.DidCallStackSave = OldDidCallStackSave;
756 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
757 ValuesToReload);
758 PerformCleanup = false;
759 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
760 }
761 };
762
763 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
764 EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
765 EHScopeStack::stable_end();
766
767 class LexicalScope : public RunCleanupsScope {
768 SourceRange Range;
769 SmallVector<const LabelDecl*, 4> Labels;
770 LexicalScope *ParentScope;
771
772 LexicalScope(const LexicalScope &) = delete;
773 void operator=(const LexicalScope &) = delete;
774
775 public:
776 /// Enter a new cleanup scope.
777 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
778 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
779 CGF.CurLexicalScope = this;
780 if (CGDebugInfo *DI = CGF.getDebugInfo())
781 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
782 }
783
784 void addLabel(const LabelDecl *label) {
785 assert(PerformCleanup && "adding label to dead scope?")((PerformCleanup && "adding label to dead scope?") ? static_cast
<void> (0) : __assert_fail ("PerformCleanup && \"adding label to dead scope?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 785, __PRETTY_FUNCTION__))
;
786 Labels.push_back(label);
787 }
788
789 /// Exit this cleanup scope, emitting any accumulated
790 /// cleanups.
791 ~LexicalScope() {
792 if (CGDebugInfo *DI = CGF.getDebugInfo())
793 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
794
795 // If we should perform a cleanup, force them now. Note that
796 // this ends the cleanup scope before rescoping any labels.
797 if (PerformCleanup) {
798 ApplyDebugLocation DL(CGF, Range.getEnd());
799 ForceCleanup();
800 }
801 }
802
803 /// Force the emission of cleanups now, instead of waiting
804 /// until this object is destroyed.
805 void ForceCleanup() {
806 CGF.CurLexicalScope = ParentScope;
807 RunCleanupsScope::ForceCleanup();
808
809 if (!Labels.empty())
810 rescopeLabels();
811 }
812
813 bool hasLabels() const {
814 return !Labels.empty();
815 }
816
817 void rescopeLabels();
818 };
819
820 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
821
822 /// The class used to assign some variables some temporarily addresses.
823 class OMPMapVars {
824 DeclMapTy SavedLocals;
825 DeclMapTy SavedTempAddresses;
826 OMPMapVars(const OMPMapVars &) = delete;
827 void operator=(const OMPMapVars &) = delete;
828
829 public:
830 explicit OMPMapVars() = default;
831 ~OMPMapVars() {
832 assert(SavedLocals.empty() && "Did not restored original addresses.")((SavedLocals.empty() && "Did not restored original addresses."
) ? static_cast<void> (0) : __assert_fail ("SavedLocals.empty() && \"Did not restored original addresses.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 832, __PRETTY_FUNCTION__))
;
833 };
834
835 /// Sets the address of the variable \p LocalVD to be \p TempAddr in
836 /// function \p CGF.
837 /// \return true if at least one variable was set already, false otherwise.
838 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
839 Address TempAddr) {
840 LocalVD = LocalVD->getCanonicalDecl();
841 // Only save it once.
842 if (SavedLocals.count(LocalVD)) return false;
843
844 // Copy the existing local entry to SavedLocals.
845 auto it = CGF.LocalDeclMap.find(LocalVD);
846 if (it != CGF.LocalDeclMap.end())
847 SavedLocals.try_emplace(LocalVD, it->second);
848 else
849 SavedLocals.try_emplace(LocalVD, Address::invalid());
850
851 // Generate the private entry.
852 QualType VarTy = LocalVD->getType();
853 if (VarTy->isReferenceType()) {
854 Address Temp = CGF.CreateMemTemp(VarTy);
855 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
856 TempAddr = Temp;
857 }
858 SavedTempAddresses.try_emplace(LocalVD, TempAddr);
859
860 return true;
861 }
862
863 /// Applies new addresses to the list of the variables.
864 /// \return true if at least one variable is using new address, false
865 /// otherwise.
866 bool apply(CodeGenFunction &CGF) {
867 copyInto(SavedTempAddresses, CGF.LocalDeclMap);
868 SavedTempAddresses.clear();
869 return !SavedLocals.empty();
870 }
871
872 /// Restores original addresses of the variables.
873 void restore(CodeGenFunction &CGF) {
874 if (!SavedLocals.empty()) {
875 copyInto(SavedLocals, CGF.LocalDeclMap);
876 SavedLocals.clear();
877 }
878 }
879
880 private:
881 /// Copy all the entries in the source map over the corresponding
882 /// entries in the destination, which must exist.
883 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
884 for (auto &Pair : Src) {
885 if (!Pair.second.isValid()) {
886 Dest.erase(Pair.first);
887 continue;
888 }
889
890 auto I = Dest.find(Pair.first);
891 if (I != Dest.end())
892 I->second = Pair.second;
893 else
894 Dest.insert(Pair);
895 }
896 }
897 };
898
899 /// The scope used to remap some variables as private in the OpenMP loop body
900 /// (or other captured region emitted without outlining), and to restore old
901 /// vars back on exit.
902 class OMPPrivateScope : public RunCleanupsScope {
903 OMPMapVars MappedVars;
904 OMPPrivateScope(const OMPPrivateScope &) = delete;
905 void operator=(const OMPPrivateScope &) = delete;
906
907 public:
908 /// Enter a new OpenMP private scope.
909 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
910
911 /// Registers \p LocalVD variable as a private and apply \p PrivateGen
912 /// function for it to generate corresponding private variable. \p
913 /// PrivateGen returns an address of the generated private variable.
914 /// \return true if the variable is registered as private, false if it has
915 /// been privatized already.
916 bool addPrivate(const VarDecl *LocalVD,
917 const llvm::function_ref<Address()> PrivateGen) {
918 assert(PerformCleanup && "adding private to dead scope")((PerformCleanup && "adding private to dead scope") ?
static_cast<void> (0) : __assert_fail ("PerformCleanup && \"adding private to dead scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 918, __PRETTY_FUNCTION__))
;
919 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
920 }
921
922 /// Privatizes local variables previously registered as private.
923 /// Registration is separate from the actual privatization to allow
924 /// initializers use values of the original variables, not the private one.
925 /// This is important, for example, if the private variable is a class
926 /// variable initialized by a constructor that references other private
927 /// variables. But at initialization original variables must be used, not
928 /// private copies.
929 /// \return true if at least one variable was privatized, false otherwise.
930 bool Privatize() { return MappedVars.apply(CGF); }
931
932 void ForceCleanup() {
933 RunCleanupsScope::ForceCleanup();
934 MappedVars.restore(CGF);
935 }
936
937 /// Exit scope - all the mapped variables are restored.
938 ~OMPPrivateScope() {
939 if (PerformCleanup)
940 ForceCleanup();
941 }
942
943 /// Checks if the global variable is captured in current function.
944 bool isGlobalVarCaptured(const VarDecl *VD) const {
945 VD = VD->getCanonicalDecl();
946 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
947 }
948 };
949
950 /// Takes the old cleanup stack size and emits the cleanup blocks
951 /// that have been added.
952 void
953 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
954 std::initializer_list<llvm::Value **> ValuesToReload = {});
955
956 /// Takes the old cleanup stack size and emits the cleanup blocks
957 /// that have been added, then adds all lifetime-extended cleanups from
958 /// the given position to the stack.
959 void
960 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
961 size_t OldLifetimeExtendedStackSize,
962 std::initializer_list<llvm::Value **> ValuesToReload = {});
963
964 void ResolveBranchFixups(llvm::BasicBlock *Target);
965
966 /// The given basic block lies in the current EH scope, but may be a
967 /// target of a potentially scope-crossing jump; get a stable handle
968 /// to which we can perform this jump later.
969 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
970 return JumpDest(Target,
971 EHStack.getInnermostNormalCleanup(),
972 NextCleanupDestIndex++);
973 }
974
975 /// The given basic block lies in the current EH scope, but may be a
976 /// target of a potentially scope-crossing jump; get a stable handle
977 /// to which we can perform this jump later.
978 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
979 return getJumpDestInCurrentScope(createBasicBlock(Name));
980 }
981
982 /// EmitBranchThroughCleanup - Emit a branch from the current insert
983 /// block through the normal cleanup handling code (if any) and then
984 /// on to \arg Dest.
985 void EmitBranchThroughCleanup(JumpDest Dest);
986
987 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
988 /// specified destination obviously has no cleanups to run. 'false' is always
989 /// a conservatively correct answer for this method.
990 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
991
992 /// popCatchScope - Pops the catch scope at the top of the EHScope
993 /// stack, emitting any required code (other than the catch handlers
994 /// themselves).
995 void popCatchScope();
996
997 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
998 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
999 llvm::BasicBlock *
1000 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
1001
1002 /// An object to manage conditionally-evaluated expressions.
1003 class ConditionalEvaluation {
1004 llvm::BasicBlock *StartBB;
1005
1006 public:
1007 ConditionalEvaluation(CodeGenFunction &CGF)
1008 : StartBB(CGF.Builder.GetInsertBlock()) {}
1009
1010 void begin(CodeGenFunction &CGF) {
1011 assert(CGF.OutermostConditional != this)((CGF.OutermostConditional != this) ? static_cast<void>
(0) : __assert_fail ("CGF.OutermostConditional != this", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1011, __PRETTY_FUNCTION__))
;
1012 if (!CGF.OutermostConditional)
1013 CGF.OutermostConditional = this;
1014 }
1015
1016 void end(CodeGenFunction &CGF) {
1017 assert(CGF.OutermostConditional != nullptr)((CGF.OutermostConditional != nullptr) ? static_cast<void>
(0) : __assert_fail ("CGF.OutermostConditional != nullptr", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1017, __PRETTY_FUNCTION__))
;
1018 if (CGF.OutermostConditional == this)
1019 CGF.OutermostConditional = nullptr;
1020 }
1021
1022 /// Returns a block which will be executed prior to each
1023 /// evaluation of the conditional code.
1024 llvm::BasicBlock *getStartingBlock() const {
1025 return StartBB;
1026 }
1027 };
1028
1029 /// isInConditionalBranch - Return true if we're currently emitting
1030 /// one branch or the other of a conditional expression.
1031 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1032
1033 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1034 assert(isInConditionalBranch())((isInConditionalBranch()) ? static_cast<void> (0) : __assert_fail
("isInConditionalBranch()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1034, __PRETTY_FUNCTION__))
;
1035 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1036 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1037 store->setAlignment(addr.getAlignment().getQuantity());
1038 }
1039
1040 /// An RAII object to record that we're evaluating a statement
1041 /// expression.
1042 class StmtExprEvaluation {
1043 CodeGenFunction &CGF;
1044
1045 /// We have to save the outermost conditional: cleanups in a
1046 /// statement expression aren't conditional just because the
1047 /// StmtExpr is.
1048 ConditionalEvaluation *SavedOutermostConditional;
1049
1050 public:
1051 StmtExprEvaluation(CodeGenFunction &CGF)
1052 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1053 CGF.OutermostConditional = nullptr;
1054 }
1055
1056 ~StmtExprEvaluation() {
1057 CGF.OutermostConditional = SavedOutermostConditional;
1058 CGF.EnsureInsertPoint();
1059 }
1060 };
1061
1062 /// An object which temporarily prevents a value from being
1063 /// destroyed by aggressive peephole optimizations that assume that
1064 /// all uses of a value have been realized in the IR.
1065 class PeepholeProtection {
1066 llvm::Instruction *Inst;
1067 friend class CodeGenFunction;
1068
1069 public:
1070 PeepholeProtection() : Inst(nullptr) {}
1071 };
1072
1073 /// A non-RAII class containing all the information about a bound
1074 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1075 /// this which makes individual mappings very simple; using this
1076 /// class directly is useful when you have a variable number of
1077 /// opaque values or don't want the RAII functionality for some
1078 /// reason.
1079 class OpaqueValueMappingData {
1080 const OpaqueValueExpr *OpaqueValue;
1081 bool BoundLValue;
1082 CodeGenFunction::PeepholeProtection Protection;
1083
1084 OpaqueValueMappingData(const OpaqueValueExpr *ov,
1085 bool boundLValue)
1086 : OpaqueValue(ov), BoundLValue(boundLValue) {}
1087 public:
1088 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1089
1090 static bool shouldBindAsLValue(const Expr *expr) {
1091 // gl-values should be bound as l-values for obvious reasons.
1092 // Records should be bound as l-values because IR generation
1093 // always keeps them in memory. Expressions of function type
1094 // act exactly like l-values but are formally required to be
1095 // r-values in C.
1096 return expr->isGLValue() ||
1097 expr->getType()->isFunctionType() ||
1098 hasAggregateEvaluationKind(expr->getType());
1099 }
1100
1101 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1102 const OpaqueValueExpr *ov,
1103 const Expr *e) {
1104 if (shouldBindAsLValue(ov))
1105 return bind(CGF, ov, CGF.EmitLValue(e));
1106 return bind(CGF, ov, CGF.EmitAnyExpr(e));
1107 }
1108
1109 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1110 const OpaqueValueExpr *ov,
1111 const LValue &lv) {
1112 assert(shouldBindAsLValue(ov))((shouldBindAsLValue(ov)) ? static_cast<void> (0) : __assert_fail
("shouldBindAsLValue(ov)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1112, __PRETTY_FUNCTION__))
;
1113 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1114 return OpaqueValueMappingData(ov, true);
1115 }
1116
1117 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1118 const OpaqueValueExpr *ov,
1119 const RValue &rv) {
1120 assert(!shouldBindAsLValue(ov))((!shouldBindAsLValue(ov)) ? static_cast<void> (0) : __assert_fail
("!shouldBindAsLValue(ov)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1120, __PRETTY_FUNCTION__))
;
1121 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1122
1123 OpaqueValueMappingData data(ov, false);
1124
1125 // Work around an extremely aggressive peephole optimization in
1126 // EmitScalarConversion which assumes that all other uses of a
1127 // value are extant.
1128 data.Protection = CGF.protectFromPeepholes(rv);
1129
1130 return data;
1131 }
1132
1133 bool isValid() const { return OpaqueValue != nullptr; }
1134 void clear() { OpaqueValue = nullptr; }
1135
1136 void unbind(CodeGenFunction &CGF) {
1137 assert(OpaqueValue && "no data to unbind!")((OpaqueValue && "no data to unbind!") ? static_cast<
void> (0) : __assert_fail ("OpaqueValue && \"no data to unbind!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1137, __PRETTY_FUNCTION__))
;
1138
1139 if (BoundLValue) {
1140 CGF.OpaqueLValues.erase(OpaqueValue);
1141 } else {
1142 CGF.OpaqueRValues.erase(OpaqueValue);
1143 CGF.unprotectFromPeepholes(Protection);
1144 }
1145 }
1146 };
1147
1148 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1149 class OpaqueValueMapping {
1150 CodeGenFunction &CGF;
1151 OpaqueValueMappingData Data;
1152
1153 public:
1154 static bool shouldBindAsLValue(const Expr *expr) {
1155 return OpaqueValueMappingData::shouldBindAsLValue(expr);
1156 }
1157
1158 /// Build the opaque value mapping for the given conditional
1159 /// operator if it's the GNU ?: extension. This is a common
1160 /// enough pattern that the convenience operator is really
1161 /// helpful.
1162 ///
1163 OpaqueValueMapping(CodeGenFunction &CGF,
1164 const AbstractConditionalOperator *op) : CGF(CGF) {
1165 if (isa<ConditionalOperator>(op))
1166 // Leave Data empty.
1167 return;
1168
1169 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1170 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1171 e->getCommon());
1172 }
1173
1174 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1175 /// expression is set to the expression the OVE represents.
1176 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1177 : CGF(CGF) {
1178 if (OV) {
1179 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "((OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
"for OVE with no source expression") ? static_cast<void>
(0) : __assert_fail ("OV->getSourceExpr() && \"wrong form of OpaqueValueMapping used \" \"for OVE with no source expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1180, __PRETTY_FUNCTION__))
1180 "for OVE with no source expression")((OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
"for OVE with no source expression") ? static_cast<void>
(0) : __assert_fail ("OV->getSourceExpr() && \"wrong form of OpaqueValueMapping used \" \"for OVE with no source expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1180, __PRETTY_FUNCTION__))
;
1181 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1182 }
1183 }
1184
1185 OpaqueValueMapping(CodeGenFunction &CGF,
1186 const OpaqueValueExpr *opaqueValue,
1187 LValue lvalue)
1188 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1189 }
1190
1191 OpaqueValueMapping(CodeGenFunction &CGF,
1192 const OpaqueValueExpr *opaqueValue,
1193 RValue rvalue)
1194 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1195 }
1196
1197 void pop() {
1198 Data.unbind(CGF);
1199 Data.clear();
1200 }
1201
1202 ~OpaqueValueMapping() {
1203 if (Data.isValid()) Data.unbind(CGF);
1204 }
1205 };
1206
1207private:
1208 CGDebugInfo *DebugInfo;
1209 /// Used to create unique names for artificial VLA size debug info variables.
1210 unsigned VLAExprCounter = 0;
1211 bool DisableDebugInfo = false;
1212
1213 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1214 /// calling llvm.stacksave for multiple VLAs in the same scope.
1215 bool DidCallStackSave = false;
1216
1217 /// IndirectBranch - The first time an indirect goto is seen we create a block
1218 /// with an indirect branch. Every time we see the address of a label taken,
1219 /// we add the label to the indirect goto. Every subsequent indirect goto is
1220 /// codegen'd as a jump to the IndirectBranch's basic block.
1221 llvm::IndirectBrInst *IndirectBranch = nullptr;
1222
1223 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1224 /// decls.
1225 DeclMapTy LocalDeclMap;
1226
1227 // Keep track of the cleanups for callee-destructed parameters pushed to the
1228 // cleanup stack so that they can be deactivated later.
1229 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1230 CalleeDestructedParamCleanups;
1231
1232 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1233 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1234 /// parameter.
1235 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1236 SizeArguments;
1237
1238 /// Track escaped local variables with auto storage. Used during SEH
1239 /// outlining to produce a call to llvm.localescape.
1240 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1241
1242 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1243 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1244
1245 // BreakContinueStack - This keeps track of where break and continue
1246 // statements should jump to.
1247 struct BreakContinue {
1248 BreakContinue(JumpDest Break, JumpDest Continue)
1249 : BreakBlock(Break), ContinueBlock(Continue) {}
1250
1251 JumpDest BreakBlock;
1252 JumpDest ContinueBlock;
1253 };
1254 SmallVector<BreakContinue, 8> BreakContinueStack;
1255
1256 /// Handles cancellation exit points in OpenMP-related constructs.
1257 class OpenMPCancelExitStack {
1258 /// Tracks cancellation exit point and join point for cancel-related exit
1259 /// and normal exit.
1260 struct CancelExit {
1261 CancelExit() = default;
1262 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1263 JumpDest ContBlock)
1264 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1265 OpenMPDirectiveKind Kind = OMPD_unknown;
1266 /// true if the exit block has been emitted already by the special
1267 /// emitExit() call, false if the default codegen is used.
1268 bool HasBeenEmitted = false;
1269 JumpDest ExitBlock;
1270 JumpDest ContBlock;
1271 };
1272
1273 SmallVector<CancelExit, 8> Stack;
1274
1275 public:
1276 OpenMPCancelExitStack() : Stack(1) {}
1277 ~OpenMPCancelExitStack() = default;
1278 /// Fetches the exit block for the current OpenMP construct.
1279 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1280 /// Emits exit block with special codegen procedure specific for the related
1281 /// OpenMP construct + emits code for normal construct cleanup.
1282 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1283 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1284 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1285 assert(CGF.getOMPCancelDestination(Kind).isValid())((CGF.getOMPCancelDestination(Kind).isValid()) ? static_cast<
void> (0) : __assert_fail ("CGF.getOMPCancelDestination(Kind).isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1285, __PRETTY_FUNCTION__))
;
1286 assert(CGF.HaveInsertPoint())((CGF.HaveInsertPoint()) ? static_cast<void> (0) : __assert_fail
("CGF.HaveInsertPoint()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1286, __PRETTY_FUNCTION__))
;
1287 assert(!Stack.back().HasBeenEmitted)((!Stack.back().HasBeenEmitted) ? static_cast<void> (0)
: __assert_fail ("!Stack.back().HasBeenEmitted", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1287, __PRETTY_FUNCTION__))
;
1288 auto IP = CGF.Builder.saveAndClearIP();
1289 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1290 CodeGen(CGF);
1291 CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1292 CGF.Builder.restoreIP(IP);
1293 Stack.back().HasBeenEmitted = true;
1294 }
1295 CodeGen(CGF);
1296 }
1297 /// Enter the cancel supporting \a Kind construct.
1298 /// \param Kind OpenMP directive that supports cancel constructs.
1299 /// \param HasCancel true, if the construct has inner cancel directive,
1300 /// false otherwise.
1301 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1302 Stack.push_back({Kind,
1303 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1304 : JumpDest(),
1305 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1306 : JumpDest()});
1307 }
1308 /// Emits default exit point for the cancel construct (if the special one
1309 /// has not be used) + join point for cancel/normal exits.
1310 void exit(CodeGenFunction &CGF) {
1311 if (getExitBlock().isValid()) {
1312 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid())((CGF.getOMPCancelDestination(Stack.back().Kind).isValid()) ?
static_cast<void> (0) : __assert_fail ("CGF.getOMPCancelDestination(Stack.back().Kind).isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1312, __PRETTY_FUNCTION__))
;
1313 bool HaveIP = CGF.HaveInsertPoint();
1314 if (!Stack.back().HasBeenEmitted) {
1315 if (HaveIP)
1316 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1317 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1318 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1319 }
1320 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1321 if (!HaveIP) {
1322 CGF.Builder.CreateUnreachable();
1323 CGF.Builder.ClearInsertionPoint();
1324 }
1325 }
1326 Stack.pop_back();
1327 }
1328 };
1329 OpenMPCancelExitStack OMPCancelStack;
1330
1331 CodeGenPGO PGO;
1332
1333 /// Calculate branch weights appropriate for PGO data
1334 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1335 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1336 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1337 uint64_t LoopCount);
1338
1339public:
1340 /// Increment the profiler's counter for the given statement by \p StepV.
1341 /// If \p StepV is null, the default increment is 1.
1342 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1343 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1344 PGO.emitCounterIncrement(Builder, S, StepV);
1345 PGO.setCurrentStmt(S);
1346 }
1347
1348 /// Get the profiler's count for the given statement.
1349 uint64_t getProfileCount(const Stmt *S) {
1350 Optional<uint64_t> Count = PGO.getStmtCount(S);
1351 if (!Count.hasValue())
1352 return 0;
1353 return *Count;
1354 }
1355
1356 /// Set the profiler's current count.
1357 void setCurrentProfileCount(uint64_t Count) {
1358 PGO.setCurrentRegionCount(Count);
1359 }
1360
1361 /// Get the profiler's current count. This is generally the count for the most
1362 /// recently incremented counter.
1363 uint64_t getCurrentProfileCount() {
1364 return PGO.getCurrentRegionCount();
1365 }
1366
1367private:
1368
1369 /// SwitchInsn - This is nearest current switch instruction. It is null if
1370 /// current context is not in a switch.
1371 llvm::SwitchInst *SwitchInsn = nullptr;
1372 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1373 SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1374
1375 /// CaseRangeBlock - This block holds if condition check for last case
1376 /// statement range in current switch instruction.
1377 llvm::BasicBlock *CaseRangeBlock = nullptr;
1378
1379 /// OpaqueLValues - Keeps track of the current set of opaque value
1380 /// expressions.
1381 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1382 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1383
1384 // VLASizeMap - This keeps track of the associated size for each VLA type.
1385 // We track this by the size expression rather than the type itself because
1386 // in certain situations, like a const qualifier applied to an VLA typedef,
1387 // multiple VLA types can share the same size expression.
1388 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1389 // enter/leave scopes.
1390 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1391
1392 /// A block containing a single 'unreachable' instruction. Created
1393 /// lazily by getUnreachableBlock().
1394 llvm::BasicBlock *UnreachableBlock = nullptr;
1395
1396 /// Counts of the number return expressions in the function.
1397 unsigned NumReturnExprs = 0;
1398
1399 /// Count the number of simple (constant) return expressions in the function.
1400 unsigned NumSimpleReturnExprs = 0;
1401
1402 /// The last regular (non-return) debug location (breakpoint) in the function.
1403 SourceLocation LastStopPoint;
1404
1405public:
1406 /// Source location information about the default argument or member
1407 /// initializer expression we're evaluating, if any.
1408 CurrentSourceLocExprScope CurSourceLocExprScope;
1409 using SourceLocExprScopeGuard =
1410 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
1411
1412 /// A scope within which we are constructing the fields of an object which
1413 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1414 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1415 class FieldConstructionScope {
1416 public:
1417 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1418 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1419 CGF.CXXDefaultInitExprThis = This;
1420 }
1421 ~FieldConstructionScope() {
1422 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1423 }
1424
1425 private:
1426 CodeGenFunction &CGF;
1427 Address OldCXXDefaultInitExprThis;
1428 };
1429
1430 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1431 /// is overridden to be the object under construction.
1432 class CXXDefaultInitExprScope {
1433 public:
1434 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
1435 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1436 OldCXXThisAlignment(CGF.CXXThisAlignment),
1437 SourceLocScope(E, CGF.CurSourceLocExprScope) {
1438 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1439 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1440 }
1441 ~CXXDefaultInitExprScope() {
1442 CGF.CXXThisValue = OldCXXThisValue;
1443 CGF.CXXThisAlignment = OldCXXThisAlignment;
1444 }
1445
1446 public:
1447 CodeGenFunction &CGF;
1448 llvm::Value *OldCXXThisValue;
1449 CharUnits OldCXXThisAlignment;
1450 SourceLocExprScopeGuard SourceLocScope;
1451 };
1452
1453 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
1454 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
1455 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
1456 };
1457
1458 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1459 /// current loop index is overridden.
1460 class ArrayInitLoopExprScope {
1461 public:
1462 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1463 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1464 CGF.ArrayInitIndex = Index;
1465 }
1466 ~ArrayInitLoopExprScope() {
1467 CGF.ArrayInitIndex = OldArrayInitIndex;
1468 }
1469
1470 private:
1471 CodeGenFunction &CGF;
1472 llvm::Value *OldArrayInitIndex;
1473 };
1474
1475 class InlinedInheritingConstructorScope {
1476 public:
1477 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1478 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1479 OldCurCodeDecl(CGF.CurCodeDecl),
1480 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1481 OldCXXABIThisValue(CGF.CXXABIThisValue),
1482 OldCXXThisValue(CGF.CXXThisValue),
1483 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1484 OldCXXThisAlignment(CGF.CXXThisAlignment),
1485 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1486 OldCXXInheritedCtorInitExprArgs(
1487 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1488 CGF.CurGD = GD;
1489 CGF.CurFuncDecl = CGF.CurCodeDecl =
1490 cast<CXXConstructorDecl>(GD.getDecl());
1491 CGF.CXXABIThisDecl = nullptr;
1492 CGF.CXXABIThisValue = nullptr;
1493 CGF.CXXThisValue = nullptr;
1494 CGF.CXXABIThisAlignment = CharUnits();
1495 CGF.CXXThisAlignment = CharUnits();
1496 CGF.ReturnValue = Address::invalid();
1497 CGF.FnRetTy = QualType();
1498 CGF.CXXInheritedCtorInitExprArgs.clear();
1499 }
1500 ~InlinedInheritingConstructorScope() {
1501 CGF.CurGD = OldCurGD;
1502 CGF.CurFuncDecl = OldCurFuncDecl;
1503 CGF.CurCodeDecl = OldCurCodeDecl;
1504 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1505 CGF.CXXABIThisValue = OldCXXABIThisValue;
1506 CGF.CXXThisValue = OldCXXThisValue;
1507 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1508 CGF.CXXThisAlignment = OldCXXThisAlignment;
1509 CGF.ReturnValue = OldReturnValue;
1510 CGF.FnRetTy = OldFnRetTy;
1511 CGF.CXXInheritedCtorInitExprArgs =
1512 std::move(OldCXXInheritedCtorInitExprArgs);
1513 }
1514
1515 private:
1516 CodeGenFunction &CGF;
1517 GlobalDecl OldCurGD;
1518 const Decl *OldCurFuncDecl;
1519 const Decl *OldCurCodeDecl;
1520 ImplicitParamDecl *OldCXXABIThisDecl;
1521 llvm::Value *OldCXXABIThisValue;
1522 llvm::Value *OldCXXThisValue;
1523 CharUnits OldCXXABIThisAlignment;
1524 CharUnits OldCXXThisAlignment;
1525 Address OldReturnValue;
1526 QualType OldFnRetTy;
1527 CallArgList OldCXXInheritedCtorInitExprArgs;
1528 };
1529
1530private:
1531 /// CXXThisDecl - When generating code for a C++ member function,
1532 /// this will hold the implicit 'this' declaration.
1533 ImplicitParamDecl *CXXABIThisDecl = nullptr;
1534 llvm::Value *CXXABIThisValue = nullptr;
1535 llvm::Value *CXXThisValue = nullptr;
1536 CharUnits CXXABIThisAlignment;
1537 CharUnits CXXThisAlignment;
1538
1539 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1540 /// this expression.
1541 Address CXXDefaultInitExprThis = Address::invalid();
1542
1543 /// The current array initialization index when evaluating an
1544 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1545 llvm::Value *ArrayInitIndex = nullptr;
1546
1547 /// The values of function arguments to use when evaluating
1548 /// CXXInheritedCtorInitExprs within this context.
1549 CallArgList CXXInheritedCtorInitExprArgs;
1550
1551 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1552 /// destructor, this will hold the implicit argument (e.g. VTT).
1553 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1554 llvm::Value *CXXStructorImplicitParamValue = nullptr;
1555
1556 /// OutermostConditional - Points to the outermost active
1557 /// conditional control. This is used so that we know if a
1558 /// temporary should be destroyed conditionally.
1559 ConditionalEvaluation *OutermostConditional = nullptr;
1560
1561 /// The current lexical scope.
1562 LexicalScope *CurLexicalScope = nullptr;
1563
1564 /// The current source location that should be used for exception
1565 /// handling code.
1566 SourceLocation CurEHLocation;
1567
1568 /// BlockByrefInfos - For each __block variable, contains
1569 /// information about the layout of the variable.
1570 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1571
1572 /// Used by -fsanitize=nullability-return to determine whether the return
1573 /// value can be checked.
1574 llvm::Value *RetValNullabilityPrecondition = nullptr;
1575
1576 /// Check if -fsanitize=nullability-return instrumentation is required for
1577 /// this function.
1578 bool requiresReturnValueNullabilityCheck() const {
1579 return RetValNullabilityPrecondition;
1580 }
1581
1582 /// Used to store precise source locations for return statements by the
1583 /// runtime return value checks.
1584 Address ReturnLocation = Address::invalid();
1585
1586 /// Check if the return value of this function requires sanitization.
1587 bool requiresReturnValueCheck() const {
1588 return requiresReturnValueNullabilityCheck() ||
1589 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1590 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
1591 }
1592
1593 llvm::BasicBlock *TerminateLandingPad = nullptr;
1594 llvm::BasicBlock *TerminateHandler = nullptr;
1595 llvm::BasicBlock *TrapBB = nullptr;
1596
1597 /// Terminate funclets keyed by parent funclet pad.
1598 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
1599
1600 /// Largest vector width used in ths function. Will be used to create a
1601 /// function attribute.
1602 unsigned LargestVectorWidth = 0;
1603
1604 /// True if we need emit the life-time markers.
1605 const bool ShouldEmitLifetimeMarkers;
1606
1607 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
1608 /// the function metadata.
1609 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1610 llvm::Function *Fn);
1611
1612public:
1613 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1614 ~CodeGenFunction();
1615
1616 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1617 ASTContext &getContext() const { return CGM.getContext(); }
1618 CGDebugInfo *getDebugInfo() {
1619 if (DisableDebugInfo)
1620 return nullptr;
1621 return DebugInfo;
1622 }
1623 void disableDebugInfo() { DisableDebugInfo = true; }
1624 void enableDebugInfo() { DisableDebugInfo = false; }
1625
1626 bool shouldUseFusedARCCalls() {
1627 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1628 }
1629
1630 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1631
1632 /// Returns a pointer to the function's exception object and selector slot,
1633 /// which is assigned in every landing pad.
1634 Address getExceptionSlot();
1635 Address getEHSelectorSlot();
1636
1637 /// Returns the contents of the function's exception object and selector
1638 /// slots.
1639 llvm::Value *getExceptionFromSlot();
1640 llvm::Value *getSelectorFromSlot();
1641
1642 Address getNormalCleanupDestSlot();
1643
1644 llvm::BasicBlock *getUnreachableBlock() {
1645 if (!UnreachableBlock) {
1646 UnreachableBlock = createBasicBlock("unreachable");
1647 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1648 }
1649 return UnreachableBlock;
1650 }
1651
1652 llvm::BasicBlock *getInvokeDest() {
1653 if (!EHStack.requiresLandingPad()) return nullptr;
1654 return getInvokeDestImpl();
1655 }
1656
1657 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1658
1659 const TargetInfo &getTarget() const { return Target; }
1660 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1661 const TargetCodeGenInfo &getTargetHooks() const {
1662 return CGM.getTargetCodeGenInfo();
1663 }
1664
1665 //===--------------------------------------------------------------------===//
1666 // Cleanups
1667 //===--------------------------------------------------------------------===//
1668
1669 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1670
1671 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1672 Address arrayEndPointer,
1673 QualType elementType,
1674 CharUnits elementAlignment,
1675 Destroyer *destroyer);
1676 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1677 llvm::Value *arrayEnd,
1678 QualType elementType,
1679 CharUnits elementAlignment,
1680 Destroyer *destroyer);
1681
1682 void pushDestroy(QualType::DestructionKind dtorKind,
1683 Address addr, QualType type);
1684 void pushEHDestroy(QualType::DestructionKind dtorKind,
1685 Address addr, QualType type);
1686 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1687 Destroyer *destroyer, bool useEHCleanupForArray);
1688 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1689 QualType type, Destroyer *destroyer,
1690 bool useEHCleanupForArray);
1691 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1692 llvm::Value *CompletePtr,
1693 QualType ElementType);
1694 void pushStackRestore(CleanupKind kind, Address SPMem);
1695 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1696 bool useEHCleanupForArray);
1697 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1698 Destroyer *destroyer,
1699 bool useEHCleanupForArray,
1700 const VarDecl *VD);
1701 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1702 QualType elementType, CharUnits elementAlign,
1703 Destroyer *destroyer,
1704 bool checkZeroLength, bool useEHCleanup);
1705
1706 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1707
1708 /// Determines whether an EH cleanup is required to destroy a type
1709 /// with the given destruction kind.
1710 bool needsEHCleanup(QualType::DestructionKind kind) {
1711 switch (kind) {
1712 case QualType::DK_none:
1713 return false;
1714 case QualType::DK_cxx_destructor:
1715 case QualType::DK_objc_weak_lifetime:
1716 case QualType::DK_nontrivial_c_struct:
1717 return getLangOpts().Exceptions;
1718 case QualType::DK_objc_strong_lifetime:
1719 return getLangOpts().Exceptions &&
1720 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1721 }
1722 llvm_unreachable("bad destruction kind")::llvm::llvm_unreachable_internal("bad destruction kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 1722)
;
1723 }
1724
1725 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1726 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1727 }
1728
1729 //===--------------------------------------------------------------------===//
1730 // Objective-C
1731 //===--------------------------------------------------------------------===//
1732
1733 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1734
1735 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1736
1737 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1738 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1739 const ObjCPropertyImplDecl *PID);
1740 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1741 const ObjCPropertyImplDecl *propImpl,
1742 const ObjCMethodDecl *GetterMothodDecl,
1743 llvm::Constant *AtomicHelperFn);
1744
1745 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1746 ObjCMethodDecl *MD, bool ctor);
1747
1748 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1749 /// for the given property.
1750 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1751 const ObjCPropertyImplDecl *PID);
1752 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1753 const ObjCPropertyImplDecl *propImpl,
1754 llvm::Constant *AtomicHelperFn);
1755
1756 //===--------------------------------------------------------------------===//
1757 // Block Bits
1758 //===--------------------------------------------------------------------===//
1759
1760 /// Emit block literal.
1761 /// \return an LLVM value which is a pointer to a struct which contains
1762 /// information about the block, including the block invoke function, the
1763 /// captured variables, etc.
1764 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1765 static void destroyBlockInfos(CGBlockInfo *info);
1766
1767 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1768 const CGBlockInfo &Info,
1769 const DeclMapTy &ldm,
1770 bool IsLambdaConversionToBlock,
1771 bool BuildGlobalBlock);
1772
1773 /// Check if \p T is a C++ class that has a destructor that can throw.
1774 static bool cxxDestructorCanThrow(QualType T);
1775
1776 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1777 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1778 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1779 const ObjCPropertyImplDecl *PID);
1780 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1781 const ObjCPropertyImplDecl *PID);
1782 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1783
1784 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
1785 bool CanThrow);
1786
1787 class AutoVarEmission;
1788
1789 void emitByrefStructureInit(const AutoVarEmission &emission);
1790
1791 /// Enter a cleanup to destroy a __block variable. Note that this
1792 /// cleanup should be a no-op if the variable hasn't left the stack
1793 /// yet; if a cleanup is required for the variable itself, that needs
1794 /// to be done externally.
1795 ///
1796 /// \param Kind Cleanup kind.
1797 ///
1798 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
1799 /// structure that will be passed to _Block_object_dispose. When
1800 /// \p LoadBlockVarAddr is true, the address of the field of the block
1801 /// structure that holds the address of the __block structure.
1802 ///
1803 /// \param Flags The flag that will be passed to _Block_object_dispose.
1804 ///
1805 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
1806 /// \p Addr to get the address of the __block structure.
1807 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
1808 bool LoadBlockVarAddr, bool CanThrow);
1809
1810 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1811 llvm::Value *ptr);
1812
1813 Address LoadBlockStruct();
1814 Address GetAddrOfBlockDecl(const VarDecl *var);
1815
1816 /// BuildBlockByrefAddress - Computes the location of the
1817 /// data in a variable which is declared as __block.
1818 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1819 bool followForward = true);
1820 Address emitBlockByrefAddress(Address baseAddr,
1821 const BlockByrefInfo &info,
1822 bool followForward,
1823 const llvm::Twine &name);
1824
1825 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1826
1827 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1828
1829 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1830 const CGFunctionInfo &FnInfo);
1831
1832 /// Annotate the function with an attribute that disables TSan checking at
1833 /// runtime.
1834 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
1835
1836 /// Emit code for the start of a function.
1837 /// \param Loc The location to be associated with the function.
1838 /// \param StartLoc The location of the function body.
1839 void StartFunction(GlobalDecl GD,
1840 QualType RetTy,
1841 llvm::Function *Fn,
1842 const CGFunctionInfo &FnInfo,
1843 const FunctionArgList &Args,
1844 SourceLocation Loc = SourceLocation(),
1845 SourceLocation StartLoc = SourceLocation());
1846
1847 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1848
1849 void EmitConstructorBody(FunctionArgList &Args);
1850 void EmitDestructorBody(FunctionArgList &Args);
1851 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1852 void EmitFunctionBody(const Stmt *Body);
1853 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1854
1855 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1856 CallArgList &CallArgs);
1857 void EmitLambdaBlockInvokeBody();
1858 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1859 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
1860 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
1861 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1862 }
1863 void EmitAsanPrologueOrEpilogue(bool Prologue);
1864
1865 /// Emit the unified return block, trying to avoid its emission when
1866 /// possible.
1867 /// \return The debug location of the user written return statement if the
1868 /// return block is is avoided.
1869 llvm::DebugLoc EmitReturnBlock();
1870
1871 /// FinishFunction - Complete IR generation of the current function. It is
1872 /// legal to call this function even if there is no current insertion point.
1873 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1874
1875 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1876 const CGFunctionInfo &FnInfo, bool IsUnprototyped);
1877
1878 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
1879 const ThunkInfo *Thunk, bool IsUnprototyped);
1880
1881 void FinishThunk();
1882
1883 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1884 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
1885 llvm::FunctionCallee Callee);
1886
1887 /// Generate a thunk for the given method.
1888 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1889 GlobalDecl GD, const ThunkInfo &Thunk,
1890 bool IsUnprototyped);
1891
1892 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1893 const CGFunctionInfo &FnInfo,
1894 GlobalDecl GD, const ThunkInfo &Thunk);
1895
1896 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1897 FunctionArgList &Args);
1898
1899 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1900
1901 /// Struct with all information about dynamic [sub]class needed to set vptr.
1902 struct VPtr {
1903 BaseSubobject Base;
1904 const CXXRecordDecl *NearestVBase;
1905 CharUnits OffsetFromNearestVBase;
1906 const CXXRecordDecl *VTableClass;
1907 };
1908
1909 /// Initialize the vtable pointer of the given subobject.
1910 void InitializeVTablePointer(const VPtr &vptr);
1911
1912 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1913
1914 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1915 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1916
1917 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1918 CharUnits OffsetFromNearestVBase,
1919 bool BaseIsNonVirtualPrimaryBase,
1920 const CXXRecordDecl *VTableClass,
1921 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1922
1923 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1924
1925 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1926 /// to by This.
1927 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1928 const CXXRecordDecl *VTableClass);
1929
1930 enum CFITypeCheckKind {
1931 CFITCK_VCall,
1932 CFITCK_NVCall,
1933 CFITCK_DerivedCast,
1934 CFITCK_UnrelatedCast,
1935 CFITCK_ICall,
1936 CFITCK_NVMFCall,
1937 CFITCK_VMFCall,
1938 };
1939
1940 /// Derived is the presumed address of an object of type T after a
1941 /// cast. If T is a polymorphic class type, emit a check that the virtual
1942 /// table for Derived belongs to a class derived from T.
1943 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1944 bool MayBeNull, CFITypeCheckKind TCK,
1945 SourceLocation Loc);
1946
1947 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1948 /// If vptr CFI is enabled, emit a check that VTable is valid.
1949 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1950 CFITypeCheckKind TCK, SourceLocation Loc);
1951
1952 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1953 /// RD using llvm.type.test.
1954 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1955 CFITypeCheckKind TCK, SourceLocation Loc);
1956
1957 /// If whole-program virtual table optimization is enabled, emit an assumption
1958 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1959 /// enabled, emit a check that VTable is a member of RD's type identifier.
1960 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1961 llvm::Value *VTable, SourceLocation Loc);
1962
1963 /// Returns whether we should perform a type checked load when loading a
1964 /// virtual function for virtual calls to members of RD. This is generally
1965 /// true when both vcall CFI and whole-program-vtables are enabled.
1966 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1967
1968 /// Emit a type checked load from the given vtable.
1969 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1970 uint64_t VTableByteOffset);
1971
1972 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1973 /// given phase of destruction for a destructor. The end result
1974 /// should call destructors on members and base classes in reverse
1975 /// order of their construction.
1976 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1977
1978 /// ShouldInstrumentFunction - Return true if the current function should be
1979 /// instrumented with __cyg_profile_func_* calls
1980 bool ShouldInstrumentFunction();
1981
1982 /// ShouldXRayInstrument - Return true if the current function should be
1983 /// instrumented with XRay nop sleds.
1984 bool ShouldXRayInstrumentFunction() const;
1985
1986 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
1987 /// XRay custom event handling calls.
1988 bool AlwaysEmitXRayCustomEvents() const;
1989
1990 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
1991 /// XRay typed event handling calls.
1992 bool AlwaysEmitXRayTypedEvents() const;
1993
1994 /// Encode an address into a form suitable for use in a function prologue.
1995 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
1996 llvm::Constant *Addr);
1997
1998 /// Decode an address used in a function prologue, encoded by \c
1999 /// EncodeAddrForUseInPrologue.
2000 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
2001 llvm::Value *EncodedAddr);
2002
2003 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2004 /// arguments for the given function. This is also responsible for naming the
2005 /// LLVM function arguments.
2006 void EmitFunctionProlog(const CGFunctionInfo &FI,
2007 llvm::Function *Fn,
2008 const FunctionArgList &Args);
2009
2010 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2011 /// given temporary.
2012 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2013 SourceLocation EndLoc);
2014
2015 /// Emit a test that checks if the return value \p RV is nonnull.
2016 void EmitReturnValueCheck(llvm::Value *RV);
2017
2018 /// EmitStartEHSpec - Emit the start of the exception spec.
2019 void EmitStartEHSpec(const Decl *D);
2020
2021 /// EmitEndEHSpec - Emit the end of the exception spec.
2022 void EmitEndEHSpec(const Decl *D);
2023
2024 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2025 llvm::BasicBlock *getTerminateLandingPad();
2026
2027 /// getTerminateLandingPad - Return a cleanup funclet that just calls
2028 /// terminate.
2029 llvm::BasicBlock *getTerminateFunclet();
2030
2031 /// getTerminateHandler - Return a handler (not a landing pad, just
2032 /// a catch handler) that just calls terminate. This is used when
2033 /// a terminate scope encloses a try.
2034 llvm::BasicBlock *getTerminateHandler();
2035
2036 llvm::Type *ConvertTypeForMem(QualType T);
2037 llvm::Type *ConvertType(QualType T);
2038 llvm::Type *ConvertType(const TypeDecl *T) {
2039 return ConvertType(getContext().getTypeDeclType(T));
2040 }
2041
2042 /// LoadObjCSelf - Load the value of self. This function is only valid while
2043 /// generating code for an Objective-C method.
2044 llvm::Value *LoadObjCSelf();
2045
2046 /// TypeOfSelfObject - Return type of object that this self represents.
2047 QualType TypeOfSelfObject();
2048
2049 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2050 static TypeEvaluationKind getEvaluationKind(QualType T);
2051
2052 static bool hasScalarEvaluationKind(QualType T) {
2053 return getEvaluationKind(T) == TEK_Scalar;
2054 }
2055
2056 static bool hasAggregateEvaluationKind(QualType T) {
2057 return getEvaluationKind(T) == TEK_Aggregate;
22
Assuming the condition is true
23
Returning the value 1, which participates in a condition later
2058 }
2059
2060 /// createBasicBlock - Create an LLVM basic block.
2061 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2062 llvm::Function *parent = nullptr,
2063 llvm::BasicBlock *before = nullptr) {
2064 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2065 }
2066
2067 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2068 /// label maps to.
2069 JumpDest getJumpDestForLabel(const LabelDecl *S);
2070
2071 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2072 /// another basic block, simplify it. This assumes that no other code could
2073 /// potentially reference the basic block.
2074 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2075
2076 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2077 /// adding a fall-through branch from the current insert block if
2078 /// necessary. It is legal to call this function even if there is no current
2079 /// insertion point.
2080 ///
2081 /// IsFinished - If true, indicates that the caller has finished emitting
2082 /// branches to the given block and does not expect to emit code into it. This
2083 /// means the block can be ignored if it is unreachable.
2084 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2085
2086 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2087 /// near its uses, and leave the insertion point in it.
2088 void EmitBlockAfterUses(llvm::BasicBlock *BB);
2089
2090 /// EmitBranch - Emit a branch to the specified basic block from the current
2091 /// insert block, taking care to avoid creation of branches from dummy
2092 /// blocks. It is legal to call this function even if there is no current
2093 /// insertion point.
2094 ///
2095 /// This function clears the current insertion point. The caller should follow
2096 /// calls to this function with calls to Emit*Block prior to generation new
2097 /// code.
2098 void EmitBranch(llvm::BasicBlock *Block);
2099
2100 /// HaveInsertPoint - True if an insertion point is defined. If not, this
2101 /// indicates that the current code being emitted is unreachable.
2102 bool HaveInsertPoint() const {
2103 return Builder.GetInsertBlock() != nullptr;
2104 }
2105
2106 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2107 /// emitted IR has a place to go. Note that by definition, if this function
2108 /// creates a block then that block is unreachable; callers may do better to
2109 /// detect when no insertion point is defined and simply skip IR generation.
2110 void EnsureInsertPoint() {
2111 if (!HaveInsertPoint())
2112 EmitBlock(createBasicBlock());
2113 }
2114
2115 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2116 /// specified stmt yet.
2117 void ErrorUnsupported(const Stmt *S, const char *Type);
2118
2119 //===--------------------------------------------------------------------===//
2120 // Helpers
2121 //===--------------------------------------------------------------------===//
2122
2123 LValue MakeAddrLValue(Address Addr, QualType T,
2124 AlignmentSource Source = AlignmentSource::Type) {
2125 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2126 CGM.getTBAAAccessInfo(T));
2127 }
2128
2129 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
2130 TBAAAccessInfo TBAAInfo) {
2131 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2132 }
2133
2134 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2135 AlignmentSource Source = AlignmentSource::Type) {
2136 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2137 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
2138 }
2139
2140 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2141 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
2142 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2143 BaseInfo, TBAAInfo);
2144 }
2145
2146 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
2147 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
2148 CharUnits getNaturalTypeAlignment(QualType T,
2149 LValueBaseInfo *BaseInfo = nullptr,
2150 TBAAAccessInfo *TBAAInfo = nullptr,
2151 bool forPointeeType = false);
2152 CharUnits getNaturalPointeeTypeAlignment(QualType T,
2153 LValueBaseInfo *BaseInfo = nullptr,
2154 TBAAAccessInfo *TBAAInfo = nullptr);
2155
2156 Address EmitLoadOfReference(LValue RefLVal,
2157 LValueBaseInfo *PointeeBaseInfo = nullptr,
2158 TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2159 LValue EmitLoadOfReferenceLValue(LValue RefLVal);
2160 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
2161 AlignmentSource Source =
2162 AlignmentSource::Type) {
2163 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2164 CGM.getTBAAAccessInfo(RefTy));
2165 return EmitLoadOfReferenceLValue(RefLVal);
2166 }
2167
2168 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2169 LValueBaseInfo *BaseInfo = nullptr,
2170 TBAAAccessInfo *TBAAInfo = nullptr);
2171 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
2172
2173 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2174 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2175 /// insertion point of the builder. The caller is responsible for setting an
2176 /// appropriate alignment on
2177 /// the alloca.
2178 ///
2179 /// \p ArraySize is the number of array elements to be allocated if it
2180 /// is not nullptr.
2181 ///
2182 /// LangAS::Default is the address space of pointers to local variables and
2183 /// temporaries, as exposed in the source language. In certain
2184 /// configurations, this is not the same as the alloca address space, and a
2185 /// cast is needed to lift the pointer from the alloca AS into
2186 /// LangAS::Default. This can happen when the target uses a restricted
2187 /// address space for the stack but the source language requires
2188 /// LangAS::Default to be a generic address space. The latter condition is
2189 /// common for most programming languages; OpenCL is an exception in that
2190 /// LangAS::Default is the private address space, which naturally maps
2191 /// to the stack.
2192 ///
2193 /// Because the address of a temporary is often exposed to the program in
2194 /// various ways, this function will perform the cast. The original alloca
2195 /// instruction is returned through \p Alloca if it is not nullptr.
2196 ///
2197 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2198 /// more efficient if the caller knows that the address will not be exposed.
2199 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2200 llvm::Value *ArraySize = nullptr);
2201 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2202 const Twine &Name = "tmp",
2203 llvm::Value *ArraySize = nullptr,
2204 Address *Alloca = nullptr);
2205 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
2206 const Twine &Name = "tmp",
2207 llvm::Value *ArraySize = nullptr);
2208
2209 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2210 /// default ABI alignment of the given LLVM type.
2211 ///
2212 /// IMPORTANT NOTE: This is *not* generally the right alignment for
2213 /// any given AST type that happens to have been lowered to the
2214 /// given IR type. This should only ever be used for function-local,
2215 /// IR-driven manipulations like saving and restoring a value. Do
2216 /// not hand this address off to arbitrary IRGen routines, and especially
2217 /// do not pass it as an argument to a function that might expect a
2218 /// properly ABI-aligned value.
2219 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2220 const Twine &Name = "tmp");
2221
2222 /// InitTempAlloca - Provide an initial value for the given alloca which
2223 /// will be observable at all locations in the function.
2224 ///
2225 /// The address should be something that was returned from one of
2226 /// the CreateTempAlloca or CreateMemTemp routines, and the
2227 /// initializer must be valid in the entry block (i.e. it must
2228 /// either be a constant or an argument value).
2229 void InitTempAlloca(Address Alloca, llvm::Value *Value);
2230
2231 /// CreateIRTemp - Create a temporary IR object of the given type, with
2232 /// appropriate alignment. This routine should only be used when an temporary
2233 /// value needs to be stored into an alloca (for example, to avoid explicit
2234 /// PHI construction), but the type is the IR type, not the type appropriate
2235 /// for storing in memory.
2236 ///
2237 /// That is, this is exactly equivalent to CreateMemTemp, but calling
2238 /// ConvertType instead of ConvertTypeForMem.
2239 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2240
2241 /// CreateMemTemp - Create a temporary memory object of the given type, with
2242 /// appropriate alignmen and cast it to the default address space. Returns
2243 /// the original alloca instruction by \p Alloca if it is not nullptr.
2244 Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2245 Address *Alloca = nullptr);
2246 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2247 Address *Alloca = nullptr);
2248
2249 /// CreateMemTemp - Create a temporary memory object of the given type, with
2250 /// appropriate alignmen without casting it to the default address space.
2251 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2252 Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
2253 const Twine &Name = "tmp");
2254
2255 /// CreateAggTemp - Create a temporary memory object for the given
2256 /// aggregate type.
2257 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
2258 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
2259 T.getQualifiers(),
2260 AggValueSlot::IsNotDestructed,
2261 AggValueSlot::DoesNotNeedGCBarriers,
2262 AggValueSlot::IsNotAliased,
2263 AggValueSlot::DoesNotOverlap);
2264 }
2265
2266 /// Emit a cast to void* in the appropriate address space.
2267 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
2268
2269 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2270 /// expression and compare the result against zero, returning an Int1Ty value.
2271 llvm::Value *EvaluateExprAsBool(const Expr *E);
2272
2273 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2274 void EmitIgnoredExpr(const Expr *E);
2275
2276 /// EmitAnyExpr - Emit code to compute the specified expression which can have
2277 /// any type. The result is returned as an RValue struct. If this is an
2278 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2279 /// the result should be returned.
2280 ///
2281 /// \param ignoreResult True if the resulting value isn't used.
2282 RValue EmitAnyExpr(const Expr *E,
2283 AggValueSlot aggSlot = AggValueSlot::ignored(),
2284 bool ignoreResult = false);
2285
2286 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2287 // or the value of the expression, depending on how va_list is defined.
2288 Address EmitVAListRef(const Expr *E);
2289
2290 /// Emit a "reference" to a __builtin_ms_va_list; this is
2291 /// always the value of the expression, because a __builtin_ms_va_list is a
2292 /// pointer to a char.
2293 Address EmitMSVAListRef(const Expr *E);
2294
2295 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2296 /// always be accessible even if no aggregate location is provided.
2297 RValue EmitAnyExprToTemp(const Expr *E);
2298
2299 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2300 /// arbitrary expression into the given memory location.
2301 void EmitAnyExprToMem(const Expr *E, Address Location,
2302 Qualifiers Quals, bool IsInitializer);
2303
2304 void EmitAnyExprToExn(const Expr *E, Address Addr);
2305
2306 /// EmitExprAsInit - Emits the code necessary to initialize a
2307 /// location in memory with the given initializer.
2308 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2309 bool capturedByInit);
2310
2311 /// hasVolatileMember - returns true if aggregate type has a volatile
2312 /// member.
2313 bool hasVolatileMember(QualType T) {
2314 if (const RecordType *RT = T->getAs<RecordType>()) {
2315 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2316 return RD->hasVolatileMember();
2317 }
2318 return false;
2319 }
2320
2321 /// Determine whether a return value slot may overlap some other object.
2322 AggValueSlot::Overlap_t getOverlapForReturnValue() {
2323 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2324 // class subobjects. These cases may need to be revisited depending on the
2325 // resolution of the relevant core issue.
2326 return AggValueSlot::DoesNotOverlap;
2327 }
2328
2329 /// Determine whether a field initialization may overlap some other object.
2330 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
2331
2332 /// Determine whether a base class initialization may overlap some other
2333 /// object.
2334 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
2335 const CXXRecordDecl *BaseRD,
2336 bool IsVirtual);
2337
2338 /// Emit an aggregate assignment.
2339 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
2340 bool IsVolatile = hasVolatileMember(EltTy);
2341 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2342 }
2343
2344 void EmitAggregateCopyCtor(LValue Dest, LValue Src,
2345 AggValueSlot::Overlap_t MayOverlap) {
2346 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2347 }
2348
2349 /// EmitAggregateCopy - Emit an aggregate copy.
2350 ///
2351 /// \param isVolatile \c true iff either the source or the destination is
2352 /// volatile.
2353 /// \param MayOverlap Whether the tail padding of the destination might be
2354 /// occupied by some other object. More efficient code can often be
2355 /// generated if not.
2356 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
2357 AggValueSlot::Overlap_t MayOverlap,
2358 bool isVolatile = false);
2359
2360 /// GetAddrOfLocalVar - Return the address of a local variable.
2361 Address GetAddrOfLocalVar(const VarDecl *VD) {
2362 auto it = LocalDeclMap.find(VD);
2363 assert(it != LocalDeclMap.end() &&((it != LocalDeclMap.end() && "Invalid argument to GetAddrOfLocalVar(), no decl!"
) ? static_cast<void> (0) : __assert_fail ("it != LocalDeclMap.end() && \"Invalid argument to GetAddrOfLocalVar(), no decl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2364, __PRETTY_FUNCTION__))
2364 "Invalid argument to GetAddrOfLocalVar(), no decl!")((it != LocalDeclMap.end() && "Invalid argument to GetAddrOfLocalVar(), no decl!"
) ? static_cast<void> (0) : __assert_fail ("it != LocalDeclMap.end() && \"Invalid argument to GetAddrOfLocalVar(), no decl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2364, __PRETTY_FUNCTION__))
;
2365 return it->second;
2366 }
2367
2368 /// Given an opaque value expression, return its LValue mapping if it exists,
2369 /// otherwise create one.
2370 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
2371
2372 /// Given an opaque value expression, return its RValue mapping if it exists,
2373 /// otherwise create one.
2374 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
2375
2376 /// Get the index of the current ArrayInitLoopExpr, if any.
2377 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2378
2379 /// getAccessedFieldNo - Given an encoded value and a result number, return
2380 /// the input field number being accessed.
2381 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2382
2383 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2384 llvm::BasicBlock *GetIndirectGotoBlock();
2385
2386 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2387 static bool IsWrappedCXXThis(const Expr *E);
2388
2389 /// EmitNullInitialization - Generate code to set a value of the given type to
2390 /// null, If the type contains data member pointers, they will be initialized
2391 /// to -1 in accordance with the Itanium C++ ABI.
2392 void EmitNullInitialization(Address DestPtr, QualType Ty);
2393
2394 /// Emits a call to an LLVM variable-argument intrinsic, either
2395 /// \c llvm.va_start or \c llvm.va_end.
2396 /// \param ArgValue A reference to the \c va_list as emitted by either
2397 /// \c EmitVAListRef or \c EmitMSVAListRef.
2398 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2399 /// calls \c llvm.va_end.
2400 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2401
2402 /// Generate code to get an argument from the passed in pointer
2403 /// and update it accordingly.
2404 /// \param VE The \c VAArgExpr for which to generate code.
2405 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2406 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2407 /// \returns A pointer to the argument.
2408 // FIXME: We should be able to get rid of this method and use the va_arg
2409 // instruction in LLVM instead once it works well enough.
2410 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2411
2412 /// emitArrayLength - Compute the length of an array, even if it's a
2413 /// VLA, and drill down to the base element type.
2414 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2415 QualType &baseType,
2416 Address &addr);
2417
2418 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2419 /// the given variably-modified type and store them in the VLASizeMap.
2420 ///
2421 /// This function can be called with a null (unreachable) insert point.
2422 void EmitVariablyModifiedType(QualType Ty);
2423
2424 struct VlaSizePair {
2425 llvm::Value *NumElts;
2426 QualType Type;
2427
2428 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2429 };
2430
2431 /// Return the number of elements for a single dimension
2432 /// for the given array type.
2433 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
2434 VlaSizePair getVLAElements1D(QualType vla);
2435
2436 /// Returns an LLVM value that corresponds to the size,
2437 /// in non-variably-sized elements, of a variable length array type,
2438 /// plus that largest non-variably-sized element type. Assumes that
2439 /// the type has already been emitted with EmitVariablyModifiedType.
2440 VlaSizePair getVLASize(const VariableArrayType *vla);
2441 VlaSizePair getVLASize(QualType vla);
2442
2443 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2444 /// generating code for an C++ member function.
2445 llvm::Value *LoadCXXThis() {
2446 assert(CXXThisValue && "no 'this' value for this function")((CXXThisValue && "no 'this' value for this function"
) ? static_cast<void> (0) : __assert_fail ("CXXThisValue && \"no 'this' value for this function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2446, __PRETTY_FUNCTION__))
;
2447 return CXXThisValue;
2448 }
2449 Address LoadCXXThisAddress();
2450
2451 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2452 /// virtual bases.
2453 // FIXME: Every place that calls LoadCXXVTT is something
2454 // that needs to be abstracted properly.
2455 llvm::Value *LoadCXXVTT() {
2456 assert(CXXStructorImplicitParamValue && "no VTT value for this function")((CXXStructorImplicitParamValue && "no VTT value for this function"
) ? static_cast<void> (0) : __assert_fail ("CXXStructorImplicitParamValue && \"no VTT value for this function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2456, __PRETTY_FUNCTION__))
;
2457 return CXXStructorImplicitParamValue;
2458 }
2459
2460 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2461 /// complete class to the given direct base.
2462 Address
2463 GetAddressOfDirectBaseInCompleteClass(Address Value,
2464 const CXXRecordDecl *Derived,
2465 const CXXRecordDecl *Base,
2466 bool BaseIsVirtual);
2467
2468 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2469
2470 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2471 /// load of 'this' and returns address of the base class.
2472 Address GetAddressOfBaseClass(Address Value,
2473 const CXXRecordDecl *Derived,
2474 CastExpr::path_const_iterator PathBegin,
2475 CastExpr::path_const_iterator PathEnd,
2476 bool NullCheckValue, SourceLocation Loc);
2477
2478 Address GetAddressOfDerivedClass(Address Value,
2479 const CXXRecordDecl *Derived,
2480 CastExpr::path_const_iterator PathBegin,
2481 CastExpr::path_const_iterator PathEnd,
2482 bool NullCheckValue);
2483
2484 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2485 /// base constructor/destructor with virtual bases.
2486 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2487 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2488 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2489 bool Delegating);
2490
2491 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2492 CXXCtorType CtorType,
2493 const FunctionArgList &Args,
2494 SourceLocation Loc);
2495 // It's important not to confuse this and the previous function. Delegating
2496 // constructors are the C++0x feature. The constructor delegate optimization
2497 // is used to reduce duplication in the base and complete consturctors where
2498 // they are substantially the same.
2499 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2500 const FunctionArgList &Args);
2501
2502 /// Emit a call to an inheriting constructor (that is, one that invokes a
2503 /// constructor inherited from a base class) by inlining its definition. This
2504 /// is necessary if the ABI does not support forwarding the arguments to the
2505 /// base class constructor (because they're variadic or similar).
2506 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2507 CXXCtorType CtorType,
2508 bool ForVirtualBase,
2509 bool Delegating,
2510 CallArgList &Args);
2511
2512 /// Emit a call to a constructor inherited from a base class, passing the
2513 /// current constructor's arguments along unmodified (without even making
2514 /// a copy).
2515 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2516 bool ForVirtualBase, Address This,
2517 bool InheritedFromVBase,
2518 const CXXInheritedCtorInitExpr *E);
2519
2520 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2521 bool ForVirtualBase, bool Delegating,
2522 AggValueSlot ThisAVS, const CXXConstructExpr *E);
2523
2524 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2525 bool ForVirtualBase, bool Delegating,
2526 Address This, CallArgList &Args,
2527 AggValueSlot::Overlap_t Overlap,
2528 SourceLocation Loc, bool NewPointerIsChecked);
2529
2530 /// Emit assumption load for all bases. Requires to be be called only on
2531 /// most-derived class and not under construction of the object.
2532 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2533
2534 /// Emit assumption that vptr load == global vtable.
2535 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2536
2537 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2538 Address This, Address Src,
2539 const CXXConstructExpr *E);
2540
2541 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2542 const ArrayType *ArrayTy,
2543 Address ArrayPtr,
2544 const CXXConstructExpr *E,
2545 bool NewPointerIsChecked,
2546 bool ZeroInitialization = false);
2547
2548 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2549 llvm::Value *NumElements,
2550 Address ArrayPtr,
2551 const CXXConstructExpr *E,
2552 bool NewPointerIsChecked,
2553 bool ZeroInitialization = false);
2554
2555 static Destroyer destroyCXXObject;
2556
2557 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2558 bool ForVirtualBase, bool Delegating, Address This,
2559 QualType ThisTy);
2560
2561 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2562 llvm::Type *ElementTy, Address NewPtr,
2563 llvm::Value *NumElements,
2564 llvm::Value *AllocSizeWithoutCookie);
2565
2566 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2567 Address Ptr);
2568
2569 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2570 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2571
2572 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2573 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2574
2575 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2576 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2577 CharUnits CookieSize = CharUnits());
2578
2579 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2580 const CallExpr *TheCallExpr, bool IsDelete);
2581
2582 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2583 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2584 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2585
2586 /// Situations in which we might emit a check for the suitability of a
2587 /// pointer or glvalue.
2588 enum TypeCheckKind {
2589 /// Checking the operand of a load. Must be suitably sized and aligned.
2590 TCK_Load,
2591 /// Checking the destination of a store. Must be suitably sized and aligned.
2592 TCK_Store,
2593 /// Checking the bound value in a reference binding. Must be suitably sized
2594 /// and aligned, but is not required to refer to an object (until the
2595 /// reference is used), per core issue 453.
2596 TCK_ReferenceBinding,
2597 /// Checking the object expression in a non-static data member access. Must
2598 /// be an object within its lifetime.
2599 TCK_MemberAccess,
2600 /// Checking the 'this' pointer for a call to a non-static member function.
2601 /// Must be an object within its lifetime.
2602 TCK_MemberCall,
2603 /// Checking the 'this' pointer for a constructor call.
2604 TCK_ConstructorCall,
2605 /// Checking the operand of a static_cast to a derived pointer type. Must be
2606 /// null or an object within its lifetime.
2607 TCK_DowncastPointer,
2608 /// Checking the operand of a static_cast to a derived reference type. Must
2609 /// be an object within its lifetime.
2610 TCK_DowncastReference,
2611 /// Checking the operand of a cast to a base object. Must be suitably sized
2612 /// and aligned.
2613 TCK_Upcast,
2614 /// Checking the operand of a cast to a virtual base object. Must be an
2615 /// object within its lifetime.
2616 TCK_UpcastToVirtualBase,
2617 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2618 TCK_NonnullAssign,
2619 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
2620 /// null or an object within its lifetime.
2621 TCK_DynamicOperation
2622 };
2623
2624 /// Determine whether the pointer type check \p TCK permits null pointers.
2625 static bool isNullPointerAllowed(TypeCheckKind TCK);
2626
2627 /// Determine whether the pointer type check \p TCK requires a vptr check.
2628 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
2629
2630 /// Whether any type-checking sanitizers are enabled. If \c false,
2631 /// calls to EmitTypeCheck can be skipped.
2632 bool sanitizePerformTypeCheck() const;
2633
2634 /// Emit a check that \p V is the address of storage of the
2635 /// appropriate size and alignment for an object of type \p Type
2636 /// (or if ArraySize is provided, for an array of that bound).
2637 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2638 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2639 SanitizerSet SkippedChecks = SanitizerSet(),
2640 llvm::Value *ArraySize = nullptr);
2641
2642 /// Emit a check that \p Base points into an array object, which
2643 /// we can access at index \p Index. \p Accessed should be \c false if we
2644 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2645 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2646 QualType IndexType, bool Accessed);
2647
2648 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2649 bool isInc, bool isPre);
2650 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2651 bool isInc, bool isPre);
2652
2653 /// Converts Location to a DebugLoc, if debug information is enabled.
2654 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2655
2656 /// Get the record field index as represented in debug info.
2657 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
2658
2659
2660 //===--------------------------------------------------------------------===//
2661 // Declaration Emission
2662 //===--------------------------------------------------------------------===//
2663
2664 /// EmitDecl - Emit a declaration.
2665 ///
2666 /// This function can be called with a null (unreachable) insert point.
2667 void EmitDecl(const Decl &D);
2668
2669 /// EmitVarDecl - Emit a local variable declaration.
2670 ///
2671 /// This function can be called with a null (unreachable) insert point.
2672 void EmitVarDecl(const VarDecl &D);
2673
2674 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2675 bool capturedByInit);
2676
2677 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2678 llvm::Value *Address);
2679
2680 /// Determine whether the given initializer is trivial in the sense
2681 /// that it requires no code to be generated.
2682 bool isTrivialInitializer(const Expr *Init);
2683
2684 /// EmitAutoVarDecl - Emit an auto variable declaration.
2685 ///
2686 /// This function can be called with a null (unreachable) insert point.
2687 void EmitAutoVarDecl(const VarDecl &D);
2688
2689 class AutoVarEmission {
2690 friend class CodeGenFunction;
2691
2692 const VarDecl *Variable;
2693
2694 /// The address of the alloca for languages with explicit address space
2695 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
2696 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
2697 /// as a global constant.
2698 Address Addr;
2699
2700 llvm::Value *NRVOFlag;
2701
2702 /// True if the variable is a __block variable that is captured by an
2703 /// escaping block.
2704 bool IsEscapingByRef;
2705
2706 /// True if the variable is of aggregate type and has a constant
2707 /// initializer.
2708 bool IsConstantAggregate;
2709
2710 /// Non-null if we should use lifetime annotations.
2711 llvm::Value *SizeForLifetimeMarkers;
2712
2713 /// Address with original alloca instruction. Invalid if the variable was
2714 /// emitted as a global constant.
2715 Address AllocaAddr;
2716
2717 struct Invalid {};
2718 AutoVarEmission(Invalid)
2719 : Variable(nullptr), Addr(Address::invalid()),
2720 AllocaAddr(Address::invalid()) {}
2721
2722 AutoVarEmission(const VarDecl &variable)
2723 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2724 IsEscapingByRef(false), IsConstantAggregate(false),
2725 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
2726
2727 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2728
2729 public:
2730 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2731
2732 bool useLifetimeMarkers() const {
2733 return SizeForLifetimeMarkers != nullptr;
2734 }
2735 llvm::Value *getSizeForLifetimeMarkers() const {
2736 assert(useLifetimeMarkers())((useLifetimeMarkers()) ? static_cast<void> (0) : __assert_fail
("useLifetimeMarkers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2736, __PRETTY_FUNCTION__))
;
2737 return SizeForLifetimeMarkers;
2738 }
2739
2740 /// Returns the raw, allocated address, which is not necessarily
2741 /// the address of the object itself. It is casted to default
2742 /// address space for address space agnostic languages.
2743 Address getAllocatedAddress() const {
2744 return Addr;
2745 }
2746
2747 /// Returns the address for the original alloca instruction.
2748 Address getOriginalAllocatedAddress() const { return AllocaAddr; }
2749
2750 /// Returns the address of the object within this declaration.
2751 /// Note that this does not chase the forwarding pointer for
2752 /// __block decls.
2753 Address getObjectAddress(CodeGenFunction &CGF) const {
2754 if (!IsEscapingByRef) return Addr;
2755
2756 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2757 }
2758 };
2759 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2760 void EmitAutoVarInit(const AutoVarEmission &emission);
2761 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2762 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2763 QualType::DestructionKind dtorKind);
2764
2765 /// Emits the alloca and debug information for the size expressions for each
2766 /// dimension of an array. It registers the association of its (1-dimensional)
2767 /// QualTypes and size expression's debug node, so that CGDebugInfo can
2768 /// reference this node when creating the DISubrange object to describe the
2769 /// array types.
2770 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
2771 const VarDecl &D,
2772 bool EmitDebugInfo);
2773
2774 void EmitStaticVarDecl(const VarDecl &D,
2775 llvm::GlobalValue::LinkageTypes Linkage);
2776
2777 class ParamValue {
2778 llvm::Value *Value;
2779 unsigned Alignment;
2780 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2781 public:
2782 static ParamValue forDirect(llvm::Value *value) {
2783 return ParamValue(value, 0);
2784 }
2785 static ParamValue forIndirect(Address addr) {
2786 assert(!addr.getAlignment().isZero())((!addr.getAlignment().isZero()) ? static_cast<void> (0
) : __assert_fail ("!addr.getAlignment().isZero()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2786, __PRETTY_FUNCTION__))
;
2787 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2788 }
2789
2790 bool isIndirect() const { return Alignment != 0; }
2791 llvm::Value *getAnyValue() const { return Value; }
2792
2793 llvm::Value *getDirectValue() const {
2794 assert(!isIndirect())((!isIndirect()) ? static_cast<void> (0) : __assert_fail
("!isIndirect()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2794, __PRETTY_FUNCTION__))
;
2795 return Value;
2796 }
2797
2798 Address getIndirectAddress() const {
2799 assert(isIndirect())((isIndirect()) ? static_cast<void> (0) : __assert_fail
("isIndirect()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 2799, __PRETTY_FUNCTION__))
;
2800 return Address(Value, CharUnits::fromQuantity(Alignment));
2801 }
2802 };
2803
2804 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2805 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2806
2807 /// protectFromPeepholes - Protect a value that we're intending to
2808 /// store to the side, but which will probably be used later, from
2809 /// aggressive peepholing optimizations that might delete it.
2810 ///
2811 /// Pass the result to unprotectFromPeepholes to declare that
2812 /// protection is no longer required.
2813 ///
2814 /// There's no particular reason why this shouldn't apply to
2815 /// l-values, it's just that no existing peepholes work on pointers.
2816 PeepholeProtection protectFromPeepholes(RValue rvalue);
2817 void unprotectFromPeepholes(PeepholeProtection protection);
2818
2819 void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
2820 SourceLocation Loc,
2821 SourceLocation AssumptionLoc,
2822 llvm::Value *Alignment,
2823 llvm::Value *OffsetValue,
2824 llvm::Value *TheCheck,
2825 llvm::Instruction *Assumption);
2826
2827 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2828 SourceLocation Loc, SourceLocation AssumptionLoc,
2829 llvm::Value *Alignment,
2830 llvm::Value *OffsetValue = nullptr);
2831
2832 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2833 SourceLocation Loc, SourceLocation AssumptionLoc,
2834 unsigned Alignment,
2835 llvm::Value *OffsetValue = nullptr);
2836
2837 void EmitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
2838 SourceLocation AssumptionLoc, unsigned Alignment,
2839 llvm::Value *OffsetValue = nullptr);
2840
2841 //===--------------------------------------------------------------------===//
2842 // Statement Emission
2843 //===--------------------------------------------------------------------===//
2844
2845 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2846 void EmitStopPoint(const Stmt *S);
2847
2848 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2849 /// this function even if there is no current insertion point.
2850 ///
2851 /// This function may clear the current insertion point; callers should use
2852 /// EnsureInsertPoint if they wish to subsequently generate code without first
2853 /// calling EmitBlock, EmitBranch, or EmitStmt.
2854 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
2855
2856 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2857 /// necessarily require an insertion point or debug information; typically
2858 /// because the statement amounts to a jump or a container of other
2859 /// statements.
2860 ///
2861 /// \return True if the statement was handled.
2862 bool EmitSimpleStmt(const Stmt *S);
2863
2864 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2865 AggValueSlot AVS = AggValueSlot::ignored());
2866 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2867 bool GetLast = false,
2868 AggValueSlot AVS =
2869 AggValueSlot::ignored());
2870
2871 /// EmitLabel - Emit the block for the given label. It is legal to call this
2872 /// function even if there is no current insertion point.
2873 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2874
2875 void EmitLabelStmt(const LabelStmt &S);
2876 void EmitAttributedStmt(const AttributedStmt &S);
2877 void EmitGotoStmt(const GotoStmt &S);
2878 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2879 void EmitIfStmt(const IfStmt &S);
2880
2881 void EmitWhileStmt(const WhileStmt &S,
2882 ArrayRef<const Attr *> Attrs = None);
2883 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2884 void EmitForStmt(const ForStmt &S,
2885 ArrayRef<const Attr *> Attrs = None);
2886 void EmitReturnStmt(const ReturnStmt &S);
2887 void EmitDeclStmt(const DeclStmt &S);
2888 void EmitBreakStmt(const BreakStmt &S);
2889 void EmitContinueStmt(const ContinueStmt &S);
2890 void EmitSwitchStmt(const SwitchStmt &S);
2891 void EmitDefaultStmt(const DefaultStmt &S);
2892 void EmitCaseStmt(const CaseStmt &S);
2893 void EmitCaseStmtRange(const CaseStmt &S);
2894 void EmitAsmStmt(const AsmStmt &S);
2895
2896 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2897 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2898 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2899 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2900 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2901
2902 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2903 void EmitCoreturnStmt(const CoreturnStmt &S);
2904 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2905 AggValueSlot aggSlot = AggValueSlot::ignored(),
2906 bool ignoreResult = false);
2907 LValue EmitCoawaitLValue(const CoawaitExpr *E);
2908 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2909 AggValueSlot aggSlot = AggValueSlot::ignored(),
2910 bool ignoreResult = false);
2911 LValue EmitCoyieldLValue(const CoyieldExpr *E);
2912 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2913
2914 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2915 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2916
2917 void EmitCXXTryStmt(const CXXTryStmt &S);
2918 void EmitSEHTryStmt(const SEHTryStmt &S);
2919 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2920 void EnterSEHTryStmt(const SEHTryStmt &S);
2921 void ExitSEHTryStmt(const SEHTryStmt &S);
2922
2923 void pushSEHCleanup(CleanupKind kind,
2924 llvm::Function *FinallyFunc);
2925 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2926 const Stmt *OutlinedStmt);
2927
2928 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2929 const SEHExceptStmt &Except);
2930
2931 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2932 const SEHFinallyStmt &Finally);
2933
2934 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2935 llvm::Value *ParentFP,
2936 llvm::Value *EntryEBP);
2937 llvm::Value *EmitSEHExceptionCode();
2938 llvm::Value *EmitSEHExceptionInfo();
2939 llvm::Value *EmitSEHAbnormalTermination();
2940
2941 /// Emit simple code for OpenMP directives in Simd-only mode.
2942 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
2943
2944 /// Scan the outlined statement for captures from the parent function. For
2945 /// each capture, mark the capture as escaped and emit a call to
2946 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2947 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2948 bool IsFilter);
2949
2950 /// Recovers the address of a local in a parent function. ParentVar is the
2951 /// address of the variable used in the immediate parent function. It can
2952 /// either be an alloca or a call to llvm.localrecover if there are nested
2953 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2954 /// frame.
2955 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2956 Address ParentVar,
2957 llvm::Value *ParentFP);
2958
2959 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2960 ArrayRef<const Attr *> Attrs = None);
2961
2962 /// Controls insertion of cancellation exit blocks in worksharing constructs.
2963 class OMPCancelStackRAII {
2964 CodeGenFunction &CGF;
2965
2966 public:
2967 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
2968 bool HasCancel)
2969 : CGF(CGF) {
2970 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
2971 }
2972 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
2973 };
2974
2975 /// Returns calculated size of the specified type.
2976 llvm::Value *getTypeSize(QualType Ty);
2977 LValue InitCapturedStruct(const CapturedStmt &S);
2978 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2979 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2980 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2981 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2982 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2983 SmallVectorImpl<llvm::Value *> &CapturedVars);
2984 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2985 SourceLocation Loc);
2986 /// Perform element by element copying of arrays with type \a
2987 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2988 /// generated by \a CopyGen.
2989 ///
2990 /// \param DestAddr Address of the destination array.
2991 /// \param SrcAddr Address of the source array.
2992 /// \param OriginalType Type of destination and source arrays.
2993 /// \param CopyGen Copying procedure that copies value of single array element
2994 /// to another single array element.
2995 void EmitOMPAggregateAssign(
2996 Address DestAddr, Address SrcAddr, QualType OriginalType,
2997 const llvm::function_ref<void(Address, Address)> CopyGen);
2998 /// Emit proper copying of data from one variable to another.
2999 ///
3000 /// \param OriginalType Original type of the copied variables.
3001 /// \param DestAddr Destination address.
3002 /// \param SrcAddr Source address.
3003 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3004 /// type of the base array element).
3005 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3006 /// the base array element).
3007 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3008 /// DestVD.
3009 void EmitOMPCopy(QualType OriginalType,
3010 Address DestAddr, Address SrcAddr,
3011 const VarDecl *DestVD, const VarDecl *SrcVD,
3012 const Expr *Copy);
3013 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3014 /// \a X = \a E \a BO \a E.
3015 ///
3016 /// \param X Value to be updated.
3017 /// \param E Update value.
3018 /// \param BO Binary operation for update operation.
3019 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3020 /// expression, false otherwise.
3021 /// \param AO Atomic ordering of the generated atomic instructions.
3022 /// \param CommonGen Code generator for complex expressions that cannot be
3023 /// expressed through atomicrmw instruction.
3024 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3025 /// generated, <false, RValue::get(nullptr)> otherwise.
3026 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3027 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3028 llvm::AtomicOrdering AO, SourceLocation Loc,
3029 const llvm::function_ref<RValue(RValue)> CommonGen);
3030 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
3031 OMPPrivateScope &PrivateScope);
3032 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
3033 OMPPrivateScope &PrivateScope);
3034 void EmitOMPUseDevicePtrClause(
3035 const OMPClause &C, OMPPrivateScope &PrivateScope,
3036 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
3037 /// Emit code for copyin clause in \a D directive. The next code is
3038 /// generated at the start of outlined functions for directives:
3039 /// \code
3040 /// threadprivate_var1 = master_threadprivate_var1;
3041 /// operator=(threadprivate_var2, master_threadprivate_var2);
3042 /// ...
3043 /// __kmpc_barrier(&loc, global_tid);
3044 /// \endcode
3045 ///
3046 /// \param D OpenMP directive possibly with 'copyin' clause(s).
3047 /// \returns true if at least one copyin variable is found, false otherwise.
3048 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
3049 /// Emit initial code for lastprivate variables. If some variable is
3050 /// not also firstprivate, then the default initialization is used. Otherwise
3051 /// initialization of this variable is performed by EmitOMPFirstprivateClause
3052 /// method.
3053 ///
3054 /// \param D Directive that may have 'lastprivate' directives.
3055 /// \param PrivateScope Private scope for capturing lastprivate variables for
3056 /// proper codegen in internal captured statement.
3057 ///
3058 /// \returns true if there is at least one lastprivate variable, false
3059 /// otherwise.
3060 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
3061 OMPPrivateScope &PrivateScope);
3062 /// Emit final copying of lastprivate values to original variables at
3063 /// the end of the worksharing or simd directive.
3064 ///
3065 /// \param D Directive that has at least one 'lastprivate' directives.
3066 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3067 /// it is the last iteration of the loop code in associated directive, or to
3068 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3069 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
3070 bool NoFinals,
3071 llvm::Value *IsLastIterCond = nullptr);
3072 /// Emit initial code for linear clauses.
3073 void EmitOMPLinearClause(const OMPLoopDirective &D,
3074 CodeGenFunction::OMPPrivateScope &PrivateScope);
3075 /// Emit final code for linear clauses.
3076 /// \param CondGen Optional conditional code for final part of codegen for
3077 /// linear clause.
3078 void EmitOMPLinearClauseFinal(
3079 const OMPLoopDirective &D,
3080 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3081 /// Emit initial code for reduction variables. Creates reduction copies
3082 /// and initializes them with the values according to OpenMP standard.
3083 ///
3084 /// \param D Directive (possibly) with the 'reduction' clause.
3085 /// \param PrivateScope Private scope for capturing reduction variables for
3086 /// proper codegen in internal captured statement.
3087 ///
3088 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
3089 OMPPrivateScope &PrivateScope);
3090 /// Emit final update of reduction values to original variables at
3091 /// the end of the directive.
3092 ///
3093 /// \param D Directive that has at least one 'reduction' directives.
3094 /// \param ReductionKind The kind of reduction to perform.
3095 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
3096 const OpenMPDirectiveKind ReductionKind);
3097 /// Emit initial code for linear variables. Creates private copies
3098 /// and initializes them with the values according to OpenMP standard.
3099 ///
3100 /// \param D Directive (possibly) with the 'linear' clause.
3101 /// \return true if at least one linear variable is found that should be
3102 /// initialized with the value of the original variable, false otherwise.
3103 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
3104
3105 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3106 llvm::Function * /*OutlinedFn*/,
3107 const OMPTaskDataTy & /*Data*/)>
3108 TaskGenTy;
3109 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
3110 const OpenMPDirectiveKind CapturedRegion,
3111 const RegionCodeGenTy &BodyGen,
3112 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3113 struct OMPTargetDataInfo {
3114 Address BasePointersArray = Address::invalid();
3115 Address PointersArray = Address::invalid();
3116 Address SizesArray = Address::invalid();
3117 unsigned NumberOfTargetItems = 0;
3118 explicit OMPTargetDataInfo() = default;
3119 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
3120 Address SizesArray, unsigned NumberOfTargetItems)
3121 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
3122 SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {}
3123 };
3124 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
3125 const RegionCodeGenTy &BodyGen,
3126 OMPTargetDataInfo &InputInfo);
3127
3128 void EmitOMPParallelDirective(const OMPParallelDirective &S);
3129 void EmitOMPSimdDirective(const OMPSimdDirective &S);
3130 void EmitOMPForDirective(const OMPForDirective &S);
3131 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
3132 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
3133 void EmitOMPSectionDirective(const OMPSectionDirective &S);
3134 void EmitOMPSingleDirective(const OMPSingleDirective &S);
3135 void EmitOMPMasterDirective(const OMPMasterDirective &S);
3136 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
3137 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
3138 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
3139 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
3140 void EmitOMPTaskDirective(const OMPTaskDirective &S);
3141 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
3142 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
3143 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
3144 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
3145 void EmitOMPFlushDirective(const OMPFlushDirective &S);
3146 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
3147 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
3148 void EmitOMPTargetDirective(const OMPTargetDirective &S);
3149 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
3150 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
3151 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
3152 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
3153 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
3154 void
3155 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
3156 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
3157 void
3158 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
3159 void EmitOMPCancelDirective(const OMPCancelDirective &S);
3160 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
3161 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
3162 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
3163 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
3164 void EmitOMPDistributeParallelForDirective(
3165 const OMPDistributeParallelForDirective &S);
3166 void EmitOMPDistributeParallelForSimdDirective(
3167 const OMPDistributeParallelForSimdDirective &S);
3168 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
3169 void EmitOMPTargetParallelForSimdDirective(
3170 const OMPTargetParallelForSimdDirective &S);
3171 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
3172 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
3173 void
3174 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
3175 void EmitOMPTeamsDistributeParallelForSimdDirective(
3176 const OMPTeamsDistributeParallelForSimdDirective &S);
3177 void EmitOMPTeamsDistributeParallelForDirective(
3178 const OMPTeamsDistributeParallelForDirective &S);
3179 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
3180 void EmitOMPTargetTeamsDistributeDirective(
3181 const OMPTargetTeamsDistributeDirective &S);
3182 void EmitOMPTargetTeamsDistributeParallelForDirective(
3183 const OMPTargetTeamsDistributeParallelForDirective &S);
3184 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
3185 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3186 void EmitOMPTargetTeamsDistributeSimdDirective(
3187 const OMPTargetTeamsDistributeSimdDirective &S);
3188
3189 /// Emit device code for the target directive.
3190 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3191 StringRef ParentName,
3192 const OMPTargetDirective &S);
3193 static void
3194 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3195 const OMPTargetParallelDirective &S);
3196 /// Emit device code for the target parallel for directive.
3197 static void EmitOMPTargetParallelForDeviceFunction(
3198 CodeGenModule &CGM, StringRef ParentName,
3199 const OMPTargetParallelForDirective &S);
3200 /// Emit device code for the target parallel for simd directive.
3201 static void EmitOMPTargetParallelForSimdDeviceFunction(
3202 CodeGenModule &CGM, StringRef ParentName,
3203 const OMPTargetParallelForSimdDirective &S);
3204 /// Emit device code for the target teams directive.
3205 static void
3206 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3207 const OMPTargetTeamsDirective &S);
3208 /// Emit device code for the target teams distribute directive.
3209 static void EmitOMPTargetTeamsDistributeDeviceFunction(
3210 CodeGenModule &CGM, StringRef ParentName,
3211 const OMPTargetTeamsDistributeDirective &S);
3212 /// Emit device code for the target teams distribute simd directive.
3213 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
3214 CodeGenModule &CGM, StringRef ParentName,
3215 const OMPTargetTeamsDistributeSimdDirective &S);
3216 /// Emit device code for the target simd directive.
3217 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
3218 StringRef ParentName,
3219 const OMPTargetSimdDirective &S);
3220 /// Emit device code for the target teams distribute parallel for simd
3221 /// directive.
3222 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
3223 CodeGenModule &CGM, StringRef ParentName,
3224 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3225
3226 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
3227 CodeGenModule &CGM, StringRef ParentName,
3228 const OMPTargetTeamsDistributeParallelForDirective &S);
3229 /// Emit inner loop of the worksharing/simd construct.
3230 ///
3231 /// \param S Directive, for which the inner loop must be emitted.
3232 /// \param RequiresCleanup true, if directive has some associated private
3233 /// variables.
3234 /// \param LoopCond Bollean condition for loop continuation.
3235 /// \param IncExpr Increment expression for loop control variable.
3236 /// \param BodyGen Generator for the inner body of the inner loop.
3237 /// \param PostIncGen Genrator for post-increment code (required for ordered
3238 /// loop directvies).
3239 void EmitOMPInnerLoop(
3240 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
3241 const Expr *IncExpr,
3242 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3243 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3244
3245 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
3246 /// Emit initial code for loop counters of loop-based directives.
3247 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
3248 OMPPrivateScope &LoopScope);
3249
3250 /// Helper for the OpenMP loop directives.
3251 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
3252
3253 /// Emit code for the worksharing loop-based directive.
3254 /// \return true, if this construct has any lastprivate clause, false -
3255 /// otherwise.
3256 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
3257 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3258 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3259
3260 /// Emit code for the distribute loop-based directive.
3261 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
3262 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3263
3264 /// Helpers for the OpenMP loop directives.
3265 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
3266 void EmitOMPSimdFinal(
3267 const OMPLoopDirective &D,
3268 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3269
3270 /// Emits the lvalue for the expression with possibly captured variable.
3271 LValue EmitOMPSharedLValue(const Expr *E);
3272
3273private:
3274 /// Helpers for blocks.
3275 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3276
3277 /// struct with the values to be passed to the OpenMP loop-related functions
3278 struct OMPLoopArguments {
3279 /// loop lower bound
3280 Address LB = Address::invalid();
3281 /// loop upper bound
3282 Address UB = Address::invalid();
3283 /// loop stride
3284 Address ST = Address::invalid();
3285 /// isLastIteration argument for runtime functions
3286 Address IL = Address::invalid();
3287 /// Chunk value generated by sema
3288 llvm::Value *Chunk = nullptr;
3289 /// EnsureUpperBound
3290 Expr *EUB = nullptr;
3291 /// IncrementExpression
3292 Expr *IncExpr = nullptr;
3293 /// Loop initialization
3294 Expr *Init = nullptr;
3295 /// Loop exit condition
3296 Expr *Cond = nullptr;
3297 /// Update of LB after a whole chunk has been executed
3298 Expr *NextLB = nullptr;
3299 /// Update of UB after a whole chunk has been executed
3300 Expr *NextUB = nullptr;
3301 OMPLoopArguments() = default;
3302 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3303 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3304 Expr *IncExpr = nullptr, Expr *Init = nullptr,
3305 Expr *Cond = nullptr, Expr *NextLB = nullptr,
3306 Expr *NextUB = nullptr)
3307 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3308 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3309 NextUB(NextUB) {}
3310 };
3311 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3312 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3313 const OMPLoopArguments &LoopArgs,
3314 const CodeGenLoopTy &CodeGenLoop,
3315 const CodeGenOrderedTy &CodeGenOrdered);
3316 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3317 bool IsMonotonic, const OMPLoopDirective &S,
3318 OMPPrivateScope &LoopScope, bool Ordered,
3319 const OMPLoopArguments &LoopArgs,
3320 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3321 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3322 const OMPLoopDirective &S,
3323 OMPPrivateScope &LoopScope,
3324 const OMPLoopArguments &LoopArgs,
3325 const CodeGenLoopTy &CodeGenLoopContent);
3326 /// Emit code for sections directive.
3327 void EmitSections(const OMPExecutableDirective &S);
3328
3329public:
3330
3331 //===--------------------------------------------------------------------===//
3332 // LValue Expression Emission
3333 //===--------------------------------------------------------------------===//
3334
3335 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3336 RValue GetUndefRValue(QualType Ty);
3337
3338 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3339 /// and issue an ErrorUnsupported style diagnostic (using the
3340 /// provided Name).
3341 RValue EmitUnsupportedRValue(const Expr *E,
3342 const char *Name);
3343
3344 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3345 /// an ErrorUnsupported style diagnostic (using the provided Name).
3346 LValue EmitUnsupportedLValue(const Expr *E,
3347 const char *Name);
3348
3349 /// EmitLValue - Emit code to compute a designator that specifies the location
3350 /// of the expression.
3351 ///
3352 /// This can return one of two things: a simple address or a bitfield
3353 /// reference. In either case, the LLVM Value* in the LValue structure is
3354 /// guaranteed to be an LLVM pointer type.
3355 ///
3356 /// If this returns a bitfield reference, nothing about the pointee type of
3357 /// the LLVM value is known: For example, it may not be a pointer to an
3358 /// integer.
3359 ///
3360 /// If this returns a normal address, and if the lvalue's C type is fixed
3361 /// size, this method guarantees that the returned pointer type will point to
3362 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
3363 /// variable length type, this is not possible.
3364 ///
3365 LValue EmitLValue(const Expr *E);
3366
3367 /// Same as EmitLValue but additionally we generate checking code to
3368 /// guard against undefined behavior. This is only suitable when we know
3369 /// that the address will be used to access the object.
3370 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
3371
3372 RValue convertTempToRValue(Address addr, QualType type,
3373 SourceLocation Loc);
3374
3375 void EmitAtomicInit(Expr *E, LValue lvalue);
3376
3377 bool LValueIsSuitableForInlineAtomic(LValue Src);
3378
3379 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
3380 AggValueSlot Slot = AggValueSlot::ignored());
3381
3382 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
3383 llvm::AtomicOrdering AO, bool IsVolatile = false,
3384 AggValueSlot slot = AggValueSlot::ignored());
3385
3386 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3387
3388 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3389 bool IsVolatile, bool isInit);
3390
3391 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3392 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3393 llvm::AtomicOrdering Success =
3394 llvm::AtomicOrdering::SequentiallyConsistent,
3395 llvm::AtomicOrdering Failure =
3396 llvm::AtomicOrdering::SequentiallyConsistent,
3397 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3398
3399 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3400 const llvm::function_ref<RValue(RValue)> &UpdateOp,
3401 bool IsVolatile);
3402
3403 /// EmitToMemory - Change a scalar value from its value
3404 /// representation to its in-memory representation.
3405 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3406
3407 /// EmitFromMemory - Change a scalar value from its memory
3408 /// representation to its value representation.
3409 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3410
3411 /// Check if the scalar \p Value is within the valid range for the given
3412 /// type \p Ty.
3413 ///
3414 /// Returns true if a check is needed (even if the range is unknown).
3415 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3416 SourceLocation Loc);
3417
3418 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3419 /// care to appropriately convert from the memory representation to
3420 /// the LLVM value representation.
3421 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3422 SourceLocation Loc,
3423 AlignmentSource Source = AlignmentSource::Type,
3424 bool isNontemporal = false) {
3425 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3426 CGM.getTBAAAccessInfo(Ty), isNontemporal);
3427 }
3428
3429 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3430 SourceLocation Loc, LValueBaseInfo BaseInfo,
3431 TBAAAccessInfo TBAAInfo,
3432 bool isNontemporal = false);
3433
3434 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3435 /// care to appropriately convert from the memory representation to
3436 /// the LLVM value representation. The l-value must be a simple
3437 /// l-value.
3438 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3439
3440 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3441 /// care to appropriately convert from the memory representation to
3442 /// the LLVM value representation.
3443 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3444 bool Volatile, QualType Ty,
3445 AlignmentSource Source = AlignmentSource::Type,
3446 bool isInit = false, bool isNontemporal = false) {
3447 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3448 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3449 }
3450
3451 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3452 bool Volatile, QualType Ty,
3453 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3454 bool isInit = false, bool isNontemporal = false);
3455
3456 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3457 /// care to appropriately convert from the memory representation to
3458 /// the LLVM value representation. The l-value must be a simple
3459 /// l-value. The isInit flag indicates whether this is an initialization.
3460 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3461 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3462
3463 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3464 /// this method emits the address of the lvalue, then loads the result as an
3465 /// rvalue, returning the rvalue.
3466 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3467 RValue EmitLoadOfExtVectorElementLValue(LValue V);
3468 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3469 RValue EmitLoadOfGlobalRegLValue(LValue LV);
3470
3471 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3472 /// lvalue, where both are guaranteed to the have the same type, and that type
3473 /// is 'Ty'.
3474 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3475 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3476 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3477
3478 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3479 /// as EmitStoreThroughLValue.
3480 ///
3481 /// \param Result [out] - If non-null, this will be set to a Value* for the
3482 /// bit-field contents after the store, appropriate for use as the result of
3483 /// an assignment to the bit-field.
3484 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3485 llvm::Value **Result=nullptr);
3486
3487 /// Emit an l-value for an assignment (simple or compound) of complex type.
3488 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3489 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3490 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3491 llvm::Value *&Result);
3492
3493 // Note: only available for agg return types
3494 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3495 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3496 // Note: only available for agg return types
3497 LValue EmitCallExprLValue(const CallExpr *E);
3498 // Note: only available for agg return types
3499 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3500 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3501 LValue EmitStringLiteralLValue(const StringLiteral *E);
3502 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3503 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3504 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3505 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3506 bool Accessed = false);
3507 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3508 bool IsLowerBound = true);
3509 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3510 LValue EmitMemberExpr(const MemberExpr *E);
3511 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3512 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3513 LValue EmitInitListLValue(const InitListExpr *E);
3514 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3515 LValue EmitCastLValue(const CastExpr *E);
3516 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3517 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3518
3519 Address EmitExtVectorElementLValue(LValue V);
3520
3521 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3522
3523 Address EmitArrayToPointerDecay(const Expr *Array,
3524 LValueBaseInfo *BaseInfo = nullptr,
3525 TBAAAccessInfo *TBAAInfo = nullptr);
3526
3527 class ConstantEmission {
3528 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3529 ConstantEmission(llvm::Constant *C, bool isReference)
3530 : ValueAndIsReference(C, isReference) {}
3531 public:
3532 ConstantEmission() {}
3533 static ConstantEmission forReference(llvm::Constant *C) {
3534 return ConstantEmission(C, true);
3535 }
3536 static ConstantEmission forValue(llvm::Constant *C) {
3537 return ConstantEmission(C, false);
3538 }
3539
3540 explicit operator bool() const {
3541 return ValueAndIsReference.getOpaqueValue() != nullptr;
3542 }
3543
3544 bool isReference() const { return ValueAndIsReference.getInt(); }
3545 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3546 assert(isReference())((isReference()) ? static_cast<void> (0) : __assert_fail
("isReference()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 3546, __PRETTY_FUNCTION__))
;
3547 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3548 refExpr->getType());
3549 }
3550
3551 llvm::Constant *getValue() const {
3552 assert(!isReference())((!isReference()) ? static_cast<void> (0) : __assert_fail
("!isReference()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 3552, __PRETTY_FUNCTION__))
;
3553 return ValueAndIsReference.getPointer();
3554 }
3555 };
3556
3557 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3558 ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
3559 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
3560
3561 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3562 AggValueSlot slot = AggValueSlot::ignored());
3563 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3564
3565 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3566 const ObjCIvarDecl *Ivar);
3567 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3568 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3569
3570 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3571 /// if the Field is a reference, this will return the address of the reference
3572 /// and not the address of the value stored in the reference.
3573 LValue EmitLValueForFieldInitialization(LValue Base,
3574 const FieldDecl* Field);
3575
3576 LValue EmitLValueForIvar(QualType ObjectTy,
3577 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3578 unsigned CVRQualifiers);
3579
3580 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3581 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3582 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3583 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3584
3585 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3586 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3587 LValue EmitStmtExprLValue(const StmtExpr *E);
3588 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3589 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3590 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3591
3592 //===--------------------------------------------------------------------===//
3593 // Scalar Expression Emission
3594 //===--------------------------------------------------------------------===//
3595
3596 /// EmitCall - Generate a call of the given function, expecting the given
3597 /// result type, and using the given argument list which specifies both the
3598 /// LLVM arguments and the types they were derived from.
3599 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3600 ReturnValueSlot ReturnValue, const CallArgList &Args,
3601 llvm::CallBase **callOrInvoke, SourceLocation Loc);
3602 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3603 ReturnValueSlot ReturnValue, const CallArgList &Args,
3604 llvm::CallBase **callOrInvoke = nullptr) {
3605 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
3606 SourceLocation());
3607 }
3608 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3609 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
3610 RValue EmitCallExpr(const CallExpr *E,
3611 ReturnValueSlot ReturnValue = ReturnValueSlot());
3612 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3613 CGCallee EmitCallee(const Expr *E);
3614
3615 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3616 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
3617
3618 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
3619 const Twine &name = "");
3620 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
3621 ArrayRef<llvm::Value *> args,
3622 const Twine &name = "");
3623 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
3624 const Twine &name = "");
3625 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
3626 ArrayRef<llvm::Value *> args,
3627 const Twine &name = "");
3628
3629 SmallVector<llvm::OperandBundleDef, 1>
3630 getBundlesForFunclet(llvm::Value *Callee);
3631
3632 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
3633 ArrayRef<llvm::Value *> Args,
3634 const Twine &Name = "");
3635 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3636 ArrayRef<llvm::Value *> args,
3637 const Twine &name = "");
3638 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3639 const Twine &name = "");
3640 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3641 ArrayRef<llvm::Value *> args);
3642
3643 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3644 NestedNameSpecifier *Qual,
3645 llvm::Type *Ty);
3646
3647 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3648 CXXDtorType Type,
3649 const CXXRecordDecl *RD);
3650
3651 // Return the copy constructor name with the prefix "__copy_constructor_"
3652 // removed.
3653 static std::string getNonTrivialCopyConstructorStr(QualType QT,
3654 CharUnits Alignment,
3655 bool IsVolatile,
3656 ASTContext &Ctx);
3657
3658 // Return the destructor name with the prefix "__destructor_" removed.
3659 static std::string getNonTrivialDestructorStr(QualType QT,
3660 CharUnits Alignment,
3661 bool IsVolatile,
3662 ASTContext &Ctx);
3663
3664 // These functions emit calls to the special functions of non-trivial C
3665 // structs.
3666 void defaultInitNonTrivialCStructVar(LValue Dst);
3667 void callCStructDefaultConstructor(LValue Dst);
3668 void callCStructDestructor(LValue Dst);
3669 void callCStructCopyConstructor(LValue Dst, LValue Src);
3670 void callCStructMoveConstructor(LValue Dst, LValue Src);
3671 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
3672 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
3673
3674 RValue
3675 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3676 const CGCallee &Callee,
3677 ReturnValueSlot ReturnValue, llvm::Value *This,
3678 llvm::Value *ImplicitParam,
3679 QualType ImplicitParamTy, const CallExpr *E,
3680 CallArgList *RtlArgs);
3681 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
3682 llvm::Value *This, QualType ThisTy,
3683 llvm::Value *ImplicitParam,
3684 QualType ImplicitParamTy, const CallExpr *E);
3685 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3686 ReturnValueSlot ReturnValue);
3687 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3688 const CXXMethodDecl *MD,
3689 ReturnValueSlot ReturnValue,
3690 bool HasQualifier,
3691 NestedNameSpecifier *Qualifier,
3692 bool IsArrow, const Expr *Base);
3693 // Compute the object pointer.
3694 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3695 llvm::Value *memberPtr,
3696 const MemberPointerType *memberPtrType,
3697 LValueBaseInfo *BaseInfo = nullptr,
3698 TBAAAccessInfo *TBAAInfo = nullptr);
3699 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3700 ReturnValueSlot ReturnValue);
3701
3702 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3703 const CXXMethodDecl *MD,
3704 ReturnValueSlot ReturnValue);
3705 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3706
3707 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3708 ReturnValueSlot ReturnValue);
3709
3710 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3711 ReturnValueSlot ReturnValue);
3712
3713 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
3714 const CallExpr *E, ReturnValueSlot ReturnValue);
3715
3716 RValue emitRotate(const CallExpr *E, bool IsRotateRight);
3717
3718 /// Emit IR for __builtin_os_log_format.
3719 RValue emitBuiltinOSLogFormat(const CallExpr &E);
3720
3721 llvm::Function *generateBuiltinOSLogHelperFunction(
3722 const analyze_os_log::OSLogBufferLayout &Layout,
3723 CharUnits BufferAlignment);
3724
3725 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3726
3727 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3728 /// is unhandled by the current target.
3729 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3730
3731 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3732 const llvm::CmpInst::Predicate Fp,
3733 const llvm::CmpInst::Predicate Ip,
3734 const llvm::Twine &Name = "");
3735 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3736 llvm::Triple::ArchType Arch);
3737
3738 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3739 unsigned LLVMIntrinsic,
3740 unsigned AltLLVMIntrinsic,
3741 const char *NameHint,
3742 unsigned Modifier,
3743 const CallExpr *E,
3744 SmallVectorImpl<llvm::Value *> &Ops,
3745 Address PtrOp0, Address PtrOp1,
3746 llvm::Triple::ArchType Arch);
3747
3748 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3749 unsigned Modifier, llvm::Type *ArgTy,
3750 const CallExpr *E);
3751 llvm::Value *EmitNeonCall(llvm::Function *F,
3752 SmallVectorImpl<llvm::Value*> &O,
3753 const char *name,
3754 unsigned shift = 0, bool rightshift = false);
3755 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3756 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3757 bool negateForRightShift);
3758 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3759 llvm::Type *Ty, bool usgn, const char *name);
3760 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3761 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3762 llvm::Triple::ArchType Arch);
3763
3764 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3765 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3766 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3767 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3768 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3769 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3770 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3771 const CallExpr *E);
3772 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3773
3774private:
3775 enum class MSVCIntrin;
3776
3777public:
3778 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3779
3780 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3781
3782 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3783 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3784 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3785 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3786 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3787 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3788 const ObjCMethodDecl *MethodWithObjects);
3789 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3790 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3791 ReturnValueSlot Return = ReturnValueSlot());
3792
3793 /// Retrieves the default cleanup kind for an ARC cleanup.
3794 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3795 CleanupKind getARCCleanupKind() {
3796 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3797 ? NormalAndEHCleanup : NormalCleanup;
3798 }
3799
3800 // ARC primitives.
3801 void EmitARCInitWeak(Address addr, llvm::Value *value);
3802 void EmitARCDestroyWeak(Address addr);
3803 llvm::Value *EmitARCLoadWeak(Address addr);
3804 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3805 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3806 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3807 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3808 void EmitARCCopyWeak(Address dst, Address src);
3809 void EmitARCMoveWeak(Address dst, Address src);
3810 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3811 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3812 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3813 bool resultIgnored);
3814 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3815 bool resultIgnored);
3816 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3817 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3818 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3819 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3820 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3821 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3822 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3823 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3824 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3825 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3826
3827 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
3828 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
3829 llvm::Type *returnType);
3830 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3831
3832 std::pair<LValue,llvm::Value*>
3833 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3834 std::pair<LValue,llvm::Value*>
3835 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3836 std::pair<LValue,llvm::Value*>
3837 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3838
3839 llvm::Value *EmitObjCAlloc(llvm::Value *value,
3840 llvm::Type *returnType);
3841 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
3842 llvm::Type *returnType);
3843 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
3844
3845 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3846 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3847 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3848
3849 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3850 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3851 bool allowUnsafeClaim);
3852 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3853 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3854 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3855
3856 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3857
3858 static Destroyer destroyARCStrongImprecise;
3859 static Destroyer destroyARCStrongPrecise;
3860 static Destroyer destroyARCWeak;
3861 static Destroyer emitARCIntrinsicUse;
3862 static Destroyer destroyNonTrivialCStruct;
3863
3864 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3865 llvm::Value *EmitObjCAutoreleasePoolPush();
3866 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3867 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3868 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3869
3870 /// Emits a reference binding to the passed in expression.
3871 RValue EmitReferenceBindingToExpr(const Expr *E);
3872
3873 //===--------------------------------------------------------------------===//
3874 // Expression Emission
3875 //===--------------------------------------------------------------------===//
3876
3877 // Expressions are broken into three classes: scalar, complex, aggregate.
3878
3879 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3880 /// scalar type, returning the result.
3881 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3882
3883 /// Emit a conversion from the specified type to the specified destination
3884 /// type, both of which are LLVM scalar types.
3885 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3886 QualType DstTy, SourceLocation Loc);
3887
3888 /// Emit a conversion from the specified complex type to the specified
3889 /// destination type, where the destination type is an LLVM scalar type.
3890 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3891 QualType DstTy,
3892 SourceLocation Loc);
3893
3894 /// EmitAggExpr - Emit the computation of the specified expression
3895 /// of aggregate type. The result is computed into the given slot,
3896 /// which may be null to indicate that the value is not needed.
3897 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3898
3899 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3900 /// aggregate type into a temporary LValue.
3901 LValue EmitAggExprToLValue(const Expr *E);
3902
3903 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3904 /// make sure it survives garbage collection until this point.
3905 void EmitExtendGCLifetime(llvm::Value *object);
3906
3907 /// EmitComplexExpr - Emit the computation of the specified expression of
3908 /// complex type, returning the result.
3909 ComplexPairTy EmitComplexExpr(const Expr *E,
3910 bool IgnoreReal = false,
3911 bool IgnoreImag = false);
3912
3913 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3914 /// type and place its result into the specified l-value.
3915 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3916
3917 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3918 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3919
3920 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3921 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3922
3923 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3924 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3925
3926 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3927 /// global variable that has already been created for it. If the initializer
3928 /// has a different type than GV does, this may free GV and return a different
3929 /// one. Otherwise it just returns GV.
3930 llvm::GlobalVariable *
3931 AddInitializerToStaticVarDecl(const VarDecl &D,
3932 llvm::GlobalVariable *GV);
3933
3934 // Emit an @llvm.invariant.start call for the given memory region.
3935 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
3936
3937 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3938 /// variable with global storage.
3939 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3940 bool PerformInit);
3941
3942 llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
3943 llvm::Constant *Addr);
3944
3945 /// Call atexit() with a function that passes the given argument to
3946 /// the given function.
3947 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
3948 llvm::Constant *addr);
3949
3950 /// Call atexit() with function dtorStub.
3951 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
3952
3953 /// Emit code in this function to perform a guarded variable
3954 /// initialization. Guarded initializations are used when it's not
3955 /// possible to prove that an initialization will be done exactly
3956 /// once, e.g. with a static local variable or a static data member
3957 /// of a class template.
3958 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3959 bool PerformInit);
3960
3961 enum class GuardKind { VariableGuard, TlsGuard };
3962
3963 /// Emit a branch to select whether or not to perform guarded initialization.
3964 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
3965 llvm::BasicBlock *InitBlock,
3966 llvm::BasicBlock *NoInitBlock,
3967 GuardKind Kind, const VarDecl *D);
3968
3969 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3970 /// variables.
3971 void
3972 GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3973 ArrayRef<llvm::Function *> CXXThreadLocals,
3974 ConstantAddress Guard = ConstantAddress::invalid());
3975
3976 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3977 /// variables.
3978 void GenerateCXXGlobalDtorsFunc(
3979 llvm::Function *Fn,
3980 const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
3981 llvm::Constant *>> &DtorsAndObjects);
3982
3983 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3984 const VarDecl *D,
3985 llvm::GlobalVariable *Addr,
3986 bool PerformInit);
3987
3988 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3989
3990 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3991
3992 void enterFullExpression(const FullExpr *E) {
3993 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E))
3994 if (EWC->getNumObjects() == 0)
3995 return;
3996 enterNonTrivialFullExpression(E);
3997 }
3998 void enterNonTrivialFullExpression(const FullExpr *E);
3999
4000 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
4001
4002 RValue EmitAtomicExpr(AtomicExpr *E);
4003
4004 //===--------------------------------------------------------------------===//
4005 // Annotations Emission
4006 //===--------------------------------------------------------------------===//
4007
4008 /// Emit an annotation call (intrinsic).
4009 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
4010 llvm::Value *AnnotatedVal,
4011 StringRef AnnotationStr,
4012 SourceLocation Location);
4013
4014 /// Emit local annotations for the local variable V, declared by D.
4015 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
4016
4017 /// Emit field annotations for the given field & value. Returns the
4018 /// annotation result.
4019 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
4020
4021 //===--------------------------------------------------------------------===//
4022 // Internal Helpers
4023 //===--------------------------------------------------------------------===//
4024
4025 /// ContainsLabel - Return true if the statement contains a label in it. If
4026 /// this statement is not executed normally, it not containing a label means
4027 /// that we can just remove the code.
4028 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
4029
4030 /// containsBreak - Return true if the statement contains a break out of it.
4031 /// If the statement (recursively) contains a switch or loop with a break
4032 /// inside of it, this is fine.
4033 static bool containsBreak(const Stmt *S);
4034
4035 /// Determine if the given statement might introduce a declaration into the
4036 /// current scope, by being a (possibly-labelled) DeclStmt.
4037 static bool mightAddDeclToScope(const Stmt *S);
4038
4039 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4040 /// to a constant, or if it does but contains a label, return false. If it
4041 /// constant folds return true and set the boolean result in Result.
4042 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
4043 bool AllowLabels = false);
4044
4045 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4046 /// to a constant, or if it does but contains a label, return false. If it
4047 /// constant folds return true and set the folded value.
4048 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
4049 bool AllowLabels = false);
4050
4051 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
4052 /// if statement) to the specified blocks. Based on the condition, this might
4053 /// try to simplify the codegen of the conditional based on the branch.
4054 /// TrueCount should be the number of times we expect the condition to
4055 /// evaluate to true based on PGO data.
4056 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
4057 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
4058
4059 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
4060 /// nonnull, if \p LHS is marked _Nonnull.
4061 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
4062
4063 /// An enumeration which makes it easier to specify whether or not an
4064 /// operation is a subtraction.
4065 enum { NotSubtraction = false, IsSubtraction = true };
4066
4067 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
4068 /// detect undefined behavior when the pointer overflow sanitizer is enabled.
4069 /// \p SignedIndices indicates whether any of the GEP indices are signed.
4070 /// \p IsSubtraction indicates whether the expression used to form the GEP
4071 /// is a subtraction.
4072 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
4073 ArrayRef<llvm::Value *> IdxList,
4074 bool SignedIndices,
4075 bool IsSubtraction,
4076 SourceLocation Loc,
4077 const Twine &Name = "");
4078
4079 /// Specifies which type of sanitizer check to apply when handling a
4080 /// particular builtin.
4081 enum BuiltinCheckKind {
4082 BCK_CTZPassedZero,
4083 BCK_CLZPassedZero,
4084 };
4085
4086 /// Emits an argument for a call to a builtin. If the builtin sanitizer is
4087 /// enabled, a runtime check specified by \p Kind is also emitted.
4088 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
4089
4090 /// Emit a description of a type in a format suitable for passing to
4091 /// a runtime sanitizer handler.
4092 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
4093
4094 /// Convert a value into a format suitable for passing to a runtime
4095 /// sanitizer handler.
4096 llvm::Value *EmitCheckValue(llvm::Value *V);
4097
4098 /// Emit a description of a source location in a format suitable for
4099 /// passing to a runtime sanitizer handler.
4100 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
4101
4102 /// Create a basic block that will either trap or call a handler function in
4103 /// the UBSan runtime with the provided arguments, and create a conditional
4104 /// branch to it.
4105 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
4106 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
4107 ArrayRef<llvm::Value *> DynamicArgs);
4108
4109 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
4110 /// if Cond if false.
4111 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
4112 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4113 ArrayRef<llvm::Constant *> StaticArgs);
4114
4115 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
4116 /// checking is enabled. Otherwise, just emit an unreachable instruction.
4117 void EmitUnreachable(SourceLocation Loc);
4118
4119 /// Create a basic block that will call the trap intrinsic, and emit a
4120 /// conditional branch to it, for the -ftrapv checks.
4121 void EmitTrapCheck(llvm::Value *Checked);
4122
4123 /// Emit a call to trap or debugtrap and attach function attribute
4124 /// "trap-func-name" if specified.
4125 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
4126
4127 /// Emit a stub for the cross-DSO CFI check function.
4128 void EmitCfiCheckStub();
4129
4130 /// Emit a cross-DSO CFI failure handling function.
4131 void EmitCfiCheckFail();
4132
4133 /// Create a check for a function parameter that may potentially be
4134 /// declared as non-null.
4135 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
4136 AbstractCallee AC, unsigned ParmNum);
4137
4138 /// EmitCallArg - Emit a single call argument.
4139 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
4140
4141 /// EmitDelegateCallArg - We are performing a delegate call; that
4142 /// is, the current function is delegating to another one. Produce
4143 /// a r-value suitable for passing the given parameter.
4144 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
4145 SourceLocation loc);
4146
4147 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
4148 /// point operation, expressed as the maximum relative error in ulp.
4149 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
4150
4151private:
4152 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
4153 void EmitReturnOfRValue(RValue RV, QualType Ty);
4154
4155 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
4156
4157 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
4158 DeferredReplacements;
4159
4160 /// Set the address of a local variable.
4161 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
4162 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!")((!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"
) ? static_cast<void> (0) : __assert_fail ("!LocalDeclMap.count(VD) && \"Decl already exists in LocalDeclMap!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4162, __PRETTY_FUNCTION__))
;
4163 LocalDeclMap.insert({VD, Addr});
4164 }
4165
4166 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
4167 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
4168 ///
4169 /// \param AI - The first function argument of the expansion.
4170 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
4171 SmallVectorImpl<llvm::Value *>::iterator &AI);
4172
4173 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
4174 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
4175 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
4176 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
4177 SmallVectorImpl<llvm::Value *> &IRCallArgs,
4178 unsigned &IRCallArgPos);
4179
4180 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
4181 const Expr *InputExpr, std::string &ConstraintStr);
4182
4183 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
4184 LValue InputValue, QualType InputType,
4185 std::string &ConstraintStr,
4186 SourceLocation Loc);
4187
4188 /// Attempts to statically evaluate the object size of E. If that
4189 /// fails, emits code to figure the size of E out for us. This is
4190 /// pass_object_size aware.
4191 ///
4192 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
4193 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
4194 llvm::IntegerType *ResType,
4195 llvm::Value *EmittedE,
4196 bool IsDynamic);
4197
4198 /// Emits the size of E, as required by __builtin_object_size. This
4199 /// function is aware of pass_object_size parameters, and will act accordingly
4200 /// if E is a parameter with the pass_object_size attribute.
4201 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
4202 llvm::IntegerType *ResType,
4203 llvm::Value *EmittedE,
4204 bool IsDynamic);
4205
4206 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
4207 Address Loc);
4208
4209public:
4210#ifndef NDEBUG
4211 // Determine whether the given argument is an Objective-C method
4212 // that may have type parameters in its signature.
4213 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4214 const DeclContext *dc = method->getDeclContext();
4215 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
4216 return classDecl->getTypeParamListAsWritten();
4217 }
4218
4219 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4220 return catDecl->getTypeParamList();
4221 }
4222
4223 return false;
4224 }
4225
4226 template<typename T>
4227 static bool isObjCMethodWithTypeParams(const T *) { return false; }
4228#endif
4229
4230 enum class EvaluationOrder {
4231 ///! No language constraints on evaluation order.
4232 Default,
4233 ///! Language semantics require left-to-right evaluation.
4234 ForceLeftToRight,
4235 ///! Language semantics require right-to-left evaluation.
4236 ForceRightToLeft
4237 };
4238
4239 /// EmitCallArgs - Emit call arguments for a function.
4240 template <typename T>
4241 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
4242 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4243 AbstractCallee AC = AbstractCallee(),
4244 unsigned ParamsToSkip = 0,
4245 EvaluationOrder Order = EvaluationOrder::Default) {
4246 SmallVector<QualType, 16> ArgTypes;
4247 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4248
4249 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&(((ParamsToSkip == 0 || CallArgTypeInfo) && "Can't skip parameters if type info is not provided"
) ? static_cast<void> (0) : __assert_fail ("(ParamsToSkip == 0 || CallArgTypeInfo) && \"Can't skip parameters if type info is not provided\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4250, __PRETTY_FUNCTION__))
4250 "Can't skip parameters if type info is not provided")(((ParamsToSkip == 0 || CallArgTypeInfo) && "Can't skip parameters if type info is not provided"
) ? static_cast<void> (0) : __assert_fail ("(ParamsToSkip == 0 || CallArgTypeInfo) && \"Can't skip parameters if type info is not provided\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4250, __PRETTY_FUNCTION__))
;
4251 if (CallArgTypeInfo) {
4252#ifndef NDEBUG
4253 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
4254#endif
4255
4256 // First, use the argument types that the type info knows about
4257 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
4258 E = CallArgTypeInfo->param_type_end();
4259 I != E; ++I, ++Arg) {
4260 assert(Arg != ArgRange.end() && "Running over edge of argument list!")((Arg != ArgRange.end() && "Running over edge of argument list!"
) ? static_cast<void> (0) : __assert_fail ("Arg != ArgRange.end() && \"Running over edge of argument list!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4260, __PRETTY_FUNCTION__))
;
4261 assert((isGenericMethod ||(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4262 ((*I)->isVariablyModifiedType() ||(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4263 (*I).getNonReferenceType()->isObjCRetainableType() ||(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4264 getContext()(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4265 .getCanonicalType((*I).getNonReferenceType())(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4266 .getTypePtr() ==(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4267 getContext()(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4268 .getCanonicalType((*Arg)->getType())(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4269 .getTypePtr())) &&(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
4270 "type mismatch in call argument!")(((isGenericMethod || ((*I)->isVariablyModifiedType() || (
*I).getNonReferenceType()->isObjCRetainableType() || getContext
() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr(
) == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr
())) && "type mismatch in call argument!") ? static_cast
<void> (0) : __assert_fail ("(isGenericMethod || ((*I)->isVariablyModifiedType() || (*I).getNonReferenceType()->isObjCRetainableType() || getContext() .getCanonicalType((*I).getNonReferenceType()) .getTypePtr() == getContext() .getCanonicalType((*Arg)->getType()) .getTypePtr())) && \"type mismatch in call argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4270, __PRETTY_FUNCTION__))
;
4271 ArgTypes.push_back(*I);
4272 }
4273 }
4274
4275 // Either we've emitted all the call args, or we have a call to variadic
4276 // function.
4277 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||(((Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo
->isVariadic()) && "Extra arguments in non-variadic function!"
) ? static_cast<void> (0) : __assert_fail ("(Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) && \"Extra arguments in non-variadic function!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4279, __PRETTY_FUNCTION__))
4278 CallArgTypeInfo->isVariadic()) &&(((Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo
->isVariadic()) && "Extra arguments in non-variadic function!"
) ? static_cast<void> (0) : __assert_fail ("(Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) && \"Extra arguments in non-variadic function!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4279, __PRETTY_FUNCTION__))
4279 "Extra arguments in non-variadic function!")(((Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo
->isVariadic()) && "Extra arguments in non-variadic function!"
) ? static_cast<void> (0) : __assert_fail ("(Arg == ArgRange.end() || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) && \"Extra arguments in non-variadic function!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CodeGenFunction.h"
, 4279, __PRETTY_FUNCTION__))
;
4280
4281 // If we still have any arguments, emit them using the type of the argument.
4282 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
4283 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
4284
4285 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
4286 }
4287
4288 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
4289 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4290 AbstractCallee AC = AbstractCallee(),
4291 unsigned ParamsToSkip = 0,
4292 EvaluationOrder Order = EvaluationOrder::Default);
4293
4294 /// EmitPointerWithAlignment - Given an expression with a pointer type,
4295 /// emit the value and compute our best estimate of the alignment of the
4296 /// pointee.
4297 ///
4298 /// \param BaseInfo - If non-null, this will be initialized with
4299 /// information about the source of the alignment and the may-alias
4300 /// attribute. Note that this function will conservatively fall back on
4301 /// the type when it doesn't recognize the expression and may-alias will
4302 /// be set to false.
4303 ///
4304 /// One reasonable way to use this information is when there's a language
4305 /// guarantee that the pointer must be aligned to some stricter value, and
4306 /// we're simply trying to ensure that sufficiently obvious uses of under-
4307 /// aligned objects don't get miscompiled; for example, a placement new
4308 /// into the address of a local variable. In such a case, it's quite
4309 /// reasonable to just ignore the returned alignment when it isn't from an
4310 /// explicit source.
4311 Address EmitPointerWithAlignment(const Expr *Addr,
4312 LValueBaseInfo *BaseInfo = nullptr,
4313 TBAAAccessInfo *TBAAInfo = nullptr);
4314
4315 /// If \p E references a parameter with pass_object_size info or a constant
4316 /// array size modifier, emit the object size divided by the size of \p EltTy.
4317 /// Otherwise return null.
4318 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
4319
4320 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
4321
4322 struct MultiVersionResolverOption {
4323 llvm::Function *Function;
4324 FunctionDecl *FD;
4325 struct Conds {
4326 StringRef Architecture;
4327 llvm::SmallVector<StringRef, 8> Features;
4328
4329 Conds(StringRef Arch, ArrayRef<StringRef> Feats)
4330 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
4331 } Conditions;
4332
4333 MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
4334 ArrayRef<StringRef> Feats)
4335 : Function(F), Conditions(Arch, Feats) {}
4336 };
4337
4338 // Emits the body of a multiversion function's resolver. Assumes that the
4339 // options are already sorted in the proper order, with the 'default' option
4340 // last (if it exists).
4341 void EmitMultiVersionResolver(llvm::Function *Resolver,
4342 ArrayRef<MultiVersionResolverOption> Options);
4343
4344 static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs);
4345
4346private:
4347 QualType getVarArgType(const Expr *Arg);
4348
4349 void EmitDeclMetadata();
4350
4351 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
4352 const AutoVarEmission &emission);
4353
4354 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
4355
4356 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
4357 llvm::Value *EmitX86CpuIs(const CallExpr *E);
4358 llvm::Value *EmitX86CpuIs(StringRef CPUStr);
4359 llvm::Value *EmitX86CpuSupports(const CallExpr *E);
4360 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
4361 llvm::Value *EmitX86CpuSupports(uint64_t Mask);
4362 llvm::Value *EmitX86CpuInit();
4363 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
4364};
4365
4366inline DominatingLLVMValue::saved_type
4367DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
4368 if (!needsSaving(value)) return saved_type(value, false);
4369
4370 // Otherwise, we need an alloca.
4371 auto align = CharUnits::fromQuantity(
4372 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
4373 Address alloca =
4374 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
4375 CGF.Builder.CreateStore(value, alloca);
4376
4377 return saved_type(alloca.getPointer(), true);
4378}
4379
4380inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
4381 saved_type value) {
4382 // If the value says it wasn't saved, trust that it's still dominating.
4383 if (!value.getInt()) return value.getPointer();
4384
4385 // Otherwise, it should be an alloca instruction, as set up in save().
4386 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
4387 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
4388}
4389
4390} // end namespace CodeGen
4391} // end namespace clang
4392
4393#endif