Bug Summary

File:clang/lib/CodeGen/CGExprCXX.cpp
Warning:line 133, column 19
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 CGExprCXX.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -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~++20200110111110+a1cc19b5814/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include -I /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/llvm/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~++20200110111110+a1cc19b5814/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2020-01-11-115256-23437-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp

/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp

1//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
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 contains code dealing with code generation of C++ expressions
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCUDARuntime.h"
14#include "CGCXXABI.h"
15#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "ConstantEmitter.h"
19#include "TargetInfo.h"
20#include "clang/Basic/CodeGenOptions.h"
21#include "clang/CodeGen/CGFunctionInfo.h"
22#include "llvm/IR/Intrinsics.h"
23
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28struct MemberCallInfo {
29 RequiredArgs ReqArgs;
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
31 unsigned PrefixSize;
32};
33}
34
35static MemberCallInfo
36commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37 llvm::Value *This, llvm::Value *ImplicitParam,
38 QualType ImplicitParamTy, const CallExpr *CE,
39 CallArgList &Args, CallArgList *RtlArgs) {
40 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||((CE == nullptr || isa<CXXMemberCallExpr>(CE) || isa<
CXXOperatorCallExpr>(CE)) ? static_cast<void> (0) : __assert_fail
("CE == nullptr || isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 41, __PRETTY_FUNCTION__))
41 isa<CXXOperatorCallExpr>(CE))((CE == nullptr || isa<CXXMemberCallExpr>(CE) || isa<
CXXOperatorCallExpr>(CE)) ? static_cast<void> (0) : __assert_fail
("CE == nullptr || isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 41, __PRETTY_FUNCTION__))
;
42 assert(MD->isInstance() &&((MD->isInstance() && "Trying to emit a member or operator call expr on a static method!"
) ? static_cast<void> (0) : __assert_fail ("MD->isInstance() && \"Trying to emit a member or operator call expr on a static method!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 43, __PRETTY_FUNCTION__))
43 "Trying to emit a member or operator call expr on a static method!")((MD->isInstance() && "Trying to emit a member or operator call expr on a static method!"
) ? static_cast<void> (0) : __assert_fail ("MD->isInstance() && \"Trying to emit a member or operator call expr on a static method!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 43, __PRETTY_FUNCTION__))
;
44
45 // Push the this ptr.
46 const CXXRecordDecl *RD =
47 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48 Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
49
50 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
53 }
54
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
57 unsigned PrefixSize = Args.size() - 1;
58
59 // And the rest of the call args.
60 if (RtlArgs) {
61 // Special case: if the caller emitted the arguments right-to-left already
62 // (prior to emitting the *this argument), we're done. This happens for
63 // assignment operators.
64 Args.addFrom(*RtlArgs);
65 } else if (CE) {
66 // Special case: skip first argument of CXXOperatorCall (it is "this").
67 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
68 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
69 CE->getDirectCallee());
70 } else {
71 assert(((FPT->getNumParams() == 0 && "No CallExpr specified for function with non-zero number of arguments"
) ? static_cast<void> (0) : __assert_fail ("FPT->getNumParams() == 0 && \"No CallExpr specified for function with non-zero number of arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 73, __PRETTY_FUNCTION__))
72 FPT->getNumParams() == 0 &&((FPT->getNumParams() == 0 && "No CallExpr specified for function with non-zero number of arguments"
) ? static_cast<void> (0) : __assert_fail ("FPT->getNumParams() == 0 && \"No CallExpr specified for function with non-zero number of arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 73, __PRETTY_FUNCTION__))
73 "No CallExpr specified for function with non-zero number of arguments")((FPT->getNumParams() == 0 && "No CallExpr specified for function with non-zero number of arguments"
) ? static_cast<void> (0) : __assert_fail ("FPT->getNumParams() == 0 && \"No CallExpr specified for function with non-zero number of arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 73, __PRETTY_FUNCTION__))
;
74 }
75 return {required, PrefixSize};
76}
77
78RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
79 const CXXMethodDecl *MD, const CGCallee &Callee,
80 ReturnValueSlot ReturnValue,
81 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
82 const CallExpr *CE, CallArgList *RtlArgs) {
83 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
84 CallArgList Args;
85 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
86 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
87 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
88 Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
89 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
90 CE ? CE->getExprLoc() : SourceLocation());
91}
92
93RValue CodeGenFunction::EmitCXXDestructorCall(
94 GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
95 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
96 const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
97
98 assert(!ThisTy.isNull())((!ThisTy.isNull()) ? static_cast<void> (0) : __assert_fail
("!ThisTy.isNull()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 98, __PRETTY_FUNCTION__))
;
99 assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&((ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent()
&& "Pointer/Object mixup") ? static_cast<void>
(0) : __assert_fail ("ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() && \"Pointer/Object mixup\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 100, __PRETTY_FUNCTION__))
100 "Pointer/Object mixup")((ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent()
&& "Pointer/Object mixup") ? static_cast<void>
(0) : __assert_fail ("ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() && \"Pointer/Object mixup\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 100, __PRETTY_FUNCTION__))
;
101
102 LangAS SrcAS = ThisTy.getAddressSpace();
103 LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
104 if (SrcAS != DstAS) {
105 QualType DstTy = DtorDecl->getThisType();
106 llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
107 This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
108 NewType);
109 }
110
111 CallArgList Args;
112 commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
113 ImplicitParamTy, CE, Args, nullptr);
114 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
115 ReturnValueSlot(), Args);
116}
117
118RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
119 const CXXPseudoDestructorExpr *E) {
120 QualType DestroyedType = E->getDestroyedType();
121 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
1
Calling 'QualType::hasStrongOrWeakObjCLifetime'
7
Returning from 'QualType::hasStrongOrWeakObjCLifetime'
8
Taking true branch
122 // Automatic Reference Counting:
123 // If the pseudo-expression names a retainable object with weak or
124 // strong lifetime, the object shall be released.
125 Expr *BaseExpr = E->getBase();
126 Address BaseValue = Address::invalid();
127 Qualifiers BaseQuals;
128
129 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
130 if (E->isArrow()) {
9
Assuming the condition is true
10
Taking true branch
131 BaseValue = EmitPointerWithAlignment(BaseExpr);
132 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
11
Assuming the object is not a 'PointerType'
12
'PTy' initialized to a null pointer value
133 BaseQuals = PTy->getPointeeType().getQualifiers();
13
Called C++ object pointer is null
134 } else {
135 LValue BaseLV = EmitLValue(BaseExpr);
136 BaseValue = BaseLV.getAddress(*this);
137 QualType BaseTy = BaseExpr->getType();
138 BaseQuals = BaseTy.getQualifiers();
139 }
140
141 switch (DestroyedType.getObjCLifetime()) {
142 case Qualifiers::OCL_None:
143 case Qualifiers::OCL_ExplicitNone:
144 case Qualifiers::OCL_Autoreleasing:
145 break;
146
147 case Qualifiers::OCL_Strong:
148 EmitARCRelease(Builder.CreateLoad(BaseValue,
149 DestroyedType.isVolatileQualified()),
150 ARCPreciseLifetime);
151 break;
152
153 case Qualifiers::OCL_Weak:
154 EmitARCDestroyWeak(BaseValue);
155 break;
156 }
157 } else {
158 // C++ [expr.pseudo]p1:
159 // The result shall only be used as the operand for the function call
160 // operator (), and the result of such a call has type void. The only
161 // effect is the evaluation of the postfix-expression before the dot or
162 // arrow.
163 EmitIgnoredExpr(E->getBase());
164 }
165
166 return RValue::get(nullptr);
167}
168
169static CXXRecordDecl *getCXXRecord(const Expr *E) {
170 QualType T = E->getType();
171 if (const PointerType *PTy = T->getAs<PointerType>())
172 T = PTy->getPointeeType();
173 const RecordType *Ty = T->castAs<RecordType>();
174 return cast<CXXRecordDecl>(Ty->getDecl());
175}
176
177// Note: This function also emit constructor calls to support a MSVC
178// extensions allowing explicit constructor function call.
179RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
180 ReturnValueSlot ReturnValue) {
181 const Expr *callee = CE->getCallee()->IgnoreParens();
182
183 if (isa<BinaryOperator>(callee))
184 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
185
186 const MemberExpr *ME = cast<MemberExpr>(callee);
187 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
188
189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
191 CGCallee callee =
192 CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
193 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
194 ReturnValue);
195 }
196
197 bool HasQualifier = ME->hasQualifier();
198 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
199 bool IsArrow = ME->isArrow();
200 const Expr *Base = ME->getBase();
201
202 return EmitCXXMemberOrOperatorMemberCallExpr(
203 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
204}
205
206RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
207 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
208 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
209 const Expr *Base) {
210 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE))((isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr
>(CE)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 210, __PRETTY_FUNCTION__))
;
211
212 // Compute the object pointer.
213 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
214
215 const CXXMethodDecl *DevirtualizedMethod = nullptr;
216 if (CanUseVirtualCall &&
217 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
218 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
219 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
220 assert(DevirtualizedMethod)((DevirtualizedMethod) ? static_cast<void> (0) : __assert_fail
("DevirtualizedMethod", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
222 const Expr *Inner = Base->ignoreParenBaseCasts();
223 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
224 MD->getReturnType().getCanonicalType())
225 // If the return types are not the same, this might be a case where more
226 // code needs to run to compensate for it. For example, the derived
227 // method might return a type that inherits form from the return
228 // type of MD and has a prefix.
229 // For now we just avoid devirtualizing these covariant cases.
230 DevirtualizedMethod = nullptr;
231 else if (getCXXRecord(Inner) == DevirtualizedClass)
232 // If the class of the Inner expression is where the dynamic method
233 // is defined, build the this pointer from it.
234 Base = Inner;
235 else if (getCXXRecord(Base) != DevirtualizedClass) {
236 // If the method is defined in a class that is not the best dynamic
237 // one or the one of the full expression, we would have to build
238 // a derived-to-base cast to compute the correct this pointer, but
239 // we don't have support for that yet, so do a virtual call.
240 DevirtualizedMethod = nullptr;
241 }
242 }
243
244 bool TrivialForCodegen =
245 MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
246 bool TrivialAssignment =
247 TrivialForCodegen &&
248 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
249 !MD->getParent()->mayInsertExtraPadding();
250
251 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
252 // operator before the LHS.
253 CallArgList RtlArgStorage;
254 CallArgList *RtlArgs = nullptr;
255 LValue TrivialAssignmentRHS;
256 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
257 if (OCE->isAssignmentOp()) {
258 if (TrivialAssignment) {
259 TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
260 } else {
261 RtlArgs = &RtlArgStorage;
262 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
263 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
264 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
265 }
266 }
267 }
268
269 LValue This;
270 if (IsArrow) {
271 LValueBaseInfo BaseInfo;
272 TBAAAccessInfo TBAAInfo;
273 Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
274 This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
275 } else {
276 This = EmitLValue(Base);
277 }
278
279 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
280 // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
281 // constructing a new complete object of type Ctor.
282 assert(!RtlArgs)((!RtlArgs) ? static_cast<void> (0) : __assert_fail ("!RtlArgs"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 282, __PRETTY_FUNCTION__))
;
283 assert(ReturnValue.isNull() && "Constructor shouldn't have return value")((ReturnValue.isNull() && "Constructor shouldn't have return value"
) ? static_cast<void> (0) : __assert_fail ("ReturnValue.isNull() && \"Constructor shouldn't have return value\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 283, __PRETTY_FUNCTION__))
;
284 CallArgList Args;
285 commonEmitCXXMemberOrOperatorCall(
286 *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
287 /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
288
289 EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
290 /*Delegating=*/false, This.getAddress(*this), Args,
291 AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
292 /*NewPointerIsChecked=*/false);
293 return RValue::get(nullptr);
294 }
295
296 if (TrivialForCodegen) {
297 if (isa<CXXDestructorDecl>(MD))
298 return RValue::get(nullptr);
299
300 if (TrivialAssignment) {
301 // We don't like to generate the trivial copy/move assignment operator
302 // when it isn't necessary; just produce the proper effect here.
303 // It's important that we use the result of EmitLValue here rather than
304 // emitting call arguments, in order to preserve TBAA information from
305 // the RHS.
306 LValue RHS = isa<CXXOperatorCallExpr>(CE)
307 ? TrivialAssignmentRHS
308 : EmitLValue(*CE->arg_begin());
309 EmitAggregateAssign(This, RHS, CE->getType());
310 return RValue::get(This.getPointer(*this));
311 }
312
313 assert(MD->getParent()->mayInsertExtraPadding() &&((MD->getParent()->mayInsertExtraPadding() && "unknown trivial member function"
) ? static_cast<void> (0) : __assert_fail ("MD->getParent()->mayInsertExtraPadding() && \"unknown trivial member function\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 314, __PRETTY_FUNCTION__))
314 "unknown trivial member function")((MD->getParent()->mayInsertExtraPadding() && "unknown trivial member function"
) ? static_cast<void> (0) : __assert_fail ("MD->getParent()->mayInsertExtraPadding() && \"unknown trivial member function\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 314, __PRETTY_FUNCTION__))
;
315 }
316
317 // Compute the function type we're calling.
318 const CXXMethodDecl *CalleeDecl =
319 DevirtualizedMethod ? DevirtualizedMethod : MD;
320 const CGFunctionInfo *FInfo = nullptr;
321 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
322 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
323 GlobalDecl(Dtor, Dtor_Complete));
324 else
325 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
326
327 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
328
329 // C++11 [class.mfct.non-static]p2:
330 // If a non-static member function of a class X is called for an object that
331 // is not of type X, or of a type derived from X, the behavior is undefined.
332 SourceLocation CallLoc;
333 ASTContext &C = getContext();
334 if (CE)
335 CallLoc = CE->getExprLoc();
336
337 SanitizerSet SkippedChecks;
338 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
339 auto *IOA = CMCE->getImplicitObjectArgument();
340 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
341 if (IsImplicitObjectCXXThis)
342 SkippedChecks.set(SanitizerKind::Alignment, true);
343 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
344 SkippedChecks.set(SanitizerKind::Null, true);
345 }
346 EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
347 This.getPointer(*this),
348 C.getRecordType(CalleeDecl->getParent()),
349 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
350
351 // C++ [class.virtual]p12:
352 // Explicit qualification with the scope operator (5.1) suppresses the
353 // virtual call mechanism.
354 //
355 // We also don't emit a virtual call if the base expression has a record type
356 // because then we know what the type is.
357 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
358
359 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
360 assert(CE->arg_begin() == CE->arg_end() &&((CE->arg_begin() == CE->arg_end() && "Destructor shouldn't have explicit parameters"
) ? static_cast<void> (0) : __assert_fail ("CE->arg_begin() == CE->arg_end() && \"Destructor shouldn't have explicit parameters\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 361, __PRETTY_FUNCTION__))
361 "Destructor shouldn't have explicit parameters")((CE->arg_begin() == CE->arg_end() && "Destructor shouldn't have explicit parameters"
) ? static_cast<void> (0) : __assert_fail ("CE->arg_begin() == CE->arg_end() && \"Destructor shouldn't have explicit parameters\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 361, __PRETTY_FUNCTION__))
;
362 assert(ReturnValue.isNull() && "Destructor shouldn't have return value")((ReturnValue.isNull() && "Destructor shouldn't have return value"
) ? static_cast<void> (0) : __assert_fail ("ReturnValue.isNull() && \"Destructor shouldn't have return value\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 362, __PRETTY_FUNCTION__))
;
363 if (UseVirtualCall) {
364 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
365 This.getAddress(*this),
366 cast<CXXMemberCallExpr>(CE));
367 } else {
368 GlobalDecl GD(Dtor, Dtor_Complete);
369 CGCallee Callee;
370 if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
371 Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
372 else if (!DevirtualizedMethod)
373 Callee =
374 CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
375 else {
376 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
377 }
378
379 QualType ThisTy =
380 IsArrow ? Base->getType()->getPointeeType() : Base->getType();
381 EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
382 /*ImplicitParam=*/nullptr,
383 /*ImplicitParamTy=*/QualType(), nullptr);
384 }
385 return RValue::get(nullptr);
386 }
387
388 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
389 // 'CalleeDecl' instead.
390
391 CGCallee Callee;
392 if (UseVirtualCall) {
393 Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
394 } else {
395 if (SanOpts.has(SanitizerKind::CFINVCall) &&
396 MD->getParent()->isDynamicClass()) {
397 llvm::Value *VTable;
398 const CXXRecordDecl *RD;
399 std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
400 *this, This.getAddress(*this), CalleeDecl->getParent());
401 EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
402 }
403
404 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
405 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
406 else if (!DevirtualizedMethod)
407 Callee =
408 CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
409 else {
410 Callee =
411 CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
412 GlobalDecl(DevirtualizedMethod));
413 }
414 }
415
416 if (MD->isVirtual()) {
417 Address NewThisAddr =
418 CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
419 *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
420 This.setAddress(NewThisAddr);
421 }
422
423 return EmitCXXMemberOrOperatorCall(
424 CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
425 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
426}
427
428RValue
429CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
430 ReturnValueSlot ReturnValue) {
431 const BinaryOperator *BO =
432 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
433 const Expr *BaseExpr = BO->getLHS();
434 const Expr *MemFnExpr = BO->getRHS();
435
436 const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
437 const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
438 const auto *RD =
439 cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
440
441 // Emit the 'this' pointer.
442 Address This = Address::invalid();
443 if (BO->getOpcode() == BO_PtrMemI)
444 This = EmitPointerWithAlignment(BaseExpr);
445 else
446 This = EmitLValue(BaseExpr).getAddress(*this);
447
448 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
449 QualType(MPT->getClass(), 0));
450
451 // Get the member function pointer.
452 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
453
454 // Ask the ABI to load the callee. Note that This is modified.
455 llvm::Value *ThisPtrForCall = nullptr;
456 CGCallee Callee =
457 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
458 ThisPtrForCall, MemFnPtr, MPT);
459
460 CallArgList Args;
461
462 QualType ThisType =
463 getContext().getPointerType(getContext().getTagDeclType(RD));
464
465 // Push the this ptr.
466 Args.add(RValue::get(ThisPtrForCall), ThisType);
467
468 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
469
470 // And the rest of the call args
471 EmitCallArgs(Args, FPT, E->arguments());
472 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
473 /*PrefixSize=*/0),
474 Callee, ReturnValue, Args, nullptr, E->getExprLoc());
475}
476
477RValue
478CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
479 const CXXMethodDecl *MD,
480 ReturnValueSlot ReturnValue) {
481 assert(MD->isInstance() &&((MD->isInstance() && "Trying to emit a member call expr on a static method!"
) ? static_cast<void> (0) : __assert_fail ("MD->isInstance() && \"Trying to emit a member call expr on a static method!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 482, __PRETTY_FUNCTION__))
482 "Trying to emit a member call expr on a static method!")((MD->isInstance() && "Trying to emit a member call expr on a static method!"
) ? static_cast<void> (0) : __assert_fail ("MD->isInstance() && \"Trying to emit a member call expr on a static method!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 482, __PRETTY_FUNCTION__))
;
483 return EmitCXXMemberOrOperatorMemberCallExpr(
484 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
485 /*IsArrow=*/false, E->getArg(0));
486}
487
488RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
489 ReturnValueSlot ReturnValue) {
490 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
491}
492
493static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
494 Address DestPtr,
495 const CXXRecordDecl *Base) {
496 if (Base->isEmpty())
497 return;
498
499 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
500
501 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
502 CharUnits NVSize = Layout.getNonVirtualSize();
503
504 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
505 // present, they are initialized by the most derived class before calling the
506 // constructor.
507 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
508 Stores.emplace_back(CharUnits::Zero(), NVSize);
509
510 // Each store is split by the existence of a vbptr.
511 CharUnits VBPtrWidth = CGF.getPointerSize();
512 std::vector<CharUnits> VBPtrOffsets =
513 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
514 for (CharUnits VBPtrOffset : VBPtrOffsets) {
515 // Stop before we hit any virtual base pointers located in virtual bases.
516 if (VBPtrOffset >= NVSize)
517 break;
518 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
519 CharUnits LastStoreOffset = LastStore.first;
520 CharUnits LastStoreSize = LastStore.second;
521
522 CharUnits SplitBeforeOffset = LastStoreOffset;
523 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
524 assert(!SplitBeforeSize.isNegative() && "negative store size!")((!SplitBeforeSize.isNegative() && "negative store size!"
) ? static_cast<void> (0) : __assert_fail ("!SplitBeforeSize.isNegative() && \"negative store size!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 524, __PRETTY_FUNCTION__))
;
525 if (!SplitBeforeSize.isZero())
526 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
527
528 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
529 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
530 assert(!SplitAfterSize.isNegative() && "negative store size!")((!SplitAfterSize.isNegative() && "negative store size!"
) ? static_cast<void> (0) : __assert_fail ("!SplitAfterSize.isNegative() && \"negative store size!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 530, __PRETTY_FUNCTION__))
;
531 if (!SplitAfterSize.isZero())
532 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
533 }
534
535 // If the type contains a pointer to data member we can't memset it to zero.
536 // Instead, create a null constant and copy it to the destination.
537 // TODO: there are other patterns besides zero that we can usefully memset,
538 // like -1, which happens to be the pattern used by member-pointers.
539 // TODO: isZeroInitializable can be over-conservative in the case where a
540 // virtual base contains a member pointer.
541 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
542 if (!NullConstantForBase->isNullValue()) {
543 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
544 CGF.CGM.getModule(), NullConstantForBase->getType(),
545 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
546 NullConstantForBase, Twine());
547
548 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
549 DestPtr.getAlignment());
550 NullVariable->setAlignment(Align.getAsAlign());
551
552 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
553
554 // Get and call the appropriate llvm.memcpy overload.
555 for (std::pair<CharUnits, CharUnits> Store : Stores) {
556 CharUnits StoreOffset = Store.first;
557 CharUnits StoreSize = Store.second;
558 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
559 CGF.Builder.CreateMemCpy(
560 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
561 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
562 StoreSizeVal);
563 }
564
565 // Otherwise, just memset the whole thing to zero. This is legal
566 // because in LLVM, all default initializers (other than the ones we just
567 // handled above) are guaranteed to have a bit pattern of all zeros.
568 } else {
569 for (std::pair<CharUnits, CharUnits> Store : Stores) {
570 CharUnits StoreOffset = Store.first;
571 CharUnits StoreSize = Store.second;
572 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
573 CGF.Builder.CreateMemSet(
574 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
575 CGF.Builder.getInt8(0), StoreSizeVal);
576 }
577 }
578}
579
580void
581CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
582 AggValueSlot Dest) {
583 assert(!Dest.isIgnored() && "Must have a destination!")((!Dest.isIgnored() && "Must have a destination!") ? static_cast
<void> (0) : __assert_fail ("!Dest.isIgnored() && \"Must have a destination!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 583, __PRETTY_FUNCTION__))
;
584 const CXXConstructorDecl *CD = E->getConstructor();
585
586 // If we require zero initialization before (or instead of) calling the
587 // constructor, as can be the case with a non-user-provided default
588 // constructor, emit the zero initialization now, unless destination is
589 // already zeroed.
590 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
591 switch (E->getConstructionKind()) {
592 case CXXConstructExpr::CK_Delegating:
593 case CXXConstructExpr::CK_Complete:
594 EmitNullInitialization(Dest.getAddress(), E->getType());
595 break;
596 case CXXConstructExpr::CK_VirtualBase:
597 case CXXConstructExpr::CK_NonVirtualBase:
598 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
599 CD->getParent());
600 break;
601 }
602 }
603
604 // If this is a call to a trivial default constructor, do nothing.
605 if (CD->isTrivial() && CD->isDefaultConstructor())
606 return;
607
608 // Elide the constructor if we're constructing from a temporary.
609 // The temporary check is required because Sema sets this on NRVO
610 // returns.
611 if (getLangOpts().ElideConstructors && E->isElidable()) {
612 assert(getContext().hasSameUnqualifiedType(E->getType(),((getContext().hasSameUnqualifiedType(E->getType(), E->
getArg(0)->getType())) ? static_cast<void> (0) : __assert_fail
("getContext().hasSameUnqualifiedType(E->getType(), E->getArg(0)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 613, __PRETTY_FUNCTION__))
613 E->getArg(0)->getType()))((getContext().hasSameUnqualifiedType(E->getType(), E->
getArg(0)->getType())) ? static_cast<void> (0) : __assert_fail
("getContext().hasSameUnqualifiedType(E->getType(), E->getArg(0)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 613, __PRETTY_FUNCTION__))
;
614 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
615 EmitAggExpr(E->getArg(0), Dest);
616 return;
617 }
618 }
619
620 if (const ArrayType *arrayType
621 = getContext().getAsArrayType(E->getType())) {
622 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
623 Dest.isSanitizerChecked());
624 } else {
625 CXXCtorType Type = Ctor_Complete;
626 bool ForVirtualBase = false;
627 bool Delegating = false;
628
629 switch (E->getConstructionKind()) {
630 case CXXConstructExpr::CK_Delegating:
631 // We should be emitting a constructor; GlobalDecl will assert this
632 Type = CurGD.getCtorType();
633 Delegating = true;
634 break;
635
636 case CXXConstructExpr::CK_Complete:
637 Type = Ctor_Complete;
638 break;
639
640 case CXXConstructExpr::CK_VirtualBase:
641 ForVirtualBase = true;
642 LLVM_FALLTHROUGH[[gnu::fallthrough]];
643
644 case CXXConstructExpr::CK_NonVirtualBase:
645 Type = Ctor_Base;
646 }
647
648 // Call the constructor.
649 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
650 }
651}
652
653void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
654 const Expr *Exp) {
655 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
656 Exp = E->getSubExpr();
657 assert(isa<CXXConstructExpr>(Exp) &&((isa<CXXConstructExpr>(Exp) && "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConstructExpr>(Exp) && \"EmitSynthesizedCXXCopyCtor - unknown copy ctor expr\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 658, __PRETTY_FUNCTION__))
658 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr")((isa<CXXConstructExpr>(Exp) && "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConstructExpr>(Exp) && \"EmitSynthesizedCXXCopyCtor - unknown copy ctor expr\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 658, __PRETTY_FUNCTION__))
;
659 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
660 const CXXConstructorDecl *CD = E->getConstructor();
661 RunCleanupsScope Scope(*this);
662
663 // If we require zero initialization before (or instead of) calling the
664 // constructor, as can be the case with a non-user-provided default
665 // constructor, emit the zero initialization now.
666 // FIXME. Do I still need this for a copy ctor synthesis?
667 if (E->requiresZeroInitialization())
668 EmitNullInitialization(Dest, E->getType());
669
670 assert(!getContext().getAsConstantArrayType(E->getType())((!getContext().getAsConstantArrayType(E->getType()) &&
"EmitSynthesizedCXXCopyCtor - Copied-in Array") ? static_cast
<void> (0) : __assert_fail ("!getContext().getAsConstantArrayType(E->getType()) && \"EmitSynthesizedCXXCopyCtor - Copied-in Array\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 671, __PRETTY_FUNCTION__))
671 && "EmitSynthesizedCXXCopyCtor - Copied-in Array")((!getContext().getAsConstantArrayType(E->getType()) &&
"EmitSynthesizedCXXCopyCtor - Copied-in Array") ? static_cast
<void> (0) : __assert_fail ("!getContext().getAsConstantArrayType(E->getType()) && \"EmitSynthesizedCXXCopyCtor - Copied-in Array\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 671, __PRETTY_FUNCTION__))
;
672 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
673}
674
675static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
676 const CXXNewExpr *E) {
677 if (!E->isArray())
678 return CharUnits::Zero();
679
680 // No cookie is required if the operator new[] being used is the
681 // reserved placement operator new[].
682 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
683 return CharUnits::Zero();
684
685 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
686}
687
688static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
689 const CXXNewExpr *e,
690 unsigned minElements,
691 llvm::Value *&numElements,
692 llvm::Value *&sizeWithoutCookie) {
693 QualType type = e->getAllocatedType();
694
695 if (!e->isArray()) {
696 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
697 sizeWithoutCookie
698 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
699 return sizeWithoutCookie;
700 }
701
702 // The width of size_t.
703 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
704
705 // Figure out the cookie size.
706 llvm::APInt cookieSize(sizeWidth,
707 CalculateCookiePadding(CGF, e).getQuantity());
708
709 // Emit the array size expression.
710 // We multiply the size of all dimensions for NumElements.
711 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
712 numElements =
713 ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
714 if (!numElements)
715 numElements = CGF.EmitScalarExpr(*e->getArraySize());
716 assert(isa<llvm::IntegerType>(numElements->getType()))((isa<llvm::IntegerType>(numElements->getType())) ? static_cast
<void> (0) : __assert_fail ("isa<llvm::IntegerType>(numElements->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 716, __PRETTY_FUNCTION__))
;
717
718 // The number of elements can be have an arbitrary integer type;
719 // essentially, we need to multiply it by a constant factor, add a
720 // cookie size, and verify that the result is representable as a
721 // size_t. That's just a gloss, though, and it's wrong in one
722 // important way: if the count is negative, it's an error even if
723 // the cookie size would bring the total size >= 0.
724 bool isSigned
725 = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
726 llvm::IntegerType *numElementsType
727 = cast<llvm::IntegerType>(numElements->getType());
728 unsigned numElementsWidth = numElementsType->getBitWidth();
729
730 // Compute the constant factor.
731 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
732 while (const ConstantArrayType *CAT
733 = CGF.getContext().getAsConstantArrayType(type)) {
734 type = CAT->getElementType();
735 arraySizeMultiplier *= CAT->getSize();
736 }
737
738 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
739 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
740 typeSizeMultiplier *= arraySizeMultiplier;
741
742 // This will be a size_t.
743 llvm::Value *size;
744
745 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
746 // Don't bloat the -O0 code.
747 if (llvm::ConstantInt *numElementsC =
748 dyn_cast<llvm::ConstantInt>(numElements)) {
749 const llvm::APInt &count = numElementsC->getValue();
750
751 bool hasAnyOverflow = false;
752
753 // If 'count' was a negative number, it's an overflow.
754 if (isSigned && count.isNegative())
755 hasAnyOverflow = true;
756
757 // We want to do all this arithmetic in size_t. If numElements is
758 // wider than that, check whether it's already too big, and if so,
759 // overflow.
760 else if (numElementsWidth > sizeWidth &&
761 numElementsWidth - sizeWidth > count.countLeadingZeros())
762 hasAnyOverflow = true;
763
764 // Okay, compute a count at the right width.
765 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
766
767 // If there is a brace-initializer, we cannot allocate fewer elements than
768 // there are initializers. If we do, that's treated like an overflow.
769 if (adjustedCount.ult(minElements))
770 hasAnyOverflow = true;
771
772 // Scale numElements by that. This might overflow, but we don't
773 // care because it only overflows if allocationSize does, too, and
774 // if that overflows then we shouldn't use this.
775 numElements = llvm::ConstantInt::get(CGF.SizeTy,
776 adjustedCount * arraySizeMultiplier);
777
778 // Compute the size before cookie, and track whether it overflowed.
779 bool overflow;
780 llvm::APInt allocationSize
781 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
782 hasAnyOverflow |= overflow;
783
784 // Add in the cookie, and check whether it's overflowed.
785 if (cookieSize != 0) {
786 // Save the current size without a cookie. This shouldn't be
787 // used if there was overflow.
788 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
789
790 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
791 hasAnyOverflow |= overflow;
792 }
793
794 // On overflow, produce a -1 so operator new will fail.
795 if (hasAnyOverflow) {
796 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
797 } else {
798 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
799 }
800
801 // Otherwise, we might need to use the overflow intrinsics.
802 } else {
803 // There are up to five conditions we need to test for:
804 // 1) if isSigned, we need to check whether numElements is negative;
805 // 2) if numElementsWidth > sizeWidth, we need to check whether
806 // numElements is larger than something representable in size_t;
807 // 3) if minElements > 0, we need to check whether numElements is smaller
808 // than that.
809 // 4) we need to compute
810 // sizeWithoutCookie := numElements * typeSizeMultiplier
811 // and check whether it overflows; and
812 // 5) if we need a cookie, we need to compute
813 // size := sizeWithoutCookie + cookieSize
814 // and check whether it overflows.
815
816 llvm::Value *hasOverflow = nullptr;
817
818 // If numElementsWidth > sizeWidth, then one way or another, we're
819 // going to have to do a comparison for (2), and this happens to
820 // take care of (1), too.
821 if (numElementsWidth > sizeWidth) {
822 llvm::APInt threshold(numElementsWidth, 1);
823 threshold <<= sizeWidth;
824
825 llvm::Value *thresholdV
826 = llvm::ConstantInt::get(numElementsType, threshold);
827
828 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
829 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
830
831 // Otherwise, if we're signed, we want to sext up to size_t.
832 } else if (isSigned) {
833 if (numElementsWidth < sizeWidth)
834 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
835
836 // If there's a non-1 type size multiplier, then we can do the
837 // signedness check at the same time as we do the multiply
838 // because a negative number times anything will cause an
839 // unsigned overflow. Otherwise, we have to do it here. But at least
840 // in this case, we can subsume the >= minElements check.
841 if (typeSizeMultiplier == 1)
842 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
843 llvm::ConstantInt::get(CGF.SizeTy, minElements));
844
845 // Otherwise, zext up to size_t if necessary.
846 } else if (numElementsWidth < sizeWidth) {
847 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
848 }
849
850 assert(numElements->getType() == CGF.SizeTy)((numElements->getType() == CGF.SizeTy) ? static_cast<void
> (0) : __assert_fail ("numElements->getType() == CGF.SizeTy"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 850, __PRETTY_FUNCTION__))
;
851
852 if (minElements) {
853 // Don't allow allocation of fewer elements than we have initializers.
854 if (!hasOverflow) {
855 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
856 llvm::ConstantInt::get(CGF.SizeTy, minElements));
857 } else if (numElementsWidth > sizeWidth) {
858 // The other existing overflow subsumes this check.
859 // We do an unsigned comparison, since any signed value < -1 is
860 // taken care of either above or below.
861 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
862 CGF.Builder.CreateICmpULT(numElements,
863 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
864 }
865 }
866
867 size = numElements;
868
869 // Multiply by the type size if necessary. This multiplier
870 // includes all the factors for nested arrays.
871 //
872 // This step also causes numElements to be scaled up by the
873 // nested-array factor if necessary. Overflow on this computation
874 // can be ignored because the result shouldn't be used if
875 // allocation fails.
876 if (typeSizeMultiplier != 1) {
877 llvm::Function *umul_with_overflow
878 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
879
880 llvm::Value *tsmV =
881 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
882 llvm::Value *result =
883 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
884
885 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
886 if (hasOverflow)
887 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
888 else
889 hasOverflow = overflowed;
890
891 size = CGF.Builder.CreateExtractValue(result, 0);
892
893 // Also scale up numElements by the array size multiplier.
894 if (arraySizeMultiplier != 1) {
895 // If the base element type size is 1, then we can re-use the
896 // multiply we just did.
897 if (typeSize.isOne()) {
898 assert(arraySizeMultiplier == typeSizeMultiplier)((arraySizeMultiplier == typeSizeMultiplier) ? static_cast<
void> (0) : __assert_fail ("arraySizeMultiplier == typeSizeMultiplier"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 898, __PRETTY_FUNCTION__))
;
899 numElements = size;
900
901 // Otherwise we need a separate multiply.
902 } else {
903 llvm::Value *asmV =
904 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
905 numElements = CGF.Builder.CreateMul(numElements, asmV);
906 }
907 }
908 } else {
909 // numElements doesn't need to be scaled.
910 assert(arraySizeMultiplier == 1)((arraySizeMultiplier == 1) ? static_cast<void> (0) : __assert_fail
("arraySizeMultiplier == 1", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 910, __PRETTY_FUNCTION__))
;
911 }
912
913 // Add in the cookie size if necessary.
914 if (cookieSize != 0) {
915 sizeWithoutCookie = size;
916
917 llvm::Function *uadd_with_overflow
918 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
919
920 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
921 llvm::Value *result =
922 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
923
924 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
925 if (hasOverflow)
926 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
927 else
928 hasOverflow = overflowed;
929
930 size = CGF.Builder.CreateExtractValue(result, 0);
931 }
932
933 // If we had any possibility of dynamic overflow, make a select to
934 // overwrite 'size' with an all-ones value, which should cause
935 // operator new to throw.
936 if (hasOverflow)
937 size = CGF.Builder.CreateSelect(hasOverflow,
938 llvm::Constant::getAllOnesValue(CGF.SizeTy),
939 size);
940 }
941
942 if (cookieSize == 0)
943 sizeWithoutCookie = size;
944 else
945 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?")((sizeWithoutCookie && "didn't set sizeWithoutCookie?"
) ? static_cast<void> (0) : __assert_fail ("sizeWithoutCookie && \"didn't set sizeWithoutCookie?\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 945, __PRETTY_FUNCTION__))
;
946
947 return size;
948}
949
950static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
951 QualType AllocType, Address NewPtr,
952 AggValueSlot::Overlap_t MayOverlap) {
953 // FIXME: Refactor with EmitExprAsInit.
954 switch (CGF.getEvaluationKind(AllocType)) {
955 case TEK_Scalar:
956 CGF.EmitScalarInit(Init, nullptr,
957 CGF.MakeAddrLValue(NewPtr, AllocType), false);
958 return;
959 case TEK_Complex:
960 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
961 /*isInit*/ true);
962 return;
963 case TEK_Aggregate: {
964 AggValueSlot Slot
965 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
966 AggValueSlot::IsDestructed,
967 AggValueSlot::DoesNotNeedGCBarriers,
968 AggValueSlot::IsNotAliased,
969 MayOverlap, AggValueSlot::IsNotZeroed,
970 AggValueSlot::IsSanitizerChecked);
971 CGF.EmitAggExpr(Init, Slot);
972 return;
973 }
974 }
975 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 975)
;
976}
977
978void CodeGenFunction::EmitNewArrayInitializer(
979 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
980 Address BeginPtr, llvm::Value *NumElements,
981 llvm::Value *AllocSizeWithoutCookie) {
982 // If we have a type with trivial initialization and no initializer,
983 // there's nothing to do.
984 if (!E->hasInitializer())
985 return;
986
987 Address CurPtr = BeginPtr;
988
989 unsigned InitListElements = 0;
990
991 const Expr *Init = E->getInitializer();
992 Address EndOfInit = Address::invalid();
993 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
994 EHScopeStack::stable_iterator Cleanup;
995 llvm::Instruction *CleanupDominator = nullptr;
996
997 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
998 CharUnits ElementAlign =
999 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1000
1001 // Attempt to perform zero-initialization using memset.
1002 auto TryMemsetInitialization = [&]() -> bool {
1003 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1004 // we can initialize with a memset to -1.
1005 if (!CGM.getTypes().isZeroInitializable(ElementType))
1006 return false;
1007
1008 // Optimization: since zero initialization will just set the memory
1009 // to all zeroes, generate a single memset to do it in one shot.
1010
1011 // Subtract out the size of any elements we've already initialized.
1012 auto *RemainingSize = AllocSizeWithoutCookie;
1013 if (InitListElements) {
1014 // We know this can't overflow; we check this when doing the allocation.
1015 auto *InitializedSize = llvm::ConstantInt::get(
1016 RemainingSize->getType(),
1017 getContext().getTypeSizeInChars(ElementType).getQuantity() *
1018 InitListElements);
1019 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1020 }
1021
1022 // Create the memset.
1023 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1024 return true;
1025 };
1026
1027 // If the initializer is an initializer list, first do the explicit elements.
1028 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1029 // Initializing from a (braced) string literal is a special case; the init
1030 // list element does not initialize a (single) array element.
1031 if (ILE->isStringLiteralInit()) {
1032 // Initialize the initial portion of length equal to that of the string
1033 // literal. The allocation must be for at least this much; we emitted a
1034 // check for that earlier.
1035 AggValueSlot Slot =
1036 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1037 AggValueSlot::IsDestructed,
1038 AggValueSlot::DoesNotNeedGCBarriers,
1039 AggValueSlot::IsNotAliased,
1040 AggValueSlot::DoesNotOverlap,
1041 AggValueSlot::IsNotZeroed,
1042 AggValueSlot::IsSanitizerChecked);
1043 EmitAggExpr(ILE->getInit(0), Slot);
1044
1045 // Move past these elements.
1046 InitListElements =
1047 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1048 ->getSize().getZExtValue();
1049 CurPtr =
1050 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1051 Builder.getSize(InitListElements),
1052 "string.init.end"),
1053 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1054 ElementSize));
1055
1056 // Zero out the rest, if any remain.
1057 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1058 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1059 bool OK = TryMemsetInitialization();
1060 (void)OK;
1061 assert(OK && "couldn't memset character type?")((OK && "couldn't memset character type?") ? static_cast
<void> (0) : __assert_fail ("OK && \"couldn't memset character type?\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1061, __PRETTY_FUNCTION__))
;
1062 }
1063 return;
1064 }
1065
1066 InitListElements = ILE->getNumInits();
1067
1068 // If this is a multi-dimensional array new, we will initialize multiple
1069 // elements with each init list element.
1070 QualType AllocType = E->getAllocatedType();
1071 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1072 AllocType->getAsArrayTypeUnsafe())) {
1073 ElementTy = ConvertTypeForMem(AllocType);
1074 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1075 InitListElements *= getContext().getConstantArrayElementCount(CAT);
1076 }
1077
1078 // Enter a partial-destruction Cleanup if necessary.
1079 if (needsEHCleanup(DtorKind)) {
1080 // In principle we could tell the Cleanup where we are more
1081 // directly, but the control flow can get so varied here that it
1082 // would actually be quite complex. Therefore we go through an
1083 // alloca.
1084 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1085 "array.init.end");
1086 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1087 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1088 ElementType, ElementAlign,
1089 getDestroyer(DtorKind));
1090 Cleanup = EHStack.stable_begin();
1091 }
1092
1093 CharUnits StartAlign = CurPtr.getAlignment();
1094 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1095 // Tell the cleanup that it needs to destroy up to this
1096 // element. TODO: some of these stores can be trivially
1097 // observed to be unnecessary.
1098 if (EndOfInit.isValid()) {
1099 auto FinishedPtr =
1100 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1101 Builder.CreateStore(FinishedPtr, EndOfInit);
1102 }
1103 // FIXME: If the last initializer is an incomplete initializer list for
1104 // an array, and we have an array filler, we can fold together the two
1105 // initialization loops.
1106 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1107 ILE->getInit(i)->getType(), CurPtr,
1108 AggValueSlot::DoesNotOverlap);
1109 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1110 Builder.getSize(1),
1111 "array.exp.next"),
1112 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1113 }
1114
1115 // The remaining elements are filled with the array filler expression.
1116 Init = ILE->getArrayFiller();
1117
1118 // Extract the initializer for the individual array elements by pulling
1119 // out the array filler from all the nested initializer lists. This avoids
1120 // generating a nested loop for the initialization.
1121 while (Init && Init->getType()->isConstantArrayType()) {
1122 auto *SubILE = dyn_cast<InitListExpr>(Init);
1123 if (!SubILE)
1124 break;
1125 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?")((SubILE->getNumInits() == 0 && "explicit inits in array filler?"
) ? static_cast<void> (0) : __assert_fail ("SubILE->getNumInits() == 0 && \"explicit inits in array filler?\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1125, __PRETTY_FUNCTION__))
;
1126 Init = SubILE->getArrayFiller();
1127 }
1128
1129 // Switch back to initializing one base element at a time.
1130 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1131 }
1132
1133 // If all elements have already been initialized, skip any further
1134 // initialization.
1135 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1136 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1137 // If there was a Cleanup, deactivate it.
1138 if (CleanupDominator)
1139 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1140 return;
1141 }
1142
1143 assert(Init && "have trailing elements to initialize but no initializer")((Init && "have trailing elements to initialize but no initializer"
) ? static_cast<void> (0) : __assert_fail ("Init && \"have trailing elements to initialize but no initializer\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1143, __PRETTY_FUNCTION__))
;
1144
1145 // If this is a constructor call, try to optimize it out, and failing that
1146 // emit a single loop to initialize all remaining elements.
1147 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1148 CXXConstructorDecl *Ctor = CCE->getConstructor();
1149 if (Ctor->isTrivial()) {
1150 // If new expression did not specify value-initialization, then there
1151 // is no initialization.
1152 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1153 return;
1154
1155 if (TryMemsetInitialization())
1156 return;
1157 }
1158
1159 // Store the new Cleanup position for irregular Cleanups.
1160 //
1161 // FIXME: Share this cleanup with the constructor call emission rather than
1162 // having it create a cleanup of its own.
1163 if (EndOfInit.isValid())
1164 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1165
1166 // Emit a constructor call loop to initialize the remaining elements.
1167 if (InitListElements)
1168 NumElements = Builder.CreateSub(
1169 NumElements,
1170 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1171 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1172 /*NewPointerIsChecked*/true,
1173 CCE->requiresZeroInitialization());
1174 return;
1175 }
1176
1177 // If this is value-initialization, we can usually use memset.
1178 ImplicitValueInitExpr IVIE(ElementType);
1179 if (isa<ImplicitValueInitExpr>(Init)) {
1180 if (TryMemsetInitialization())
1181 return;
1182
1183 // Switch to an ImplicitValueInitExpr for the element type. This handles
1184 // only one case: multidimensional array new of pointers to members. In
1185 // all other cases, we already have an initializer for the array element.
1186 Init = &IVIE;
1187 }
1188
1189 // At this point we should have found an initializer for the individual
1190 // elements of the array.
1191 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&((getContext().hasSameUnqualifiedType(ElementType, Init->getType
()) && "got wrong type of element to initialize") ? static_cast
<void> (0) : __assert_fail ("getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && \"got wrong type of element to initialize\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1192, __PRETTY_FUNCTION__))
1192 "got wrong type of element to initialize")((getContext().hasSameUnqualifiedType(ElementType, Init->getType
()) && "got wrong type of element to initialize") ? static_cast
<void> (0) : __assert_fail ("getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && \"got wrong type of element to initialize\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1192, __PRETTY_FUNCTION__))
;
1193
1194 // If we have an empty initializer list, we can usually use memset.
1195 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1196 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1197 return;
1198
1199 // If we have a struct whose every field is value-initialized, we can
1200 // usually use memset.
1201 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1202 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1203 if (RType->getDecl()->isStruct()) {
1204 unsigned NumElements = 0;
1205 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1206 NumElements = CXXRD->getNumBases();
1207 for (auto *Field : RType->getDecl()->fields())
1208 if (!Field->isUnnamedBitfield())
1209 ++NumElements;
1210 // FIXME: Recurse into nested InitListExprs.
1211 if (ILE->getNumInits() == NumElements)
1212 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1213 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1214 --NumElements;
1215 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1216 return;
1217 }
1218 }
1219 }
1220
1221 // Create the loop blocks.
1222 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1223 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1224 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1225
1226 // Find the end of the array, hoisted out of the loop.
1227 llvm::Value *EndPtr =
1228 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1229
1230 // If the number of elements isn't constant, we have to now check if there is
1231 // anything left to initialize.
1232 if (!ConstNum) {
1233 llvm::Value *IsEmpty =
1234 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1235 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1236 }
1237
1238 // Enter the loop.
1239 EmitBlock(LoopBB);
1240
1241 // Set up the current-element phi.
1242 llvm::PHINode *CurPtrPhi =
1243 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1244 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1245
1246 CurPtr = Address(CurPtrPhi, ElementAlign);
1247
1248 // Store the new Cleanup position for irregular Cleanups.
1249 if (EndOfInit.isValid())
1250 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1251
1252 // Enter a partial-destruction Cleanup if necessary.
1253 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1254 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1255 ElementType, ElementAlign,
1256 getDestroyer(DtorKind));
1257 Cleanup = EHStack.stable_begin();
1258 CleanupDominator = Builder.CreateUnreachable();
1259 }
1260
1261 // Emit the initializer into this element.
1262 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1263 AggValueSlot::DoesNotOverlap);
1264
1265 // Leave the Cleanup if we entered one.
1266 if (CleanupDominator) {
1267 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1268 CleanupDominator->eraseFromParent();
1269 }
1270
1271 // Advance to the next element by adjusting the pointer type as necessary.
1272 llvm::Value *NextPtr =
1273 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1274 "array.next");
1275
1276 // Check whether we've gotten to the end of the array and, if so,
1277 // exit the loop.
1278 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1279 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1280 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1281
1282 EmitBlock(ContBB);
1283}
1284
1285static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1286 QualType ElementType, llvm::Type *ElementTy,
1287 Address NewPtr, llvm::Value *NumElements,
1288 llvm::Value *AllocSizeWithoutCookie) {
1289 ApplyDebugLocation DL(CGF, E);
1290 if (E->isArray())
1291 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1292 AllocSizeWithoutCookie);
1293 else if (const Expr *Init = E->getInitializer())
1294 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1295 AggValueSlot::DoesNotOverlap);
1296}
1297
1298/// Emit a call to an operator new or operator delete function, as implicitly
1299/// created by new-expressions and delete-expressions.
1300static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1301 const FunctionDecl *CalleeDecl,
1302 const FunctionProtoType *CalleeType,
1303 const CallArgList &Args) {
1304 llvm::CallBase *CallOrInvoke;
1305 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1306 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1307 RValue RV =
1308 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1309 Args, CalleeType, /*ChainCall=*/false),
1310 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1311
1312 /// C++1y [expr.new]p10:
1313 /// [In a new-expression,] an implementation is allowed to omit a call
1314 /// to a replaceable global allocation function.
1315 ///
1316 /// We model such elidable calls with the 'builtin' attribute.
1317 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1318 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1319 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1320 CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex,
1321 llvm::Attribute::Builtin);
1322 }
1323
1324 return RV;
1325}
1326
1327RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1328 const CallExpr *TheCall,
1329 bool IsDelete) {
1330 CallArgList Args;
1331 EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments());
1332 // Find the allocation or deallocation function that we're calling.
1333 ASTContext &Ctx = getContext();
1334 DeclarationName Name = Ctx.DeclarationNames
1335 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1336
1337 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1338 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1339 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1340 return EmitNewDeleteCall(*this, FD, Type, Args);
1341 llvm_unreachable("predeclared global operator new/delete is missing")::llvm::llvm_unreachable_internal("predeclared global operator new/delete is missing"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1341)
;
1342}
1343
1344namespace {
1345/// The parameters to pass to a usual operator delete.
1346struct UsualDeleteParams {
1347 bool DestroyingDelete = false;
1348 bool Size = false;
1349 bool Alignment = false;
1350};
1351}
1352
1353static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1354 UsualDeleteParams Params;
1355
1356 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1357 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1358
1359 // The first argument is always a void*.
1360 ++AI;
1361
1362 // The next parameter may be a std::destroying_delete_t.
1363 if (FD->isDestroyingOperatorDelete()) {
1364 Params.DestroyingDelete = true;
1365 assert(AI != AE)((AI != AE) ? static_cast<void> (0) : __assert_fail ("AI != AE"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1365, __PRETTY_FUNCTION__))
;
1366 ++AI;
1367 }
1368
1369 // Figure out what other parameters we should be implicitly passing.
1370 if (AI != AE && (*AI)->isIntegerType()) {
1371 Params.Size = true;
1372 ++AI;
1373 }
1374
1375 if (AI != AE && (*AI)->isAlignValT()) {
1376 Params.Alignment = true;
1377 ++AI;
1378 }
1379
1380 assert(AI == AE && "unexpected usual deallocation function parameter")((AI == AE && "unexpected usual deallocation function parameter"
) ? static_cast<void> (0) : __assert_fail ("AI == AE && \"unexpected usual deallocation function parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1380, __PRETTY_FUNCTION__))
;
1381 return Params;
1382}
1383
1384namespace {
1385 /// A cleanup to call the given 'operator delete' function upon abnormal
1386 /// exit from a new expression. Templated on a traits type that deals with
1387 /// ensuring that the arguments dominate the cleanup if necessary.
1388 template<typename Traits>
1389 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1390 /// Type used to hold llvm::Value*s.
1391 typedef typename Traits::ValueTy ValueTy;
1392 /// Type used to hold RValues.
1393 typedef typename Traits::RValueTy RValueTy;
1394 struct PlacementArg {
1395 RValueTy ArgValue;
1396 QualType ArgType;
1397 };
1398
1399 unsigned NumPlacementArgs : 31;
1400 unsigned PassAlignmentToPlacementDelete : 1;
1401 const FunctionDecl *OperatorDelete;
1402 ValueTy Ptr;
1403 ValueTy AllocSize;
1404 CharUnits AllocAlign;
1405
1406 PlacementArg *getPlacementArgs() {
1407 return reinterpret_cast<PlacementArg *>(this + 1);
1408 }
1409
1410 public:
1411 static size_t getExtraSize(size_t NumPlacementArgs) {
1412 return NumPlacementArgs * sizeof(PlacementArg);
1413 }
1414
1415 CallDeleteDuringNew(size_t NumPlacementArgs,
1416 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1417 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1418 CharUnits AllocAlign)
1419 : NumPlacementArgs(NumPlacementArgs),
1420 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1421 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1422 AllocAlign(AllocAlign) {}
1423
1424 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1425 assert(I < NumPlacementArgs && "index out of range")((I < NumPlacementArgs && "index out of range") ? static_cast
<void> (0) : __assert_fail ("I < NumPlacementArgs && \"index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1425, __PRETTY_FUNCTION__))
;
1426 getPlacementArgs()[I] = {Arg, Type};
1427 }
1428
1429 void Emit(CodeGenFunction &CGF, Flags flags) override {
1430 const FunctionProtoType *FPT =
1431 OperatorDelete->getType()->getAs<FunctionProtoType>();
1432 CallArgList DeleteArgs;
1433
1434 // The first argument is always a void* (or C* for a destroying operator
1435 // delete for class type C).
1436 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1437
1438 // Figure out what other parameters we should be implicitly passing.
1439 UsualDeleteParams Params;
1440 if (NumPlacementArgs) {
1441 // A placement deallocation function is implicitly passed an alignment
1442 // if the placement allocation function was, but is never passed a size.
1443 Params.Alignment = PassAlignmentToPlacementDelete;
1444 } else {
1445 // For a non-placement new-expression, 'operator delete' can take a
1446 // size and/or an alignment if it has the right parameters.
1447 Params = getUsualDeleteParams(OperatorDelete);
1448 }
1449
1450 assert(!Params.DestroyingDelete &&((!Params.DestroyingDelete && "should not call destroying delete in a new-expression"
) ? static_cast<void> (0) : __assert_fail ("!Params.DestroyingDelete && \"should not call destroying delete in a new-expression\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1451, __PRETTY_FUNCTION__))
1451 "should not call destroying delete in a new-expression")((!Params.DestroyingDelete && "should not call destroying delete in a new-expression"
) ? static_cast<void> (0) : __assert_fail ("!Params.DestroyingDelete && \"should not call destroying delete in a new-expression\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1451, __PRETTY_FUNCTION__))
;
1452
1453 // The second argument can be a std::size_t (for non-placement delete).
1454 if (Params.Size)
1455 DeleteArgs.add(Traits::get(CGF, AllocSize),
1456 CGF.getContext().getSizeType());
1457
1458 // The next (second or third) argument can be a std::align_val_t, which
1459 // is an enum whose underlying type is std::size_t.
1460 // FIXME: Use the right type as the parameter type. Note that in a call
1461 // to operator delete(size_t, ...), we may not have it available.
1462 if (Params.Alignment)
1463 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1464 CGF.SizeTy, AllocAlign.getQuantity())),
1465 CGF.getContext().getSizeType());
1466
1467 // Pass the rest of the arguments, which must match exactly.
1468 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1469 auto Arg = getPlacementArgs()[I];
1470 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1471 }
1472
1473 // Call 'operator delete'.
1474 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1475 }
1476 };
1477}
1478
1479/// Enter a cleanup to call 'operator delete' if the initializer in a
1480/// new-expression throws.
1481static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1482 const CXXNewExpr *E,
1483 Address NewPtr,
1484 llvm::Value *AllocSize,
1485 CharUnits AllocAlign,
1486 const CallArgList &NewArgs) {
1487 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1488
1489 // If we're not inside a conditional branch, then the cleanup will
1490 // dominate and we can do the easier (and more efficient) thing.
1491 if (!CGF.isInConditionalBranch()) {
1492 struct DirectCleanupTraits {
1493 typedef llvm::Value *ValueTy;
1494 typedef RValue RValueTy;
1495 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1496 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1497 };
1498
1499 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1500
1501 DirectCleanup *Cleanup = CGF.EHStack
1502 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1503 E->getNumPlacementArgs(),
1504 E->getOperatorDelete(),
1505 NewPtr.getPointer(),
1506 AllocSize,
1507 E->passAlignment(),
1508 AllocAlign);
1509 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1510 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1511 Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1512 }
1513
1514 return;
1515 }
1516
1517 // Otherwise, we need to save all this stuff.
1518 DominatingValue<RValue>::saved_type SavedNewPtr =
1519 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1520 DominatingValue<RValue>::saved_type SavedAllocSize =
1521 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1522
1523 struct ConditionalCleanupTraits {
1524 typedef DominatingValue<RValue>::saved_type ValueTy;
1525 typedef DominatingValue<RValue>::saved_type RValueTy;
1526 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1527 return V.restore(CGF);
1528 }
1529 };
1530 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1531
1532 ConditionalCleanup *Cleanup = CGF.EHStack
1533 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1534 E->getNumPlacementArgs(),
1535 E->getOperatorDelete(),
1536 SavedNewPtr,
1537 SavedAllocSize,
1538 E->passAlignment(),
1539 AllocAlign);
1540 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1541 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1542 Cleanup->setPlacementArg(
1543 I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1544 }
1545
1546 CGF.initFullExprCleanup();
1547}
1548
1549llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1550 // The element type being allocated.
1551 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1552
1553 // 1. Build a call to the allocation function.
1554 FunctionDecl *allocator = E->getOperatorNew();
1555
1556 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1557 unsigned minElements = 0;
1558 if (E->isArray() && E->hasInitializer()) {
1559 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1560 if (ILE && ILE->isStringLiteralInit())
1561 minElements =
1562 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1563 ->getSize().getZExtValue();
1564 else if (ILE)
1565 minElements = ILE->getNumInits();
1566 }
1567
1568 llvm::Value *numElements = nullptr;
1569 llvm::Value *allocSizeWithoutCookie = nullptr;
1570 llvm::Value *allocSize =
1571 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1572 allocSizeWithoutCookie);
1573 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1574
1575 // Emit the allocation call. If the allocator is a global placement
1576 // operator, just "inline" it directly.
1577 Address allocation = Address::invalid();
1578 CallArgList allocatorArgs;
1579 if (allocator->isReservedGlobalPlacementOperator()) {
1580 assert(E->getNumPlacementArgs() == 1)((E->getNumPlacementArgs() == 1) ? static_cast<void>
(0) : __assert_fail ("E->getNumPlacementArgs() == 1", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1580, __PRETTY_FUNCTION__))
;
1581 const Expr *arg = *E->placement_arguments().begin();
1582
1583 LValueBaseInfo BaseInfo;
1584 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1585
1586 // The pointer expression will, in many cases, be an opaque void*.
1587 // In these cases, discard the computed alignment and use the
1588 // formal alignment of the allocated type.
1589 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1590 allocation = Address(allocation.getPointer(), allocAlign);
1591
1592 // Set up allocatorArgs for the call to operator delete if it's not
1593 // the reserved global operator.
1594 if (E->getOperatorDelete() &&
1595 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1596 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1597 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1598 }
1599
1600 } else {
1601 const FunctionProtoType *allocatorType =
1602 allocator->getType()->castAs<FunctionProtoType>();
1603 unsigned ParamsToSkip = 0;
1604
1605 // The allocation size is the first argument.
1606 QualType sizeType = getContext().getSizeType();
1607 allocatorArgs.add(RValue::get(allocSize), sizeType);
1608 ++ParamsToSkip;
1609
1610 if (allocSize != allocSizeWithoutCookie) {
1611 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1612 allocAlign = std::max(allocAlign, cookieAlign);
1613 }
1614
1615 // The allocation alignment may be passed as the second argument.
1616 if (E->passAlignment()) {
1617 QualType AlignValT = sizeType;
1618 if (allocatorType->getNumParams() > 1) {
1619 AlignValT = allocatorType->getParamType(1);
1620 assert(getContext().hasSameUnqualifiedType(((getContext().hasSameUnqualifiedType( AlignValT->castAs<
EnumType>()->getDecl()->getIntegerType(), sizeType) &&
"wrong type for alignment parameter") ? static_cast<void>
(0) : __assert_fail ("getContext().hasSameUnqualifiedType( AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), sizeType) && \"wrong type for alignment parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1623, __PRETTY_FUNCTION__))
1621 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),((getContext().hasSameUnqualifiedType( AlignValT->castAs<
EnumType>()->getDecl()->getIntegerType(), sizeType) &&
"wrong type for alignment parameter") ? static_cast<void>
(0) : __assert_fail ("getContext().hasSameUnqualifiedType( AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), sizeType) && \"wrong type for alignment parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1623, __PRETTY_FUNCTION__))
1622 sizeType) &&((getContext().hasSameUnqualifiedType( AlignValT->castAs<
EnumType>()->getDecl()->getIntegerType(), sizeType) &&
"wrong type for alignment parameter") ? static_cast<void>
(0) : __assert_fail ("getContext().hasSameUnqualifiedType( AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), sizeType) && \"wrong type for alignment parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1623, __PRETTY_FUNCTION__))
1623 "wrong type for alignment parameter")((getContext().hasSameUnqualifiedType( AlignValT->castAs<
EnumType>()->getDecl()->getIntegerType(), sizeType) &&
"wrong type for alignment parameter") ? static_cast<void>
(0) : __assert_fail ("getContext().hasSameUnqualifiedType( AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), sizeType) && \"wrong type for alignment parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1623, __PRETTY_FUNCTION__))
;
1624 ++ParamsToSkip;
1625 } else {
1626 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1627 assert(allocator->isVariadic() && "can't pass alignment to allocator")((allocator->isVariadic() && "can't pass alignment to allocator"
) ? static_cast<void> (0) : __assert_fail ("allocator->isVariadic() && \"can't pass alignment to allocator\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1627, __PRETTY_FUNCTION__))
;
1628 }
1629 allocatorArgs.add(
1630 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1631 AlignValT);
1632 }
1633
1634 // FIXME: Why do we not pass a CalleeDecl here?
1635 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1636 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1637
1638 RValue RV =
1639 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1640
1641 // If this was a call to a global replaceable allocation function that does
1642 // not take an alignment argument, the allocator is known to produce
1643 // storage that's suitably aligned for any object that fits, up to a known
1644 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1645 CharUnits allocationAlign = allocAlign;
1646 if (!E->passAlignment() &&
1647 allocator->isReplaceableGlobalAllocationFunction()) {
1648 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1649 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1650 allocationAlign = std::max(
1651 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1652 }
1653
1654 allocation = Address(RV.getScalarVal(), allocationAlign);
1655 }
1656
1657 // Emit a null check on the allocation result if the allocation
1658 // function is allowed to return null (because it has a non-throwing
1659 // exception spec or is the reserved placement new) and we have an
1660 // interesting initializer will be running sanitizers on the initialization.
1661 bool nullCheck = E->shouldNullCheckAllocation() &&
1662 (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1663 sanitizePerformTypeCheck());
1664
1665 llvm::BasicBlock *nullCheckBB = nullptr;
1666 llvm::BasicBlock *contBB = nullptr;
1667
1668 // The null-check means that the initializer is conditionally
1669 // evaluated.
1670 ConditionalEvaluation conditional(*this);
1671
1672 if (nullCheck) {
1673 conditional.begin(*this);
1674
1675 nullCheckBB = Builder.GetInsertBlock();
1676 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1677 contBB = createBasicBlock("new.cont");
1678
1679 llvm::Value *isNull =
1680 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1681 Builder.CreateCondBr(isNull, contBB, notNullBB);
1682 EmitBlock(notNullBB);
1683 }
1684
1685 // If there's an operator delete, enter a cleanup to call it if an
1686 // exception is thrown.
1687 EHScopeStack::stable_iterator operatorDeleteCleanup;
1688 llvm::Instruction *cleanupDominator = nullptr;
1689 if (E->getOperatorDelete() &&
1690 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1691 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1692 allocatorArgs);
1693 operatorDeleteCleanup = EHStack.stable_begin();
1694 cleanupDominator = Builder.CreateUnreachable();
1695 }
1696
1697 assert((allocSize == allocSizeWithoutCookie) ==(((allocSize == allocSizeWithoutCookie) == CalculateCookiePadding
(*this, E).isZero()) ? static_cast<void> (0) : __assert_fail
("(allocSize == allocSizeWithoutCookie) == CalculateCookiePadding(*this, E).isZero()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1698, __PRETTY_FUNCTION__))
1698 CalculateCookiePadding(*this, E).isZero())(((allocSize == allocSizeWithoutCookie) == CalculateCookiePadding
(*this, E).isZero()) ? static_cast<void> (0) : __assert_fail
("(allocSize == allocSizeWithoutCookie) == CalculateCookiePadding(*this, E).isZero()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1698, __PRETTY_FUNCTION__))
;
1699 if (allocSize != allocSizeWithoutCookie) {
1700 assert(E->isArray())((E->isArray()) ? static_cast<void> (0) : __assert_fail
("E->isArray()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1700, __PRETTY_FUNCTION__))
;
1701 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1702 numElements,
1703 E, allocType);
1704 }
1705
1706 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1707 Address result = Builder.CreateElementBitCast(allocation, elementTy);
1708
1709 // Passing pointer through launder.invariant.group to avoid propagation of
1710 // vptrs information which may be included in previous type.
1711 // To not break LTO with different optimizations levels, we do it regardless
1712 // of optimization level.
1713 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1714 allocator->isReservedGlobalPlacementOperator())
1715 result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
1716 result.getAlignment());
1717
1718 // Emit sanitizer checks for pointer value now, so that in the case of an
1719 // array it was checked only once and not at each constructor call. We may
1720 // have already checked that the pointer is non-null.
1721 // FIXME: If we have an array cookie and a potentially-throwing allocator,
1722 // we'll null check the wrong pointer here.
1723 SanitizerSet SkippedChecks;
1724 SkippedChecks.set(SanitizerKind::Null, nullCheck);
1725 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1726 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1727 result.getPointer(), allocType, result.getAlignment(),
1728 SkippedChecks, numElements);
1729
1730 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1731 allocSizeWithoutCookie);
1732 if (E->isArray()) {
1733 // NewPtr is a pointer to the base element type. If we're
1734 // allocating an array of arrays, we'll need to cast back to the
1735 // array pointer type.
1736 llvm::Type *resultType = ConvertTypeForMem(E->getType());
1737 if (result.getType() != resultType)
1738 result = Builder.CreateBitCast(result, resultType);
1739 }
1740
1741 // Deactivate the 'operator delete' cleanup if we finished
1742 // initialization.
1743 if (operatorDeleteCleanup.isValid()) {
1744 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1745 cleanupDominator->eraseFromParent();
1746 }
1747
1748 llvm::Value *resultPtr = result.getPointer();
1749 if (nullCheck) {
1750 conditional.end(*this);
1751
1752 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1753 EmitBlock(contBB);
1754
1755 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1756 PHI->addIncoming(resultPtr, notNullBB);
1757 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1758 nullCheckBB);
1759
1760 resultPtr = PHI;
1761 }
1762
1763 return resultPtr;
1764}
1765
1766void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1767 llvm::Value *Ptr, QualType DeleteTy,
1768 llvm::Value *NumElements,
1769 CharUnits CookieSize) {
1770 assert((!NumElements && CookieSize.isZero()) ||(((!NumElements && CookieSize.isZero()) || DeleteFD->
getOverloadedOperator() == OO_Array_Delete) ? static_cast<
void> (0) : __assert_fail ("(!NumElements && CookieSize.isZero()) || DeleteFD->getOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1771, __PRETTY_FUNCTION__))
1771 DeleteFD->getOverloadedOperator() == OO_Array_Delete)(((!NumElements && CookieSize.isZero()) || DeleteFD->
getOverloadedOperator() == OO_Array_Delete) ? static_cast<
void> (0) : __assert_fail ("(!NumElements && CookieSize.isZero()) || DeleteFD->getOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1771, __PRETTY_FUNCTION__))
;
1772
1773 const FunctionProtoType *DeleteFTy =
1774 DeleteFD->getType()->getAs<FunctionProtoType>();
1775
1776 CallArgList DeleteArgs;
1777
1778 auto Params = getUsualDeleteParams(DeleteFD);
1779 auto ParamTypeIt = DeleteFTy->param_type_begin();
1780
1781 // Pass the pointer itself.
1782 QualType ArgTy = *ParamTypeIt++;
1783 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1784 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1785
1786 // Pass the std::destroying_delete tag if present.
1787 if (Params.DestroyingDelete) {
1788 QualType DDTag = *ParamTypeIt++;
1789 // Just pass an 'undef'. We expect the tag type to be an empty struct.
1790 auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1791 DeleteArgs.add(RValue::get(V), DDTag);
1792 }
1793
1794 // Pass the size if the delete function has a size_t parameter.
1795 if (Params.Size) {
1796 QualType SizeType = *ParamTypeIt++;
1797 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1798 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1799 DeleteTypeSize.getQuantity());
1800
1801 // For array new, multiply by the number of elements.
1802 if (NumElements)
1803 Size = Builder.CreateMul(Size, NumElements);
1804
1805 // If there is a cookie, add the cookie size.
1806 if (!CookieSize.isZero())
1807 Size = Builder.CreateAdd(
1808 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1809
1810 DeleteArgs.add(RValue::get(Size), SizeType);
1811 }
1812
1813 // Pass the alignment if the delete function has an align_val_t parameter.
1814 if (Params.Alignment) {
1815 QualType AlignValType = *ParamTypeIt++;
1816 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1817 getContext().getTypeAlignIfKnown(DeleteTy));
1818 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1819 DeleteTypeAlign.getQuantity());
1820 DeleteArgs.add(RValue::get(Align), AlignValType);
1821 }
1822
1823 assert(ParamTypeIt == DeleteFTy->param_type_end() &&((ParamTypeIt == DeleteFTy->param_type_end() && "unknown parameter to usual delete function"
) ? static_cast<void> (0) : __assert_fail ("ParamTypeIt == DeleteFTy->param_type_end() && \"unknown parameter to usual delete function\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1824, __PRETTY_FUNCTION__))
1824 "unknown parameter to usual delete function")((ParamTypeIt == DeleteFTy->param_type_end() && "unknown parameter to usual delete function"
) ? static_cast<void> (0) : __assert_fail ("ParamTypeIt == DeleteFTy->param_type_end() && \"unknown parameter to usual delete function\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1824, __PRETTY_FUNCTION__))
;
1825
1826 // Emit the call to delete.
1827 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1828}
1829
1830namespace {
1831 /// Calls the given 'operator delete' on a single object.
1832 struct CallObjectDelete final : EHScopeStack::Cleanup {
1833 llvm::Value *Ptr;
1834 const FunctionDecl *OperatorDelete;
1835 QualType ElementType;
1836
1837 CallObjectDelete(llvm::Value *Ptr,
1838 const FunctionDecl *OperatorDelete,
1839 QualType ElementType)
1840 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1841
1842 void Emit(CodeGenFunction &CGF, Flags flags) override {
1843 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1844 }
1845 };
1846}
1847
1848void
1849CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1850 llvm::Value *CompletePtr,
1851 QualType ElementType) {
1852 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1853 OperatorDelete, ElementType);
1854}
1855
1856/// Emit the code for deleting a single object with a destroying operator
1857/// delete. If the element type has a non-virtual destructor, Ptr has already
1858/// been converted to the type of the parameter of 'operator delete'. Otherwise
1859/// Ptr points to an object of the static type.
1860static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1861 const CXXDeleteExpr *DE, Address Ptr,
1862 QualType ElementType) {
1863 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1864 if (Dtor && Dtor->isVirtual())
1865 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1866 Dtor);
1867 else
1868 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1869}
1870
1871/// Emit the code for deleting a single object.
1872static void EmitObjectDelete(CodeGenFunction &CGF,
1873 const CXXDeleteExpr *DE,
1874 Address Ptr,
1875 QualType ElementType) {
1876 // C++11 [expr.delete]p3:
1877 // If the static type of the object to be deleted is different from its
1878 // dynamic type, the static type shall be a base class of the dynamic type
1879 // of the object to be deleted and the static type shall have a virtual
1880 // destructor or the behavior is undefined.
1881 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1882 DE->getExprLoc(), Ptr.getPointer(),
1883 ElementType);
1884
1885 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1886 assert(!OperatorDelete->isDestroyingOperatorDelete())((!OperatorDelete->isDestroyingOperatorDelete()) ? static_cast
<void> (0) : __assert_fail ("!OperatorDelete->isDestroyingOperatorDelete()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1886, __PRETTY_FUNCTION__))
;
1887
1888 // Find the destructor for the type, if applicable. If the
1889 // destructor is virtual, we'll just emit the vcall and return.
1890 const CXXDestructorDecl *Dtor = nullptr;
1891 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1892 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1893 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1894 Dtor = RD->getDestructor();
1895
1896 if (Dtor->isVirtual()) {
1897 bool UseVirtualCall = true;
1898 const Expr *Base = DE->getArgument();
1899 if (auto *DevirtualizedDtor =
1900 dyn_cast_or_null<const CXXDestructorDecl>(
1901 Dtor->getDevirtualizedMethod(
1902 Base, CGF.CGM.getLangOpts().AppleKext))) {
1903 UseVirtualCall = false;
1904 const CXXRecordDecl *DevirtualizedClass =
1905 DevirtualizedDtor->getParent();
1906 if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1907 // Devirtualized to the class of the base type (the type of the
1908 // whole expression).
1909 Dtor = DevirtualizedDtor;
1910 } else {
1911 // Devirtualized to some other type. Would need to cast the this
1912 // pointer to that type but we don't have support for that yet, so
1913 // do a virtual call. FIXME: handle the case where it is
1914 // devirtualized to the derived type (the type of the inner
1915 // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1916 UseVirtualCall = true;
1917 }
1918 }
1919 if (UseVirtualCall) {
1920 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1921 Dtor);
1922 return;
1923 }
1924 }
1925 }
1926 }
1927
1928 // Make sure that we call delete even if the dtor throws.
1929 // This doesn't have to a conditional cleanup because we're going
1930 // to pop it off in a second.
1931 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1932 Ptr.getPointer(),
1933 OperatorDelete, ElementType);
1934
1935 if (Dtor)
1936 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1937 /*ForVirtualBase=*/false,
1938 /*Delegating=*/false,
1939 Ptr, ElementType);
1940 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1941 switch (Lifetime) {
1942 case Qualifiers::OCL_None:
1943 case Qualifiers::OCL_ExplicitNone:
1944 case Qualifiers::OCL_Autoreleasing:
1945 break;
1946
1947 case Qualifiers::OCL_Strong:
1948 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1949 break;
1950
1951 case Qualifiers::OCL_Weak:
1952 CGF.EmitARCDestroyWeak(Ptr);
1953 break;
1954 }
1955 }
1956
1957 CGF.PopCleanupBlock();
1958}
1959
1960namespace {
1961 /// Calls the given 'operator delete' on an array of objects.
1962 struct CallArrayDelete final : EHScopeStack::Cleanup {
1963 llvm::Value *Ptr;
1964 const FunctionDecl *OperatorDelete;
1965 llvm::Value *NumElements;
1966 QualType ElementType;
1967 CharUnits CookieSize;
1968
1969 CallArrayDelete(llvm::Value *Ptr,
1970 const FunctionDecl *OperatorDelete,
1971 llvm::Value *NumElements,
1972 QualType ElementType,
1973 CharUnits CookieSize)
1974 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1975 ElementType(ElementType), CookieSize(CookieSize) {}
1976
1977 void Emit(CodeGenFunction &CGF, Flags flags) override {
1978 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1979 CookieSize);
1980 }
1981 };
1982}
1983
1984/// Emit the code for deleting an array of objects.
1985static void EmitArrayDelete(CodeGenFunction &CGF,
1986 const CXXDeleteExpr *E,
1987 Address deletedPtr,
1988 QualType elementType) {
1989 llvm::Value *numElements = nullptr;
1990 llvm::Value *allocatedPtr = nullptr;
1991 CharUnits cookieSize;
1992 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1993 numElements, allocatedPtr, cookieSize);
1994
1995 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer")((allocatedPtr && "ReadArrayCookie didn't set allocated pointer"
) ? static_cast<void> (0) : __assert_fail ("allocatedPtr && \"ReadArrayCookie didn't set allocated pointer\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 1995, __PRETTY_FUNCTION__))
;
1996
1997 // Make sure that we call delete even if one of the dtors throws.
1998 const FunctionDecl *operatorDelete = E->getOperatorDelete();
1999 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
2000 allocatedPtr, operatorDelete,
2001 numElements, elementType,
2002 cookieSize);
2003
2004 // Destroy the elements.
2005 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2006 assert(numElements && "no element count for a type with a destructor!")((numElements && "no element count for a type with a destructor!"
) ? static_cast<void> (0) : __assert_fail ("numElements && \"no element count for a type with a destructor!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 2006, __PRETTY_FUNCTION__))
;
2007
2008 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2009 CharUnits elementAlign =
2010 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2011
2012 llvm::Value *arrayBegin = deletedPtr.getPointer();
2013 llvm::Value *arrayEnd =
2014 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
2015
2016 // Note that it is legal to allocate a zero-length array, and we
2017 // can never fold the check away because the length should always
2018 // come from a cookie.
2019 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
2020 CGF.getDestroyer(dtorKind),
2021 /*checkZeroLength*/ true,
2022 CGF.needsEHCleanup(dtorKind));
2023 }
2024
2025 // Pop the cleanup block.
2026 CGF.PopCleanupBlock();
2027}
2028
2029void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
2030 const Expr *Arg = E->getArgument();
2031 Address Ptr = EmitPointerWithAlignment(Arg);
2032
2033 // Null check the pointer.
2034 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2035 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2036
2037 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
2038
2039 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2040 EmitBlock(DeleteNotNull);
2041
2042 QualType DeleteTy = E->getDestroyedType();
2043
2044 // A destroying operator delete overrides the entire operation of the
2045 // delete expression.
2046 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2047 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2048 EmitBlock(DeleteEnd);
2049 return;
2050 }
2051
2052 // We might be deleting a pointer to array. If so, GEP down to the
2053 // first non-array element.
2054 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2055 if (DeleteTy->isConstantArrayType()) {
2056 llvm::Value *Zero = Builder.getInt32(0);
2057 SmallVector<llvm::Value*,8> GEP;
2058
2059 GEP.push_back(Zero); // point at the outermost array
2060
2061 // For each layer of array type we're pointing at:
2062 while (const ConstantArrayType *Arr
2063 = getContext().getAsConstantArrayType(DeleteTy)) {
2064 // 1. Unpeel the array type.
2065 DeleteTy = Arr->getElementType();
2066
2067 // 2. GEP to the first element of the array.
2068 GEP.push_back(Zero);
2069 }
2070
2071 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2072 Ptr.getAlignment());
2073 }
2074
2075 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType())((ConvertTypeForMem(DeleteTy) == Ptr.getElementType()) ? static_cast
<void> (0) : __assert_fail ("ConvertTypeForMem(DeleteTy) == Ptr.getElementType()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 2075, __PRETTY_FUNCTION__))
;
2076
2077 if (E->isArrayForm()) {
2078 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2079 } else {
2080 EmitObjectDelete(*this, E, Ptr, DeleteTy);
2081 }
2082
2083 EmitBlock(DeleteEnd);
2084}
2085
2086static bool isGLValueFromPointerDeref(const Expr *E) {
2087 E = E->IgnoreParens();
2088
2089 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2090 if (!CE->getSubExpr()->isGLValue())
2091 return false;
2092 return isGLValueFromPointerDeref(CE->getSubExpr());
2093 }
2094
2095 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2096 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2097
2098 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2099 if (BO->getOpcode() == BO_Comma)
2100 return isGLValueFromPointerDeref(BO->getRHS());
2101
2102 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2103 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2104 isGLValueFromPointerDeref(ACO->getFalseExpr());
2105
2106 // C++11 [expr.sub]p1:
2107 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2108 if (isa<ArraySubscriptExpr>(E))
2109 return true;
2110
2111 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2112 if (UO->getOpcode() == UO_Deref)
2113 return true;
2114
2115 return false;
2116}
2117
2118static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2119 llvm::Type *StdTypeInfoPtrTy) {
2120 // Get the vtable pointer.
2121 Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
2122
2123 QualType SrcRecordTy = E->getType();
2124
2125 // C++ [class.cdtor]p4:
2126 // If the operand of typeid refers to the object under construction or
2127 // destruction and the static type of the operand is neither the constructor
2128 // or destructor’s class nor one of its bases, the behavior is undefined.
2129 CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2130 ThisPtr.getPointer(), SrcRecordTy);
2131
2132 // C++ [expr.typeid]p2:
2133 // If the glvalue expression is obtained by applying the unary * operator to
2134 // a pointer and the pointer is a null pointer value, the typeid expression
2135 // throws the std::bad_typeid exception.
2136 //
2137 // However, this paragraph's intent is not clear. We choose a very generous
2138 // interpretation which implores us to consider comma operators, conditional
2139 // operators, parentheses and other such constructs.
2140 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2141 isGLValueFromPointerDeref(E), SrcRecordTy)) {
2142 llvm::BasicBlock *BadTypeidBlock =
2143 CGF.createBasicBlock("typeid.bad_typeid");
2144 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2145
2146 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2147 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2148
2149 CGF.EmitBlock(BadTypeidBlock);
2150 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2151 CGF.EmitBlock(EndBlock);
2152 }
2153
2154 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2155 StdTypeInfoPtrTy);
2156}
2157
2158llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2159 llvm::Type *StdTypeInfoPtrTy =
2160 ConvertType(E->getType())->getPointerTo();
2161
2162 if (E->isTypeOperand()) {
2163 llvm::Constant *TypeInfo =
2164 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2165 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2166 }
2167
2168 // C++ [expr.typeid]p2:
2169 // When typeid is applied to a glvalue expression whose type is a
2170 // polymorphic class type, the result refers to a std::type_info object
2171 // representing the type of the most derived object (that is, the dynamic
2172 // type) to which the glvalue refers.
2173 if (E->isPotentiallyEvaluated())
2174 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2175 StdTypeInfoPtrTy);
2176
2177 QualType OperandTy = E->getExprOperand()->getType();
2178 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2179 StdTypeInfoPtrTy);
2180}
2181
2182static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2183 QualType DestTy) {
2184 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2185 if (DestTy->isPointerType())
2186 return llvm::Constant::getNullValue(DestLTy);
2187
2188 /// C++ [expr.dynamic.cast]p9:
2189 /// A failed cast to reference type throws std::bad_cast
2190 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2191 return nullptr;
2192
2193 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2194 return llvm::UndefValue::get(DestLTy);
2195}
2196
2197llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2198 const CXXDynamicCastExpr *DCE) {
2199 CGM.EmitExplicitCastExprType(DCE, this);
2200 QualType DestTy = DCE->getTypeAsWritten();
2201
2202 QualType SrcTy = DCE->getSubExpr()->getType();
2203
2204 // C++ [expr.dynamic.cast]p7:
2205 // If T is "pointer to cv void," then the result is a pointer to the most
2206 // derived object pointed to by v.
2207 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2208
2209 bool isDynamicCastToVoid;
2210 QualType SrcRecordTy;
2211 QualType DestRecordTy;
2212 if (DestPTy) {
2213 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2214 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2215 DestRecordTy = DestPTy->getPointeeType();
2216 } else {
2217 isDynamicCastToVoid = false;
2218 SrcRecordTy = SrcTy;
2219 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2220 }
2221
2222 // C++ [class.cdtor]p5:
2223 // If the operand of the dynamic_cast refers to the object under
2224 // construction or destruction and the static type of the operand is not a
2225 // pointer to or object of the constructor or destructor’s own class or one
2226 // of its bases, the dynamic_cast results in undefined behavior.
2227 EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2228 SrcRecordTy);
2229
2230 if (DCE->isAlwaysNull())
2231 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2232 return T;
2233
2234 assert(SrcRecordTy->isRecordType() && "source type must be a record type!")((SrcRecordTy->isRecordType() && "source type must be a record type!"
) ? static_cast<void> (0) : __assert_fail ("SrcRecordTy->isRecordType() && \"source type must be a record type!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 2234, __PRETTY_FUNCTION__))
;
2235
2236 // C++ [expr.dynamic.cast]p4:
2237 // If the value of v is a null pointer value in the pointer case, the result
2238 // is the null pointer value of type T.
2239 bool ShouldNullCheckSrcValue =
2240 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2241 SrcRecordTy);
2242
2243 llvm::BasicBlock *CastNull = nullptr;
2244 llvm::BasicBlock *CastNotNull = nullptr;
2245 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2246
2247 if (ShouldNullCheckSrcValue) {
2248 CastNull = createBasicBlock("dynamic_cast.null");
2249 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2250
2251 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2252 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2253 EmitBlock(CastNotNull);
2254 }
2255
2256 llvm::Value *Value;
2257 if (isDynamicCastToVoid) {
2258 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2259 DestTy);
2260 } else {
2261 assert(DestRecordTy->isRecordType() &&((DestRecordTy->isRecordType() && "destination type must be a record type!"
) ? static_cast<void> (0) : __assert_fail ("DestRecordTy->isRecordType() && \"destination type must be a record type!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 2262, __PRETTY_FUNCTION__))
2262 "destination type must be a record type!")((DestRecordTy->isRecordType() && "destination type must be a record type!"
) ? static_cast<void> (0) : __assert_fail ("DestRecordTy->isRecordType() && \"destination type must be a record type!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/CodeGen/CGExprCXX.cpp"
, 2262, __PRETTY_FUNCTION__))
;
2263 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2264 DestTy, DestRecordTy, CastEnd);
2265 CastNotNull = Builder.GetInsertBlock();
2266 }
2267
2268 if (ShouldNullCheckSrcValue) {
2269 EmitBranch(CastEnd);
2270
2271 EmitBlock(CastNull);
2272 EmitBranch(CastEnd);
2273 }
2274
2275 EmitBlock(CastEnd);
2276
2277 if (ShouldNullCheckSrcValue) {
2278 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2279 PHI->addIncoming(Value, CastNotNull);
2280 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2281
2282 Value = PHI;
2283 }
2284
2285 return Value;
2286}

/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- 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/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69namespace serialization {
70 template <class T> class AbstractTypeReader;
71 template <class T> class AbstractTypeWriter;
72}
73
74} // namespace clang
75
76namespace llvm {
77
78 template <typename T>
79 struct PointerLikeTypeTraits;
80 template<>
81 struct PointerLikeTypeTraits< ::clang::Type*> {
82 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
83
84 static inline ::clang::Type *getFromVoidPointer(void *P) {
85 return static_cast< ::clang::Type*>(P);
86 }
87
88 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
89 };
90
91 template<>
92 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
93 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
94
95 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
96 return static_cast< ::clang::ExtQuals*>(P);
97 }
98
99 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
100 };
101
102} // namespace llvm
103
104namespace clang {
105
106class ASTContext;
107template <typename> class CanQual;
108class CXXRecordDecl;
109class DeclContext;
110class EnumDecl;
111class Expr;
112class ExtQualsTypeCommonBase;
113class FunctionDecl;
114class IdentifierInfo;
115class NamedDecl;
116class ObjCInterfaceDecl;
117class ObjCProtocolDecl;
118class ObjCTypeParamDecl;
119struct PrintingPolicy;
120class RecordDecl;
121class Stmt;
122class TagDecl;
123class TemplateArgument;
124class TemplateArgumentListInfo;
125class TemplateArgumentLoc;
126class TemplateTypeParmDecl;
127class TypedefNameDecl;
128class UnresolvedUsingTypenameDecl;
129
130using CanQualType = CanQual<Type>;
131
132// Provide forward declarations for all of the *Type classes.
133#define TYPE(Class, Base) class Class##Type;
134#include "clang/AST/TypeNodes.inc"
135
136/// The collection of all-type qualifiers we support.
137/// Clang supports five independent qualifiers:
138/// * C99: const, volatile, and restrict
139/// * MS: __unaligned
140/// * Embedded C (TR18037): address spaces
141/// * Objective C: the GC attributes (none, weak, or strong)
142class Qualifiers {
143public:
144 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
145 Const = 0x1,
146 Restrict = 0x2,
147 Volatile = 0x4,
148 CVRMask = Const | Volatile | Restrict
149 };
150
151 enum GC {
152 GCNone = 0,
153 Weak,
154 Strong
155 };
156
157 enum ObjCLifetime {
158 /// There is no lifetime qualification on this type.
159 OCL_None,
160
161 /// This object can be modified without requiring retains or
162 /// releases.
163 OCL_ExplicitNone,
164
165 /// Assigning into this object requires the old value to be
166 /// released and the new value to be retained. The timing of the
167 /// release of the old value is inexact: it may be moved to
168 /// immediately after the last known point where the value is
169 /// live.
170 OCL_Strong,
171
172 /// Reading or writing from this object requires a barrier call.
173 OCL_Weak,
174
175 /// Assigning into this object requires a lifetime extension.
176 OCL_Autoreleasing
177 };
178
179 enum {
180 /// The maximum supported address space number.
181 /// 23 bits should be enough for anyone.
182 MaxAddressSpace = 0x7fffffu,
183
184 /// The width of the "fast" qualifier mask.
185 FastWidth = 3,
186
187 /// The fast qualifier mask.
188 FastMask = (1 << FastWidth) - 1
189 };
190
191 /// Returns the common set of qualifiers while removing them from
192 /// the given sets.
193 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
194 // If both are only CVR-qualified, bit operations are sufficient.
195 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
196 Qualifiers Q;
197 Q.Mask = L.Mask & R.Mask;
198 L.Mask &= ~Q.Mask;
199 R.Mask &= ~Q.Mask;
200 return Q;
201 }
202
203 Qualifiers Q;
204 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
205 Q.addCVRQualifiers(CommonCRV);
206 L.removeCVRQualifiers(CommonCRV);
207 R.removeCVRQualifiers(CommonCRV);
208
209 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
210 Q.setObjCGCAttr(L.getObjCGCAttr());
211 L.removeObjCGCAttr();
212 R.removeObjCGCAttr();
213 }
214
215 if (L.getObjCLifetime() == R.getObjCLifetime()) {
216 Q.setObjCLifetime(L.getObjCLifetime());
217 L.removeObjCLifetime();
218 R.removeObjCLifetime();
219 }
220
221 if (L.getAddressSpace() == R.getAddressSpace()) {
222 Q.setAddressSpace(L.getAddressSpace());
223 L.removeAddressSpace();
224 R.removeAddressSpace();
225 }
226 return Q;
227 }
228
229 static Qualifiers fromFastMask(unsigned Mask) {
230 Qualifiers Qs;
231 Qs.addFastQualifiers(Mask);
232 return Qs;
233 }
234
235 static Qualifiers fromCVRMask(unsigned CVR) {
236 Qualifiers Qs;
237 Qs.addCVRQualifiers(CVR);
238 return Qs;
239 }
240
241 static Qualifiers fromCVRUMask(unsigned CVRU) {
242 Qualifiers Qs;
243 Qs.addCVRUQualifiers(CVRU);
244 return Qs;
245 }
246
247 // Deserialize qualifiers from an opaque representation.
248 static Qualifiers fromOpaqueValue(unsigned opaque) {
249 Qualifiers Qs;
250 Qs.Mask = opaque;
251 return Qs;
252 }
253
254 // Serialize these qualifiers into an opaque representation.
255 unsigned getAsOpaqueValue() const {
256 return Mask;
257 }
258
259 bool hasConst() const { return Mask & Const; }
260 bool hasOnlyConst() const { return Mask == Const; }
261 void removeConst() { Mask &= ~Const; }
262 void addConst() { Mask |= Const; }
263
264 bool hasVolatile() const { return Mask & Volatile; }
265 bool hasOnlyVolatile() const { return Mask == Volatile; }
266 void removeVolatile() { Mask &= ~Volatile; }
267 void addVolatile() { Mask |= Volatile; }
268
269 bool hasRestrict() const { return Mask & Restrict; }
270 bool hasOnlyRestrict() const { return Mask == Restrict; }
271 void removeRestrict() { Mask &= ~Restrict; }
272 void addRestrict() { Mask |= Restrict; }
273
274 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
275 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
276 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
277
278 void setCVRQualifiers(unsigned mask) {
279 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 279, __PRETTY_FUNCTION__))
;
280 Mask = (Mask & ~CVRMask) | mask;
281 }
282 void removeCVRQualifiers(unsigned mask) {
283 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 283, __PRETTY_FUNCTION__))
;
284 Mask &= ~mask;
285 }
286 void removeCVRQualifiers() {
287 removeCVRQualifiers(CVRMask);
288 }
289 void addCVRQualifiers(unsigned mask) {
290 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 290, __PRETTY_FUNCTION__))
;
291 Mask |= mask;
292 }
293 void addCVRUQualifiers(unsigned mask) {
294 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 294, __PRETTY_FUNCTION__))
;
295 Mask |= mask;
296 }
297
298 bool hasUnaligned() const { return Mask & UMask; }
299 void setUnaligned(bool flag) {
300 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
301 }
302 void removeUnaligned() { Mask &= ~UMask; }
303 void addUnaligned() { Mask |= UMask; }
304
305 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
306 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
307 void setObjCGCAttr(GC type) {
308 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
309 }
310 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
311 void addObjCGCAttr(GC type) {
312 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 312, __PRETTY_FUNCTION__))
;
313 setObjCGCAttr(type);
314 }
315 Qualifiers withoutObjCGCAttr() const {
316 Qualifiers qs = *this;
317 qs.removeObjCGCAttr();
318 return qs;
319 }
320 Qualifiers withoutObjCLifetime() const {
321 Qualifiers qs = *this;
322 qs.removeObjCLifetime();
323 return qs;
324 }
325 Qualifiers withoutAddressSpace() const {
326 Qualifiers qs = *this;
327 qs.removeAddressSpace();
328 return qs;
329 }
330
331 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
332 ObjCLifetime getObjCLifetime() const {
333 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
334 }
335 void setObjCLifetime(ObjCLifetime type) {
336 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
337 }
338 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
339 void addObjCLifetime(ObjCLifetime type) {
340 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 340, __PRETTY_FUNCTION__))
;
341 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 341, __PRETTY_FUNCTION__))
;
342 Mask |= (type << LifetimeShift);
343 }
344
345 /// True if the lifetime is neither None or ExplicitNone.
346 bool hasNonTrivialObjCLifetime() const {
347 ObjCLifetime lifetime = getObjCLifetime();
348 return (lifetime > OCL_ExplicitNone);
349 }
350
351 /// True if the lifetime is either strong or weak.
352 bool hasStrongOrWeakObjCLifetime() const {
353 ObjCLifetime lifetime = getObjCLifetime();
354 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
3
Assuming 'lifetime' is equal to OCL_Strong
4
Returning the value 1, which participates in a condition later
355 }
356
357 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
358 LangAS getAddressSpace() const {
359 return static_cast<LangAS>(Mask >> AddressSpaceShift);
360 }
361 bool hasTargetSpecificAddressSpace() const {
362 return isTargetAddressSpace(getAddressSpace());
363 }
364 /// Get the address space attribute value to be printed by diagnostics.
365 unsigned getAddressSpaceAttributePrintValue() const {
366 auto Addr = getAddressSpace();
367 // This function is not supposed to be used with language specific
368 // address spaces. If that happens, the diagnostic message should consider
369 // printing the QualType instead of the address space value.
370 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 370, __PRETTY_FUNCTION__))
;
371 if (Addr != LangAS::Default)
372 return toTargetAddressSpace(Addr);
373 // TODO: The diagnostic messages where Addr may be 0 should be fixed
374 // since it cannot differentiate the situation where 0 denotes the default
375 // address space or user specified __attribute__((address_space(0))).
376 return 0;
377 }
378 void setAddressSpace(LangAS space) {
379 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 379, __PRETTY_FUNCTION__))
;
380 Mask = (Mask & ~AddressSpaceMask)
381 | (((uint32_t) space) << AddressSpaceShift);
382 }
383 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
384 void addAddressSpace(LangAS space) {
385 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 385, __PRETTY_FUNCTION__))
;
386 setAddressSpace(space);
387 }
388
389 // Fast qualifiers are those that can be allocated directly
390 // on a QualType object.
391 bool hasFastQualifiers() const { return getFastQualifiers(); }
392 unsigned getFastQualifiers() const { return Mask & FastMask; }
393 void setFastQualifiers(unsigned mask) {
394 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 394, __PRETTY_FUNCTION__))
;
395 Mask = (Mask & ~FastMask) | mask;
396 }
397 void removeFastQualifiers(unsigned mask) {
398 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 398, __PRETTY_FUNCTION__))
;
399 Mask &= ~mask;
400 }
401 void removeFastQualifiers() {
402 removeFastQualifiers(FastMask);
403 }
404 void addFastQualifiers(unsigned mask) {
405 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 405, __PRETTY_FUNCTION__))
;
406 Mask |= mask;
407 }
408
409 /// Return true if the set contains any qualifiers which require an ExtQuals
410 /// node to be allocated.
411 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
412 Qualifiers getNonFastQualifiers() const {
413 Qualifiers Quals = *this;
414 Quals.setFastQualifiers(0);
415 return Quals;
416 }
417
418 /// Return true if the set contains any qualifiers.
419 bool hasQualifiers() const { return Mask; }
420 bool empty() const { return !Mask; }
421
422 /// Add the qualifiers from the given set to this set.
423 void addQualifiers(Qualifiers Q) {
424 // If the other set doesn't have any non-boolean qualifiers, just
425 // bit-or it in.
426 if (!(Q.Mask & ~CVRMask))
427 Mask |= Q.Mask;
428 else {
429 Mask |= (Q.Mask & CVRMask);
430 if (Q.hasAddressSpace())
431 addAddressSpace(Q.getAddressSpace());
432 if (Q.hasObjCGCAttr())
433 addObjCGCAttr(Q.getObjCGCAttr());
434 if (Q.hasObjCLifetime())
435 addObjCLifetime(Q.getObjCLifetime());
436 }
437 }
438
439 /// Remove the qualifiers from the given set from this set.
440 void removeQualifiers(Qualifiers Q) {
441 // If the other set doesn't have any non-boolean qualifiers, just
442 // bit-and the inverse in.
443 if (!(Q.Mask & ~CVRMask))
444 Mask &= ~Q.Mask;
445 else {
446 Mask &= ~(Q.Mask & CVRMask);
447 if (getObjCGCAttr() == Q.getObjCGCAttr())
448 removeObjCGCAttr();
449 if (getObjCLifetime() == Q.getObjCLifetime())
450 removeObjCLifetime();
451 if (getAddressSpace() == Q.getAddressSpace())
452 removeAddressSpace();
453 }
454 }
455
456 /// Add the qualifiers from the given set to this set, given that
457 /// they don't conflict.
458 void addConsistentQualifiers(Qualifiers qs) {
459 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 460, __PRETTY_FUNCTION__))
460 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 460, __PRETTY_FUNCTION__))
;
461 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 Mask |= qs.Mask;
466 }
467
468 /// Returns true if address space A is equal to or a superset of B.
469 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
470 /// overlapping address spaces.
471 /// CL1.1 or CL1.2:
472 /// every address space is a superset of itself.
473 /// CL2.0 adds:
474 /// __generic is a superset of any address space except for __constant.
475 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
476 // Address spaces must match exactly.
477 return A == B ||
478 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
479 // for __constant can be used as __generic.
480 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
481 // Consider pointer size address spaces to be equivalent to default.
482 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
483 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
484 }
485
486 /// Returns true if the address space in these qualifiers is equal to or
487 /// a superset of the address space in the argument qualifiers.
488 bool isAddressSpaceSupersetOf(Qualifiers other) const {
489 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
490 }
491
492 /// Determines if these qualifiers compatibly include another set.
493 /// Generally this answers the question of whether an object with the other
494 /// qualifiers can be safely used as an object with these qualifiers.
495 bool compatiblyIncludes(Qualifiers other) const {
496 return isAddressSpaceSupersetOf(other) &&
497 // ObjC GC qualifiers can match, be added, or be removed, but can't
498 // be changed.
499 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
500 !other.hasObjCGCAttr()) &&
501 // ObjC lifetime qualifiers must match exactly.
502 getObjCLifetime() == other.getObjCLifetime() &&
503 // CVR qualifiers may subset.
504 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
505 // U qualifier may superset.
506 (!other.hasUnaligned() || hasUnaligned());
507 }
508
509 /// Determines if these qualifiers compatibly include another set of
510 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
511 ///
512 /// One set of Objective-C lifetime qualifiers compatibly includes the other
513 /// if the lifetime qualifiers match, or if both are non-__weak and the
514 /// including set also contains the 'const' qualifier, or both are non-__weak
515 /// and one is None (which can only happen in non-ARC modes).
516 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
517 if (getObjCLifetime() == other.getObjCLifetime())
518 return true;
519
520 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
521 return false;
522
523 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
524 return true;
525
526 return hasConst();
527 }
528
529 /// Determine whether this set of qualifiers is a strict superset of
530 /// another set of qualifiers, not considering qualifier compatibility.
531 bool isStrictSupersetOf(Qualifiers Other) const;
532
533 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
534 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
535
536 explicit operator bool() const { return hasQualifiers(); }
537
538 Qualifiers &operator+=(Qualifiers R) {
539 addQualifiers(R);
540 return *this;
541 }
542
543 // Union two qualifier sets. If an enumerated qualifier appears
544 // in both sets, use the one from the right.
545 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
546 L += R;
547 return L;
548 }
549
550 Qualifiers &operator-=(Qualifiers R) {
551 removeQualifiers(R);
552 return *this;
553 }
554
555 /// Compute the difference between two qualifier sets.
556 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
557 L -= R;
558 return L;
559 }
560
561 std::string getAsString() const;
562 std::string getAsString(const PrintingPolicy &Policy) const;
563
564 static std::string getAddrSpaceAsString(LangAS AS);
565
566 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
567 void print(raw_ostream &OS, const PrintingPolicy &Policy,
568 bool appendSpaceIfNonEmpty = false) const;
569
570 void Profile(llvm::FoldingSetNodeID &ID) const {
571 ID.AddInteger(Mask);
572 }
573
574private:
575 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
576 // |C R V|U|GCAttr|Lifetime|AddressSpace|
577 uint32_t Mask = 0;
578
579 static const uint32_t UMask = 0x8;
580 static const uint32_t UShift = 3;
581 static const uint32_t GCAttrMask = 0x30;
582 static const uint32_t GCAttrShift = 4;
583 static const uint32_t LifetimeMask = 0x1C0;
584 static const uint32_t LifetimeShift = 6;
585 static const uint32_t AddressSpaceMask =
586 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
587 static const uint32_t AddressSpaceShift = 9;
588};
589
590/// A std::pair-like structure for storing a qualified type split
591/// into its local qualifiers and its locally-unqualified type.
592struct SplitQualType {
593 /// The locally-unqualified type.
594 const Type *Ty = nullptr;
595
596 /// The local qualifiers.
597 Qualifiers Quals;
598
599 SplitQualType() = default;
600 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
601
602 SplitQualType getSingleStepDesugaredType() const; // end of this file
603
604 // Make std::tie work.
605 std::pair<const Type *,Qualifiers> asPair() const {
606 return std::pair<const Type *, Qualifiers>(Ty, Quals);
607 }
608
609 friend bool operator==(SplitQualType a, SplitQualType b) {
610 return a.Ty == b.Ty && a.Quals == b.Quals;
611 }
612 friend bool operator!=(SplitQualType a, SplitQualType b) {
613 return a.Ty != b.Ty || a.Quals != b.Quals;
614 }
615};
616
617/// The kind of type we are substituting Objective-C type arguments into.
618///
619/// The kind of substitution affects the replacement of type parameters when
620/// no concrete type information is provided, e.g., when dealing with an
621/// unspecialized type.
622enum class ObjCSubstitutionContext {
623 /// An ordinary type.
624 Ordinary,
625
626 /// The result type of a method or function.
627 Result,
628
629 /// The parameter type of a method or function.
630 Parameter,
631
632 /// The type of a property.
633 Property,
634
635 /// The superclass of a type.
636 Superclass,
637};
638
639/// A (possibly-)qualified type.
640///
641/// For efficiency, we don't store CV-qualified types as nodes on their
642/// own: instead each reference to a type stores the qualifiers. This
643/// greatly reduces the number of nodes we need to allocate for types (for
644/// example we only need one for 'int', 'const int', 'volatile int',
645/// 'const volatile int', etc).
646///
647/// As an added efficiency bonus, instead of making this a pair, we
648/// just store the two bits we care about in the low bits of the
649/// pointer. To handle the packing/unpacking, we make QualType be a
650/// simple wrapper class that acts like a smart pointer. A third bit
651/// indicates whether there are extended qualifiers present, in which
652/// case the pointer points to a special structure.
653class QualType {
654 friend class QualifierCollector;
655
656 // Thankfully, these are efficiently composable.
657 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
658 Qualifiers::FastWidth> Value;
659
660 const ExtQuals *getExtQualsUnsafe() const {
661 return Value.getPointer().get<const ExtQuals*>();
662 }
663
664 const Type *getTypePtrUnsafe() const {
665 return Value.getPointer().get<const Type*>();
666 }
667
668 const ExtQualsTypeCommonBase *getCommonPtr() const {
669 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 669, __PRETTY_FUNCTION__))
;
670 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
671 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
672 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
673 }
674
675public:
676 QualType() = default;
677 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
678 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
679
680 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
681 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
682
683 /// Retrieves a pointer to the underlying (unqualified) type.
684 ///
685 /// This function requires that the type not be NULL. If the type might be
686 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
687 const Type *getTypePtr() const;
688
689 const Type *getTypePtrOrNull() const;
690
691 /// Retrieves a pointer to the name of the base type.
692 const IdentifierInfo *getBaseTypeIdentifier() const;
693
694 /// Divides a QualType into its unqualified type and a set of local
695 /// qualifiers.
696 SplitQualType split() const;
697
698 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
699
700 static QualType getFromOpaquePtr(const void *Ptr) {
701 QualType T;
702 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
703 return T;
704 }
705
706 const Type &operator*() const {
707 return *getTypePtr();
708 }
709
710 const Type *operator->() const {
711 return getTypePtr();
712 }
713
714 bool isCanonical() const;
715 bool isCanonicalAsParam() const;
716
717 /// Return true if this QualType doesn't point to a type yet.
718 bool isNull() const {
719 return Value.getPointer().isNull();
720 }
721
722 /// Determine whether this particular QualType instance has the
723 /// "const" qualifier set, without looking through typedefs that may have
724 /// added "const" at a different level.
725 bool isLocalConstQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Const);
727 }
728
729 /// Determine whether this type is const-qualified.
730 bool isConstQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "restrict" qualifier set, without looking through typedefs that may have
734 /// added "restrict" at a different level.
735 bool isLocalRestrictQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Restrict);
737 }
738
739 /// Determine whether this type is restrict-qualified.
740 bool isRestrictQualified() const;
741
742 /// Determine whether this particular QualType instance has the
743 /// "volatile" qualifier set, without looking through typedefs that may have
744 /// added "volatile" at a different level.
745 bool isLocalVolatileQualified() const {
746 return (getLocalFastQualifiers() & Qualifiers::Volatile);
747 }
748
749 /// Determine whether this type is volatile-qualified.
750 bool isVolatileQualified() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// qualifiers, without looking through any typedefs that might add
754 /// qualifiers at a different level.
755 bool hasLocalQualifiers() const {
756 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
757 }
758
759 /// Determine whether this type has any qualifiers.
760 bool hasQualifiers() const;
761
762 /// Determine whether this particular QualType instance has any
763 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
764 /// instance.
765 bool hasLocalNonFastQualifiers() const {
766 return Value.getPointer().is<const ExtQuals*>();
767 }
768
769 /// Retrieve the set of qualifiers local to this particular QualType
770 /// instance, not including any qualifiers acquired through typedefs or
771 /// other sugar.
772 Qualifiers getLocalQualifiers() const;
773
774 /// Retrieve the set of qualifiers applied to this type.
775 Qualifiers getQualifiers() const;
776
777 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
778 /// local to this particular QualType instance, not including any qualifiers
779 /// acquired through typedefs or other sugar.
780 unsigned getLocalCVRQualifiers() const {
781 return getLocalFastQualifiers();
782 }
783
784 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
785 /// applied to this type.
786 unsigned getCVRQualifiers() const;
787
788 bool isConstant(const ASTContext& Ctx) const {
789 return QualType::isConstant(*this, Ctx);
790 }
791
792 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
793 bool isPODType(const ASTContext &Context) const;
794
795 /// Return true if this is a POD type according to the rules of the C++98
796 /// standard, regardless of the current compilation's language.
797 bool isCXX98PODType(const ASTContext &Context) const;
798
799 /// Return true if this is a POD type according to the more relaxed rules
800 /// of the C++11 standard, regardless of the current compilation's language.
801 /// (C++0x [basic.types]p9). Note that, unlike
802 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
803 bool isCXX11PODType(const ASTContext &Context) const;
804
805 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
806 bool isTrivialType(const ASTContext &Context) const;
807
808 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
809 bool isTriviallyCopyableType(const ASTContext &Context) const;
810
811
812 /// Returns true if it is a class and it might be dynamic.
813 bool mayBeDynamicClass() const;
814
815 /// Returns true if it is not a class or if the class might not be dynamic.
816 bool mayBeNotDynamicClass() const;
817
818 // Don't promise in the API that anything besides 'const' can be
819 // easily added.
820
821 /// Add the `const` type qualifier to this QualType.
822 void addConst() {
823 addFastQualifiers(Qualifiers::Const);
824 }
825 QualType withConst() const {
826 return withFastQualifiers(Qualifiers::Const);
827 }
828
829 /// Add the `volatile` type qualifier to this QualType.
830 void addVolatile() {
831 addFastQualifiers(Qualifiers::Volatile);
832 }
833 QualType withVolatile() const {
834 return withFastQualifiers(Qualifiers::Volatile);
835 }
836
837 /// Add the `restrict` qualifier to this QualType.
838 void addRestrict() {
839 addFastQualifiers(Qualifiers::Restrict);
840 }
841 QualType withRestrict() const {
842 return withFastQualifiers(Qualifiers::Restrict);
843 }
844
845 QualType withCVRQualifiers(unsigned CVR) const {
846 return withFastQualifiers(CVR);
847 }
848
849 void addFastQualifiers(unsigned TQs) {
850 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 851, __PRETTY_FUNCTION__))
851 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 851, __PRETTY_FUNCTION__))
;
852 Value.setInt(Value.getInt() | TQs);
853 }
854
855 void removeLocalConst();
856 void removeLocalVolatile();
857 void removeLocalRestrict();
858 void removeLocalCVRQualifiers(unsigned Mask);
859
860 void removeLocalFastQualifiers() { Value.setInt(0); }
861 void removeLocalFastQualifiers(unsigned Mask) {
862 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 862, __PRETTY_FUNCTION__))
;
863 Value.setInt(Value.getInt() & ~Mask);
864 }
865
866 // Creates a type with the given qualifiers in addition to any
867 // qualifiers already on this type.
868 QualType withFastQualifiers(unsigned TQs) const {
869 QualType T = *this;
870 T.addFastQualifiers(TQs);
871 return T;
872 }
873
874 // Creates a type with exactly the given fast qualifiers, removing
875 // any existing fast qualifiers.
876 QualType withExactLocalFastQualifiers(unsigned TQs) const {
877 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
878 }
879
880 // Removes fast qualifiers, but leaves any extended qualifiers in place.
881 QualType withoutLocalFastQualifiers() const {
882 QualType T = *this;
883 T.removeLocalFastQualifiers();
884 return T;
885 }
886
887 QualType getCanonicalType() const;
888
889 /// Return this type with all of the instance-specific qualifiers
890 /// removed, but without removing any qualifiers that may have been applied
891 /// through typedefs.
892 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
893
894 /// Retrieve the unqualified variant of the given type,
895 /// removing as little sugar as possible.
896 ///
897 /// This routine looks through various kinds of sugar to find the
898 /// least-desugared type that is unqualified. For example, given:
899 ///
900 /// \code
901 /// typedef int Integer;
902 /// typedef const Integer CInteger;
903 /// typedef CInteger DifferenceType;
904 /// \endcode
905 ///
906 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
907 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
908 ///
909 /// The resulting type might still be qualified if it's sugar for an array
910 /// type. To strip qualifiers even from within a sugared array type, use
911 /// ASTContext::getUnqualifiedArrayType.
912 inline QualType getUnqualifiedType() const;
913
914 /// Retrieve the unqualified variant of the given type, removing as little
915 /// sugar as possible.
916 ///
917 /// Like getUnqualifiedType(), but also returns the set of
918 /// qualifiers that were built up.
919 ///
920 /// The resulting type might still be qualified if it's sugar for an array
921 /// type. To strip qualifiers even from within a sugared array type, use
922 /// ASTContext::getUnqualifiedArrayType.
923 inline SplitQualType getSplitUnqualifiedType() const;
924
925 /// Determine whether this type is more qualified than the other
926 /// given type, requiring exact equality for non-CVR qualifiers.
927 bool isMoreQualifiedThan(QualType Other) const;
928
929 /// Determine whether this type is at least as qualified as the other
930 /// given type, requiring exact equality for non-CVR qualifiers.
931 bool isAtLeastAsQualifiedAs(QualType Other) const;
932
933 QualType getNonReferenceType() const;
934
935 /// Determine the type of a (typically non-lvalue) expression with the
936 /// specified result type.
937 ///
938 /// This routine should be used for expressions for which the return type is
939 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
940 /// an lvalue. It removes a top-level reference (since there are no
941 /// expressions of reference type) and deletes top-level cvr-qualifiers
942 /// from non-class types (in C++) or all types (in C).
943 QualType getNonLValueExprType(const ASTContext &Context) const;
944
945 /// Return the specified type with any "sugar" removed from
946 /// the type. This takes off typedefs, typeof's etc. If the outer level of
947 /// the type is already concrete, it returns it unmodified. This is similar
948 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
949 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
950 /// concrete.
951 ///
952 /// Qualifiers are left in place.
953 QualType getDesugaredType(const ASTContext &Context) const {
954 return getDesugaredType(*this, Context);
955 }
956
957 SplitQualType getSplitDesugaredType() const {
958 return getSplitDesugaredType(*this);
959 }
960
961 /// Return the specified type with one level of "sugar" removed from
962 /// the type.
963 ///
964 /// This routine takes off the first typedef, typeof, etc. If the outer level
965 /// of the type is already concrete, it returns it unmodified.
966 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
967 return getSingleStepDesugaredTypeImpl(*this, Context);
968 }
969
970 /// Returns the specified type after dropping any
971 /// outer-level parentheses.
972 QualType IgnoreParens() const {
973 if (isa<ParenType>(*this))
974 return QualType::IgnoreParens(*this);
975 return *this;
976 }
977
978 /// Indicate whether the specified types and qualifiers are identical.
979 friend bool operator==(const QualType &LHS, const QualType &RHS) {
980 return LHS.Value == RHS.Value;
981 }
982 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
983 return LHS.Value != RHS.Value;
984 }
985 friend bool operator<(const QualType &LHS, const QualType &RHS) {
986 return LHS.Value < RHS.Value;
987 }
988
989 static std::string getAsString(SplitQualType split,
990 const PrintingPolicy &Policy) {
991 return getAsString(split.Ty, split.Quals, Policy);
992 }
993 static std::string getAsString(const Type *ty, Qualifiers qs,
994 const PrintingPolicy &Policy);
995
996 std::string getAsString() const;
997 std::string getAsString(const PrintingPolicy &Policy) const;
998
999 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1000 const Twine &PlaceHolder = Twine(),
1001 unsigned Indentation = 0) const;
1002
1003 static void print(SplitQualType split, raw_ostream &OS,
1004 const PrintingPolicy &policy, const Twine &PlaceHolder,
1005 unsigned Indentation = 0) {
1006 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1007 }
1008
1009 static void print(const Type *ty, Qualifiers qs,
1010 raw_ostream &OS, const PrintingPolicy &policy,
1011 const Twine &PlaceHolder,
1012 unsigned Indentation = 0);
1013
1014 void getAsStringInternal(std::string &Str,
1015 const PrintingPolicy &Policy) const;
1016
1017 static void getAsStringInternal(SplitQualType split, std::string &out,
1018 const PrintingPolicy &policy) {
1019 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1020 }
1021
1022 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1023 std::string &out,
1024 const PrintingPolicy &policy);
1025
1026 class StreamedQualTypeHelper {
1027 const QualType &T;
1028 const PrintingPolicy &Policy;
1029 const Twine &PlaceHolder;
1030 unsigned Indentation;
1031
1032 public:
1033 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1034 const Twine &PlaceHolder, unsigned Indentation)
1035 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1036 Indentation(Indentation) {}
1037
1038 friend raw_ostream &operator<<(raw_ostream &OS,
1039 const StreamedQualTypeHelper &SQT) {
1040 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1041 return OS;
1042 }
1043 };
1044
1045 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1046 const Twine &PlaceHolder = Twine(),
1047 unsigned Indentation = 0) const {
1048 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1049 }
1050
1051 void dump(const char *s) const;
1052 void dump() const;
1053 void dump(llvm::raw_ostream &OS) const;
1054
1055 void Profile(llvm::FoldingSetNodeID &ID) const {
1056 ID.AddPointer(getAsOpaquePtr());
1057 }
1058
1059 /// Check if this type has any address space qualifier.
1060 inline bool hasAddressSpace() const;
1061
1062 /// Return the address space of this type.
1063 inline LangAS getAddressSpace() const;
1064
1065 /// Returns gc attribute of this type.
1066 inline Qualifiers::GC getObjCGCAttr() const;
1067
1068 /// true when Type is objc's weak.
1069 bool isObjCGCWeak() const {
1070 return getObjCGCAttr() == Qualifiers::Weak;
1071 }
1072
1073 /// true when Type is objc's strong.
1074 bool isObjCGCStrong() const {
1075 return getObjCGCAttr() == Qualifiers::Strong;
1076 }
1077
1078 /// Returns lifetime attribute of this type.
1079 Qualifiers::ObjCLifetime getObjCLifetime() const {
1080 return getQualifiers().getObjCLifetime();
1081 }
1082
1083 bool hasNonTrivialObjCLifetime() const {
1084 return getQualifiers().hasNonTrivialObjCLifetime();
1085 }
1086
1087 bool hasStrongOrWeakObjCLifetime() const {
1088 return getQualifiers().hasStrongOrWeakObjCLifetime();
2
Calling 'Qualifiers::hasStrongOrWeakObjCLifetime'
5
Returning from 'Qualifiers::hasStrongOrWeakObjCLifetime'
6
Returning the value 1, which participates in a condition later
1089 }
1090
1091 // true when Type is objc's weak and weak is enabled but ARC isn't.
1092 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1093
1094 enum PrimitiveDefaultInitializeKind {
1095 /// The type does not fall into any of the following categories. Note that
1096 /// this case is zero-valued so that values of this enum can be used as a
1097 /// boolean condition for non-triviality.
1098 PDIK_Trivial,
1099
1100 /// The type is an Objective-C retainable pointer type that is qualified
1101 /// with the ARC __strong qualifier.
1102 PDIK_ARCStrong,
1103
1104 /// The type is an Objective-C retainable pointer type that is qualified
1105 /// with the ARC __weak qualifier.
1106 PDIK_ARCWeak,
1107
1108 /// The type is a struct containing a field whose type is not PCK_Trivial.
1109 PDIK_Struct
1110 };
1111
1112 /// Functions to query basic properties of non-trivial C struct types.
1113
1114 /// Check if this is a non-trivial type that would cause a C struct
1115 /// transitively containing this type to be non-trivial to default initialize
1116 /// and return the kind.
1117 PrimitiveDefaultInitializeKind
1118 isNonTrivialToPrimitiveDefaultInitialize() const;
1119
1120 enum PrimitiveCopyKind {
1121 /// The type does not fall into any of the following categories. Note that
1122 /// this case is zero-valued so that values of this enum can be used as a
1123 /// boolean condition for non-triviality.
1124 PCK_Trivial,
1125
1126 /// The type would be trivial except that it is volatile-qualified. Types
1127 /// that fall into one of the other non-trivial cases may additionally be
1128 /// volatile-qualified.
1129 PCK_VolatileTrivial,
1130
1131 /// The type is an Objective-C retainable pointer type that is qualified
1132 /// with the ARC __strong qualifier.
1133 PCK_ARCStrong,
1134
1135 /// The type is an Objective-C retainable pointer type that is qualified
1136 /// with the ARC __weak qualifier.
1137 PCK_ARCWeak,
1138
1139 /// The type is a struct containing a field whose type is neither
1140 /// PCK_Trivial nor PCK_VolatileTrivial.
1141 /// Note that a C++ struct type does not necessarily match this; C++ copying
1142 /// semantics are too complex to express here, in part because they depend
1143 /// on the exact constructor or assignment operator that is chosen by
1144 /// overload resolution to do the copy.
1145 PCK_Struct
1146 };
1147
1148 /// Check if this is a non-trivial type that would cause a C struct
1149 /// transitively containing this type to be non-trivial to copy and return the
1150 /// kind.
1151 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1152
1153 /// Check if this is a non-trivial type that would cause a C struct
1154 /// transitively containing this type to be non-trivial to destructively
1155 /// move and return the kind. Destructive move in this context is a C++-style
1156 /// move in which the source object is placed in a valid but unspecified state
1157 /// after it is moved, as opposed to a truly destructive move in which the
1158 /// source object is placed in an uninitialized state.
1159 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1160
1161 enum DestructionKind {
1162 DK_none,
1163 DK_cxx_destructor,
1164 DK_objc_strong_lifetime,
1165 DK_objc_weak_lifetime,
1166 DK_nontrivial_c_struct
1167 };
1168
1169 /// Returns a nonzero value if objects of this type require
1170 /// non-trivial work to clean up after. Non-zero because it's
1171 /// conceivable that qualifiers (objc_gc(weak)?) could make
1172 /// something require destruction.
1173 DestructionKind isDestructedType() const {
1174 return isDestructedTypeImpl(*this);
1175 }
1176
1177 /// Check if this is or contains a C union that is non-trivial to
1178 /// default-initialize, which is a union that has a member that is non-trivial
1179 /// to default-initialize. If this returns true,
1180 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1181 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1182
1183 /// Check if this is or contains a C union that is non-trivial to destruct,
1184 /// which is a union that has a member that is non-trivial to destruct. If
1185 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1186 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1187
1188 /// Check if this is or contains a C union that is non-trivial to copy, which
1189 /// is a union that has a member that is non-trivial to copy. If this returns
1190 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1191 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1192
1193 /// Determine whether expressions of the given type are forbidden
1194 /// from being lvalues in C.
1195 ///
1196 /// The expression types that are forbidden to be lvalues are:
1197 /// - 'void', but not qualified void
1198 /// - function types
1199 ///
1200 /// The exact rule here is C99 6.3.2.1:
1201 /// An lvalue is an expression with an object type or an incomplete
1202 /// type other than void.
1203 bool isCForbiddenLValueType() const;
1204
1205 /// Substitute type arguments for the Objective-C type parameters used in the
1206 /// subject type.
1207 ///
1208 /// \param ctx ASTContext in which the type exists.
1209 ///
1210 /// \param typeArgs The type arguments that will be substituted for the
1211 /// Objective-C type parameters in the subject type, which are generally
1212 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1213 /// parameters will be replaced with their bounds or id/Class, as appropriate
1214 /// for the context.
1215 ///
1216 /// \param context The context in which the subject type was written.
1217 ///
1218 /// \returns the resulting type.
1219 QualType substObjCTypeArgs(ASTContext &ctx,
1220 ArrayRef<QualType> typeArgs,
1221 ObjCSubstitutionContext context) const;
1222
1223 /// Substitute type arguments from an object type for the Objective-C type
1224 /// parameters used in the subject type.
1225 ///
1226 /// This operation combines the computation of type arguments for
1227 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1228 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1229 /// callers that need to perform a single substitution in isolation.
1230 ///
1231 /// \param objectType The type of the object whose member type we're
1232 /// substituting into. For example, this might be the receiver of a message
1233 /// or the base of a property access.
1234 ///
1235 /// \param dc The declaration context from which the subject type was
1236 /// retrieved, which indicates (for example) which type parameters should
1237 /// be substituted.
1238 ///
1239 /// \param context The context in which the subject type was written.
1240 ///
1241 /// \returns the subject type after replacing all of the Objective-C type
1242 /// parameters with their corresponding arguments.
1243 QualType substObjCMemberType(QualType objectType,
1244 const DeclContext *dc,
1245 ObjCSubstitutionContext context) const;
1246
1247 /// Strip Objective-C "__kindof" types from the given type.
1248 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1249
1250 /// Remove all qualifiers including _Atomic.
1251 QualType getAtomicUnqualifiedType() const;
1252
1253private:
1254 // These methods are implemented in a separate translation unit;
1255 // "static"-ize them to avoid creating temporary QualTypes in the
1256 // caller.
1257 static bool isConstant(QualType T, const ASTContext& Ctx);
1258 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1259 static SplitQualType getSplitDesugaredType(QualType T);
1260 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1261 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1262 const ASTContext &C);
1263 static QualType IgnoreParens(QualType T);
1264 static DestructionKind isDestructedTypeImpl(QualType type);
1265
1266 /// Check if \param RD is or contains a non-trivial C union.
1267 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1268 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1269 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1270};
1271
1272} // namespace clang
1273
1274namespace llvm {
1275
1276/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1277/// to a specific Type class.
1278template<> struct simplify_type< ::clang::QualType> {
1279 using SimpleType = const ::clang::Type *;
1280
1281 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1282 return Val.getTypePtr();
1283 }
1284};
1285
1286// Teach SmallPtrSet that QualType is "basically a pointer".
1287template<>
1288struct PointerLikeTypeTraits<clang::QualType> {
1289 static inline void *getAsVoidPointer(clang::QualType P) {
1290 return P.getAsOpaquePtr();
1291 }
1292
1293 static inline clang::QualType getFromVoidPointer(void *P) {
1294 return clang::QualType::getFromOpaquePtr(P);
1295 }
1296
1297 // Various qualifiers go in low bits.
1298 enum { NumLowBitsAvailable = 0 };
1299};
1300
1301} // namespace llvm
1302
1303namespace clang {
1304
1305/// Base class that is common to both the \c ExtQuals and \c Type
1306/// classes, which allows \c QualType to access the common fields between the
1307/// two.
1308class ExtQualsTypeCommonBase {
1309 friend class ExtQuals;
1310 friend class QualType;
1311 friend class Type;
1312
1313 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1314 /// a self-referential pointer (for \c Type).
1315 ///
1316 /// This pointer allows an efficient mapping from a QualType to its
1317 /// underlying type pointer.
1318 const Type *const BaseType;
1319
1320 /// The canonical type of this type. A QualType.
1321 QualType CanonicalType;
1322
1323 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1324 : BaseType(baseType), CanonicalType(canon) {}
1325};
1326
1327/// We can encode up to four bits in the low bits of a
1328/// type pointer, but there are many more type qualifiers that we want
1329/// to be able to apply to an arbitrary type. Therefore we have this
1330/// struct, intended to be heap-allocated and used by QualType to
1331/// store qualifiers.
1332///
1333/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1334/// in three low bits on the QualType pointer; a fourth bit records whether
1335/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1336/// Objective-C GC attributes) are much more rare.
1337class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1338 // NOTE: changing the fast qualifiers should be straightforward as
1339 // long as you don't make 'const' non-fast.
1340 // 1. Qualifiers:
1341 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1342 // Fast qualifiers must occupy the low-order bits.
1343 // b) Update Qualifiers::FastWidth and FastMask.
1344 // 2. QualType:
1345 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1346 // b) Update remove{Volatile,Restrict}, defined near the end of
1347 // this header.
1348 // 3. ASTContext:
1349 // a) Update get{Volatile,Restrict}Type.
1350
1351 /// The immutable set of qualifiers applied by this node. Always contains
1352 /// extended qualifiers.
1353 Qualifiers Quals;
1354
1355 ExtQuals *this_() { return this; }
1356
1357public:
1358 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1359 : ExtQualsTypeCommonBase(baseType,
1360 canon.isNull() ? QualType(this_(), 0) : canon),
1361 Quals(quals) {
1362 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1363, __PRETTY_FUNCTION__))
1363 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1363, __PRETTY_FUNCTION__))
;
1364 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
1365 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
;
1366 }
1367
1368 Qualifiers getQualifiers() const { return Quals; }
1369
1370 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1371 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1372
1373 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1374 Qualifiers::ObjCLifetime getObjCLifetime() const {
1375 return Quals.getObjCLifetime();
1376 }
1377
1378 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1379 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1380
1381 const Type *getBaseType() const { return BaseType; }
1382
1383public:
1384 void Profile(llvm::FoldingSetNodeID &ID) const {
1385 Profile(ID, getBaseType(), Quals);
1386 }
1387
1388 static void Profile(llvm::FoldingSetNodeID &ID,
1389 const Type *BaseType,
1390 Qualifiers Quals) {
1391 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1391, __PRETTY_FUNCTION__))
;
1392 ID.AddPointer(BaseType);
1393 Quals.Profile(ID);
1394 }
1395};
1396
1397/// The kind of C++11 ref-qualifier associated with a function type.
1398/// This determines whether a member function's "this" object can be an
1399/// lvalue, rvalue, or neither.
1400enum RefQualifierKind {
1401 /// No ref-qualifier was provided.
1402 RQ_None = 0,
1403
1404 /// An lvalue ref-qualifier was provided (\c &).
1405 RQ_LValue,
1406
1407 /// An rvalue ref-qualifier was provided (\c &&).
1408 RQ_RValue
1409};
1410
1411/// Which keyword(s) were used to create an AutoType.
1412enum class AutoTypeKeyword {
1413 /// auto
1414 Auto,
1415
1416 /// decltype(auto)
1417 DecltypeAuto,
1418
1419 /// __auto_type (GNU extension)
1420 GNUAutoType
1421};
1422
1423/// The base class of the type hierarchy.
1424///
1425/// A central concept with types is that each type always has a canonical
1426/// type. A canonical type is the type with any typedef names stripped out
1427/// of it or the types it references. For example, consider:
1428///
1429/// typedef int foo;
1430/// typedef foo* bar;
1431/// 'int *' 'foo *' 'bar'
1432///
1433/// There will be a Type object created for 'int'. Since int is canonical, its
1434/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1435/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1436/// there is a PointerType that represents 'int*', which, like 'int', is
1437/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1438/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1439/// is also 'int*'.
1440///
1441/// Non-canonical types are useful for emitting diagnostics, without losing
1442/// information about typedefs being used. Canonical types are useful for type
1443/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1444/// about whether something has a particular form (e.g. is a function type),
1445/// because they implicitly, recursively, strip all typedefs out of a type.
1446///
1447/// Types, once created, are immutable.
1448///
1449class alignas(8) Type : public ExtQualsTypeCommonBase {
1450public:
1451 enum TypeClass {
1452#define TYPE(Class, Base) Class,
1453#define LAST_TYPE(Class) TypeLast = Class
1454#define ABSTRACT_TYPE(Class, Base)
1455#include "clang/AST/TypeNodes.inc"
1456 };
1457
1458private:
1459 /// Bitfields required by the Type class.
1460 class TypeBitfields {
1461 friend class Type;
1462 template <class T> friend class TypePropertyCache;
1463
1464 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1465 unsigned TC : 8;
1466
1467 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1468 unsigned Dependent : 1;
1469
1470 /// Whether this type somehow involves a template parameter, even
1471 /// if the resolution of the type does not depend on a template parameter.
1472 unsigned InstantiationDependent : 1;
1473
1474 /// Whether this type is a variably-modified type (C99 6.7.5).
1475 unsigned VariablyModified : 1;
1476
1477 /// Whether this type contains an unexpanded parameter pack
1478 /// (for C++11 variadic templates).
1479 unsigned ContainsUnexpandedParameterPack : 1;
1480
1481 /// True if the cache (i.e. the bitfields here starting with
1482 /// 'Cache') is valid.
1483 mutable unsigned CacheValid : 1;
1484
1485 /// Linkage of this type.
1486 mutable unsigned CachedLinkage : 3;
1487
1488 /// Whether this type involves and local or unnamed types.
1489 mutable unsigned CachedLocalOrUnnamed : 1;
1490
1491 /// Whether this type comes from an AST file.
1492 mutable unsigned FromAST : 1;
1493
1494 bool isCacheValid() const {
1495 return CacheValid;
1496 }
1497
1498 Linkage getLinkage() const {
1499 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1499, __PRETTY_FUNCTION__))
;
1500 return static_cast<Linkage>(CachedLinkage);
1501 }
1502
1503 bool hasLocalOrUnnamedType() const {
1504 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 1504, __PRETTY_FUNCTION__))
;
1505 return CachedLocalOrUnnamed;
1506 }
1507 };
1508 enum { NumTypeBits = 18 };
1509
1510protected:
1511 // These classes allow subclasses to somewhat cleanly pack bitfields
1512 // into Type.
1513
1514 class ArrayTypeBitfields {
1515 friend class ArrayType;
1516
1517 unsigned : NumTypeBits;
1518
1519 /// CVR qualifiers from declarations like
1520 /// 'int X[static restrict 4]'. For function parameters only.
1521 unsigned IndexTypeQuals : 3;
1522
1523 /// Storage class qualifiers from declarations like
1524 /// 'int X[static restrict 4]'. For function parameters only.
1525 /// Actually an ArrayType::ArraySizeModifier.
1526 unsigned SizeModifier : 3;
1527 };
1528
1529 class ConstantArrayTypeBitfields {
1530 friend class ConstantArrayType;
1531
1532 unsigned : NumTypeBits + 3 + 3;
1533
1534 /// Whether we have a stored size expression.
1535 unsigned HasStoredSizeExpr : 1;
1536 };
1537
1538 class BuiltinTypeBitfields {
1539 friend class BuiltinType;
1540
1541 unsigned : NumTypeBits;
1542
1543 /// The kind (BuiltinType::Kind) of builtin type this is.
1544 unsigned Kind : 8;
1545 };
1546
1547 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1548 /// Only common bits are stored here. Additional uncommon bits are stored
1549 /// in a trailing object after FunctionProtoType.
1550 class FunctionTypeBitfields {
1551 friend class FunctionProtoType;
1552 friend class FunctionType;
1553
1554 unsigned : NumTypeBits;
1555
1556 /// Extra information which affects how the function is called, like
1557 /// regparm and the calling convention.
1558 unsigned ExtInfo : 12;
1559
1560 /// The ref-qualifier associated with a \c FunctionProtoType.
1561 ///
1562 /// This is a value of type \c RefQualifierKind.
1563 unsigned RefQualifier : 2;
1564
1565 /// Used only by FunctionProtoType, put here to pack with the
1566 /// other bitfields.
1567 /// The qualifiers are part of FunctionProtoType because...
1568 ///
1569 /// C++ 8.3.5p4: The return type, the parameter type list and the
1570 /// cv-qualifier-seq, [...], are part of the function type.
1571 unsigned FastTypeQuals : Qualifiers::FastWidth;
1572 /// Whether this function has extended Qualifiers.
1573 unsigned HasExtQuals : 1;
1574
1575 /// The number of parameters this function has, not counting '...'.
1576 /// According to [implimits] 8 bits should be enough here but this is
1577 /// somewhat easy to exceed with metaprogramming and so we would like to
1578 /// keep NumParams as wide as reasonably possible.
1579 unsigned NumParams : 16;
1580
1581 /// The type of exception specification this function has.
1582 unsigned ExceptionSpecType : 4;
1583
1584 /// Whether this function has extended parameter information.
1585 unsigned HasExtParameterInfos : 1;
1586
1587 /// Whether the function is variadic.
1588 unsigned Variadic : 1;
1589
1590 /// Whether this function has a trailing return type.
1591 unsigned HasTrailingReturn : 1;
1592 };
1593
1594 class ObjCObjectTypeBitfields {
1595 friend class ObjCObjectType;
1596
1597 unsigned : NumTypeBits;
1598
1599 /// The number of type arguments stored directly on this object type.
1600 unsigned NumTypeArgs : 7;
1601
1602 /// The number of protocols stored directly on this object type.
1603 unsigned NumProtocols : 6;
1604
1605 /// Whether this is a "kindof" type.
1606 unsigned IsKindOf : 1;
1607 };
1608
1609 class ReferenceTypeBitfields {
1610 friend class ReferenceType;
1611
1612 unsigned : NumTypeBits;
1613
1614 /// True if the type was originally spelled with an lvalue sigil.
1615 /// This is never true of rvalue references but can also be false
1616 /// on lvalue references because of C++0x [dcl.typedef]p9,
1617 /// as follows:
1618 ///
1619 /// typedef int &ref; // lvalue, spelled lvalue
1620 /// typedef int &&rvref; // rvalue
1621 /// ref &a; // lvalue, inner ref, spelled lvalue
1622 /// ref &&a; // lvalue, inner ref
1623 /// rvref &a; // lvalue, inner ref, spelled lvalue
1624 /// rvref &&a; // rvalue, inner ref
1625 unsigned SpelledAsLValue : 1;
1626
1627 /// True if the inner type is a reference type. This only happens
1628 /// in non-canonical forms.
1629 unsigned InnerRef : 1;
1630 };
1631
1632 class TypeWithKeywordBitfields {
1633 friend class TypeWithKeyword;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1638 unsigned Keyword : 8;
1639 };
1640
1641 enum { NumTypeWithKeywordBits = 8 };
1642
1643 class ElaboratedTypeBitfields {
1644 friend class ElaboratedType;
1645
1646 unsigned : NumTypeBits;
1647 unsigned : NumTypeWithKeywordBits;
1648
1649 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1650 unsigned HasOwnedTagDecl : 1;
1651 };
1652
1653 class VectorTypeBitfields {
1654 friend class VectorType;
1655 friend class DependentVectorType;
1656
1657 unsigned : NumTypeBits;
1658
1659 /// The kind of vector, either a generic vector type or some
1660 /// target-specific vector type such as for AltiVec or Neon.
1661 unsigned VecKind : 3;
1662
1663 /// The number of elements in the vector.
1664 unsigned NumElements : 29 - NumTypeBits;
1665
1666 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1667 };
1668
1669 class AttributedTypeBitfields {
1670 friend class AttributedType;
1671
1672 unsigned : NumTypeBits;
1673
1674 /// An AttributedType::Kind
1675 unsigned AttrKind : 32 - NumTypeBits;
1676 };
1677
1678 class AutoTypeBitfields {
1679 friend class AutoType;
1680
1681 unsigned : NumTypeBits;
1682
1683 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1684 /// or '__auto_type'? AutoTypeKeyword value.
1685 unsigned Keyword : 2;
1686 };
1687
1688 class SubstTemplateTypeParmPackTypeBitfields {
1689 friend class SubstTemplateTypeParmPackType;
1690
1691 unsigned : NumTypeBits;
1692
1693 /// The number of template arguments in \c Arguments, which is
1694 /// expected to be able to hold at least 1024 according to [implimits].
1695 /// However as this limit is somewhat easy to hit with template
1696 /// metaprogramming we'd prefer to keep it as large as possible.
1697 /// At the moment it has been left as a non-bitfield since this type
1698 /// safely fits in 64 bits as an unsigned, so there is no reason to
1699 /// introduce the performance impact of a bitfield.
1700 unsigned NumArgs;
1701 };
1702
1703 class TemplateSpecializationTypeBitfields {
1704 friend class TemplateSpecializationType;
1705
1706 unsigned : NumTypeBits;
1707
1708 /// Whether this template specialization type is a substituted type alias.
1709 unsigned TypeAlias : 1;
1710
1711 /// The number of template arguments named in this class template
1712 /// specialization, which is expected to be able to hold at least 1024
1713 /// according to [implimits]. However, as this limit is somewhat easy to
1714 /// hit with template metaprogramming we'd prefer to keep it as large
1715 /// as possible. At the moment it has been left as a non-bitfield since
1716 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1717 /// to introduce the performance impact of a bitfield.
1718 unsigned NumArgs;
1719 };
1720
1721 class DependentTemplateSpecializationTypeBitfields {
1722 friend class DependentTemplateSpecializationType;
1723
1724 unsigned : NumTypeBits;
1725 unsigned : NumTypeWithKeywordBits;
1726
1727 /// The number of template arguments named in this class template
1728 /// specialization, which is expected to be able to hold at least 1024
1729 /// according to [implimits]. However, as this limit is somewhat easy to
1730 /// hit with template metaprogramming we'd prefer to keep it as large
1731 /// as possible. At the moment it has been left as a non-bitfield since
1732 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1733 /// to introduce the performance impact of a bitfield.
1734 unsigned NumArgs;
1735 };
1736
1737 class PackExpansionTypeBitfields {
1738 friend class PackExpansionType;
1739
1740 unsigned : NumTypeBits;
1741
1742 /// The number of expansions that this pack expansion will
1743 /// generate when substituted (+1), which is expected to be able to
1744 /// hold at least 1024 according to [implimits]. However, as this limit
1745 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1746 /// keep it as large as possible. At the moment it has been left as a
1747 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1748 /// there is no reason to introduce the performance impact of a bitfield.
1749 ///
1750 /// This field will only have a non-zero value when some of the parameter
1751 /// packs that occur within the pattern have been substituted but others
1752 /// have not.
1753 unsigned NumExpansions;
1754 };
1755
1756 union {
1757 TypeBitfields TypeBits;
1758 ArrayTypeBitfields ArrayTypeBits;
1759 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1760 AttributedTypeBitfields AttributedTypeBits;
1761 AutoTypeBitfields AutoTypeBits;
1762 BuiltinTypeBitfields BuiltinTypeBits;
1763 FunctionTypeBitfields FunctionTypeBits;
1764 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1765 ReferenceTypeBitfields ReferenceTypeBits;
1766 TypeWithKeywordBitfields TypeWithKeywordBits;
1767 ElaboratedTypeBitfields ElaboratedTypeBits;
1768 VectorTypeBitfields VectorTypeBits;
1769 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1770 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1771 DependentTemplateSpecializationTypeBitfields
1772 DependentTemplateSpecializationTypeBits;
1773 PackExpansionTypeBitfields PackExpansionTypeBits;
1774
1775 static_assert(sizeof(TypeBitfields) <= 8,
1776 "TypeBitfields is larger than 8 bytes!");
1777 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1778 "ArrayTypeBitfields is larger than 8 bytes!");
1779 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1780 "AttributedTypeBitfields is larger than 8 bytes!");
1781 static_assert(sizeof(AutoTypeBitfields) <= 8,
1782 "AutoTypeBitfields is larger than 8 bytes!");
1783 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1784 "BuiltinTypeBitfields is larger than 8 bytes!");
1785 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1786 "FunctionTypeBitfields is larger than 8 bytes!");
1787 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1788 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1789 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1790 "ReferenceTypeBitfields is larger than 8 bytes!");
1791 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1792 "TypeWithKeywordBitfields is larger than 8 bytes!");
1793 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1794 "ElaboratedTypeBitfields is larger than 8 bytes!");
1795 static_assert(sizeof(VectorTypeBitfields) <= 8,
1796 "VectorTypeBitfields is larger than 8 bytes!");
1797 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1798 "SubstTemplateTypeParmPackTypeBitfields is larger"
1799 " than 8 bytes!");
1800 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1801 "TemplateSpecializationTypeBitfields is larger"
1802 " than 8 bytes!");
1803 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1804 "DependentTemplateSpecializationTypeBitfields is larger"
1805 " than 8 bytes!");
1806 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1807 "PackExpansionTypeBitfields is larger than 8 bytes");
1808 };
1809
1810private:
1811 template <class T> friend class TypePropertyCache;
1812
1813 /// Set whether this type comes from an AST file.
1814 void setFromAST(bool V = true) const {
1815 TypeBits.FromAST = V;
1816 }
1817
1818protected:
1819 friend class ASTContext;
1820
1821 Type(TypeClass tc, QualType canon, bool Dependent,
1822 bool InstantiationDependent, bool VariablyModified,
1823 bool ContainsUnexpandedParameterPack)
1824 : ExtQualsTypeCommonBase(this,
1825 canon.isNull() ? QualType(this_(), 0) : canon) {
1826 TypeBits.TC = tc;
1827 TypeBits.Dependent = Dependent;
1828 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1829 TypeBits.VariablyModified = VariablyModified;
1830 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1831 TypeBits.CacheValid = false;
1832 TypeBits.CachedLocalOrUnnamed = false;
1833 TypeBits.CachedLinkage = NoLinkage;
1834 TypeBits.FromAST = false;
1835 }
1836
1837 // silence VC++ warning C4355: 'this' : used in base member initializer list
1838 Type *this_() { return this; }
1839
1840 void setDependent(bool D = true) {
1841 TypeBits.Dependent = D;
1842 if (D)
1843 TypeBits.InstantiationDependent = true;
1844 }
1845
1846 void setInstantiationDependent(bool D = true) {
1847 TypeBits.InstantiationDependent = D; }
1848
1849 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1850
1851 void setContainsUnexpandedParameterPack(bool PP = true) {
1852 TypeBits.ContainsUnexpandedParameterPack = PP;
1853 }
1854
1855public:
1856 friend class ASTReader;
1857 friend class ASTWriter;
1858 template <class T> friend class serialization::AbstractTypeReader;
1859 template <class T> friend class serialization::AbstractTypeWriter;
1860
1861 Type(const Type &) = delete;
1862 Type(Type &&) = delete;
1863 Type &operator=(const Type &) = delete;
1864 Type &operator=(Type &&) = delete;
1865
1866 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1867
1868 /// Whether this type comes from an AST file.
1869 bool isFromAST() const { return TypeBits.FromAST; }
1870
1871 /// Whether this type is or contains an unexpanded parameter
1872 /// pack, used to support C++0x variadic templates.
1873 ///
1874 /// A type that contains a parameter pack shall be expanded by the
1875 /// ellipsis operator at some point. For example, the typedef in the
1876 /// following example contains an unexpanded parameter pack 'T':
1877 ///
1878 /// \code
1879 /// template<typename ...T>
1880 /// struct X {
1881 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1882 /// };
1883 /// \endcode
1884 ///
1885 /// Note that this routine does not specify which
1886 bool containsUnexpandedParameterPack() const {
1887 return TypeBits.ContainsUnexpandedParameterPack;
1888 }
1889
1890 /// Determines if this type would be canonical if it had no further
1891 /// qualification.
1892 bool isCanonicalUnqualified() const {
1893 return CanonicalType == QualType(this, 0);
1894 }
1895
1896 /// Pull a single level of sugar off of this locally-unqualified type.
1897 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1898 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1899 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1900
1901 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1902 /// object types, function types, and incomplete types.
1903
1904 /// Return true if this is an incomplete type.
1905 /// A type that can describe objects, but which lacks information needed to
1906 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1907 /// routine will need to determine if the size is actually required.
1908 ///
1909 /// Def If non-null, and the type refers to some kind of declaration
1910 /// that can be completed (such as a C struct, C++ class, or Objective-C
1911 /// class), will be set to the declaration.
1912 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1913
1914 /// Return true if this is an incomplete or object
1915 /// type, in other words, not a function type.
1916 bool isIncompleteOrObjectType() const {
1917 return !isFunctionType();
1918 }
1919
1920 /// Determine whether this type is an object type.
1921 bool isObjectType() const {
1922 // C++ [basic.types]p8:
1923 // An object type is a (possibly cv-qualified) type that is not a
1924 // function type, not a reference type, and not a void type.
1925 return !isReferenceType() && !isFunctionType() && !isVoidType();
1926 }
1927
1928 /// Return true if this is a literal type
1929 /// (C++11 [basic.types]p10)
1930 bool isLiteralType(const ASTContext &Ctx) const;
1931
1932 /// Test if this type is a standard-layout type.
1933 /// (C++0x [basic.type]p9)
1934 bool isStandardLayoutType() const;
1935
1936 /// Helper methods to distinguish type categories. All type predicates
1937 /// operate on the canonical type, ignoring typedefs and qualifiers.
1938
1939 /// Returns true if the type is a builtin type.
1940 bool isBuiltinType() const;
1941
1942 /// Test for a particular builtin type.
1943 bool isSpecificBuiltinType(unsigned K) const;
1944
1945 /// Test for a type which does not represent an actual type-system type but
1946 /// is instead used as a placeholder for various convenient purposes within
1947 /// Clang. All such types are BuiltinTypes.
1948 bool isPlaceholderType() const;
1949 const BuiltinType *getAsPlaceholderType() const;
1950
1951 /// Test for a specific placeholder type.
1952 bool isSpecificPlaceholderType(unsigned K) const;
1953
1954 /// Test for a placeholder type other than Overload; see
1955 /// BuiltinType::isNonOverloadPlaceholderType.
1956 bool isNonOverloadPlaceholderType() const;
1957
1958 /// isIntegerType() does *not* include complex integers (a GCC extension).
1959 /// isComplexIntegerType() can be used to test for complex integers.
1960 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1961 bool isEnumeralType() const;
1962
1963 /// Determine whether this type is a scoped enumeration type.
1964 bool isScopedEnumeralType() const;
1965 bool isBooleanType() const;
1966 bool isCharType() const;
1967 bool isWideCharType() const;
1968 bool isChar8Type() const;
1969 bool isChar16Type() const;
1970 bool isChar32Type() const;
1971 bool isAnyCharacterType() const;
1972 bool isIntegralType(const ASTContext &Ctx) const;
1973
1974 /// Determine whether this type is an integral or enumeration type.
1975 bool isIntegralOrEnumerationType() const;
1976
1977 /// Determine whether this type is an integral or unscoped enumeration type.
1978 bool isIntegralOrUnscopedEnumerationType() const;
1979 bool isUnscopedEnumerationType() const;
1980
1981 /// Floating point categories.
1982 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1983 /// isComplexType() does *not* include complex integers (a GCC extension).
1984 /// isComplexIntegerType() can be used to test for complex integers.
1985 bool isComplexType() const; // C99 6.2.5p11 (complex)
1986 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1987 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1988 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1989 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1990 bool isFloat128Type() const;
1991 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1992 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1993 bool isVoidType() const; // C99 6.2.5p19
1994 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1995 bool isAggregateType() const;
1996 bool isFundamentalType() const;
1997 bool isCompoundType() const;
1998
1999 // Type Predicates: Check to see if this type is structurally the specified
2000 // type, ignoring typedefs and qualifiers.
2001 bool isFunctionType() const;
2002 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2003 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2004 bool isPointerType() const;
2005 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2006 bool isBlockPointerType() const;
2007 bool isVoidPointerType() const;
2008 bool isReferenceType() const;
2009 bool isLValueReferenceType() const;
2010 bool isRValueReferenceType() const;
2011 bool isObjectPointerType() const;
2012 bool isFunctionPointerType() const;
2013 bool isFunctionReferenceType() const;
2014 bool isMemberPointerType() const;
2015 bool isMemberFunctionPointerType() const;
2016 bool isMemberDataPointerType() const;
2017 bool isArrayType() const;
2018 bool isConstantArrayType() const;
2019 bool isIncompleteArrayType() const;
2020 bool isVariableArrayType() const;
2021 bool isDependentSizedArrayType() const;
2022 bool isRecordType() const;
2023 bool isClassType() const;
2024 bool isStructureType() const;
2025 bool isObjCBoxableRecordType() const;
2026 bool isInterfaceType() const;
2027 bool isStructureOrClassType() const;
2028 bool isUnionType() const;
2029 bool isComplexIntegerType() const; // GCC _Complex integer type.
2030 bool isVectorType() const; // GCC vector type.
2031 bool isExtVectorType() const; // Extended vector type.
2032 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2033 bool isObjCObjectPointerType() const; // pointer to ObjC object
2034 bool isObjCRetainableType() const; // ObjC object or block pointer
2035 bool isObjCLifetimeType() const; // (array of)* retainable type
2036 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2037 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2038 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2039 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2040 // for the common case.
2041 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2042 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2043 bool isObjCQualifiedIdType() const; // id<foo>
2044 bool isObjCQualifiedClassType() const; // Class<foo>
2045 bool isObjCObjectOrInterfaceType() const;
2046 bool isObjCIdType() const; // id
2047 bool isDecltypeType() const;
2048 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2049 /// qualifier?
2050 ///
2051 /// This approximates the answer to the following question: if this
2052 /// translation unit were compiled in ARC, would this type be qualified
2053 /// with __unsafe_unretained?
2054 bool isObjCInertUnsafeUnretainedType() const {
2055 return hasAttr(attr::ObjCInertUnsafeUnretained);
2056 }
2057
2058 /// Whether the type is Objective-C 'id' or a __kindof type of an
2059 /// object type, e.g., __kindof NSView * or __kindof id
2060 /// <NSCopying>.
2061 ///
2062 /// \param bound Will be set to the bound on non-id subtype types,
2063 /// which will be (possibly specialized) Objective-C class type, or
2064 /// null for 'id.
2065 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2066 const ObjCObjectType *&bound) const;
2067
2068 bool isObjCClassType() const; // Class
2069
2070 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2071 /// Class type, e.g., __kindof Class <NSCopying>.
2072 ///
2073 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2074 /// here because Objective-C's type system cannot express "a class
2075 /// object for a subclass of NSFoo".
2076 bool isObjCClassOrClassKindOfType() const;
2077
2078 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2079 bool isObjCSelType() const; // Class
2080 bool isObjCBuiltinType() const; // 'id' or 'Class'
2081 bool isObjCARCBridgableType() const;
2082 bool isCARCBridgableType() const;
2083 bool isTemplateTypeParmType() const; // C++ template type parameter
2084 bool isNullPtrType() const; // C++11 std::nullptr_t
2085 bool isNothrowT() const; // C++ std::nothrow_t
2086 bool isAlignValT() const; // C++17 std::align_val_t
2087 bool isStdByteType() const; // C++17 std::byte
2088 bool isAtomicType() const; // C11 _Atomic()
2089 bool isUndeducedAutoType() const; // C++11 auto or
2090 // C++14 decltype(auto)
2091
2092#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2093 bool is##Id##Type() const;
2094#include "clang/Basic/OpenCLImageTypes.def"
2095
2096 bool isImageType() const; // Any OpenCL image type
2097
2098 bool isSamplerT() const; // OpenCL sampler_t
2099 bool isEventT() const; // OpenCL event_t
2100 bool isClkEventT() const; // OpenCL clk_event_t
2101 bool isQueueT() const; // OpenCL queue_t
2102 bool isReserveIDT() const; // OpenCL reserve_id_t
2103
2104#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2105 bool is##Id##Type() const;
2106#include "clang/Basic/OpenCLExtensionTypes.def"
2107 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2108 bool isOCLIntelSubgroupAVCType() const;
2109 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2110
2111 bool isPipeType() const; // OpenCL pipe type
2112 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2113
2114 /// Determines if this type, which must satisfy
2115 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2116 /// than implicitly __strong.
2117 bool isObjCARCImplicitlyUnretainedType() const;
2118
2119 /// Return the implicit lifetime for this type, which must not be dependent.
2120 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2121
2122 enum ScalarTypeKind {
2123 STK_CPointer,
2124 STK_BlockPointer,
2125 STK_ObjCObjectPointer,
2126 STK_MemberPointer,
2127 STK_Bool,
2128 STK_Integral,
2129 STK_Floating,
2130 STK_IntegralComplex,
2131 STK_FloatingComplex,
2132 STK_FixedPoint
2133 };
2134
2135 /// Given that this is a scalar type, classify it.
2136 ScalarTypeKind getScalarTypeKind() const;
2137
2138 /// Whether this type is a dependent type, meaning that its definition
2139 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2140 bool isDependentType() const { return TypeBits.Dependent; }
2141
2142 /// Determine whether this type is an instantiation-dependent type,
2143 /// meaning that the type involves a template parameter (even if the
2144 /// definition does not actually depend on the type substituted for that
2145 /// template parameter).
2146 bool isInstantiationDependentType() const {
2147 return TypeBits.InstantiationDependent;
2148 }
2149
2150 /// Determine whether this type is an undeduced type, meaning that
2151 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2152 /// deduced.
2153 bool isUndeducedType() const;
2154
2155 /// Whether this type is a variably-modified type (C99 6.7.5).
2156 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2157
2158 /// Whether this type involves a variable-length array type
2159 /// with a definite size.
2160 bool hasSizedVLAType() const;
2161
2162 /// Whether this type is or contains a local or unnamed type.
2163 bool hasUnnamedOrLocalType() const;
2164
2165 bool isOverloadableType() const;
2166
2167 /// Determine wither this type is a C++ elaborated-type-specifier.
2168 bool isElaboratedTypeSpecifier() const;
2169
2170 bool canDecayToPointerType() const;
2171
2172 /// Whether this type is represented natively as a pointer. This includes
2173 /// pointers, references, block pointers, and Objective-C interface,
2174 /// qualified id, and qualified interface types, as well as nullptr_t.
2175 bool hasPointerRepresentation() const;
2176
2177 /// Whether this type can represent an objective pointer type for the
2178 /// purpose of GC'ability
2179 bool hasObjCPointerRepresentation() const;
2180
2181 /// Determine whether this type has an integer representation
2182 /// of some sort, e.g., it is an integer type or a vector.
2183 bool hasIntegerRepresentation() const;
2184
2185 /// Determine whether this type has an signed integer representation
2186 /// of some sort, e.g., it is an signed integer type or a vector.
2187 bool hasSignedIntegerRepresentation() const;
2188
2189 /// Determine whether this type has an unsigned integer representation
2190 /// of some sort, e.g., it is an unsigned integer type or a vector.
2191 bool hasUnsignedIntegerRepresentation() const;
2192
2193 /// Determine whether this type has a floating-point representation
2194 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2195 bool hasFloatingRepresentation() const;
2196
2197 // Type Checking Functions: Check to see if this type is structurally the
2198 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2199 // the best type we can.
2200 const RecordType *getAsStructureType() const;
2201 /// NOTE: getAs*ArrayType are methods on ASTContext.
2202 const RecordType *getAsUnionType() const;
2203 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2204 const ObjCObjectType *getAsObjCInterfaceType() const;
2205
2206 // The following is a convenience method that returns an ObjCObjectPointerType
2207 // for object declared using an interface.
2208 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2209 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2210 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2211 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2212
2213 /// Retrieves the CXXRecordDecl that this type refers to, either
2214 /// because the type is a RecordType or because it is the injected-class-name
2215 /// type of a class template or class template partial specialization.
2216 CXXRecordDecl *getAsCXXRecordDecl() const;
2217
2218 /// Retrieves the RecordDecl this type refers to.
2219 RecordDecl *getAsRecordDecl() const;
2220
2221 /// Retrieves the TagDecl that this type refers to, either
2222 /// because the type is a TagType or because it is the injected-class-name
2223 /// type of a class template or class template partial specialization.
2224 TagDecl *getAsTagDecl() const;
2225
2226 /// If this is a pointer or reference to a RecordType, return the
2227 /// CXXRecordDecl that the type refers to.
2228 ///
2229 /// If this is not a pointer or reference, or the type being pointed to does
2230 /// not refer to a CXXRecordDecl, returns NULL.
2231 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2232
2233 /// Get the DeducedType whose type will be deduced for a variable with
2234 /// an initializer of this type. This looks through declarators like pointer
2235 /// types, but not through decltype or typedefs.
2236 DeducedType *getContainedDeducedType() const;
2237
2238 /// Get the AutoType whose type will be deduced for a variable with
2239 /// an initializer of this type. This looks through declarators like pointer
2240 /// types, but not through decltype or typedefs.
2241 AutoType *getContainedAutoType() const {
2242 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2243 }
2244
2245 /// Determine whether this type was written with a leading 'auto'
2246 /// corresponding to a trailing return type (possibly for a nested
2247 /// function type within a pointer to function type or similar).
2248 bool hasAutoForTrailingReturnType() const;
2249
2250 /// Member-template getAs<specific type>'. Look through sugar for
2251 /// an instance of \<specific type>. This scheme will eventually
2252 /// replace the specific getAsXXXX methods above.
2253 ///
2254 /// There are some specializations of this member template listed
2255 /// immediately following this class.
2256 template <typename T> const T *getAs() const;
2257
2258 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2259 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2260 /// This is used when you need to walk over sugar nodes that represent some
2261 /// kind of type adjustment from a type that was written as a \<specific type>
2262 /// to another type that is still canonically a \<specific type>.
2263 template <typename T> const T *getAsAdjusted() const;
2264
2265 /// A variant of getAs<> for array types which silently discards
2266 /// qualifiers from the outermost type.
2267 const ArrayType *getAsArrayTypeUnsafe() const;
2268
2269 /// Member-template castAs<specific type>. Look through sugar for
2270 /// the underlying instance of \<specific type>.
2271 ///
2272 /// This method has the same relationship to getAs<T> as cast<T> has
2273 /// to dyn_cast<T>; which is to say, the underlying type *must*
2274 /// have the intended type, and this method will never return null.
2275 template <typename T> const T *castAs() const;
2276
2277 /// A variant of castAs<> for array type which silently discards
2278 /// qualifiers from the outermost type.
2279 const ArrayType *castAsArrayTypeUnsafe() const;
2280
2281 /// Determine whether this type had the specified attribute applied to it
2282 /// (looking through top-level type sugar).
2283 bool hasAttr(attr::Kind AK) const;
2284
2285 /// Get the base element type of this type, potentially discarding type
2286 /// qualifiers. This should never be used when type qualifiers
2287 /// are meaningful.
2288 const Type *getBaseElementTypeUnsafe() const;
2289
2290 /// If this is an array type, return the element type of the array,
2291 /// potentially with type qualifiers missing.
2292 /// This should never be used when type qualifiers are meaningful.
2293 const Type *getArrayElementTypeNoTypeQual() const;
2294
2295 /// If this is a pointer type, return the pointee type.
2296 /// If this is an array type, return the array element type.
2297 /// This should never be used when type qualifiers are meaningful.
2298 const Type *getPointeeOrArrayElementType() const;
2299
2300 /// If this is a pointer, ObjC object pointer, or block
2301 /// pointer, this returns the respective pointee.
2302 QualType getPointeeType() const;
2303
2304 /// Return the specified type with any "sugar" removed from the type,
2305 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2306 const Type *getUnqualifiedDesugaredType() const;
2307
2308 /// More type predicates useful for type checking/promotion
2309 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2310
2311 /// Return true if this is an integer type that is
2312 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2313 /// or an enum decl which has a signed representation.
2314 bool isSignedIntegerType() const;
2315
2316 /// Return true if this is an integer type that is
2317 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2318 /// or an enum decl which has an unsigned representation.
2319 bool isUnsignedIntegerType() const;
2320
2321 /// Determines whether this is an integer type that is signed or an
2322 /// enumeration types whose underlying type is a signed integer type.
2323 bool isSignedIntegerOrEnumerationType() const;
2324
2325 /// Determines whether this is an integer type that is unsigned or an
2326 /// enumeration types whose underlying type is a unsigned integer type.
2327 bool isUnsignedIntegerOrEnumerationType() const;
2328
2329 /// Return true if this is a fixed point type according to
2330 /// ISO/IEC JTC1 SC22 WG14 N1169.
2331 bool isFixedPointType() const;
2332
2333 /// Return true if this is a fixed point or integer type.
2334 bool isFixedPointOrIntegerType() const;
2335
2336 /// Return true if this is a saturated fixed point type according to
2337 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2338 bool isSaturatedFixedPointType() const;
2339
2340 /// Return true if this is a saturated fixed point type according to
2341 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2342 bool isUnsaturatedFixedPointType() const;
2343
2344 /// Return true if this is a fixed point type that is signed according
2345 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2346 bool isSignedFixedPointType() const;
2347
2348 /// Return true if this is a fixed point type that is unsigned according
2349 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2350 bool isUnsignedFixedPointType() const;
2351
2352 /// Return true if this is not a variable sized type,
2353 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2354 /// incomplete types.
2355 bool isConstantSizeType() const;
2356
2357 /// Returns true if this type can be represented by some
2358 /// set of type specifiers.
2359 bool isSpecifierType() const;
2360
2361 /// Determine the linkage of this type.
2362 Linkage getLinkage() const;
2363
2364 /// Determine the visibility of this type.
2365 Visibility getVisibility() const {
2366 return getLinkageAndVisibility().getVisibility();
2367 }
2368
2369 /// Return true if the visibility was explicitly set is the code.
2370 bool isVisibilityExplicit() const {
2371 return getLinkageAndVisibility().isVisibilityExplicit();
2372 }
2373
2374 /// Determine the linkage and visibility of this type.
2375 LinkageInfo getLinkageAndVisibility() const;
2376
2377 /// True if the computed linkage is valid. Used for consistency
2378 /// checking. Should always return true.
2379 bool isLinkageValid() const;
2380
2381 /// Determine the nullability of the given type.
2382 ///
2383 /// Note that nullability is only captured as sugar within the type
2384 /// system, not as part of the canonical type, so nullability will
2385 /// be lost by canonicalization and desugaring.
2386 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2387
2388 /// Determine whether the given type can have a nullability
2389 /// specifier applied to it, i.e., if it is any kind of pointer type.
2390 ///
2391 /// \param ResultIfUnknown The value to return if we don't yet know whether
2392 /// this type can have nullability because it is dependent.
2393 bool canHaveNullability(bool ResultIfUnknown = true) const;
2394
2395 /// Retrieve the set of substitutions required when accessing a member
2396 /// of the Objective-C receiver type that is declared in the given context.
2397 ///
2398 /// \c *this is the type of the object we're operating on, e.g., the
2399 /// receiver for a message send or the base of a property access, and is
2400 /// expected to be of some object or object pointer type.
2401 ///
2402 /// \param dc The declaration context for which we are building up a
2403 /// substitution mapping, which should be an Objective-C class, extension,
2404 /// category, or method within.
2405 ///
2406 /// \returns an array of type arguments that can be substituted for
2407 /// the type parameters of the given declaration context in any type described
2408 /// within that context, or an empty optional to indicate that no
2409 /// substitution is required.
2410 Optional<ArrayRef<QualType>>
2411 getObjCSubstitutions(const DeclContext *dc) const;
2412
2413 /// Determines if this is an ObjC interface type that may accept type
2414 /// parameters.
2415 bool acceptsObjCTypeParams() const;
2416
2417 const char *getTypeClassName() const;
2418
2419 QualType getCanonicalTypeInternal() const {
2420 return CanonicalType;
2421 }
2422
2423 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2424 void dump() const;
2425 void dump(llvm::raw_ostream &OS) const;
2426};
2427
2428/// This will check for a TypedefType by removing any existing sugar
2429/// until it reaches a TypedefType or a non-sugared type.
2430template <> const TypedefType *Type::getAs() const;
2431
2432/// This will check for a TemplateSpecializationType by removing any
2433/// existing sugar until it reaches a TemplateSpecializationType or a
2434/// non-sugared type.
2435template <> const TemplateSpecializationType *Type::getAs() const;
2436
2437/// This will check for an AttributedType by removing any existing sugar
2438/// until it reaches an AttributedType or a non-sugared type.
2439template <> const AttributedType *Type::getAs() const;
2440
2441// We can do canonical leaf types faster, because we don't have to
2442// worry about preserving child type decoration.
2443#define TYPE(Class, Base)
2444#define LEAF_TYPE(Class) \
2445template <> inline const Class##Type *Type::getAs() const { \
2446 return dyn_cast<Class##Type>(CanonicalType); \
2447} \
2448template <> inline const Class##Type *Type::castAs() const { \
2449 return cast<Class##Type>(CanonicalType); \
2450}
2451#include "clang/AST/TypeNodes.inc"
2452
2453/// This class is used for builtin types like 'int'. Builtin
2454/// types are always canonical and have a literal name field.
2455class BuiltinType : public Type {
2456public:
2457 enum Kind {
2458// OpenCL image types
2459#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2460#include "clang/Basic/OpenCLImageTypes.def"
2461// OpenCL extension types
2462#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2463#include "clang/Basic/OpenCLExtensionTypes.def"
2464// SVE Types
2465#define SVE_TYPE(Name, Id, SingletonId) Id,
2466#include "clang/Basic/AArch64SVEACLETypes.def"
2467// All other builtin types
2468#define BUILTIN_TYPE(Id, SingletonId) Id,
2469#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2470#include "clang/AST/BuiltinTypes.def"
2471 };
2472
2473private:
2474 friend class ASTContext; // ASTContext creates these.
2475
2476 BuiltinType(Kind K)
2477 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2478 /*InstantiationDependent=*/(K == Dependent),
2479 /*VariablyModified=*/false,
2480 /*Unexpanded parameter pack=*/false) {
2481 BuiltinTypeBits.Kind = K;
2482 }
2483
2484public:
2485 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2486 StringRef getName(const PrintingPolicy &Policy) const;
2487
2488 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2489 // The StringRef is null-terminated.
2490 StringRef str = getName(Policy);
2491 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 2491, __PRETTY_FUNCTION__))
;
2492 return str.data();
2493 }
2494
2495 bool isSugared() const { return false; }
2496 QualType desugar() const { return QualType(this, 0); }
2497
2498 bool isInteger() const {
2499 return getKind() >= Bool && getKind() <= Int128;
2500 }
2501
2502 bool isSignedInteger() const {
2503 return getKind() >= Char_S && getKind() <= Int128;
2504 }
2505
2506 bool isUnsignedInteger() const {
2507 return getKind() >= Bool && getKind() <= UInt128;
2508 }
2509
2510 bool isFloatingPoint() const {
2511 return getKind() >= Half && getKind() <= Float128;
2512 }
2513
2514 /// Determines whether the given kind corresponds to a placeholder type.
2515 static bool isPlaceholderTypeKind(Kind K) {
2516 return K >= Overload;
2517 }
2518
2519 /// Determines whether this type is a placeholder type, i.e. a type
2520 /// which cannot appear in arbitrary positions in a fully-formed
2521 /// expression.
2522 bool isPlaceholderType() const {
2523 return isPlaceholderTypeKind(getKind());
2524 }
2525
2526 /// Determines whether this type is a placeholder type other than
2527 /// Overload. Most placeholder types require only syntactic
2528 /// information about their context in order to be resolved (e.g.
2529 /// whether it is a call expression), which means they can (and
2530 /// should) be resolved in an earlier "phase" of analysis.
2531 /// Overload expressions sometimes pick up further information
2532 /// from their context, like whether the context expects a
2533 /// specific function-pointer type, and so frequently need
2534 /// special treatment.
2535 bool isNonOverloadPlaceholderType() const {
2536 return getKind() > Overload;
2537 }
2538
2539 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2540};
2541
2542/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2543/// types (_Complex float etc) as well as the GCC integer complex extensions.
2544class ComplexType : public Type, public llvm::FoldingSetNode {
2545 friend class ASTContext; // ASTContext creates these.
2546
2547 QualType ElementType;
2548
2549 ComplexType(QualType Element, QualType CanonicalPtr)
2550 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2551 Element->isInstantiationDependentType(),
2552 Element->isVariablyModifiedType(),
2553 Element->containsUnexpandedParameterPack()),
2554 ElementType(Element) {}
2555
2556public:
2557 QualType getElementType() const { return ElementType; }
2558
2559 bool isSugared() const { return false; }
2560 QualType desugar() const { return QualType(this, 0); }
2561
2562 void Profile(llvm::FoldingSetNodeID &ID) {
2563 Profile(ID, getElementType());
2564 }
2565
2566 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2567 ID.AddPointer(Element.getAsOpaquePtr());
2568 }
2569
2570 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2571};
2572
2573/// Sugar for parentheses used when specifying types.
2574class ParenType : public Type, public llvm::FoldingSetNode {
2575 friend class ASTContext; // ASTContext creates these.
2576
2577 QualType Inner;
2578
2579 ParenType(QualType InnerType, QualType CanonType)
2580 : Type(Paren, CanonType, InnerType->isDependentType(),
2581 InnerType->isInstantiationDependentType(),
2582 InnerType->isVariablyModifiedType(),
2583 InnerType->containsUnexpandedParameterPack()),
2584 Inner(InnerType) {}
2585
2586public:
2587 QualType getInnerType() const { return Inner; }
2588
2589 bool isSugared() const { return true; }
2590 QualType desugar() const { return getInnerType(); }
2591
2592 void Profile(llvm::FoldingSetNodeID &ID) {
2593 Profile(ID, getInnerType());
2594 }
2595
2596 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2597 Inner.Profile(ID);
2598 }
2599
2600 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2601};
2602
2603/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2604class PointerType : public Type, public llvm::FoldingSetNode {
2605 friend class ASTContext; // ASTContext creates these.
2606
2607 QualType PointeeType;
2608
2609 PointerType(QualType Pointee, QualType CanonicalPtr)
2610 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2611 Pointee->isInstantiationDependentType(),
2612 Pointee->isVariablyModifiedType(),
2613 Pointee->containsUnexpandedParameterPack()),
2614 PointeeType(Pointee) {}
2615
2616public:
2617 QualType getPointeeType() const { return PointeeType; }
2618
2619 /// Returns true if address spaces of pointers overlap.
2620 /// OpenCL v2.0 defines conversion rules for pointers to different
2621 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2622 /// address spaces.
2623 /// CL1.1 or CL1.2:
2624 /// address spaces overlap iff they are they same.
2625 /// CL2.0 adds:
2626 /// __generic overlaps with any address space except for __constant.
2627 bool isAddressSpaceOverlapping(const PointerType &other) const {
2628 Qualifiers thisQuals = PointeeType.getQualifiers();
2629 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2630 // Address spaces overlap if at least one of them is a superset of another
2631 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2632 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2633 }
2634
2635 bool isSugared() const { return false; }
2636 QualType desugar() const { return QualType(this, 0); }
2637
2638 void Profile(llvm::FoldingSetNodeID &ID) {
2639 Profile(ID, getPointeeType());
2640 }
2641
2642 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2643 ID.AddPointer(Pointee.getAsOpaquePtr());
2644 }
2645
2646 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2647};
2648
2649/// Represents a type which was implicitly adjusted by the semantic
2650/// engine for arbitrary reasons. For example, array and function types can
2651/// decay, and function types can have their calling conventions adjusted.
2652class AdjustedType : public Type, public llvm::FoldingSetNode {
2653 QualType OriginalTy;
2654 QualType AdjustedTy;
2655
2656protected:
2657 friend class ASTContext; // ASTContext creates these.
2658
2659 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2660 QualType CanonicalPtr)
2661 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2662 OriginalTy->isInstantiationDependentType(),
2663 OriginalTy->isVariablyModifiedType(),
2664 OriginalTy->containsUnexpandedParameterPack()),
2665 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2666
2667public:
2668 QualType getOriginalType() const { return OriginalTy; }
2669 QualType getAdjustedType() const { return AdjustedTy; }
2670
2671 bool isSugared() const { return true; }
2672 QualType desugar() const { return AdjustedTy; }
2673
2674 void Profile(llvm::FoldingSetNodeID &ID) {
2675 Profile(ID, OriginalTy, AdjustedTy);
2676 }
2677
2678 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2679 ID.AddPointer(Orig.getAsOpaquePtr());
2680 ID.AddPointer(New.getAsOpaquePtr());
2681 }
2682
2683 static bool classof(const Type *T) {
2684 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2685 }
2686};
2687
2688/// Represents a pointer type decayed from an array or function type.
2689class DecayedType : public AdjustedType {
2690 friend class ASTContext; // ASTContext creates these.
2691
2692 inline
2693 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2694
2695public:
2696 QualType getDecayedType() const { return getAdjustedType(); }
2697
2698 inline QualType getPointeeType() const;
2699
2700 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2701};
2702
2703/// Pointer to a block type.
2704/// This type is to represent types syntactically represented as
2705/// "void (^)(int)", etc. Pointee is required to always be a function type.
2706class BlockPointerType : public Type, public llvm::FoldingSetNode {
2707 friend class ASTContext; // ASTContext creates these.
2708
2709 // Block is some kind of pointer type
2710 QualType PointeeType;
2711
2712 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2713 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2714 Pointee->isInstantiationDependentType(),
2715 Pointee->isVariablyModifiedType(),
2716 Pointee->containsUnexpandedParameterPack()),
2717 PointeeType(Pointee) {}
2718
2719public:
2720 // Get the pointee type. Pointee is required to always be a function type.
2721 QualType getPointeeType() const { return PointeeType; }
2722
2723 bool isSugared() const { return false; }
2724 QualType desugar() const { return QualType(this, 0); }
2725
2726 void Profile(llvm::FoldingSetNodeID &ID) {
2727 Profile(ID, getPointeeType());
2728 }
2729
2730 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2731 ID.AddPointer(Pointee.getAsOpaquePtr());
2732 }
2733
2734 static bool classof(const Type *T) {
2735 return T->getTypeClass() == BlockPointer;
2736 }
2737};
2738
2739/// Base for LValueReferenceType and RValueReferenceType
2740class ReferenceType : public Type, public llvm::FoldingSetNode {
2741 QualType PointeeType;
2742
2743protected:
2744 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2745 bool SpelledAsLValue)
2746 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2747 Referencee->isInstantiationDependentType(),
2748 Referencee->isVariablyModifiedType(),
2749 Referencee->containsUnexpandedParameterPack()),
2750 PointeeType(Referencee) {
2751 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2752 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2753 }
2754
2755public:
2756 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2757 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2758
2759 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2760
2761 QualType getPointeeType() const {
2762 // FIXME: this might strip inner qualifiers; okay?
2763 const ReferenceType *T = this;
2764 while (T->isInnerRef())
2765 T = T->PointeeType->castAs<ReferenceType>();
2766 return T->PointeeType;
2767 }
2768
2769 void Profile(llvm::FoldingSetNodeID &ID) {
2770 Profile(ID, PointeeType, isSpelledAsLValue());
2771 }
2772
2773 static void Profile(llvm::FoldingSetNodeID &ID,
2774 QualType Referencee,
2775 bool SpelledAsLValue) {
2776 ID.AddPointer(Referencee.getAsOpaquePtr());
2777 ID.AddBoolean(SpelledAsLValue);
2778 }
2779
2780 static bool classof(const Type *T) {
2781 return T->getTypeClass() == LValueReference ||
2782 T->getTypeClass() == RValueReference;
2783 }
2784};
2785
2786/// An lvalue reference type, per C++11 [dcl.ref].
2787class LValueReferenceType : public ReferenceType {
2788 friend class ASTContext; // ASTContext creates these
2789
2790 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2791 bool SpelledAsLValue)
2792 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2793 SpelledAsLValue) {}
2794
2795public:
2796 bool isSugared() const { return false; }
2797 QualType desugar() const { return QualType(this, 0); }
2798
2799 static bool classof(const Type *T) {
2800 return T->getTypeClass() == LValueReference;
2801 }
2802};
2803
2804/// An rvalue reference type, per C++11 [dcl.ref].
2805class RValueReferenceType : public ReferenceType {
2806 friend class ASTContext; // ASTContext creates these
2807
2808 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2809 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2810
2811public:
2812 bool isSugared() const { return false; }
2813 QualType desugar() const { return QualType(this, 0); }
2814
2815 static bool classof(const Type *T) {
2816 return T->getTypeClass() == RValueReference;
2817 }
2818};
2819
2820/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2821///
2822/// This includes both pointers to data members and pointer to member functions.
2823class MemberPointerType : public Type, public llvm::FoldingSetNode {
2824 friend class ASTContext; // ASTContext creates these.
2825
2826 QualType PointeeType;
2827
2828 /// The class of which the pointee is a member. Must ultimately be a
2829 /// RecordType, but could be a typedef or a template parameter too.
2830 const Type *Class;
2831
2832 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2833 : Type(MemberPointer, CanonicalPtr,
2834 Cls->isDependentType() || Pointee->isDependentType(),
2835 (Cls->isInstantiationDependentType() ||
2836 Pointee->isInstantiationDependentType()),
2837 Pointee->isVariablyModifiedType(),
2838 (Cls->containsUnexpandedParameterPack() ||
2839 Pointee->containsUnexpandedParameterPack())),
2840 PointeeType(Pointee), Class(Cls) {}
2841
2842public:
2843 QualType getPointeeType() const { return PointeeType; }
2844
2845 /// Returns true if the member type (i.e. the pointee type) is a
2846 /// function type rather than a data-member type.
2847 bool isMemberFunctionPointer() const {
2848 return PointeeType->isFunctionProtoType();
2849 }
2850
2851 /// Returns true if the member type (i.e. the pointee type) is a
2852 /// data type rather than a function type.
2853 bool isMemberDataPointer() const {
2854 return !PointeeType->isFunctionProtoType();
2855 }
2856
2857 const Type *getClass() const { return Class; }
2858 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2859
2860 bool isSugared() const { return false; }
2861 QualType desugar() const { return QualType(this, 0); }
2862
2863 void Profile(llvm::FoldingSetNodeID &ID) {
2864 Profile(ID, getPointeeType(), getClass());
2865 }
2866
2867 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2868 const Type *Class) {
2869 ID.AddPointer(Pointee.getAsOpaquePtr());
2870 ID.AddPointer(Class);
2871 }
2872
2873 static bool classof(const Type *T) {
2874 return T->getTypeClass() == MemberPointer;
2875 }
2876};
2877
2878/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2879class ArrayType : public Type, public llvm::FoldingSetNode {
2880public:
2881 /// Capture whether this is a normal array (e.g. int X[4])
2882 /// an array with a static size (e.g. int X[static 4]), or an array
2883 /// with a star size (e.g. int X[*]).
2884 /// 'static' is only allowed on function parameters.
2885 enum ArraySizeModifier {
2886 Normal, Static, Star
2887 };
2888
2889private:
2890 /// The element type of the array.
2891 QualType ElementType;
2892
2893protected:
2894 friend class ASTContext; // ASTContext creates these.
2895
2896 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2897 unsigned tq, const Expr *sz = nullptr);
2898
2899public:
2900 QualType getElementType() const { return ElementType; }
2901
2902 ArraySizeModifier getSizeModifier() const {
2903 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2904 }
2905
2906 Qualifiers getIndexTypeQualifiers() const {
2907 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2908 }
2909
2910 unsigned getIndexTypeCVRQualifiers() const {
2911 return ArrayTypeBits.IndexTypeQuals;
2912 }
2913
2914 static bool classof(const Type *T) {
2915 return T->getTypeClass() == ConstantArray ||
2916 T->getTypeClass() == VariableArray ||
2917 T->getTypeClass() == IncompleteArray ||
2918 T->getTypeClass() == DependentSizedArray;
2919 }
2920};
2921
2922/// Represents the canonical version of C arrays with a specified constant size.
2923/// For example, the canonical type for 'int A[4 + 4*100]' is a
2924/// ConstantArrayType where the element type is 'int' and the size is 404.
2925class ConstantArrayType final
2926 : public ArrayType,
2927 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2928 friend class ASTContext; // ASTContext creates these.
2929 friend TrailingObjects;
2930
2931 llvm::APInt Size; // Allows us to unique the type.
2932
2933 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2934 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2935 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2936 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2937 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2938 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 2938, __PRETTY_FUNCTION__))
;
2939 *getTrailingObjects<const Expr*>() = sz;
2940 }
2941 }
2942
2943 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2944 return ConstantArrayTypeBits.HasStoredSizeExpr;
2945 }
2946
2947public:
2948 const llvm::APInt &getSize() const { return Size; }
2949 const Expr *getSizeExpr() const {
2950 return ConstantArrayTypeBits.HasStoredSizeExpr
2951 ? *getTrailingObjects<const Expr *>()
2952 : nullptr;
2953 }
2954 bool isSugared() const { return false; }
2955 QualType desugar() const { return QualType(this, 0); }
2956
2957 /// Determine the number of bits required to address a member of
2958 // an array with the given element type and number of elements.
2959 static unsigned getNumAddressingBits(const ASTContext &Context,
2960 QualType ElementType,
2961 const llvm::APInt &NumElements);
2962
2963 /// Determine the maximum number of active bits that an array's size
2964 /// can require, which limits the maximum size of the array.
2965 static unsigned getMaxSizeBits(const ASTContext &Context);
2966
2967 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2968 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2969 getSizeModifier(), getIndexTypeCVRQualifiers());
2970 }
2971
2972 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2973 QualType ET, const llvm::APInt &ArraySize,
2974 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2975 unsigned TypeQuals);
2976
2977 static bool classof(const Type *T) {
2978 return T->getTypeClass() == ConstantArray;
2979 }
2980};
2981
2982/// Represents a C array with an unspecified size. For example 'int A[]' has
2983/// an IncompleteArrayType where the element type is 'int' and the size is
2984/// unspecified.
2985class IncompleteArrayType : public ArrayType {
2986 friend class ASTContext; // ASTContext creates these.
2987
2988 IncompleteArrayType(QualType et, QualType can,
2989 ArraySizeModifier sm, unsigned tq)
2990 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2991
2992public:
2993 friend class StmtIteratorBase;
2994
2995 bool isSugared() const { return false; }
2996 QualType desugar() const { return QualType(this, 0); }
2997
2998 static bool classof(const Type *T) {
2999 return T->getTypeClass() == IncompleteArray;
3000 }
3001
3002 void Profile(llvm::FoldingSetNodeID &ID) {
3003 Profile(ID, getElementType(), getSizeModifier(),
3004 getIndexTypeCVRQualifiers());
3005 }
3006
3007 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3008 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3009 ID.AddPointer(ET.getAsOpaquePtr());
3010 ID.AddInteger(SizeMod);
3011 ID.AddInteger(TypeQuals);
3012 }
3013};
3014
3015/// Represents a C array with a specified size that is not an
3016/// integer-constant-expression. For example, 'int s[x+foo()]'.
3017/// Since the size expression is an arbitrary expression, we store it as such.
3018///
3019/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3020/// should not be: two lexically equivalent variable array types could mean
3021/// different things, for example, these variables do not have the same type
3022/// dynamically:
3023///
3024/// void foo(int x) {
3025/// int Y[x];
3026/// ++x;
3027/// int Z[x];
3028/// }
3029class VariableArrayType : public ArrayType {
3030 friend class ASTContext; // ASTContext creates these.
3031
3032 /// An assignment-expression. VLA's are only permitted within
3033 /// a function block.
3034 Stmt *SizeExpr;
3035
3036 /// The range spanned by the left and right array brackets.
3037 SourceRange Brackets;
3038
3039 VariableArrayType(QualType et, QualType can, Expr *e,
3040 ArraySizeModifier sm, unsigned tq,
3041 SourceRange brackets)
3042 : ArrayType(VariableArray, et, can, sm, tq, e),
3043 SizeExpr((Stmt*) e), Brackets(brackets) {}
3044
3045public:
3046 friend class StmtIteratorBase;
3047
3048 Expr *getSizeExpr() const {
3049 // We use C-style casts instead of cast<> here because we do not wish
3050 // to have a dependency of Type.h on Stmt.h/Expr.h.
3051 return (Expr*) SizeExpr;
3052 }
3053
3054 SourceRange getBracketsRange() const { return Brackets; }
3055 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3056 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3057
3058 bool isSugared() const { return false; }
3059 QualType desugar() const { return QualType(this, 0); }
3060
3061 static bool classof(const Type *T) {
3062 return T->getTypeClass() == VariableArray;
3063 }
3064
3065 void Profile(llvm::FoldingSetNodeID &ID) {
3066 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 3066)
;
3067 }
3068};
3069
3070/// Represents an array type in C++ whose size is a value-dependent expression.
3071///
3072/// For example:
3073/// \code
3074/// template<typename T, int Size>
3075/// class array {
3076/// T data[Size];
3077/// };
3078/// \endcode
3079///
3080/// For these types, we won't actually know what the array bound is
3081/// until template instantiation occurs, at which point this will
3082/// become either a ConstantArrayType or a VariableArrayType.
3083class DependentSizedArrayType : public ArrayType {
3084 friend class ASTContext; // ASTContext creates these.
3085
3086 const ASTContext &Context;
3087
3088 /// An assignment expression that will instantiate to the
3089 /// size of the array.
3090 ///
3091 /// The expression itself might be null, in which case the array
3092 /// type will have its size deduced from an initializer.
3093 Stmt *SizeExpr;
3094
3095 /// The range spanned by the left and right array brackets.
3096 SourceRange Brackets;
3097
3098 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3099 Expr *e, ArraySizeModifier sm, unsigned tq,
3100 SourceRange brackets);
3101
3102public:
3103 friend class StmtIteratorBase;
3104
3105 Expr *getSizeExpr() const {
3106 // We use C-style casts instead of cast<> here because we do not wish
3107 // to have a dependency of Type.h on Stmt.h/Expr.h.
3108 return (Expr*) SizeExpr;
3109 }
3110
3111 SourceRange getBracketsRange() const { return Brackets; }
3112 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3113 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3114
3115 bool isSugared() const { return false; }
3116 QualType desugar() const { return QualType(this, 0); }
3117
3118 static bool classof(const Type *T) {
3119 return T->getTypeClass() == DependentSizedArray;
3120 }
3121
3122 void Profile(llvm::FoldingSetNodeID &ID) {
3123 Profile(ID, Context, getElementType(),
3124 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3125 }
3126
3127 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3128 QualType ET, ArraySizeModifier SizeMod,
3129 unsigned TypeQuals, Expr *E);
3130};
3131
3132/// Represents an extended address space qualifier where the input address space
3133/// value is dependent. Non-dependent address spaces are not represented with a
3134/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3135///
3136/// For example:
3137/// \code
3138/// template<typename T, int AddrSpace>
3139/// class AddressSpace {
3140/// typedef T __attribute__((address_space(AddrSpace))) type;
3141/// }
3142/// \endcode
3143class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3144 friend class ASTContext;
3145
3146 const ASTContext &Context;
3147 Expr *AddrSpaceExpr;
3148 QualType PointeeType;
3149 SourceLocation loc;
3150
3151 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3152 QualType can, Expr *AddrSpaceExpr,
3153 SourceLocation loc);
3154
3155public:
3156 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3157 QualType getPointeeType() const { return PointeeType; }
3158 SourceLocation getAttributeLoc() const { return loc; }
3159
3160 bool isSugared() const { return false; }
3161 QualType desugar() const { return QualType(this, 0); }
3162
3163 static bool classof(const Type *T) {
3164 return T->getTypeClass() == DependentAddressSpace;
3165 }
3166
3167 void Profile(llvm::FoldingSetNodeID &ID) {
3168 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3169 }
3170
3171 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3172 QualType PointeeType, Expr *AddrSpaceExpr);
3173};
3174
3175/// Represents an extended vector type where either the type or size is
3176/// dependent.
3177///
3178/// For example:
3179/// \code
3180/// template<typename T, int Size>
3181/// class vector {
3182/// typedef T __attribute__((ext_vector_type(Size))) type;
3183/// }
3184/// \endcode
3185class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3186 friend class ASTContext;
3187
3188 const ASTContext &Context;
3189 Expr *SizeExpr;
3190
3191 /// The element type of the array.
3192 QualType ElementType;
3193
3194 SourceLocation loc;
3195
3196 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3197 QualType can, Expr *SizeExpr, SourceLocation loc);
3198
3199public:
3200 Expr *getSizeExpr() const { return SizeExpr; }
3201 QualType getElementType() const { return ElementType; }
3202 SourceLocation getAttributeLoc() const { return loc; }
3203
3204 bool isSugared() const { return false; }
3205 QualType desugar() const { return QualType(this, 0); }
3206
3207 static bool classof(const Type *T) {
3208 return T->getTypeClass() == DependentSizedExtVector;
3209 }
3210
3211 void Profile(llvm::FoldingSetNodeID &ID) {
3212 Profile(ID, Context, getElementType(), getSizeExpr());
3213 }
3214
3215 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3216 QualType ElementType, Expr *SizeExpr);
3217};
3218
3219
3220/// Represents a GCC generic vector type. This type is created using
3221/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3222/// bytes; or from an Altivec __vector or vector declaration.
3223/// Since the constructor takes the number of vector elements, the
3224/// client is responsible for converting the size into the number of elements.
3225class VectorType : public Type, public llvm::FoldingSetNode {
3226public:
3227 enum VectorKind {
3228 /// not a target-specific vector type
3229 GenericVector,
3230
3231 /// is AltiVec vector
3232 AltiVecVector,
3233
3234 /// is AltiVec 'vector Pixel'
3235 AltiVecPixel,
3236
3237 /// is AltiVec 'vector bool ...'
3238 AltiVecBool,
3239
3240 /// is ARM Neon vector
3241 NeonVector,
3242
3243 /// is ARM Neon polynomial vector
3244 NeonPolyVector
3245 };
3246
3247protected:
3248 friend class ASTContext; // ASTContext creates these.
3249
3250 /// The element type of the vector.
3251 QualType ElementType;
3252
3253 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3254 VectorKind vecKind);
3255
3256 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3257 QualType canonType, VectorKind vecKind);
3258
3259public:
3260 QualType getElementType() const { return ElementType; }
3261 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3262
3263 static bool isVectorSizeTooLarge(unsigned NumElements) {
3264 return NumElements > VectorTypeBitfields::MaxNumElements;
3265 }
3266
3267 bool isSugared() const { return false; }
3268 QualType desugar() const { return QualType(this, 0); }
3269
3270 VectorKind getVectorKind() const {
3271 return VectorKind(VectorTypeBits.VecKind);
3272 }
3273
3274 void Profile(llvm::FoldingSetNodeID &ID) {
3275 Profile(ID, getElementType(), getNumElements(),
3276 getTypeClass(), getVectorKind());
3277 }
3278
3279 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3280 unsigned NumElements, TypeClass TypeClass,
3281 VectorKind VecKind) {
3282 ID.AddPointer(ElementType.getAsOpaquePtr());
3283 ID.AddInteger(NumElements);
3284 ID.AddInteger(TypeClass);
3285 ID.AddInteger(VecKind);
3286 }
3287
3288 static bool classof(const Type *T) {
3289 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3290 }
3291};
3292
3293/// Represents a vector type where either the type or size is dependent.
3294////
3295/// For example:
3296/// \code
3297/// template<typename T, int Size>
3298/// class vector {
3299/// typedef T __attribute__((vector_size(Size))) type;
3300/// }
3301/// \endcode
3302class DependentVectorType : public Type, public llvm::FoldingSetNode {
3303 friend class ASTContext;
3304
3305 const ASTContext &Context;
3306 QualType ElementType;
3307 Expr *SizeExpr;
3308 SourceLocation Loc;
3309
3310 DependentVectorType(const ASTContext &Context, QualType ElementType,
3311 QualType CanonType, Expr *SizeExpr,
3312 SourceLocation Loc, VectorType::VectorKind vecKind);
3313
3314public:
3315 Expr *getSizeExpr() const { return SizeExpr; }
3316 QualType getElementType() const { return ElementType; }
3317 SourceLocation getAttributeLoc() const { return Loc; }
3318 VectorType::VectorKind getVectorKind() const {
3319 return VectorType::VectorKind(VectorTypeBits.VecKind);
3320 }
3321
3322 bool isSugared() const { return false; }
3323 QualType desugar() const { return QualType(this, 0); }
3324
3325 static bool classof(const Type *T) {
3326 return T->getTypeClass() == DependentVector;
3327 }
3328
3329 void Profile(llvm::FoldingSetNodeID &ID) {
3330 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3331 }
3332
3333 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3334 QualType ElementType, const Expr *SizeExpr,
3335 VectorType::VectorKind VecKind);
3336};
3337
3338/// ExtVectorType - Extended vector type. This type is created using
3339/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3340/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3341/// class enables syntactic extensions, like Vector Components for accessing
3342/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3343/// Shading Language).
3344class ExtVectorType : public VectorType {
3345 friend class ASTContext; // ASTContext creates these.
3346
3347 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3348 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3349
3350public:
3351 static int getPointAccessorIdx(char c) {
3352 switch (c) {
3353 default: return -1;
3354 case 'x': case 'r': return 0;
3355 case 'y': case 'g': return 1;
3356 case 'z': case 'b': return 2;
3357 case 'w': case 'a': return 3;
3358 }
3359 }
3360
3361 static int getNumericAccessorIdx(char c) {
3362 switch (c) {
3363 default: return -1;
3364 case '0': return 0;
3365 case '1': return 1;
3366 case '2': return 2;
3367 case '3': return 3;
3368 case '4': return 4;
3369 case '5': return 5;
3370 case '6': return 6;
3371 case '7': return 7;
3372 case '8': return 8;
3373 case '9': return 9;
3374 case 'A':
3375 case 'a': return 10;
3376 case 'B':
3377 case 'b': return 11;
3378 case 'C':
3379 case 'c': return 12;
3380 case 'D':
3381 case 'd': return 13;
3382 case 'E':
3383 case 'e': return 14;
3384 case 'F':
3385 case 'f': return 15;
3386 }
3387 }
3388
3389 static int getAccessorIdx(char c, bool isNumericAccessor) {
3390 if (isNumericAccessor)
3391 return getNumericAccessorIdx(c);
3392 else
3393 return getPointAccessorIdx(c);
3394 }
3395
3396 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3397 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3398 return unsigned(idx-1) < getNumElements();
3399 return false;
3400 }
3401
3402 bool isSugared() const { return false; }
3403 QualType desugar() const { return QualType(this, 0); }
3404
3405 static bool classof(const Type *T) {
3406 return T->getTypeClass() == ExtVector;
3407 }
3408};
3409
3410/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3411/// class of FunctionNoProtoType and FunctionProtoType.
3412class FunctionType : public Type {
3413 // The type returned by the function.
3414 QualType ResultType;
3415
3416public:
3417 /// Interesting information about a specific parameter that can't simply
3418 /// be reflected in parameter's type. This is only used by FunctionProtoType
3419 /// but is in FunctionType to make this class available during the
3420 /// specification of the bases of FunctionProtoType.
3421 ///
3422 /// It makes sense to model language features this way when there's some
3423 /// sort of parameter-specific override (such as an attribute) that
3424 /// affects how the function is called. For example, the ARC ns_consumed
3425 /// attribute changes whether a parameter is passed at +0 (the default)
3426 /// or +1 (ns_consumed). This must be reflected in the function type,
3427 /// but isn't really a change to the parameter type.
3428 ///
3429 /// One serious disadvantage of modelling language features this way is
3430 /// that they generally do not work with language features that attempt
3431 /// to destructure types. For example, template argument deduction will
3432 /// not be able to match a parameter declared as
3433 /// T (*)(U)
3434 /// against an argument of type
3435 /// void (*)(__attribute__((ns_consumed)) id)
3436 /// because the substitution of T=void, U=id into the former will
3437 /// not produce the latter.
3438 class ExtParameterInfo {
3439 enum {
3440 ABIMask = 0x0F,
3441 IsConsumed = 0x10,
3442 HasPassObjSize = 0x20,
3443 IsNoEscape = 0x40,
3444 };
3445 unsigned char Data = 0;
3446
3447 public:
3448 ExtParameterInfo() = default;
3449
3450 /// Return the ABI treatment of this parameter.
3451 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3452 ExtParameterInfo withABI(ParameterABI kind) const {
3453 ExtParameterInfo copy = *this;
3454 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3455 return copy;
3456 }
3457
3458 /// Is this parameter considered "consumed" by Objective-C ARC?
3459 /// Consumed parameters must have retainable object type.
3460 bool isConsumed() const { return (Data & IsConsumed); }
3461 ExtParameterInfo withIsConsumed(bool consumed) const {
3462 ExtParameterInfo copy = *this;
3463 if (consumed)
3464 copy.Data |= IsConsumed;
3465 else
3466 copy.Data &= ~IsConsumed;
3467 return copy;
3468 }
3469
3470 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3471 ExtParameterInfo withHasPassObjectSize() const {
3472 ExtParameterInfo Copy = *this;
3473 Copy.Data |= HasPassObjSize;
3474 return Copy;
3475 }
3476
3477 bool isNoEscape() const { return Data & IsNoEscape; }
3478 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3479 ExtParameterInfo Copy = *this;
3480 if (NoEscape)
3481 Copy.Data |= IsNoEscape;
3482 else
3483 Copy.Data &= ~IsNoEscape;
3484 return Copy;
3485 }
3486
3487 unsigned char getOpaqueValue() const { return Data; }
3488 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3489 ExtParameterInfo result;
3490 result.Data = data;
3491 return result;
3492 }
3493
3494 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3495 return lhs.Data == rhs.Data;
3496 }
3497
3498 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3499 return lhs.Data != rhs.Data;
3500 }
3501 };
3502
3503 /// A class which abstracts out some details necessary for
3504 /// making a call.
3505 ///
3506 /// It is not actually used directly for storing this information in
3507 /// a FunctionType, although FunctionType does currently use the
3508 /// same bit-pattern.
3509 ///
3510 // If you add a field (say Foo), other than the obvious places (both,
3511 // constructors, compile failures), what you need to update is
3512 // * Operator==
3513 // * getFoo
3514 // * withFoo
3515 // * functionType. Add Foo, getFoo.
3516 // * ASTContext::getFooType
3517 // * ASTContext::mergeFunctionTypes
3518 // * FunctionNoProtoType::Profile
3519 // * FunctionProtoType::Profile
3520 // * TypePrinter::PrintFunctionProto
3521 // * AST read and write
3522 // * Codegen
3523 class ExtInfo {
3524 friend class FunctionType;
3525
3526 // Feel free to rearrange or add bits, but if you go over 12,
3527 // you'll need to adjust both the Bits field below and
3528 // Type::FunctionTypeBitfields.
3529
3530 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3531 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3532 //
3533 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3534 enum { CallConvMask = 0x1F };
3535 enum { NoReturnMask = 0x20 };
3536 enum { ProducesResultMask = 0x40 };
3537 enum { NoCallerSavedRegsMask = 0x80 };
3538 enum { NoCfCheckMask = 0x800 };
3539 enum {
3540 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3541 NoCallerSavedRegsMask | NoCfCheckMask),
3542 RegParmOffset = 8
3543 }; // Assumed to be the last field
3544 uint16_t Bits = CC_C;
3545
3546 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3547
3548 public:
3549 // Constructor with no defaults. Use this when you know that you
3550 // have all the elements (when reading an AST file for example).
3551 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3552 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3553 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/Type.h"
, 3553, __PRETTY_FUNCTION__))
;
3554 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3555 (producesResult ? ProducesResultMask : 0) |
3556 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3557 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3558 (NoCfCheck ? NoCfCheckMask : 0);
3559 }
3560
3561 // Constructor with all defaults. Use when for example creating a
3562 // function known to use defaults.
3563 ExtInfo() = default;
3564
3565 // Constructor with just the calling convention, which is an important part
3566 // of the canonical type.
3567 ExtInfo(CallingConv CC) : Bits(CC) {}
3568
3569 bool getNoReturn() const { return Bits & NoReturnMask; }
3570 bool getProducesResult() const { return Bits & ProducesResultMask; }
3571 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3572 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3573 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3574
3575 unsigned getRegParm() const {
3576 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3577 if (RegParm > 0)
3578 --RegParm;
3579 return RegParm;
3580 }
3581
3582 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3583
3584 bool operator==(ExtInfo Other) const {
3585 return Bits == Other.Bits;
3586 }
3587 bool operator!=(ExtInfo Other) const {
3588 return Bits != Other.Bits;
3589 }
3590
3591 // Note that we don't have setters. That is by design, use
3592 // the following with methods instead of mutating these objects.
3593
3594 ExtInfo withNoReturn(bool noReturn) const {
3595 if (noReturn)
3596 return ExtInfo(Bits | NoReturnMask);
3597 else
3598 return ExtInfo(Bits & ~NoReturnMask);
3599 }
3600
3601 ExtInfo withProducesResult(bool producesResult) const {
3602 if (producesResult)
3603 return ExtInfo(Bits | ProducesResultMask);
3604