Bug Summary

File:clang/lib/AST/Expr.cpp
Warning:line 824, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Expr.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 -fdenormal-fp-math=ieee,ieee -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-11/lib/clang/11.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-11~++20200307100611+a5704f92b83/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/include -I /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/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-11/lib/clang/11.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-11~++20200307100611+a5704f92b83/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83=. -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-03-08-032253-29446-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp

/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp

1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/DependencyFlags.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/Mangle.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Lexer.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35#include <cstring>
36using namespace clang;
37
38const Expr *Expr::getBestDynamicClassTypeExpr() const {
39 const Expr *E = this;
40 while (true) {
41 E = E->ignoreParenBaseCasts();
42
43 // Follow the RHS of a comma operator.
44 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45 if (BO->getOpcode() == BO_Comma) {
46 E = BO->getRHS();
47 continue;
48 }
49 }
50
51 // Step into initializer for materialized temporaries.
52 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
53 E = MTE->getSubExpr();
54 continue;
55 }
56
57 break;
58 }
59
60 return E;
61}
62
63const CXXRecordDecl *Expr::getBestDynamicClassType() const {
64 const Expr *E = getBestDynamicClassTypeExpr();
65 QualType DerivedType = E->getType();
66 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
67 DerivedType = PTy->getPointeeType();
68
69 if (DerivedType->isDependentType())
70 return nullptr;
71
72 const RecordType *Ty = DerivedType->castAs<RecordType>();
73 Decl *D = Ty->getDecl();
74 return cast<CXXRecordDecl>(D);
75}
76
77const Expr *Expr::skipRValueSubobjectAdjustments(
78 SmallVectorImpl<const Expr *> &CommaLHSs,
79 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
80 const Expr *E = this;
81 while (true) {
82 E = E->IgnoreParens();
83
84 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
85 if ((CE->getCastKind() == CK_DerivedToBase ||
86 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
87 E->getType()->isRecordType()) {
88 E = CE->getSubExpr();
89 auto *Derived =
90 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
91 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
92 continue;
93 }
94
95 if (CE->getCastKind() == CK_NoOp) {
96 E = CE->getSubExpr();
97 continue;
98 }
99 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
100 if (!ME->isArrow()) {
101 assert(ME->getBase()->getType()->isRecordType())((ME->getBase()->getType()->isRecordType()) ? static_cast
<void> (0) : __assert_fail ("ME->getBase()->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 101, __PRETTY_FUNCTION__))
;
102 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
103 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
104 E = ME->getBase();
105 Adjustments.push_back(SubobjectAdjustment(Field));
106 continue;
107 }
108 }
109 }
110 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
111 if (BO->getOpcode() == BO_PtrMemD) {
112 assert(BO->getRHS()->isRValue())((BO->getRHS()->isRValue()) ? static_cast<void> (
0) : __assert_fail ("BO->getRHS()->isRValue()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 112, __PRETTY_FUNCTION__))
;
113 E = BO->getLHS();
114 const MemberPointerType *MPT =
115 BO->getRHS()->getType()->getAs<MemberPointerType>();
116 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
117 continue;
118 } else if (BO->getOpcode() == BO_Comma) {
119 CommaLHSs.push_back(BO->getLHS());
120 E = BO->getRHS();
121 continue;
122 }
123 }
124
125 // Nothing changed.
126 break;
127 }
128 return E;
129}
130
131bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
132 const Expr *E = IgnoreParens();
133
134 // If this value has _Bool type, it is obvious 0/1.
135 if (E->getType()->isBooleanType()) return true;
136 // If this is a non-scalar-integer type, we don't care enough to try.
137 if (!E->getType()->isIntegralOrEnumerationType()) return false;
138
139 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
140 switch (UO->getOpcode()) {
141 case UO_Plus:
142 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
143 case UO_LNot:
144 return true;
145 default:
146 return false;
147 }
148 }
149
150 // Only look through implicit casts. If the user writes
151 // '(int) (a && b)' treat it as an arbitrary int.
152 // FIXME: Should we look through any cast expression in !Semantic mode?
153 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
154 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
155
156 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
157 switch (BO->getOpcode()) {
158 default: return false;
159 case BO_LT: // Relational operators.
160 case BO_GT:
161 case BO_LE:
162 case BO_GE:
163 case BO_EQ: // Equality operators.
164 case BO_NE:
165 case BO_LAnd: // AND operator.
166 case BO_LOr: // Logical OR operator.
167 return true;
168
169 case BO_And: // Bitwise AND operator.
170 case BO_Xor: // Bitwise XOR operator.
171 case BO_Or: // Bitwise OR operator.
172 // Handle things like (x==2)|(y==12).
173 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
174 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
175
176 case BO_Comma:
177 case BO_Assign:
178 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
179 }
180 }
181
182 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
183 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
184 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
185
186 if (isa<ObjCBoolLiteralExpr>(E))
187 return true;
188
189 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
190 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
191
192 if (const FieldDecl *FD = E->getSourceBitField())
193 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
194 !FD->getBitWidth()->isValueDependent() &&
195 FD->getBitWidthValue(FD->getASTContext()) == 1)
196 return true;
197
198 return false;
199}
200
201// Amusing macro metaprogramming hack: check whether a class provides
202// a more specific implementation of getExprLoc().
203//
204// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
205namespace {
206 /// This implementation is used when a class provides a custom
207 /// implementation of getExprLoc.
208 template <class E, class T>
209 SourceLocation getExprLocImpl(const Expr *expr,
210 SourceLocation (T::*v)() const) {
211 return static_cast<const E*>(expr)->getExprLoc();
212 }
213
214 /// This implementation is used when a class doesn't provide
215 /// a custom implementation of getExprLoc. Overload resolution
216 /// should pick it over the implementation above because it's
217 /// more specialized according to function template partial ordering.
218 template <class E>
219 SourceLocation getExprLocImpl(const Expr *expr,
220 SourceLocation (Expr::*v)() const) {
221 return static_cast<const E *>(expr)->getBeginLoc();
222 }
223}
224
225SourceLocation Expr::getExprLoc() const {
226 switch (getStmtClass()) {
227 case Stmt::NoStmtClass: llvm_unreachable("statement without class")::llvm::llvm_unreachable_internal("statement without class", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 227)
;
228#define ABSTRACT_STMT(type)
229#define STMT(type, base) \
230 case Stmt::type##Class: break;
231#define EXPR(type, base) \
232 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
233#include "clang/AST/StmtNodes.inc"
234 }
235 llvm_unreachable("unknown expression kind")::llvm::llvm_unreachable_internal("unknown expression kind", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 235)
;
236}
237
238//===----------------------------------------------------------------------===//
239// Primary Expressions.
240//===----------------------------------------------------------------------===//
241
242static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
243 assert((Kind == ConstantExpr::RSK_APValue ||(((Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::
RSK_Int64 || Kind == ConstantExpr::RSK_None) && "Invalid StorageKind Value"
) ? static_cast<void> (0) : __assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 245, __PRETTY_FUNCTION__))
244 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&(((Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::
RSK_Int64 || Kind == ConstantExpr::RSK_None) && "Invalid StorageKind Value"
) ? static_cast<void> (0) : __assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 245, __PRETTY_FUNCTION__))
245 "Invalid StorageKind Value")(((Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::
RSK_Int64 || Kind == ConstantExpr::RSK_None) && "Invalid StorageKind Value"
) ? static_cast<void> (0) : __assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 245, __PRETTY_FUNCTION__))
;
246}
247
248ConstantExpr::ResultStorageKind
249ConstantExpr::getStorageKind(const APValue &Value) {
250 switch (Value.getKind()) {
251 case APValue::None:
252 case APValue::Indeterminate:
253 return ConstantExpr::RSK_None;
254 case APValue::Int:
255 if (!Value.getInt().needsCleanup())
256 return ConstantExpr::RSK_Int64;
257 LLVM_FALLTHROUGH[[gnu::fallthrough]];
258 default:
259 return ConstantExpr::RSK_APValue;
260 }
261}
262
263ConstantExpr::ResultStorageKind
264ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
265 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
266 return ConstantExpr::RSK_Int64;
267 return ConstantExpr::RSK_APValue;
268}
269
270void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
271 ConstantExprBits.ResultKind = StorageKind;
272 ConstantExprBits.APValueKind = APValue::None;
273 ConstantExprBits.HasCleanup = false;
274 if (StorageKind == ConstantExpr::RSK_APValue)
275 ::new (getTrailingObjects<APValue>()) APValue();
276}
277
278ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
279 : FullExpr(ConstantExprClass, subexpr) {
280 DefaultInit(StorageKind);
281}
282
283ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
284 ResultStorageKind StorageKind,
285 bool IsImmediateInvocation) {
286 assert(!isa<ConstantExpr>(E))((!isa<ConstantExpr>(E)) ? static_cast<void> (0) :
__assert_fail ("!isa<ConstantExpr>(E)", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 286, __PRETTY_FUNCTION__))
;
287 AssertResultStorageKind(StorageKind);
288 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
289 StorageKind == ConstantExpr::RSK_APValue,
290 StorageKind == ConstantExpr::RSK_Int64);
291 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
292 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
293 Self->ConstantExprBits.IsImmediateInvocation =
294 IsImmediateInvocation;
295 return Self;
296}
297
298ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
299 const APValue &Result) {
300 ResultStorageKind StorageKind = getStorageKind(Result);
301 ConstantExpr *Self = Create(Context, E, StorageKind);
302 Self->SetResult(Result, Context);
303 return Self;
304}
305
306ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
307 : FullExpr(ConstantExprClass, Empty) {
308 DefaultInit(StorageKind);
309}
310
311ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
312 ResultStorageKind StorageKind,
313 EmptyShell Empty) {
314 AssertResultStorageKind(StorageKind);
315 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
316 StorageKind == ConstantExpr::RSK_APValue,
317 StorageKind == ConstantExpr::RSK_Int64);
318 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
319 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
320 return Self;
321}
322
323void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
324 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&(((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind
&& "Invalid storage for this value kind") ? static_cast
<void> (0) : __assert_fail ("(unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && \"Invalid storage for this value kind\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 325, __PRETTY_FUNCTION__))
325 "Invalid storage for this value kind")(((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind
&& "Invalid storage for this value kind") ? static_cast
<void> (0) : __assert_fail ("(unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && \"Invalid storage for this value kind\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 325, __PRETTY_FUNCTION__))
;
326 ConstantExprBits.APValueKind = Value.getKind();
327 switch (ConstantExprBits.ResultKind) {
328 case RSK_None:
329 return;
330 case RSK_Int64:
331 Int64Result() = *Value.getInt().getRawData();
332 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
333 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
334 return;
335 case RSK_APValue:
336 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
337 ConstantExprBits.HasCleanup = true;
338 Context.addDestruction(&APValueResult());
339 }
340 APValueResult() = std::move(Value);
341 return;
342 }
343 llvm_unreachable("Invalid ResultKind Bits")::llvm::llvm_unreachable_internal("Invalid ResultKind Bits", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 343)
;
344}
345
346llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
347 switch (ConstantExprBits.ResultKind) {
348 case ConstantExpr::RSK_APValue:
349 return APValueResult().getInt();
350 case ConstantExpr::RSK_Int64:
351 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
352 ConstantExprBits.IsUnsigned);
353 default:
354 llvm_unreachable("invalid Accessor")::llvm::llvm_unreachable_internal("invalid Accessor", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 354)
;
355 }
356}
357
358APValue ConstantExpr::getAPValueResult() const {
359 switch (ConstantExprBits.ResultKind) {
360 case ConstantExpr::RSK_APValue:
361 return APValueResult();
362 case ConstantExpr::RSK_Int64:
363 return APValue(
364 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
365 ConstantExprBits.IsUnsigned));
366 case ConstantExpr::RSK_None:
367 return APValue();
368 }
369 llvm_unreachable("invalid ResultKind")::llvm::llvm_unreachable_internal("invalid ResultKind", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 369)
;
370}
371
372/// Compute the type-, value-, and instantiation-dependence of a
373/// declaration reference
374/// based on the declaration being referenced.
375static ExprDependence computeDeclRefDependence(const ASTContext &Ctx,
376 NamedDecl *D, QualType T) {
377 auto R = ExprDependence::None;
378 if (D->isParameterPack())
379 R |= ExprDependence::UnexpandedPack;
380
381 // (TD) C++ [temp.dep.expr]p3:
382 // An id-expression is type-dependent if it contains:
383 //
384 // and
385 //
386 // (VD) C++ [temp.dep.constexpr]p2:
387 // An identifier is value-dependent if it is:
388
389 // (TD) - an identifier that was declared with dependent type
390 // (VD) - a name declared with a dependent type,
391 if (T->isDependentType())
392 return R | ExprDependence::TypeValueInstantiation;
393 else if (T->isInstantiationDependentType())
394 R |= ExprDependence::Instantiation;
395
396 // (TD) - a conversion-function-id that specifies a dependent type
397 if (D->getDeclName().getNameKind()
398 == DeclarationName::CXXConversionFunctionName) {
399 QualType T = D->getDeclName().getCXXNameType();
400 if (T->isDependentType())
401 return R | ExprDependence::TypeValueInstantiation;
402
403 if (T->isInstantiationDependentType())
404 R |= ExprDependence::Instantiation;
405 }
406
407 // (VD) - the name of a non-type template parameter,
408 if (isa<NonTypeTemplateParmDecl>(D))
409 return R | ExprDependence::ValueInstantiation;
410
411 // (VD) - a constant with integral or enumeration type and is
412 // initialized with an expression that is value-dependent.
413 // (VD) - a constant with literal type and is initialized with an
414 // expression that is value-dependent [C++11].
415 // (VD) - FIXME: Missing from the standard:
416 // - an entity with reference type and is initialized with an
417 // expression that is value-dependent [C++11]
418 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
419 if ((Ctx.getLangOpts().CPlusPlus11 ?
420 Var->getType()->isLiteralType(Ctx) :
421 Var->getType()->isIntegralOrEnumerationType()) &&
422 (Var->getType().isConstQualified() ||
423 Var->getType()->isReferenceType())) {
424 if (const Expr *Init = Var->getAnyInitializer())
425 if (Init->isValueDependent()) {
426 R |= ExprDependence::ValueInstantiation;
427 }
428 }
429
430 // (VD) - FIXME: Missing from the standard:
431 // - a member function or a static data member of the current
432 // instantiation
433 if (Var->isStaticDataMember() &&
434 Var->getDeclContext()->isDependentContext()) {
435 R |= ExprDependence::ValueInstantiation;
436 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
437 if (TInfo->getType()->isIncompleteArrayType())
438 R |= ExprDependence::Type;
439 }
440
441 return R;
442 }
443
444 // (VD) - FIXME: Missing from the standard:
445 // - a member function or a static data member of the current
446 // instantiation
447 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext())
448 R |= ExprDependence::ValueInstantiation;
449 return R;
450}
451
452DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
453 bool RefersToEnclosingVariableOrCapture, QualType T,
454 ExprValueKind VK, SourceLocation L,
455 const DeclarationNameLoc &LocInfo,
456 NonOdrUseReason NOUR)
457 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
458 D(D), DNLoc(LocInfo) {
459 DeclRefExprBits.HasQualifier = false;
460 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
461 DeclRefExprBits.HasFoundDecl = false;
462 DeclRefExprBits.HadMultipleCandidates = false;
463 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
464 RefersToEnclosingVariableOrCapture;
465 DeclRefExprBits.NonOdrUseReason = NOUR;
466 DeclRefExprBits.Loc = L;
467 addDependence(computeDeclRefDependence(Ctx, getDecl(), getType()));
468}
469
470DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
471 NestedNameSpecifierLoc QualifierLoc,
472 SourceLocation TemplateKWLoc, ValueDecl *D,
473 bool RefersToEnclosingVariableOrCapture,
474 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
475 const TemplateArgumentListInfo *TemplateArgs,
476 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
477 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
478 D(D), DNLoc(NameInfo.getInfo()) {
479 DeclRefExprBits.Loc = NameInfo.getLoc();
480 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
481 if (QualifierLoc) {
482 new (getTrailingObjects<NestedNameSpecifierLoc>())
483 NestedNameSpecifierLoc(QualifierLoc);
484 auto *NNS = QualifierLoc.getNestedNameSpecifier();
485 if (NNS->isInstantiationDependent())
486 addDependence(ExprDependence::Instantiation);
487 if (NNS->containsUnexpandedParameterPack())
488 addDependence(ExprDependence::UnexpandedPack);
489 }
490 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
491 if (FoundD)
492 *getTrailingObjects<NamedDecl *>() = FoundD;
493 DeclRefExprBits.HasTemplateKWAndArgsInfo
494 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
495 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
496 RefersToEnclosingVariableOrCapture;
497 DeclRefExprBits.NonOdrUseReason = NOUR;
498 if (TemplateArgs) {
499 auto Deps = TemplateArgumentDependence::None;
500 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
501 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
502 Deps);
503 assert(!(Deps & TemplateArgumentDependence::Dependent) &&((!(Deps & TemplateArgumentDependence::Dependent) &&
"built a DeclRefExpr with dependent template args") ? static_cast
<void> (0) : __assert_fail ("!(Deps & TemplateArgumentDependence::Dependent) && \"built a DeclRefExpr with dependent template args\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 504, __PRETTY_FUNCTION__))
504 "built a DeclRefExpr with dependent template args")((!(Deps & TemplateArgumentDependence::Dependent) &&
"built a DeclRefExpr with dependent template args") ? static_cast
<void> (0) : __assert_fail ("!(Deps & TemplateArgumentDependence::Dependent) && \"built a DeclRefExpr with dependent template args\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 504, __PRETTY_FUNCTION__))
;
505 addDependence(toExprDependence(Deps));
506 } else if (TemplateKWLoc.isValid()) {
507 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
508 TemplateKWLoc);
509 }
510 DeclRefExprBits.HadMultipleCandidates = 0;
511 addDependence(computeDeclRefDependence(Ctx, getDecl(), getType()));
512}
513
514DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
515 NestedNameSpecifierLoc QualifierLoc,
516 SourceLocation TemplateKWLoc, ValueDecl *D,
517 bool RefersToEnclosingVariableOrCapture,
518 SourceLocation NameLoc, QualType T,
519 ExprValueKind VK, NamedDecl *FoundD,
520 const TemplateArgumentListInfo *TemplateArgs,
521 NonOdrUseReason NOUR) {
522 return Create(Context, QualifierLoc, TemplateKWLoc, D,
523 RefersToEnclosingVariableOrCapture,
524 DeclarationNameInfo(D->getDeclName(), NameLoc),
525 T, VK, FoundD, TemplateArgs, NOUR);
526}
527
528DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
529 NestedNameSpecifierLoc QualifierLoc,
530 SourceLocation TemplateKWLoc, ValueDecl *D,
531 bool RefersToEnclosingVariableOrCapture,
532 const DeclarationNameInfo &NameInfo,
533 QualType T, ExprValueKind VK,
534 NamedDecl *FoundD,
535 const TemplateArgumentListInfo *TemplateArgs,
536 NonOdrUseReason NOUR) {
537 // Filter out cases where the found Decl is the same as the value refenenced.
538 if (D == FoundD)
539 FoundD = nullptr;
540
541 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
542 std::size_t Size =
543 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
544 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
545 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
546 HasTemplateKWAndArgsInfo ? 1 : 0,
547 TemplateArgs ? TemplateArgs->size() : 0);
548
549 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
550 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
551 RefersToEnclosingVariableOrCapture, NameInfo,
552 FoundD, TemplateArgs, T, VK, NOUR);
553}
554
555DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
556 bool HasQualifier,
557 bool HasFoundDecl,
558 bool HasTemplateKWAndArgsInfo,
559 unsigned NumTemplateArgs) {
560 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo)((NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo) ? static_cast
<void> (0) : __assert_fail ("NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 560, __PRETTY_FUNCTION__))
;
561 std::size_t Size =
562 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
563 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
564 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
565 NumTemplateArgs);
566 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
567 return new (Mem) DeclRefExpr(EmptyShell());
568}
569
570SourceLocation DeclRefExpr::getBeginLoc() const {
571 if (hasQualifier())
572 return getQualifierLoc().getBeginLoc();
573 return getNameInfo().getBeginLoc();
574}
575SourceLocation DeclRefExpr::getEndLoc() const {
576 if (hasExplicitTemplateArgs())
577 return getRAngleLoc();
578 return getNameInfo().getEndLoc();
579}
580
581PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
582 StringLiteral *SL)
583 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
584 FNTy->isDependentType(), FNTy->isDependentType(),
585 FNTy->isInstantiationDependentType(),
586 /*ContainsUnexpandedParameterPack=*/false) {
587 PredefinedExprBits.Kind = IK;
588 assert((getIdentKind() == IK) &&(((getIdentKind() == IK) && "IdentKind do not fit in PredefinedExprBitfields!"
) ? static_cast<void> (0) : __assert_fail ("(getIdentKind() == IK) && \"IdentKind do not fit in PredefinedExprBitfields!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 589, __PRETTY_FUNCTION__))
589 "IdentKind do not fit in PredefinedExprBitfields!")(((getIdentKind() == IK) && "IdentKind do not fit in PredefinedExprBitfields!"
) ? static_cast<void> (0) : __assert_fail ("(getIdentKind() == IK) && \"IdentKind do not fit in PredefinedExprBitfields!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 589, __PRETTY_FUNCTION__))
;
590 bool HasFunctionName = SL != nullptr;
591 PredefinedExprBits.HasFunctionName = HasFunctionName;
592 PredefinedExprBits.Loc = L;
593 if (HasFunctionName)
594 setFunctionName(SL);
595}
596
597PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
598 : Expr(PredefinedExprClass, Empty) {
599 PredefinedExprBits.HasFunctionName = HasFunctionName;
600}
601
602PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
603 QualType FNTy, IdentKind IK,
604 StringLiteral *SL) {
605 bool HasFunctionName = SL != nullptr;
606 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
607 alignof(PredefinedExpr));
608 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
609}
610
611PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
612 bool HasFunctionName) {
613 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
614 alignof(PredefinedExpr));
615 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
616}
617
618StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
619 switch (IK) {
620 case Func:
621 return "__func__";
622 case Function:
623 return "__FUNCTION__";
624 case FuncDName:
625 return "__FUNCDNAME__";
626 case LFunction:
627 return "L__FUNCTION__";
628 case PrettyFunction:
629 return "__PRETTY_FUNCTION__";
630 case FuncSig:
631 return "__FUNCSIG__";
632 case LFuncSig:
633 return "L__FUNCSIG__";
634 case PrettyFunctionNoVirtual:
635 break;
636 }
637 llvm_unreachable("Unknown ident kind for PredefinedExpr")::llvm::llvm_unreachable_internal("Unknown ident kind for PredefinedExpr"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 637)
;
638}
639
640// FIXME: Maybe this should use DeclPrinter with a special "print predefined
641// expr" policy instead.
642std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
643 ASTContext &Context = CurrentDecl->getASTContext();
644
645 if (IK == PredefinedExpr::FuncDName) {
1
Assuming 'IK' is not equal to FuncDName
2
Taking false branch
646 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
647 std::unique_ptr<MangleContext> MC;
648 MC.reset(Context.createMangleContext());
649
650 if (MC->shouldMangleDeclName(ND)) {
651 SmallString<256> Buffer;
652 llvm::raw_svector_ostream Out(Buffer);
653 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
654 MC->mangleCXXCtor(CD, Ctor_Base, Out);
655 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
656 MC->mangleCXXDtor(DD, Dtor_Base, Out);
657 else
658 MC->mangleName(ND, Out);
659
660 if (!Buffer.empty() && Buffer.front() == '\01')
661 return std::string(Buffer.substr(1));
662 return std::string(Buffer.str());
663 } else
664 return std::string(ND->getIdentifier()->getName());
665 }
666 return "";
667 }
668 if (isa<BlockDecl>(CurrentDecl)) {
3
Assuming 'CurrentDecl' is not a 'BlockDecl'
4
Taking false branch
669 // For blocks we only emit something if it is enclosed in a function
670 // For top-level block we'd like to include the name of variable, but we
671 // don't have it at this point.
672 auto DC = CurrentDecl->getDeclContext();
673 if (DC->isFileContext())
674 return "";
675
676 SmallString<256> Buffer;
677 llvm::raw_svector_ostream Out(Buffer);
678 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
679 // For nested blocks, propagate up to the parent.
680 Out << ComputeName(IK, DCBlock);
681 else if (auto *DCDecl = dyn_cast<Decl>(DC))
682 Out << ComputeName(IK, DCDecl) << "_block_invoke";
683 return std::string(Out.str());
684 }
685 if (const FunctionDecl *FD
5.1
'FD' is non-null
5.1
'FD' is non-null
= dyn_cast<FunctionDecl>(CurrentDecl)) {
5
Assuming 'CurrentDecl' is a 'FunctionDecl'
6
Taking true branch
686 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
7
Assuming 'IK' is equal to PrettyFunction
687 IK != FuncSig && IK != LFuncSig)
688 return FD->getNameAsString();
689
690 SmallString<256> Name;
691 llvm::raw_svector_ostream Out(Name);
692
693 if (const CXXMethodDecl *MD
8.1
'MD' is null
8.1
'MD' is null
= dyn_cast<CXXMethodDecl>(FD)) {
8
Assuming 'FD' is not a 'CXXMethodDecl'
9
Taking false branch
694 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
695 Out << "virtual ";
696 if (MD->isStatic())
697 Out << "static ";
698 }
699
700 PrintingPolicy Policy(Context.getLangOpts());
701 std::string Proto;
702 llvm::raw_string_ostream POut(Proto);
703
704 const FunctionDecl *Decl = FD;
705 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
10
Assuming 'Pattern' is null
11
Taking false branch
706 Decl = Pattern;
707 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
12
Assuming the object is not a 'FunctionType'
13
'AFT' initialized to a null pointer value
708 const FunctionProtoType *FT = nullptr;
709 if (FD->hasWrittenPrototype())
14
Assuming the condition is false
15
Taking false branch
710 FT = dyn_cast<FunctionProtoType>(AFT);
711
712 if (IK
15.1
'IK' is not equal to FuncSig
15.1
'IK' is not equal to FuncSig
== FuncSig || IK
15.2
'IK' is not equal to LFuncSig
15.2
'IK' is not equal to LFuncSig
== LFuncSig) {
16
Taking false branch
713 switch (AFT->getCallConv()) {
714 case CC_C: POut << "__cdecl "; break;
715 case CC_X86StdCall: POut << "__stdcall "; break;
716 case CC_X86FastCall: POut << "__fastcall "; break;
717 case CC_X86ThisCall: POut << "__thiscall "; break;
718 case CC_X86VectorCall: POut << "__vectorcall "; break;
719 case CC_X86RegCall: POut << "__regcall "; break;
720 // Only bother printing the conventions that MSVC knows about.
721 default: break;
722 }
723 }
724
725 FD->printQualifiedName(POut, Policy);
726
727 POut << "(";
728 if (FT
16.1
'FT' is null
16.1
'FT' is null
) {
17
Taking false branch
729 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
730 if (i) POut << ", ";
731 POut << Decl->getParamDecl(i)->getType().stream(Policy);
732 }
733
734 if (FT->isVariadic()) {
735 if (FD->getNumParams()) POut << ", ";
736 POut << "...";
737 } else if ((IK == FuncSig || IK == LFuncSig ||
738 !Context.getLangOpts().CPlusPlus) &&
739 !Decl->getNumParams()) {
740 POut << "void";
741 }
742 }
743 POut << ")";
744
745 if (const CXXMethodDecl *MD
18.1
'MD' is null
18.1
'MD' is null
= dyn_cast<CXXMethodDecl>(FD)) {
18
'FD' is not a 'CXXMethodDecl'
19
Taking false branch
746 assert(FT && "We must have a written prototype in this case.")((FT && "We must have a written prototype in this case."
) ? static_cast<void> (0) : __assert_fail ("FT && \"We must have a written prototype in this case.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 746, __PRETTY_FUNCTION__))
;
747 if (FT->isConst())
748 POut << " const";
749 if (FT->isVolatile())
750 POut << " volatile";
751 RefQualifierKind Ref = MD->getRefQualifier();
752 if (Ref == RQ_LValue)
753 POut << " &";
754 else if (Ref == RQ_RValue)
755 POut << " &&";
756 }
757
758 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
759 SpecsTy Specs;
760 const DeclContext *Ctx = FD->getDeclContext();
761 while (Ctx && isa<NamedDecl>(Ctx)) {
20
Assuming 'Ctx' is null
762 const ClassTemplateSpecializationDecl *Spec
763 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
764 if (Spec && !Spec->isExplicitSpecialization())
765 Specs.push_back(Spec);
766 Ctx = Ctx->getParent();
767 }
768
769 std::string TemplateParams;
770 llvm::raw_string_ostream TOut(TemplateParams);
771 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
28
Loop condition is false. Execution continues on line 787
772 I != E; ++I) {
21
Calling 'operator!=<const clang::ClassTemplateSpecializationDecl **>'
27
Returning from 'operator!=<const clang::ClassTemplateSpecializationDecl **>'
773 const TemplateParameterList *Params
774 = (*I)->getSpecializedTemplate()->getTemplateParameters();
775 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
776 assert(Params->size() == Args.size())((Params->size() == Args.size()) ? static_cast<void>
(0) : __assert_fail ("Params->size() == Args.size()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 776, __PRETTY_FUNCTION__))
;
777 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
778 StringRef Param = Params->getParam(i)->getName();
779 if (Param.empty()) continue;
780 TOut << Param << " = ";
781 Args.get(i).print(Policy, TOut);
782 TOut << ", ";
783 }
784 }
785
786 FunctionTemplateSpecializationInfo *FSI
787 = FD->getTemplateSpecializationInfo();
788 if (FSI && !FSI->isExplicitSpecialization()) {
29
Assuming 'FSI' is null
789 const TemplateParameterList* Params
790 = FSI->getTemplate()->getTemplateParameters();
791 const TemplateArgumentList* Args = FSI->TemplateArguments;
792 assert(Params->size() == Args->size())((Params->size() == Args->size()) ? static_cast<void
> (0) : __assert_fail ("Params->size() == Args->size()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 792, __PRETTY_FUNCTION__))
;
793 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
794 StringRef Param = Params->getParam(i)->getName();
795 if (Param.empty()) continue;
796 TOut << Param << " = ";
797 Args->get(i).print(Policy, TOut);
798 TOut << ", ";
799 }
800 }
801
802 TOut.flush();
803 if (!TemplateParams.empty()) {
30
Assuming the condition is false
31
Taking false branch
804 // remove the trailing comma and space
805 TemplateParams.resize(TemplateParams.size() - 2);
806 POut << " [" << TemplateParams << "]";
807 }
808
809 POut.flush();
810
811 // Print "auto" for all deduced return types. This includes C++1y return
812 // type deduction and lambdas. For trailing return types resolve the
813 // decltype expression. Otherwise print the real type when this is
814 // not a constructor or destructor.
815 if (isa<CXXMethodDecl>(FD) &&
32
Assuming 'FD' is not a 'CXXMethodDecl'
816 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
817 Proto = "auto " + Proto;
818 else if (FT
32.1
'FT' is null
32.1
'FT' is null
&& FT->getReturnType()->getAs<DecltypeType>())
33
Taking false branch
819 FT->getReturnType()
820 ->getAs<DecltypeType>()
821 ->getUnderlyingType()
822 .getAsStringInternal(Proto, Policy);
823 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
34
Assuming 'FD' is not a 'CXXConstructorDecl'
35
Assuming 'FD' is not a 'CXXDestructorDecl'
36
Taking true branch
824 AFT->getReturnType().getAsStringInternal(Proto, Policy);
37
Called C++ object pointer is null
825
826 Out << Proto;
827
828 return std::string(Name);
829 }
830 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
831 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
832 // Skip to its enclosing function or method, but not its enclosing
833 // CapturedDecl.
834 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
835 const Decl *D = Decl::castFromDeclContext(DC);
836 return ComputeName(IK, D);
837 }
838 llvm_unreachable("CapturedDecl not inside a function or method")::llvm::llvm_unreachable_internal("CapturedDecl not inside a function or method"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 838)
;
839 }
840 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
841 SmallString<256> Name;
842 llvm::raw_svector_ostream Out(Name);
843 Out << (MD->isInstanceMethod() ? '-' : '+');
844 Out << '[';
845
846 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
847 // a null check to avoid a crash.
848 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
849 Out << *ID;
850
851 if (const ObjCCategoryImplDecl *CID =
852 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
853 Out << '(' << *CID << ')';
854
855 Out << ' ';
856 MD->getSelector().print(Out);
857 Out << ']';
858
859 return std::string(Name);
860 }
861 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
862 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
863 return "top level";
864 }
865 return "";
866}
867
868void APNumericStorage::setIntValue(const ASTContext &C,
869 const llvm::APInt &Val) {
870 if (hasAllocation())
871 C.Deallocate(pVal);
872
873 BitWidth = Val.getBitWidth();
874 unsigned NumWords = Val.getNumWords();
875 const uint64_t* Words = Val.getRawData();
876 if (NumWords > 1) {
877 pVal = new (C) uint64_t[NumWords];
878 std::copy(Words, Words + NumWords, pVal);
879 } else if (NumWords == 1)
880 VAL = Words[0];
881 else
882 VAL = 0;
883}
884
885IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
886 QualType type, SourceLocation l)
887 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
888 false, false),
889 Loc(l) {
890 assert(type->isIntegerType() && "Illegal type in IntegerLiteral")((type->isIntegerType() && "Illegal type in IntegerLiteral"
) ? static_cast<void> (0) : __assert_fail ("type->isIntegerType() && \"Illegal type in IntegerLiteral\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 890, __PRETTY_FUNCTION__))
;
891 assert(V.getBitWidth() == C.getIntWidth(type) &&((V.getBitWidth() == C.getIntWidth(type) && "Integer type is not the correct size for constant."
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == C.getIntWidth(type) && \"Integer type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 892, __PRETTY_FUNCTION__))
892 "Integer type is not the correct size for constant.")((V.getBitWidth() == C.getIntWidth(type) && "Integer type is not the correct size for constant."
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == C.getIntWidth(type) && \"Integer type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 892, __PRETTY_FUNCTION__))
;
893 setValue(C, V);
894}
895
896IntegerLiteral *
897IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
898 QualType type, SourceLocation l) {
899 return new (C) IntegerLiteral(C, V, type, l);
900}
901
902IntegerLiteral *
903IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
904 return new (C) IntegerLiteral(Empty);
905}
906
907FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
908 QualType type, SourceLocation l,
909 unsigned Scale)
910 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
911 false, false),
912 Loc(l), Scale(Scale) {
913 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral")((type->isFixedPointType() && "Illegal type in FixedPointLiteral"
) ? static_cast<void> (0) : __assert_fail ("type->isFixedPointType() && \"Illegal type in FixedPointLiteral\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 913, __PRETTY_FUNCTION__))
;
914 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&((V.getBitWidth() == C.getTypeInfo(type).Width && "Fixed point type is not the correct size for constant."
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == C.getTypeInfo(type).Width && \"Fixed point type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 915, __PRETTY_FUNCTION__))
915 "Fixed point type is not the correct size for constant.")((V.getBitWidth() == C.getTypeInfo(type).Width && "Fixed point type is not the correct size for constant."
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == C.getTypeInfo(type).Width && \"Fixed point type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 915, __PRETTY_FUNCTION__))
;
916 setValue(C, V);
917}
918
919FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
920 const llvm::APInt &V,
921 QualType type,
922 SourceLocation l,
923 unsigned Scale) {
924 return new (C) FixedPointLiteral(C, V, type, l, Scale);
925}
926
927std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
928 // Currently the longest decimal number that can be printed is the max for an
929 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
930 // which is 43 characters.
931 SmallString<64> S;
932 FixedPointValueToString(
933 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
934 return std::string(S.str());
935}
936
937FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
938 bool isexact, QualType Type, SourceLocation L)
939 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
940 false, false), Loc(L) {
941 setSemantics(V.getSemantics());
942 FloatingLiteralBits.IsExact = isexact;
943 setValue(C, V);
944}
945
946FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
947 : Expr(FloatingLiteralClass, Empty) {
948 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
949 FloatingLiteralBits.IsExact = false;
950}
951
952FloatingLiteral *
953FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
954 bool isexact, QualType Type, SourceLocation L) {
955 return new (C) FloatingLiteral(C, V, isexact, Type, L);
956}
957
958FloatingLiteral *
959FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
960 return new (C) FloatingLiteral(C, Empty);
961}
962
963/// getValueAsApproximateDouble - This returns the value as an inaccurate
964/// double. Note that this may cause loss of precision, but is useful for
965/// debugging dumps, etc.
966double FloatingLiteral::getValueAsApproximateDouble() const {
967 llvm::APFloat V = getValue();
968 bool ignored;
969 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
970 &ignored);
971 return V.convertToDouble();
972}
973
974unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
975 StringKind SK) {
976 unsigned CharByteWidth = 0;
977 switch (SK) {
978 case Ascii:
979 case UTF8:
980 CharByteWidth = Target.getCharWidth();
981 break;
982 case Wide:
983 CharByteWidth = Target.getWCharWidth();
984 break;
985 case UTF16:
986 CharByteWidth = Target.getChar16Width();
987 break;
988 case UTF32:
989 CharByteWidth = Target.getChar32Width();
990 break;
991 }
992 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple")(((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"
) ? static_cast<void> (0) : __assert_fail ("(CharByteWidth & 7) == 0 && \"Assumes character size is byte multiple\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 992, __PRETTY_FUNCTION__))
;
993 CharByteWidth /= 8;
994 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&(((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth ==
4) && "The only supported character byte widths are 1,2 and 4!"
) ? static_cast<void> (0) : __assert_fail ("(CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && \"The only supported character byte widths are 1,2 and 4!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 995, __PRETTY_FUNCTION__))
995 "The only supported character byte widths are 1,2 and 4!")(((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth ==
4) && "The only supported character byte widths are 1,2 and 4!"
) ? static_cast<void> (0) : __assert_fail ("(CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && \"The only supported character byte widths are 1,2 and 4!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 995, __PRETTY_FUNCTION__))
;
996 return CharByteWidth;
997}
998
999StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1000 StringKind Kind, bool Pascal, QualType Ty,
1001 const SourceLocation *Loc,
1002 unsigned NumConcatenated)
1003 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1004 false) {
1005 assert(Ctx.getAsConstantArrayType(Ty) &&((Ctx.getAsConstantArrayType(Ty) && "StringLiteral must be of constant array type!"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getAsConstantArrayType(Ty) && \"StringLiteral must be of constant array type!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1006, __PRETTY_FUNCTION__))
1006 "StringLiteral must be of constant array type!")((Ctx.getAsConstantArrayType(Ty) && "StringLiteral must be of constant array type!"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getAsConstantArrayType(Ty) && \"StringLiteral must be of constant array type!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1006, __PRETTY_FUNCTION__))
;
1007 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1008 unsigned ByteLength = Str.size();
1009 assert((ByteLength % CharByteWidth == 0) &&(((ByteLength % CharByteWidth == 0) && "The size of the data must be a multiple of CharByteWidth!"
) ? static_cast<void> (0) : __assert_fail ("(ByteLength % CharByteWidth == 0) && \"The size of the data must be a multiple of CharByteWidth!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1010, __PRETTY_FUNCTION__))
1010 "The size of the data must be a multiple of CharByteWidth!")(((ByteLength % CharByteWidth == 0) && "The size of the data must be a multiple of CharByteWidth!"
) ? static_cast<void> (0) : __assert_fail ("(ByteLength % CharByteWidth == 0) && \"The size of the data must be a multiple of CharByteWidth!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1010, __PRETTY_FUNCTION__))
;
1011
1012 // Avoid the expensive division. The compiler should be able to figure it
1013 // out by itself. However as of clang 7, even with the appropriate
1014 // llvm_unreachable added just here, it is not able to do so.
1015 unsigned Length;
1016 switch (CharByteWidth) {
1017 case 1:
1018 Length = ByteLength;
1019 break;
1020 case 2:
1021 Length = ByteLength / 2;
1022 break;
1023 case 4:
1024 Length = ByteLength / 4;
1025 break;
1026 default:
1027 llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1027)
;
1028 }
1029
1030 StringLiteralBits.Kind = Kind;
1031 StringLiteralBits.CharByteWidth = CharByteWidth;
1032 StringLiteralBits.IsPascal = Pascal;
1033 StringLiteralBits.NumConcatenated = NumConcatenated;
1034 *getTrailingObjects<unsigned>() = Length;
1035
1036 // Initialize the trailing array of SourceLocation.
1037 // This is safe since SourceLocation is POD-like.
1038 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1039 NumConcatenated * sizeof(SourceLocation));
1040
1041 // Initialize the trailing array of char holding the string data.
1042 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1043}
1044
1045StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1046 unsigned Length, unsigned CharByteWidth)
1047 : Expr(StringLiteralClass, Empty) {
1048 StringLiteralBits.CharByteWidth = CharByteWidth;
1049 StringLiteralBits.NumConcatenated = NumConcatenated;
1050 *getTrailingObjects<unsigned>() = Length;
1051}
1052
1053StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1054 StringKind Kind, bool Pascal, QualType Ty,
1055 const SourceLocation *Loc,
1056 unsigned NumConcatenated) {
1057 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1058 1, NumConcatenated, Str.size()),
1059 alignof(StringLiteral));
1060 return new (Mem)
1061 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1062}
1063
1064StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1065 unsigned NumConcatenated,
1066 unsigned Length,
1067 unsigned CharByteWidth) {
1068 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1069 1, NumConcatenated, Length * CharByteWidth),
1070 alignof(StringLiteral));
1071 return new (Mem)
1072 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1073}
1074
1075void StringLiteral::outputString(raw_ostream &OS) const {
1076 switch (getKind()) {
1077 case Ascii: break; // no prefix.
1078 case Wide: OS << 'L'; break;
1079 case UTF8: OS << "u8"; break;
1080 case UTF16: OS << 'u'; break;
1081 case UTF32: OS << 'U'; break;
1082 }
1083 OS << '"';
1084 static const char Hex[] = "0123456789ABCDEF";
1085
1086 unsigned LastSlashX = getLength();
1087 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1088 switch (uint32_t Char = getCodeUnit(I)) {
1089 default:
1090 // FIXME: Convert UTF-8 back to codepoints before rendering.
1091
1092 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1093 // Leave invalid surrogates alone; we'll use \x for those.
1094 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1095 Char <= 0xdbff) {
1096 uint32_t Trail = getCodeUnit(I + 1);
1097 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1098 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1099 ++I;
1100 }
1101 }
1102
1103 if (Char > 0xff) {
1104 // If this is a wide string, output characters over 0xff using \x
1105 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1106 // codepoint: use \x escapes for invalid codepoints.
1107 if (getKind() == Wide ||
1108 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1109 // FIXME: Is this the best way to print wchar_t?
1110 OS << "\\x";
1111 int Shift = 28;
1112 while ((Char >> Shift) == 0)
1113 Shift -= 4;
1114 for (/**/; Shift >= 0; Shift -= 4)
1115 OS << Hex[(Char >> Shift) & 15];
1116 LastSlashX = I;
1117 break;
1118 }
1119
1120 if (Char > 0xffff)
1121 OS << "\\U00"
1122 << Hex[(Char >> 20) & 15]
1123 << Hex[(Char >> 16) & 15];
1124 else
1125 OS << "\\u";
1126 OS << Hex[(Char >> 12) & 15]
1127 << Hex[(Char >> 8) & 15]
1128 << Hex[(Char >> 4) & 15]
1129 << Hex[(Char >> 0) & 15];
1130 break;
1131 }
1132
1133 // If we used \x... for the previous character, and this character is a
1134 // hexadecimal digit, prevent it being slurped as part of the \x.
1135 if (LastSlashX + 1 == I) {
1136 switch (Char) {
1137 case '0': case '1': case '2': case '3': case '4':
1138 case '5': case '6': case '7': case '8': case '9':
1139 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1140 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1141 OS << "\"\"";
1142 }
1143 }
1144
1145 assert(Char <= 0xff &&((Char <= 0xff && "Characters above 0xff should already have been handled."
) ? static_cast<void> (0) : __assert_fail ("Char <= 0xff && \"Characters above 0xff should already have been handled.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1146, __PRETTY_FUNCTION__))
1146 "Characters above 0xff should already have been handled.")((Char <= 0xff && "Characters above 0xff should already have been handled."
) ? static_cast<void> (0) : __assert_fail ("Char <= 0xff && \"Characters above 0xff should already have been handled.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1146, __PRETTY_FUNCTION__))
;
1147
1148 if (isPrintable(Char))
1149 OS << (char)Char;
1150 else // Output anything hard as an octal escape.
1151 OS << '\\'
1152 << (char)('0' + ((Char >> 6) & 7))
1153 << (char)('0' + ((Char >> 3) & 7))
1154 << (char)('0' + ((Char >> 0) & 7));
1155 break;
1156 // Handle some common non-printable cases to make dumps prettier.
1157 case '\\': OS << "\\\\"; break;
1158 case '"': OS << "\\\""; break;
1159 case '\a': OS << "\\a"; break;
1160 case '\b': OS << "\\b"; break;
1161 case '\f': OS << "\\f"; break;
1162 case '\n': OS << "\\n"; break;
1163 case '\r': OS << "\\r"; break;
1164 case '\t': OS << "\\t"; break;
1165 case '\v': OS << "\\v"; break;
1166 }
1167 }
1168 OS << '"';
1169}
1170
1171/// getLocationOfByte - Return a source location that points to the specified
1172/// byte of this string literal.
1173///
1174/// Strings are amazingly complex. They can be formed from multiple tokens and
1175/// can have escape sequences in them in addition to the usual trigraph and
1176/// escaped newline business. This routine handles this complexity.
1177///
1178/// The *StartToken sets the first token to be searched in this function and
1179/// the *StartTokenByteOffset is the byte offset of the first token. Before
1180/// returning, it updates the *StartToken to the TokNo of the token being found
1181/// and sets *StartTokenByteOffset to the byte offset of the token in the
1182/// string.
1183/// Using these two parameters can reduce the time complexity from O(n^2) to
1184/// O(n) if one wants to get the location of byte for all the tokens in a
1185/// string.
1186///
1187SourceLocation
1188StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1189 const LangOptions &Features,
1190 const TargetInfo &Target, unsigned *StartToken,
1191 unsigned *StartTokenByteOffset) const {
1192 assert((getKind() == StringLiteral::Ascii ||(((getKind() == StringLiteral::Ascii || getKind() == StringLiteral
::UTF8) && "Only narrow string literals are currently supported"
) ? static_cast<void> (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1194, __PRETTY_FUNCTION__))
1193 getKind() == StringLiteral::UTF8) &&(((getKind() == StringLiteral::Ascii || getKind() == StringLiteral
::UTF8) && "Only narrow string literals are currently supported"
) ? static_cast<void> (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1194, __PRETTY_FUNCTION__))
1194 "Only narrow string literals are currently supported")(((getKind() == StringLiteral::Ascii || getKind() == StringLiteral
::UTF8) && "Only narrow string literals are currently supported"
) ? static_cast<void> (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1194, __PRETTY_FUNCTION__))
;
1195
1196 // Loop over all of the tokens in this string until we find the one that
1197 // contains the byte we're looking for.
1198 unsigned TokNo = 0;
1199 unsigned StringOffset = 0;
1200 if (StartToken)
1201 TokNo = *StartToken;
1202 if (StartTokenByteOffset) {
1203 StringOffset = *StartTokenByteOffset;
1204 ByteNo -= StringOffset;
1205 }
1206 while (1) {
1207 assert(TokNo < getNumConcatenated() && "Invalid byte number!")((TokNo < getNumConcatenated() && "Invalid byte number!"
) ? static_cast<void> (0) : __assert_fail ("TokNo < getNumConcatenated() && \"Invalid byte number!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1207, __PRETTY_FUNCTION__))
;
1208 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1209
1210 // Get the spelling of the string so that we can get the data that makes up
1211 // the string literal, not the identifier for the macro it is potentially
1212 // expanded through.
1213 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1214
1215 // Re-lex the token to get its length and original spelling.
1216 std::pair<FileID, unsigned> LocInfo =
1217 SM.getDecomposedLoc(StrTokSpellingLoc);
1218 bool Invalid = false;
1219 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1220 if (Invalid) {
1221 if (StartTokenByteOffset != nullptr)
1222 *StartTokenByteOffset = StringOffset;
1223 if (StartToken != nullptr)
1224 *StartToken = TokNo;
1225 return StrTokSpellingLoc;
1226 }
1227
1228 const char *StrData = Buffer.data()+LocInfo.second;
1229
1230 // Create a lexer starting at the beginning of this token.
1231 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1232 Buffer.begin(), StrData, Buffer.end());
1233 Token TheTok;
1234 TheLexer.LexFromRawLexer(TheTok);
1235
1236 // Use the StringLiteralParser to compute the length of the string in bytes.
1237 StringLiteralParser SLP(TheTok, SM, Features, Target);
1238 unsigned TokNumBytes = SLP.GetStringLength();
1239
1240 // If the byte is in this token, return the location of the byte.
1241 if (ByteNo < TokNumBytes ||
1242 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1243 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1244
1245 // Now that we know the offset of the token in the spelling, use the
1246 // preprocessor to get the offset in the original source.
1247 if (StartTokenByteOffset != nullptr)
1248 *StartTokenByteOffset = StringOffset;
1249 if (StartToken != nullptr)
1250 *StartToken = TokNo;
1251 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1252 }
1253
1254 // Move to the next string token.
1255 StringOffset += TokNumBytes;
1256 ++TokNo;
1257 ByteNo -= TokNumBytes;
1258 }
1259}
1260
1261/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1262/// corresponds to, e.g. "sizeof" or "[pre]++".
1263StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1264 switch (Op) {
1265#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1266#include "clang/AST/OperationKinds.def"
1267 }
1268 llvm_unreachable("Unknown unary operator")::llvm::llvm_unreachable_internal("Unknown unary operator", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1268)
;
1269}
1270
1271UnaryOperatorKind
1272UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1273 switch (OO) {
1274 default: llvm_unreachable("No unary operator for overloaded function")::llvm::llvm_unreachable_internal("No unary operator for overloaded function"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1274)
;
1275 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1276 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1277 case OO_Amp: return UO_AddrOf;
1278 case OO_Star: return UO_Deref;
1279 case OO_Plus: return UO_Plus;
1280 case OO_Minus: return UO_Minus;
1281 case OO_Tilde: return UO_Not;
1282 case OO_Exclaim: return UO_LNot;
1283 case OO_Coawait: return UO_Coawait;
1284 }
1285}
1286
1287OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1288 switch (Opc) {
1289 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1290 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1291 case UO_AddrOf: return OO_Amp;
1292 case UO_Deref: return OO_Star;
1293 case UO_Plus: return OO_Plus;
1294 case UO_Minus: return OO_Minus;
1295 case UO_Not: return OO_Tilde;
1296 case UO_LNot: return OO_Exclaim;
1297 case UO_Coawait: return OO_Coawait;
1298 default: return OO_None;
1299 }
1300}
1301
1302
1303//===----------------------------------------------------------------------===//
1304// Postfix Operators.
1305//===----------------------------------------------------------------------===//
1306
1307CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1308 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1309 SourceLocation RParenLoc, unsigned MinNumArgs,
1310 ADLCallKind UsesADL)
1311 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1312 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1313 Fn->containsUnexpandedParameterPack()),
1314 RParenLoc(RParenLoc) {
1315 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1316 unsigned NumPreArgs = PreArgs.size();
1317 CallExprBits.NumPreArgs = NumPreArgs;
1318 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!"
) ? static_cast<void> (0) : __assert_fail ("(NumPreArgs == getNumPreArgs()) && \"NumPreArgs overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1318, __PRETTY_FUNCTION__))
;
1319
1320 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1321 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1322 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects
) && "OffsetToTrailingObjects overflow!") ? static_cast
<void> (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1323, __PRETTY_FUNCTION__))
1323 "OffsetToTrailingObjects overflow!")(((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects
) && "OffsetToTrailingObjects overflow!") ? static_cast
<void> (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1323, __PRETTY_FUNCTION__))
;
1324
1325 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1326
1327 setCallee(Fn);
1328 for (unsigned I = 0; I != NumPreArgs; ++I) {
1329 addDependence(PreArgs[I]->getDependence());
1330 setPreArg(I, PreArgs[I]);
1331 }
1332 for (unsigned I = 0; I != Args.size(); ++I) {
1333 addDependence(Args[I]->getDependence());
1334 setArg(I, Args[I]);
1335 }
1336 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1337 setArg(I, nullptr);
1338 }
1339}
1340
1341CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1342 EmptyShell Empty)
1343 : Expr(SC, Empty), NumArgs(NumArgs) {
1344 CallExprBits.NumPreArgs = NumPreArgs;
1345 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!"
) ? static_cast<void> (0) : __assert_fail ("(NumPreArgs == getNumPreArgs()) && \"NumPreArgs overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1345, __PRETTY_FUNCTION__))
;
1346
1347 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1348 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1349 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects
) && "OffsetToTrailingObjects overflow!") ? static_cast
<void> (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1350, __PRETTY_FUNCTION__))
1350 "OffsetToTrailingObjects overflow!")(((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects
) && "OffsetToTrailingObjects overflow!") ? static_cast
<void> (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1350, __PRETTY_FUNCTION__))
;
1351}
1352
1353CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1354 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1355 SourceLocation RParenLoc, unsigned MinNumArgs,
1356 ADLCallKind UsesADL) {
1357 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1358 unsigned SizeOfTrailingObjects =
1359 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1360 void *Mem =
1361 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1362 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1363 RParenLoc, MinNumArgs, UsesADL);
1364}
1365
1366CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1367 ExprValueKind VK, SourceLocation RParenLoc,
1368 ADLCallKind UsesADL) {
1369 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&((!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr
)) && "Misaligned memory in CallExpr::CreateTemporary!"
) ? static_cast<void> (0) : __assert_fail ("!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) && \"Misaligned memory in CallExpr::CreateTemporary!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1370, __PRETTY_FUNCTION__))
1370 "Misaligned memory in CallExpr::CreateTemporary!")((!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr
)) && "Misaligned memory in CallExpr::CreateTemporary!"
) ? static_cast<void> (0) : __assert_fail ("!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) && \"Misaligned memory in CallExpr::CreateTemporary!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1370, __PRETTY_FUNCTION__))
;
1371 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1372 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1373}
1374
1375CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1376 EmptyShell Empty) {
1377 unsigned SizeOfTrailingObjects =
1378 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1379 void *Mem =
1380 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1381 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1382}
1383
1384unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1385 switch (SC) {
1386 case CallExprClass:
1387 return sizeof(CallExpr);
1388 case CXXOperatorCallExprClass:
1389 return sizeof(CXXOperatorCallExpr);
1390 case CXXMemberCallExprClass:
1391 return sizeof(CXXMemberCallExpr);
1392 case UserDefinedLiteralClass:
1393 return sizeof(UserDefinedLiteral);
1394 case CUDAKernelCallExprClass:
1395 return sizeof(CUDAKernelCallExpr);
1396 default:
1397 llvm_unreachable("unexpected class deriving from CallExpr!")::llvm::llvm_unreachable_internal("unexpected class deriving from CallExpr!"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1397)
;
1398 }
1399}
1400
1401Decl *Expr::getReferencedDeclOfCallee() {
1402 Expr *CEE = IgnoreParenImpCasts();
1403
1404 while (SubstNonTypeTemplateParmExpr *NTTP =
1405 dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1406 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1407 }
1408
1409 // If we're calling a dereference, look at the pointer instead.
1410 while (true) {
1411 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1412 if (BO->isPtrMemOp()) {
1413 CEE = BO->getRHS()->IgnoreParenImpCasts();
1414 continue;
1415 }
1416 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1417 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1418 UO->getOpcode() == UO_Plus) {
1419 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1420 continue;
1421 }
1422 }
1423 break;
1424 }
1425
1426 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1427 return DRE->getDecl();
1428 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1429 return ME->getMemberDecl();
1430 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1431 return BE->getBlockDecl();
1432
1433 return nullptr;
1434}
1435
1436/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1437unsigned CallExpr::getBuiltinCallee() const {
1438 auto *FDecl =
1439 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1440 return FDecl ? FDecl->getBuiltinID() : 0;
1441}
1442
1443bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1444 if (unsigned BI = getBuiltinCallee())
1445 return Ctx.BuiltinInfo.isUnevaluated(BI);
1446 return false;
1447}
1448
1449QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1450 const Expr *Callee = getCallee();
1451 QualType CalleeType = Callee->getType();
1452 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1453 CalleeType = FnTypePtr->getPointeeType();
1454 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1455 CalleeType = BPT->getPointeeType();
1456 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1457 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1458 return Ctx.VoidTy;
1459
1460 // This should never be overloaded and so should never return null.
1461 CalleeType = Expr::findBoundMemberType(Callee);
1462 }
1463
1464 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1465 return FnType->getReturnType();
1466}
1467
1468const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1469 // If the return type is a struct, union, or enum that is marked nodiscard,
1470 // then return the return type attribute.
1471 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1472 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1473 return A;
1474
1475 // Otherwise, see if the callee is marked nodiscard and return that attribute
1476 // instead.
1477 const Decl *D = getCalleeDecl();
1478 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1479}
1480
1481SourceLocation CallExpr::getBeginLoc() const {
1482 if (isa<CXXOperatorCallExpr>(this))
1483 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1484
1485 SourceLocation begin = getCallee()->getBeginLoc();
1486 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1487 begin = getArg(0)->getBeginLoc();
1488 return begin;
1489}
1490SourceLocation CallExpr::getEndLoc() const {
1491 if (isa<CXXOperatorCallExpr>(this))
1492 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1493
1494 SourceLocation end = getRParenLoc();
1495 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1496 end = getArg(getNumArgs() - 1)->getEndLoc();
1497 return end;
1498}
1499
1500OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1501 SourceLocation OperatorLoc,
1502 TypeSourceInfo *tsi,
1503 ArrayRef<OffsetOfNode> comps,
1504 ArrayRef<Expr*> exprs,
1505 SourceLocation RParenLoc) {
1506 void *Mem = C.Allocate(
1507 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1508
1509 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1510 RParenLoc);
1511}
1512
1513OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1514 unsigned numComps, unsigned numExprs) {
1515 void *Mem =
1516 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1517 return new (Mem) OffsetOfExpr(numComps, numExprs);
1518}
1519
1520OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1521 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1522 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1523 SourceLocation RParenLoc)
1524 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1525 /*TypeDependent=*/false,
1526 /*ValueDependent=*/tsi->getType()->isDependentType(),
1527 tsi->getType()->isInstantiationDependentType(),
1528 tsi->getType()->containsUnexpandedParameterPack()),
1529 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1530 NumComps(comps.size()), NumExprs(exprs.size())
1531{
1532 for (unsigned i = 0; i != comps.size(); ++i) {
1533 setComponent(i, comps[i]);
1534 }
1535
1536 for (unsigned i = 0; i != exprs.size(); ++i) {
1537 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1538 addDependence(ExprDependence::Value);
1539 if (exprs[i]->containsUnexpandedParameterPack())
1540 addDependence(ExprDependence ::UnexpandedPack);
1541
1542 setIndexExpr(i, exprs[i]);
1543 }
1544}
1545
1546IdentifierInfo *OffsetOfNode::getFieldName() const {
1547 assert(getKind() == Field || getKind() == Identifier)((getKind() == Field || getKind() == Identifier) ? static_cast
<void> (0) : __assert_fail ("getKind() == Field || getKind() == Identifier"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1547, __PRETTY_FUNCTION__))
;
1548 if (getKind() == Field)
1549 return getField()->getIdentifier();
1550
1551 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1552}
1553
1554UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1555 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1556 SourceLocation op, SourceLocation rp)
1557 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1558 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1559 // Value-dependent if the argument is type-dependent.
1560 E->isTypeDependent(), E->isInstantiationDependent(),
1561 E->containsUnexpandedParameterPack()),
1562 OpLoc(op), RParenLoc(rp) {
1563 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1564 UnaryExprOrTypeTraitExprBits.IsType = false;
1565 Argument.Ex = E;
1566
1567 // Check to see if we are in the situation where alignof(decl) should be
1568 // dependent because decl's alignment is dependent.
1569 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
1570 if (!isValueDependent() || !isInstantiationDependent()) {
1571 E = E->IgnoreParens();
1572
1573 const ValueDecl *D = nullptr;
1574 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1575 D = DRE->getDecl();
1576 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1577 D = ME->getMemberDecl();
1578
1579 if (D) {
1580 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1581 if (I->isAlignmentDependent()) {
1582 addDependence(ExprDependence::ValueInstantiation);
1583 break;
1584 }
1585 }
1586 }
1587 }
1588 }
1589}
1590
1591MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1592 ValueDecl *MemberDecl,
1593 const DeclarationNameInfo &NameInfo, QualType T,
1594 ExprValueKind VK, ExprObjectKind OK,
1595 NonOdrUseReason NOUR)
1596 : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1597 Base->isValueDependent(), Base->isInstantiationDependent(),
1598 Base->containsUnexpandedParameterPack()),
1599 Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1600 MemberLoc(NameInfo.getLoc()) {
1601 assert(!NameInfo.getName() ||((!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo
.getName()) ? static_cast<void> (0) : __assert_fail ("!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo.getName()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1602, __PRETTY_FUNCTION__))
1602 MemberDecl->getDeclName() == NameInfo.getName())((!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo
.getName()) ? static_cast<void> (0) : __assert_fail ("!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo.getName()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1602, __PRETTY_FUNCTION__))
;
1603 MemberExprBits.IsArrow = IsArrow;
1604 MemberExprBits.HasQualifierOrFoundDecl = false;
1605 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1606 MemberExprBits.HadMultipleCandidates = false;
1607 MemberExprBits.NonOdrUseReason = NOUR;
1608 MemberExprBits.OperatorLoc = OperatorLoc;
1609}
1610
1611MemberExpr *MemberExpr::Create(
1612 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1613 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1614 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1615 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1616 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1617 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1618 FoundDecl.getAccess() != MemberDecl->getAccess();
1619 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1620 std::size_t Size =
1621 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1622 TemplateArgumentLoc>(
1623 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1624 TemplateArgs ? TemplateArgs->size() : 0);
1625
1626 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1627 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1628 NameInfo, T, VK, OK, NOUR);
1629
1630 if (isa<FieldDecl>(MemberDecl)) {
1631 DeclContext *DC = MemberDecl->getDeclContext();
1632 // dyn_cast_or_null is used to handle objC variables which do not
1633 // have a declaration context.
1634 CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC);
1635 if (RD && RD->isDependentContext() && RD->isCurrentInstantiation(DC)) {
1636 if (E->isTypeDependent() && !T->isDependentType())
1637 E->removeDependence(ExprDependence::Type);
1638 }
1639 // Bitfield with value-dependent width is type-dependent.
1640 FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl);
1641 if (FD && FD->isBitField() && FD->getBitWidth()->isValueDependent())
1642 E->addDependence(ExprDependence::Type);
1643 }
1644
1645 if (HasQualOrFound) {
1646 // FIXME: Wrong. We should be looking at the member declaration we found.
1647 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1648 E->addDependence(ExprDependence::TypeValueInstantiation);
1649 else if (QualifierLoc &&
1650 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1651 E->addDependence(ExprDependence::Instantiation);
1652
1653 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1654
1655 MemberExprNameQualifier *NQ =
1656 E->getTrailingObjects<MemberExprNameQualifier>();
1657 NQ->QualifierLoc = QualifierLoc;
1658 NQ->FoundDecl = FoundDecl;
1659 }
1660
1661 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1662 TemplateArgs || TemplateKWLoc.isValid();
1663
1664 if (TemplateArgs) {
1665 auto Deps = TemplateArgumentDependence::None;
1666 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1667 TemplateKWLoc, *TemplateArgs,
1668 E->getTrailingObjects<TemplateArgumentLoc>(), Deps);
1669 if (Deps & TemplateArgumentDependence::Instantiation)
1670 E->addDependence(ExprDependence::Instantiation);
1671 } else if (TemplateKWLoc.isValid()) {
1672 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1673 TemplateKWLoc);
1674 }
1675
1676 return E;
1677}
1678
1679MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1680 bool HasQualifier, bool HasFoundDecl,
1681 bool HasTemplateKWAndArgsInfo,
1682 unsigned NumTemplateArgs) {
1683 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&(((!NumTemplateArgs || HasTemplateKWAndArgsInfo) && "template args but no template arg info?"
) ? static_cast<void> (0) : __assert_fail ("(!NumTemplateArgs || HasTemplateKWAndArgsInfo) && \"template args but no template arg info?\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1684, __PRETTY_FUNCTION__))
1684 "template args but no template arg info?")(((!NumTemplateArgs || HasTemplateKWAndArgsInfo) && "template args but no template arg info?"
) ? static_cast<void> (0) : __assert_fail ("(!NumTemplateArgs || HasTemplateKWAndArgsInfo) && \"template args but no template arg info?\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1684, __PRETTY_FUNCTION__))
;
1685 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1686 std::size_t Size =
1687 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1688 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1689 HasTemplateKWAndArgsInfo ? 1 : 0,
1690 NumTemplateArgs);
1691 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1692 return new (Mem) MemberExpr(EmptyShell());
1693}
1694
1695SourceLocation MemberExpr::getBeginLoc() const {
1696 if (isImplicitAccess()) {
1697 if (hasQualifier())
1698 return getQualifierLoc().getBeginLoc();
1699 return MemberLoc;
1700 }
1701
1702 // FIXME: We don't want this to happen. Rather, we should be able to
1703 // detect all kinds of implicit accesses more cleanly.
1704 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1705 if (BaseStartLoc.isValid())
1706 return BaseStartLoc;
1707 return MemberLoc;
1708}
1709SourceLocation MemberExpr::getEndLoc() const {
1710 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1711 if (hasExplicitTemplateArgs())
1712 EndLoc = getRAngleLoc();
1713 else if (EndLoc.isInvalid())
1714 EndLoc = getBase()->getEndLoc();
1715 return EndLoc;
1716}
1717
1718bool CastExpr::CastConsistency() const {
1719 switch (getCastKind()) {
1720 case CK_DerivedToBase:
1721 case CK_UncheckedDerivedToBase:
1722 case CK_DerivedToBaseMemberPointer:
1723 case CK_BaseToDerived:
1724 case CK_BaseToDerivedMemberPointer:
1725 assert(!path_empty() && "Cast kind should have a base path!")((!path_empty() && "Cast kind should have a base path!"
) ? static_cast<void> (0) : __assert_fail ("!path_empty() && \"Cast kind should have a base path!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1725, __PRETTY_FUNCTION__))
;
1726 break;
1727
1728 case CK_CPointerToObjCPointerCast:
1729 assert(getType()->isObjCObjectPointerType())((getType()->isObjCObjectPointerType()) ? static_cast<void
> (0) : __assert_fail ("getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1729, __PRETTY_FUNCTION__))
;
1730 assert(getSubExpr()->getType()->isPointerType())((getSubExpr()->getType()->isPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1730, __PRETTY_FUNCTION__))
;
1731 goto CheckNoBasePath;
1732
1733 case CK_BlockPointerToObjCPointerCast:
1734 assert(getType()->isObjCObjectPointerType())((getType()->isObjCObjectPointerType()) ? static_cast<void
> (0) : __assert_fail ("getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1734, __PRETTY_FUNCTION__))
;
1735 assert(getSubExpr()->getType()->isBlockPointerType())((getSubExpr()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1735, __PRETTY_FUNCTION__))
;
1736 goto CheckNoBasePath;
1737
1738 case CK_ReinterpretMemberPointer:
1739 assert(getType()->isMemberPointerType())((getType()->isMemberPointerType()) ? static_cast<void>
(0) : __assert_fail ("getType()->isMemberPointerType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1739, __PRETTY_FUNCTION__))
;
1740 assert(getSubExpr()->getType()->isMemberPointerType())((getSubExpr()->getType()->isMemberPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1740, __PRETTY_FUNCTION__))
;
1741 goto CheckNoBasePath;
1742
1743 case CK_BitCast:
1744 // Arbitrary casts to C pointer types count as bitcasts.
1745 // Otherwise, we should only have block and ObjC pointer casts
1746 // here if they stay within the type kind.
1747 if (!getType()->isPointerType()) {
1748 assert(getType()->isObjCObjectPointerType() ==((getType()->isObjCObjectPointerType() == getSubExpr()->
getType()->isObjCObjectPointerType()) ? static_cast<void
> (0) : __assert_fail ("getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 getSubExpr()->getType()->isObjCObjectPointerType())((getType()->isObjCObjectPointerType() == getSubExpr()->
getType()->isObjCObjectPointerType()) ? static_cast<void
> (0) : __assert_fail ("getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1749, __PRETTY_FUNCTION__))
;
1750 assert(getType()->isBlockPointerType() ==((getType()->isBlockPointerType() == getSubExpr()->getType
()->isBlockPointerType()) ? static_cast<void> (0) : __assert_fail
("getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1751, __PRETTY_FUNCTION__))
1751 getSubExpr()->getType()->isBlockPointerType())((getType()->isBlockPointerType() == getSubExpr()->getType
()->isBlockPointerType()) ? static_cast<void> (0) : __assert_fail
("getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1751, __PRETTY_FUNCTION__))
;
1752 }
1753 goto CheckNoBasePath;
1754
1755 case CK_AnyPointerToBlockPointerCast:
1756 assert(getType()->isBlockPointerType())((getType()->isBlockPointerType()) ? static_cast<void>
(0) : __assert_fail ("getType()->isBlockPointerType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1756, __PRETTY_FUNCTION__))
;
1757 assert(getSubExpr()->getType()->isAnyPointerType() &&((getSubExpr()->getType()->isAnyPointerType() &&
!getSubExpr()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isAnyPointerType() && !getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1758, __PRETTY_FUNCTION__))
1758 !getSubExpr()->getType()->isBlockPointerType())((getSubExpr()->getType()->isAnyPointerType() &&
!getSubExpr()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isAnyPointerType() && !getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1758, __PRETTY_FUNCTION__))
;
1759 goto CheckNoBasePath;
1760
1761 case CK_CopyAndAutoreleaseBlockObject:
1762 assert(getType()->isBlockPointerType())((getType()->isBlockPointerType()) ? static_cast<void>
(0) : __assert_fail ("getType()->isBlockPointerType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1762, __PRETTY_FUNCTION__))
;
1763 assert(getSubExpr()->getType()->isBlockPointerType())((getSubExpr()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1763, __PRETTY_FUNCTION__))
;
1764 goto CheckNoBasePath;
1765
1766 case CK_FunctionToPointerDecay:
1767 assert(getType()->isPointerType())((getType()->isPointerType()) ? static_cast<void> (0
) : __assert_fail ("getType()->isPointerType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1767, __PRETTY_FUNCTION__))
;
1768 assert(getSubExpr()->getType()->isFunctionType())((getSubExpr()->getType()->isFunctionType()) ? static_cast
<void> (0) : __assert_fail ("getSubExpr()->getType()->isFunctionType()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1768, __PRETTY_FUNCTION__))
;
1769 goto CheckNoBasePath;
1770
1771 case CK_AddressSpaceConversion: {
1772 auto Ty = getType();
1773 auto SETy = getSubExpr()->getType();
1774 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy))((getValueKindForType(Ty) == Expr::getValueKindForType(SETy))
? static_cast<void> (0) : __assert_fail ("getValueKindForType(Ty) == Expr::getValueKindForType(SETy)"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1774, __PRETTY_FUNCTION__))
;
1775 if (isRValue()) {
1776 Ty = Ty->getPointeeType();
1777 SETy = SETy->getPointeeType();
1778 }
1779 assert(!Ty.isNull() && !SETy.isNull() &&((!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace
() != SETy.getAddressSpace()) ? static_cast<void> (0) :
__assert_fail ("!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace() != SETy.getAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1780, __PRETTY_FUNCTION__))
1780 Ty.getAddressSpace() != SETy.getAddressSpace())((!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace
() != SETy.getAddressSpace()) ? static_cast<void> (0) :
__assert_fail ("!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace() != SETy.getAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1780, __PRETTY_FUNCTION__))
;
1781 goto CheckNoBasePath;
1782 }
1783 // These should not have an inheritance path.
1784 case CK_Dynamic:
1785 case CK_ToUnion:
1786 case CK_ArrayToPointerDecay:
1787 case CK_NullToMemberPointer:
1788 case CK_NullToPointer:
1789 case CK_ConstructorConversion:
1790 case CK_IntegralToPointer:
1791 case CK_PointerToIntegral:
1792 case CK_ToVoid:
1793 case CK_VectorSplat:
1794 case CK_IntegralCast:
1795 case CK_BooleanToSignedIntegral:
1796 case CK_IntegralToFloating:
1797 case CK_FloatingToIntegral:
1798 case CK_FloatingCast:
1799 case CK_ObjCObjectLValueCast:
1800 case CK_FloatingRealToComplex:
1801 case CK_FloatingComplexToReal:
1802 case CK_FloatingComplexCast:
1803 case CK_FloatingComplexToIntegralComplex:
1804 case CK_IntegralRealToComplex:
1805 case CK_IntegralComplexToReal:
1806 case CK_IntegralComplexCast:
1807 case CK_IntegralComplexToFloatingComplex:
1808 case CK_ARCProduceObject:
1809 case CK_ARCConsumeObject:
1810 case CK_ARCReclaimReturnedObject:
1811 case CK_ARCExtendBlockObject:
1812 case CK_ZeroToOCLOpaqueType:
1813 case CK_IntToOCLSampler:
1814 case CK_FixedPointCast:
1815 case CK_FixedPointToIntegral:
1816 case CK_IntegralToFixedPoint:
1817 assert(!getType()->isBooleanType() && "unheralded conversion to bool")((!getType()->isBooleanType() && "unheralded conversion to bool"
) ? static_cast<void> (0) : __assert_fail ("!getType()->isBooleanType() && \"unheralded conversion to bool\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1817, __PRETTY_FUNCTION__))
;
1818 goto CheckNoBasePath;
1819
1820 case CK_Dependent:
1821 case CK_LValueToRValue:
1822 case CK_NoOp:
1823 case CK_AtomicToNonAtomic:
1824 case CK_NonAtomicToAtomic:
1825 case CK_PointerToBoolean:
1826 case CK_IntegralToBoolean:
1827 case CK_FloatingToBoolean:
1828 case CK_MemberPointerToBoolean:
1829 case CK_FloatingComplexToBoolean:
1830 case CK_IntegralComplexToBoolean:
1831 case CK_LValueBitCast: // -> bool&
1832 case CK_LValueToRValueBitCast:
1833 case CK_UserDefinedConversion: // operator bool()
1834 case CK_BuiltinFnToFnPtr:
1835 case CK_FixedPointToBoolean:
1836 CheckNoBasePath:
1837 assert(path_empty() && "Cast kind should not have a base path!")((path_empty() && "Cast kind should not have a base path!"
) ? static_cast<void> (0) : __assert_fail ("path_empty() && \"Cast kind should not have a base path!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1837, __PRETTY_FUNCTION__))
;
1838 break;
1839 }
1840 return true;
1841}
1842
1843const char *CastExpr::getCastKindName(CastKind CK) {
1844 switch (CK) {
1845#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1846#include "clang/AST/OperationKinds.def"
1847 }
1848 llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1848)
;
1849}
1850
1851namespace {
1852 const Expr *skipImplicitTemporary(const Expr *E) {
1853 // Skip through reference binding to temporary.
1854 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1855 E = Materialize->getSubExpr();
1856
1857 // Skip any temporary bindings; they're implicit.
1858 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1859 E = Binder->getSubExpr();
1860
1861 return E;
1862 }
1863}
1864
1865Expr *CastExpr::getSubExprAsWritten() {
1866 const Expr *SubExpr = nullptr;
1867 const CastExpr *E = this;
1868 do {
1869 SubExpr = skipImplicitTemporary(E->getSubExpr());
1870
1871 // Conversions by constructor and conversion functions have a
1872 // subexpression describing the call; strip it off.
1873 if (E->getCastKind() == CK_ConstructorConversion)
1874 SubExpr =
1875 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1876 else if (E->getCastKind() == CK_UserDefinedConversion) {
1877 assert((isa<CXXMemberCallExpr>(SubExpr) ||(((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>
(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? static_cast<void> (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1879, __PRETTY_FUNCTION__))
1878 isa<BlockExpr>(SubExpr)) &&(((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>
(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? static_cast<void> (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1879, __PRETTY_FUNCTION__))
1879 "Unexpected SubExpr for CK_UserDefinedConversion.")(((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>
(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? static_cast<void> (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1879, __PRETTY_FUNCTION__))
;
1880 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1881 SubExpr = MCE->getImplicitObjectArgument();
1882 }
1883
1884 // If the subexpression we're left with is an implicit cast, look
1885 // through that, too.
1886 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1887
1888 return const_cast<Expr*>(SubExpr);
1889}
1890
1891NamedDecl *CastExpr::getConversionFunction() const {
1892 const Expr *SubExpr = nullptr;
1893
1894 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1895 SubExpr = skipImplicitTemporary(E->getSubExpr());
1896
1897 if (E->getCastKind() == CK_ConstructorConversion)
1898 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1899
1900 if (E->getCastKind() == CK_UserDefinedConversion) {
1901 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1902 return MCE->getMethodDecl();
1903 }
1904 }
1905
1906 return nullptr;
1907}
1908
1909CXXBaseSpecifier **CastExpr::path_buffer() {
1910 switch (getStmtClass()) {
1911#define ABSTRACT_STMT(x)
1912#define CASTEXPR(Type, Base) \
1913 case Stmt::Type##Class: \
1914 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1915#define STMT(Type, Base)
1916#include "clang/AST/StmtNodes.inc"
1917 default:
1918 llvm_unreachable("non-cast expressions not possible here")::llvm::llvm_unreachable_internal("non-cast expressions not possible here"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1918)
;
1919 }
1920}
1921
1922const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1923 QualType opType) {
1924 auto RD = unionType->castAs<RecordType>()->getDecl();
1925 return getTargetFieldForToUnionCast(RD, opType);
1926}
1927
1928const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1929 QualType OpType) {
1930 auto &Ctx = RD->getASTContext();
1931 RecordDecl::field_iterator Field, FieldEnd;
1932 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1933 Field != FieldEnd; ++Field) {
1934 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1935 !Field->isUnnamedBitfield()) {
1936 return *Field;
1937 }
1938 }
1939 return nullptr;
1940}
1941
1942ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1943 CastKind Kind, Expr *Operand,
1944 const CXXCastPath *BasePath,
1945 ExprValueKind VK) {
1946 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1947 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1948 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1949 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1950 assert((Kind != CK_LValueToRValue ||(((Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->
getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? static_cast<void> (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1952, __PRETTY_FUNCTION__))
1951 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&(((Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->
getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? static_cast<void> (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1952, __PRETTY_FUNCTION__))
1952 "invalid type for lvalue-to-rvalue conversion")(((Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->
getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? static_cast<void> (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1952, __PRETTY_FUNCTION__))
;
1953 ImplicitCastExpr *E =
1954 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1955 if (PathSize)
1956 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1957 E->getTrailingObjects<CXXBaseSpecifier *>());
1958 return E;
1959}
1960
1961ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1962 unsigned PathSize) {
1963 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1964 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1965}
1966
1967
1968CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
1969 ExprValueKind VK, CastKind K, Expr *Op,
1970 const CXXCastPath *BasePath,
1971 TypeSourceInfo *WrittenTy,
1972 SourceLocation L, SourceLocation R) {
1973 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1974 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1975 CStyleCastExpr *E =
1976 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1977 if (PathSize)
1978 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1979 E->getTrailingObjects<CXXBaseSpecifier *>());
1980 return E;
1981}
1982
1983CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1984 unsigned PathSize) {
1985 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1986 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1987}
1988
1989/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1990/// corresponds to, e.g. "<<=".
1991StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
1992 switch (Op) {
1993#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1994#include "clang/AST/OperationKinds.def"
1995 }
1996 llvm_unreachable("Invalid OpCode!")::llvm::llvm_unreachable_internal("Invalid OpCode!", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 1996)
;
1997}
1998
1999BinaryOperatorKind
2000BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2001 switch (OO) {
2002 default: llvm_unreachable("Not an overloadable binary operator")::llvm::llvm_unreachable_internal("Not an overloadable binary operator"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2002)
;
2003 case OO_Plus: return BO_Add;
2004 case OO_Minus: return BO_Sub;
2005 case OO_Star: return BO_Mul;
2006 case OO_Slash: return BO_Div;
2007 case OO_Percent: return BO_Rem;
2008 case OO_Caret: return BO_Xor;
2009 case OO_Amp: return BO_And;
2010 case OO_Pipe: return BO_Or;
2011 case OO_Equal: return BO_Assign;
2012 case OO_Spaceship: return BO_Cmp;
2013 case OO_Less: return BO_LT;
2014 case OO_Greater: return BO_GT;
2015 case OO_PlusEqual: return BO_AddAssign;
2016 case OO_MinusEqual: return BO_SubAssign;
2017 case OO_StarEqual: return BO_MulAssign;
2018 case OO_SlashEqual: return BO_DivAssign;
2019 case OO_PercentEqual: return BO_RemAssign;
2020 case OO_CaretEqual: return BO_XorAssign;
2021 case OO_AmpEqual: return BO_AndAssign;
2022 case OO_PipeEqual: return BO_OrAssign;
2023 case OO_LessLess: return BO_Shl;
2024 case OO_GreaterGreater: return BO_Shr;
2025 case OO_LessLessEqual: return BO_ShlAssign;
2026 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2027 case OO_EqualEqual: return BO_EQ;
2028 case OO_ExclaimEqual: return BO_NE;
2029 case OO_LessEqual: return BO_LE;
2030 case OO_GreaterEqual: return BO_GE;
2031 case OO_AmpAmp: return BO_LAnd;
2032 case OO_PipePipe: return BO_LOr;
2033 case OO_Comma: return BO_Comma;
2034 case OO_ArrowStar: return BO_PtrMemI;
2035 }
2036}
2037
2038OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2039 static const OverloadedOperatorKind OverOps[] = {
2040 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2041 OO_Star, OO_Slash, OO_Percent,
2042 OO_Plus, OO_Minus,
2043 OO_LessLess, OO_GreaterGreater,
2044 OO_Spaceship,
2045 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2046 OO_EqualEqual, OO_ExclaimEqual,
2047 OO_Amp,
2048 OO_Caret,
2049 OO_Pipe,
2050 OO_AmpAmp,
2051 OO_PipePipe,
2052 OO_Equal, OO_StarEqual,
2053 OO_SlashEqual, OO_PercentEqual,
2054 OO_PlusEqual, OO_MinusEqual,
2055 OO_LessLessEqual, OO_GreaterGreaterEqual,
2056 OO_AmpEqual, OO_CaretEqual,
2057 OO_PipeEqual,
2058 OO_Comma
2059 };
2060 return OverOps[Opc];
2061}
2062
2063bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2064 Opcode Opc,
2065 Expr *LHS, Expr *RHS) {
2066 if (Opc != BO_Add)
2067 return false;
2068
2069 // Check that we have one pointer and one integer operand.
2070 Expr *PExp;
2071 if (LHS->getType()->isPointerType()) {
2072 if (!RHS->getType()->isIntegerType())
2073 return false;
2074 PExp = LHS;
2075 } else if (RHS->getType()->isPointerType()) {
2076 if (!LHS->getType()->isIntegerType())
2077 return false;
2078 PExp = RHS;
2079 } else {
2080 return false;
2081 }
2082
2083 // Check that the pointer is a nullptr.
2084 if (!PExp->IgnoreParenCasts()
2085 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2086 return false;
2087
2088 // Check that the pointee type is char-sized.
2089 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2090 if (!PTy || !PTy->getPointeeType()->isCharType())
2091 return false;
2092
2093 return true;
2094}
2095
2096static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2097 SourceLocExpr::IdentKind Kind) {
2098 switch (Kind) {
2099 case SourceLocExpr::File:
2100 case SourceLocExpr::Function: {
2101 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2102 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2103 }
2104 case SourceLocExpr::Line:
2105 case SourceLocExpr::Column:
2106 return Ctx.UnsignedIntTy;
2107 }
2108 llvm_unreachable("unhandled case")::llvm::llvm_unreachable_internal("unhandled case", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2108)
;
2109}
2110
2111SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2112 SourceLocation BLoc, SourceLocation RParenLoc,
2113 DeclContext *ParentContext)
2114 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2115 VK_RValue, OK_Ordinary, false, false, false, false),
2116 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2117 SourceLocExprBits.Kind = Kind;
2118}
2119
2120StringRef SourceLocExpr::getBuiltinStr() const {
2121 switch (getIdentKind()) {
2122 case File:
2123 return "__builtin_FILE";
2124 case Function:
2125 return "__builtin_FUNCTION";
2126 case Line:
2127 return "__builtin_LINE";
2128 case Column:
2129 return "__builtin_COLUMN";
2130 }
2131 llvm_unreachable("unexpected IdentKind!")::llvm::llvm_unreachable_internal("unexpected IdentKind!", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2131)
;
2132}
2133
2134APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2135 const Expr *DefaultExpr) const {
2136 SourceLocation Loc;
2137 const DeclContext *Context;
2138
2139 std::tie(Loc,
2140 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2141 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2142 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2143 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2144 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2145 return {this->getLocation(), this->getParentContext()};
2146 }();
2147
2148 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2149 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2150
2151 auto MakeStringLiteral = [&](StringRef Tmp) {
2152 using LValuePathEntry = APValue::LValuePathEntry;
2153 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2154 // Decay the string to a pointer to the first character.
2155 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2156 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2157 };
2158
2159 switch (getIdentKind()) {
2160 case SourceLocExpr::File:
2161 return MakeStringLiteral(PLoc.getFilename());
2162 case SourceLocExpr::Function: {
2163 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2164 return MakeStringLiteral(
2165 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2166 : std::string(""));
2167 }
2168 case SourceLocExpr::Line:
2169 case SourceLocExpr::Column: {
2170 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2171 /*isUnsigned=*/true);
2172 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2173 : PLoc.getColumn();
2174 return APValue(IntVal);
2175 }
2176 }
2177 llvm_unreachable("unhandled case")::llvm::llvm_unreachable_internal("unhandled case", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2177)
;
2178}
2179
2180InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2181 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
2182 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2183 false, false),
2184 InitExprs(C, initExprs.size()),
2185 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2186{
2187 sawArrayRangeDesignator(false);
2188 for (unsigned I = 0; I != initExprs.size(); ++I)
2189 addDependence(initExprs[I]->getDependence());
2190
2191 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2192}
2193
2194void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2195 if (NumInits > InitExprs.size())
2196 InitExprs.reserve(C, NumInits);
2197}
2198
2199void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2200 InitExprs.resize(C, NumInits, nullptr);
2201}
2202
2203Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2204 if (Init >= InitExprs.size()) {
2205 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2206 setInit(Init, expr);
2207 return nullptr;
2208 }
2209
2210 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2211 setInit(Init, expr);
2212 return Result;
2213}
2214
2215void InitListExpr::setArrayFiller(Expr *filler) {
2216 assert(!hasArrayFiller() && "Filler already set!")((!hasArrayFiller() && "Filler already set!") ? static_cast
<void> (0) : __assert_fail ("!hasArrayFiller() && \"Filler already set!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2216, __PRETTY_FUNCTION__))
;
2217 ArrayFillerOrUnionFieldInit = filler;
2218 // Fill out any "holes" in the array due to designated initializers.
2219 Expr **inits = getInits();
2220 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2221 if (inits[i] == nullptr)
2222 inits[i] = filler;
2223}
2224
2225bool InitListExpr::isStringLiteralInit() const {
2226 if (getNumInits() != 1)
2227 return false;
2228 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2229 if (!AT || !AT->getElementType()->isIntegerType())
2230 return false;
2231 // It is possible for getInit() to return null.
2232 const Expr *Init = getInit(0);
2233 if (!Init)
2234 return false;
2235 Init = Init->IgnoreParens();
2236 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2237}
2238
2239bool InitListExpr::isTransparent() const {
2240 assert(isSemanticForm() && "syntactic form never semantically transparent")((isSemanticForm() && "syntactic form never semantically transparent"
) ? static_cast<void> (0) : __assert_fail ("isSemanticForm() && \"syntactic form never semantically transparent\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2240, __PRETTY_FUNCTION__))
;
2241
2242 // A glvalue InitListExpr is always just sugar.
2243 if (isGLValue()) {
2244 assert(getNumInits() == 1 && "multiple inits in glvalue init list")((getNumInits() == 1 && "multiple inits in glvalue init list"
) ? static_cast<void> (0) : __assert_fail ("getNumInits() == 1 && \"multiple inits in glvalue init list\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2244, __PRETTY_FUNCTION__))
;
2245 return true;
2246 }
2247
2248 // Otherwise, we're sugar if and only if we have exactly one initializer that
2249 // is of the same type.
2250 if (getNumInits() != 1 || !getInit(0))
2251 return false;
2252
2253 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2254 // transparent struct copy.
2255 if (!getInit(0)->isRValue() && getType()->isRecordType())
2256 return false;
2257
2258 return getType().getCanonicalType() ==
2259 getInit(0)->getType().getCanonicalType();
2260}
2261
2262bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2263 assert(isSyntacticForm() && "only test syntactic form as zero initializer")((isSyntacticForm() && "only test syntactic form as zero initializer"
) ? static_cast<void> (0) : __assert_fail ("isSyntacticForm() && \"only test syntactic form as zero initializer\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2263, __PRETTY_FUNCTION__))
;
2264
2265 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2266 return false;
2267 }
2268
2269 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2270 return Lit && Lit->getValue() == 0;
2271}
2272
2273SourceLocation InitListExpr::getBeginLoc() const {
2274 if (InitListExpr *SyntacticForm = getSyntacticForm())
2275 return SyntacticForm->getBeginLoc();
2276 SourceLocation Beg = LBraceLoc;
2277 if (Beg.isInvalid()) {
2278 // Find the first non-null initializer.
2279 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2280 E = InitExprs.end();
2281 I != E; ++I) {
2282 if (Stmt *S = *I) {
2283 Beg = S->getBeginLoc();
2284 break;
2285 }
2286 }
2287 }
2288 return Beg;
2289}
2290
2291SourceLocation InitListExpr::getEndLoc() const {
2292 if (InitListExpr *SyntacticForm = getSyntacticForm())
2293 return SyntacticForm->getEndLoc();
2294 SourceLocation End = RBraceLoc;
2295 if (End.isInvalid()) {
2296 // Find the first non-null initializer from the end.
2297 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2298 E = InitExprs.rend();
2299 I != E; ++I) {
2300 if (Stmt *S = *I) {
2301 End = S->getEndLoc();
2302 break;
2303 }
2304 }
2305 }
2306 return End;
2307}
2308
2309/// getFunctionType - Return the underlying function type for this block.
2310///
2311const FunctionProtoType *BlockExpr::getFunctionType() const {
2312 // The block pointer is never sugared, but the function type might be.
2313 return cast<BlockPointerType>(getType())
2314 ->getPointeeType()->castAs<FunctionProtoType>();
2315}
2316
2317SourceLocation BlockExpr::getCaretLocation() const {
2318 return TheBlock->getCaretLocation();
2319}
2320const Stmt *BlockExpr::getBody() const {
2321 return TheBlock->getBody();
2322}
2323Stmt *BlockExpr::getBody() {
2324 return TheBlock->getBody();
2325}
2326
2327
2328//===----------------------------------------------------------------------===//
2329// Generic Expression Routines
2330//===----------------------------------------------------------------------===//
2331
2332/// isUnusedResultAWarning - Return true if this immediate expression should
2333/// be warned about if the result is unused. If so, fill in Loc and Ranges
2334/// with location to warn on and the source range[s] to report with the
2335/// warning.
2336bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2337 SourceRange &R1, SourceRange &R2,
2338 ASTContext &Ctx) const {
2339 // Don't warn if the expr is type dependent. The type could end up
2340 // instantiating to void.
2341 if (isTypeDependent())
2342 return false;
2343
2344 switch (getStmtClass()) {
2345 default:
2346 if (getType()->isVoidType())
2347 return false;
2348 WarnE = this;
2349 Loc = getExprLoc();
2350 R1 = getSourceRange();
2351 return true;
2352 case ParenExprClass:
2353 return cast<ParenExpr>(this)->getSubExpr()->
2354 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2355 case GenericSelectionExprClass:
2356 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2357 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2358 case CoawaitExprClass:
2359 case CoyieldExprClass:
2360 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2361 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2362 case ChooseExprClass:
2363 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2364 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2365 case UnaryOperatorClass: {
2366 const UnaryOperator *UO = cast<UnaryOperator>(this);
2367
2368 switch (UO->getOpcode()) {
2369 case UO_Plus:
2370 case UO_Minus:
2371 case UO_AddrOf:
2372 case UO_Not:
2373 case UO_LNot:
2374 case UO_Deref:
2375 break;
2376 case UO_Coawait:
2377 // This is just the 'operator co_await' call inside the guts of a
2378 // dependent co_await call.
2379 case UO_PostInc:
2380 case UO_PostDec:
2381 case UO_PreInc:
2382 case UO_PreDec: // ++/--
2383 return false; // Not a warning.
2384 case UO_Real:
2385 case UO_Imag:
2386 // accessing a piece of a volatile complex is a side-effect.
2387 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2388 .isVolatileQualified())
2389 return false;
2390 break;
2391 case UO_Extension:
2392 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2393 }
2394 WarnE = this;
2395 Loc = UO->getOperatorLoc();
2396 R1 = UO->getSubExpr()->getSourceRange();
2397 return true;
2398 }
2399 case BinaryOperatorClass: {
2400 const BinaryOperator *BO = cast<BinaryOperator>(this);
2401 switch (BO->getOpcode()) {
2402 default:
2403 break;
2404 // Consider the RHS of comma for side effects. LHS was checked by
2405 // Sema::CheckCommaOperands.
2406 case BO_Comma:
2407 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2408 // lvalue-ness) of an assignment written in a macro.
2409 if (IntegerLiteral *IE =
2410 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2411 if (IE->getValue() == 0)
2412 return false;
2413 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2414 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2415 case BO_LAnd:
2416 case BO_LOr:
2417 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2418 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2419 return false;
2420 break;
2421 }
2422 if (BO->isAssignmentOp())
2423 return false;
2424 WarnE = this;
2425 Loc = BO->getOperatorLoc();
2426 R1 = BO->getLHS()->getSourceRange();
2427 R2 = BO->getRHS()->getSourceRange();
2428 return true;
2429 }
2430 case CompoundAssignOperatorClass:
2431 case VAArgExprClass:
2432 case AtomicExprClass:
2433 return false;
2434
2435 case ConditionalOperatorClass: {
2436 // If only one of the LHS or RHS is a warning, the operator might
2437 // be being used for control flow. Only warn if both the LHS and
2438 // RHS are warnings.
2439 const auto *Exp = cast<ConditionalOperator>(this);
2440 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2441 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2442 }
2443 case BinaryConditionalOperatorClass: {
2444 const auto *Exp = cast<BinaryConditionalOperator>(this);
2445 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2446 }
2447
2448 case MemberExprClass:
2449 WarnE = this;
2450 Loc = cast<MemberExpr>(this)->getMemberLoc();
2451 R1 = SourceRange(Loc, Loc);
2452 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2453 return true;
2454
2455 case ArraySubscriptExprClass:
2456 WarnE = this;
2457 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2458 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2459 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2460 return true;
2461
2462 case CXXOperatorCallExprClass: {
2463 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2464 // overloads as there is no reasonable way to define these such that they
2465 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2466 // warning: operators == and != are commonly typo'ed, and so warning on them
2467 // provides additional value as well. If this list is updated,
2468 // DiagnoseUnusedComparison should be as well.
2469 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2470 switch (Op->getOperator()) {
2471 default:
2472 break;
2473 case OO_EqualEqual:
2474 case OO_ExclaimEqual:
2475 case OO_Less:
2476 case OO_Greater:
2477 case OO_GreaterEqual:
2478 case OO_LessEqual:
2479 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2480 Op->getCallReturnType(Ctx)->isVoidType())
2481 break;
2482 WarnE = this;
2483 Loc = Op->getOperatorLoc();
2484 R1 = Op->getSourceRange();
2485 return true;
2486 }
2487
2488 // Fallthrough for generic call handling.
2489 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2490 }
2491 case CallExprClass:
2492 case CXXMemberCallExprClass:
2493 case UserDefinedLiteralClass: {
2494 // If this is a direct call, get the callee.
2495 const CallExpr *CE = cast<CallExpr>(this);
2496 if (const Decl *FD = CE->getCalleeDecl()) {
2497 // If the callee has attribute pure, const, or warn_unused_result, warn
2498 // about it. void foo() { strlen("bar"); } should warn.
2499 //
2500 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2501 // updated to match for QoI.
2502 if (CE->hasUnusedResultAttr(Ctx) ||
2503 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2504 WarnE = this;
2505 Loc = CE->getCallee()->getBeginLoc();
2506 R1 = CE->getCallee()->getSourceRange();
2507
2508 if (unsigned NumArgs = CE->getNumArgs())
2509 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2510 CE->getArg(NumArgs - 1)->getEndLoc());
2511 return true;
2512 }
2513 }
2514 return false;
2515 }
2516
2517 // If we don't know precisely what we're looking at, let's not warn.
2518 case UnresolvedLookupExprClass:
2519 case CXXUnresolvedConstructExprClass:
2520 return false;
2521
2522 case CXXTemporaryObjectExprClass:
2523 case CXXConstructExprClass: {
2524 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2525 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2526 if (Type->hasAttr<WarnUnusedAttr>() ||
2527 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2528 WarnE = this;
2529 Loc = getBeginLoc();
2530 R1 = getSourceRange();
2531 return true;
2532 }
2533 }
2534
2535 const auto *CE = cast<CXXConstructExpr>(this);
2536 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2537 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2538 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2539 WarnE = this;
2540 Loc = getBeginLoc();
2541 R1 = getSourceRange();
2542
2543 if (unsigned NumArgs = CE->getNumArgs())
2544 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2545 CE->getArg(NumArgs - 1)->getEndLoc());
2546 return true;
2547 }
2548 }
2549
2550 return false;
2551 }
2552
2553 case ObjCMessageExprClass: {
2554 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2555 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2556 ME->isInstanceMessage() &&
2557 !ME->getType()->isVoidType() &&
2558 ME->getMethodFamily() == OMF_init) {
2559 WarnE = this;
2560 Loc = getExprLoc();
2561 R1 = ME->getSourceRange();
2562 return true;
2563 }
2564
2565 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2566 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2567 WarnE = this;
2568 Loc = getExprLoc();
2569 return true;
2570 }
2571
2572 return false;
2573 }
2574
2575 case ObjCPropertyRefExprClass:
2576 WarnE = this;
2577 Loc = getExprLoc();
2578 R1 = getSourceRange();
2579 return true;
2580
2581 case PseudoObjectExprClass: {
2582 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2583
2584 // Only complain about things that have the form of a getter.
2585 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2586 isa<BinaryOperator>(PO->getSyntacticForm()))
2587 return false;
2588
2589 WarnE = this;
2590 Loc = getExprLoc();
2591 R1 = getSourceRange();
2592 return true;
2593 }
2594
2595 case StmtExprClass: {
2596 // Statement exprs don't logically have side effects themselves, but are
2597 // sometimes used in macros in ways that give them a type that is unused.
2598 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2599 // however, if the result of the stmt expr is dead, we don't want to emit a
2600 // warning.
2601 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2602 if (!CS->body_empty()) {
2603 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2604 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2605 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2606 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2607 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2608 }
2609
2610 if (getType()->isVoidType())
2611 return false;
2612 WarnE = this;
2613 Loc = cast<StmtExpr>(this)->getLParenLoc();
2614 R1 = getSourceRange();
2615 return true;
2616 }
2617 case CXXFunctionalCastExprClass:
2618 case CStyleCastExprClass: {
2619 // Ignore an explicit cast to void unless the operand is a non-trivial
2620 // volatile lvalue.
2621 const CastExpr *CE = cast<CastExpr>(this);
2622 if (CE->getCastKind() == CK_ToVoid) {
2623 if (CE->getSubExpr()->isGLValue() &&
2624 CE->getSubExpr()->getType().isVolatileQualified()) {
2625 const DeclRefExpr *DRE =
2626 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2627 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2628 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2629 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2630 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2631 R1, R2, Ctx);
2632 }
2633 }
2634 return false;
2635 }
2636
2637 // If this is a cast to a constructor conversion, check the operand.
2638 // Otherwise, the result of the cast is unused.
2639 if (CE->getCastKind() == CK_ConstructorConversion)
2640 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2641
2642 WarnE = this;
2643 if (const CXXFunctionalCastExpr *CXXCE =
2644 dyn_cast<CXXFunctionalCastExpr>(this)) {
2645 Loc = CXXCE->getBeginLoc();
2646 R1 = CXXCE->getSubExpr()->getSourceRange();
2647 } else {
2648 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2649 Loc = CStyleCE->getLParenLoc();
2650 R1 = CStyleCE->getSubExpr()->getSourceRange();
2651 }
2652 return true;
2653 }
2654 case ImplicitCastExprClass: {
2655 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2656
2657 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2658 if (ICE->getCastKind() == CK_LValueToRValue &&
2659 ICE->getSubExpr()->getType().isVolatileQualified())
2660 return false;
2661
2662 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2663 }
2664 case CXXDefaultArgExprClass:
2665 return (cast<CXXDefaultArgExpr>(this)
2666 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2667 case CXXDefaultInitExprClass:
2668 return (cast<CXXDefaultInitExpr>(this)
2669 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2670
2671 case CXXNewExprClass:
2672 // FIXME: In theory, there might be new expressions that don't have side
2673 // effects (e.g. a placement new with an uninitialized POD).
2674 case CXXDeleteExprClass:
2675 return false;
2676 case MaterializeTemporaryExprClass:
2677 return cast<MaterializeTemporaryExpr>(this)
2678 ->getSubExpr()
2679 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2680 case CXXBindTemporaryExprClass:
2681 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2682 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2683 case ExprWithCleanupsClass:
2684 return cast<ExprWithCleanups>(this)->getSubExpr()
2685 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2686 }
2687}
2688
2689/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2690/// returns true, if it is; false otherwise.
2691bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2692 const Expr *E = IgnoreParens();
2693 switch (E->getStmtClass()) {
2694 default:
2695 return false;
2696 case ObjCIvarRefExprClass:
2697 return true;
2698 case Expr::UnaryOperatorClass:
2699 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2700 case ImplicitCastExprClass:
2701 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2702 case MaterializeTemporaryExprClass:
2703 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2704 Ctx);
2705 case CStyleCastExprClass:
2706 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2707 case DeclRefExprClass: {
2708 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2709
2710 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2711 if (VD->hasGlobalStorage())
2712 return true;
2713 QualType T = VD->getType();
2714 // dereferencing to a pointer is always a gc'able candidate,
2715 // unless it is __weak.
2716 return T->isPointerType() &&
2717 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2718 }
2719 return false;
2720 }
2721 case MemberExprClass: {
2722 const MemberExpr *M = cast<MemberExpr>(E);
2723 return M->getBase()->isOBJCGCCandidate(Ctx);
2724 }
2725 case ArraySubscriptExprClass:
2726 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2727 }
2728}
2729
2730bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2731 if (isTypeDependent())
2732 return false;
2733 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2734}
2735
2736QualType Expr::findBoundMemberType(const Expr *expr) {
2737 assert(expr->hasPlaceholderType(BuiltinType::BoundMember))((expr->hasPlaceholderType(BuiltinType::BoundMember)) ? static_cast
<void> (0) : __assert_fail ("expr->hasPlaceholderType(BuiltinType::BoundMember)"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2737, __PRETTY_FUNCTION__))
;
2738
2739 // Bound member expressions are always one of these possibilities:
2740 // x->m x.m x->*y x.*y
2741 // (possibly parenthesized)
2742
2743 expr = expr->IgnoreParens();
2744 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2745 assert(isa<CXXMethodDecl>(mem->getMemberDecl()))((isa<CXXMethodDecl>(mem->getMemberDecl())) ? static_cast
<void> (0) : __assert_fail ("isa<CXXMethodDecl>(mem->getMemberDecl())"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2745, __PRETTY_FUNCTION__))
;
2746 return mem->getMemberDecl()->getType();
2747 }
2748
2749 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2750 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2751 ->getPointeeType();
2752 assert(type->isFunctionType())((type->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("type->isFunctionType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2752, __PRETTY_FUNCTION__))
;
2753 return type;
2754 }
2755
2756 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr))((isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr
>(expr)) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr)"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 2756, __PRETTY_FUNCTION__))
;
2757 return QualType();
2758}
2759
2760static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2761 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2762 return ICE->getSubExpr();
2763
2764 if (auto *FE = dyn_cast<FullExpr>(E))
2765 return FE->getSubExpr();
2766
2767 return E;
2768}
2769
2770static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2771 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2772 // addition to what IgnoreImpCasts() skips to account for the current
2773 // behaviour of IgnoreParenImpCasts().
2774 Expr *SubE = IgnoreImpCastsSingleStep(E);
2775 if (SubE != E)
2776 return SubE;
2777
2778 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2779 return MTE->getSubExpr();
2780
2781 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2782 return NTTP->getReplacement();
2783
2784 return E;
2785}
2786
2787static Expr *IgnoreCastsSingleStep(Expr *E) {
2788 if (auto *CE = dyn_cast<CastExpr>(E))
2789 return CE->getSubExpr();
2790
2791 if (auto *FE = dyn_cast<FullExpr>(E))
2792 return FE->getSubExpr();
2793
2794 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2795 return MTE->getSubExpr();
2796
2797 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2798 return NTTP->getReplacement();
2799
2800 return E;
2801}
2802
2803static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2804 // Skip what IgnoreCastsSingleStep skips, except that only
2805 // lvalue-to-rvalue casts are skipped.
2806 if (auto *CE = dyn_cast<CastExpr>(E))
2807 if (CE->getCastKind() != CK_LValueToRValue)
2808 return E;
2809
2810 return IgnoreCastsSingleStep(E);
2811}
2812
2813static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2814 if (auto *CE = dyn_cast<CastExpr>(E))
2815 if (CE->getCastKind() == CK_DerivedToBase ||
2816 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2817 CE->getCastKind() == CK_NoOp)
2818 return CE->getSubExpr();
2819
2820 return E;
2821}
2822
2823static Expr *IgnoreImplicitSingleStep(Expr *E) {
2824 Expr *SubE = IgnoreImpCastsSingleStep(E);
2825 if (SubE != E)
2826 return SubE;
2827
2828 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2829 return MTE->getSubExpr();
2830
2831 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2832 return BTE->getSubExpr();
2833
2834 return E;
2835}
2836
2837static Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E) {
2838 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2839 return ICE->getSubExprAsWritten();
2840
2841 return IgnoreImplicitSingleStep(E);
2842}
2843
2844static Expr *IgnoreParensOnlySingleStep(Expr *E) {
2845 if (auto *PE = dyn_cast<ParenExpr>(E))
2846 return PE->getSubExpr();
2847 return E;
2848}
2849
2850static Expr *IgnoreParensSingleStep(Expr *E) {
2851 if (auto *PE = dyn_cast<ParenExpr>(E))
2852 return PE->getSubExpr();
2853
2854 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2855 if (UO->getOpcode() == UO_Extension)
2856 return UO->getSubExpr();
2857 }
2858
2859 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2860 if (!GSE->isResultDependent())
2861 return GSE->getResultExpr();
2862 }
2863
2864 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2865 if (!CE->isConditionDependent())
2866 return CE->getChosenSubExpr();
2867 }
2868
2869 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2870 return CE->getSubExpr();
2871
2872 return E;
2873}
2874
2875static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2876 if (auto *CE = dyn_cast<CastExpr>(E)) {
2877 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2878 // ptr<->int casts of the same width. We also ignore all identity casts.
2879 Expr *SubExpr = CE->getSubExpr();
2880 bool IsIdentityCast =
2881 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2882 bool IsSameWidthCast =
2883 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2884 (SubExpr->getType()->isPointerType() ||
2885 SubExpr->getType()->isIntegralType(Ctx)) &&
2886 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2887
2888 if (IsIdentityCast || IsSameWidthCast)
2889 return SubExpr;
2890 }
2891
2892 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2893 return NTTP->getReplacement();
2894
2895 return E;
2896}
2897
2898static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2899template <typename FnTy, typename... FnTys>
2900static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2901 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2902}
2903
2904/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2905/// Recursively apply each of the functions to E until reaching a fixed point.
2906/// Note that a null E is valid; in this case nothing is done.
2907template <typename... FnTys>
2908static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2909 Expr *LastE = nullptr;
2910 while (E != LastE) {
2911 LastE = E;
2912 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2913 }
2914 return E;
2915}
2916
2917Expr *Expr::IgnoreImpCasts() {
2918 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
2919}
2920
2921Expr *Expr::IgnoreCasts() {
2922 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2923}
2924
2925Expr *Expr::IgnoreImplicit() {
2926 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2927}
2928
2929Expr *Expr::IgnoreImplicitAsWritten() {
2930 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2931}
2932
2933Expr *Expr::IgnoreParens() {
2934 return IgnoreExprNodes(this, IgnoreParensSingleStep);
2935}
2936
2937Expr *Expr::IgnoreParenImpCasts() {
2938 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2939 IgnoreImpCastsExtraSingleStep);
2940}
2941
2942Expr *Expr::IgnoreParenCasts() {
2943 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2944}
2945
2946Expr *Expr::IgnoreConversionOperator() {
2947 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2948 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2949 return MCE->getImplicitObjectArgument();
2950 }
2951 return this;
2952}
2953
2954Expr *Expr::IgnoreParenLValueCasts() {
2955 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2956 IgnoreLValueCastsSingleStep);
2957}
2958
2959Expr *Expr::ignoreParenBaseCasts() {
2960 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2961 IgnoreBaseCastsSingleStep);
2962}
2963
2964Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2965 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2966 return IgnoreNoopCastsSingleStep(Ctx, E);
2967 });
2968}
2969
2970Expr *Expr::IgnoreUnlessSpelledInSource() {
2971 Expr *E = this;
2972
2973 Expr *LastE = nullptr;
2974 while (E != LastE) {
2975 LastE = E;
2976 E = IgnoreExprNodes(E, IgnoreImplicitSingleStep, IgnoreImpCastsSingleStep,
2977 IgnoreParensOnlySingleStep);
2978
2979 auto SR = E->getSourceRange();
2980
2981 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2982 if (C->getNumArgs() == 1) {
2983 Expr *A = C->getArg(0);
2984 if (A->getSourceRange() == SR || !isa<CXXTemporaryObjectExpr>(C))
2985 E = A;
2986 }
2987 }
2988
2989 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
2990 Expr *ExprNode = C->getImplicitObjectArgument()->IgnoreParenImpCasts();
2991 if (ExprNode->getSourceRange() == SR)
2992 E = ExprNode;
2993 }
2994 }
2995
2996 return E;
2997}
2998
2999bool Expr::isDefaultArgument() const {
3000 const Expr *E = this;
3001 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3002 E = M->getSubExpr();
3003
3004 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3005 E = ICE->getSubExprAsWritten();
3006
3007 return isa<CXXDefaultArgExpr>(E);
3008}
3009
3010/// Skip over any no-op casts and any temporary-binding
3011/// expressions.
3012static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3013 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3014 E = M->getSubExpr();
3015
3016 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3017 if (ICE->getCastKind() == CK_NoOp)
3018 E = ICE->getSubExpr();
3019 else
3020 break;
3021 }
3022
3023 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3024 E = BE->getSubExpr();
3025
3026 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3027 if (ICE->getCastKind() == CK_NoOp)
3028 E = ICE->getSubExpr();
3029 else
3030 break;
3031 }
3032
3033 return E->IgnoreParens();
3034}
3035
3036/// isTemporaryObject - Determines if this expression produces a
3037/// temporary of the given class type.
3038bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3039 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3040 return false;
3041
3042 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3043
3044 // Temporaries are by definition pr-values of class type.
3045 if (!E->Classify(C).isPRValue()) {
3046 // In this context, property reference is a message call and is pr-value.
3047 if (!isa<ObjCPropertyRefExpr>(E))
3048 return false;
3049 }
3050
3051 // Black-list a few cases which yield pr-values of class type that don't
3052 // refer to temporaries of that type:
3053
3054 // - implicit derived-to-base conversions
3055 if (isa<ImplicitCastExpr>(E)) {
3056 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3057 case CK_DerivedToBase:
3058 case CK_UncheckedDerivedToBase:
3059 return false;
3060 default:
3061 break;
3062 }
3063 }
3064
3065 // - member expressions (all)
3066 if (isa<MemberExpr>(E))
3067 return false;
3068
3069 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3070 if (BO->isPtrMemOp())
3071 return false;
3072
3073 // - opaque values (all)
3074 if (isa<OpaqueValueExpr>(E))
3075 return false;
3076
3077 return true;
3078}
3079
3080bool Expr::isImplicitCXXThis() const {
3081 const Expr *E = this;
3082
3083 // Strip away parentheses and casts we don't care about.
3084 while (true) {
3085 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3086 E = Paren->getSubExpr();
3087 continue;
3088 }
3089
3090 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3091 if (ICE->getCastKind() == CK_NoOp ||
3092 ICE->getCastKind() == CK_LValueToRValue ||
3093 ICE->getCastKind() == CK_DerivedToBase ||
3094 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3095 E = ICE->getSubExpr();
3096 continue;
3097 }
3098 }
3099
3100 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3101 if (UnOp->getOpcode() == UO_Extension) {
3102 E = UnOp->getSubExpr();
3103 continue;
3104 }
3105 }
3106
3107 if (const MaterializeTemporaryExpr *M
3108 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3109 E = M->getSubExpr();
3110 continue;
3111 }
3112
3113 break;
3114 }
3115
3116 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3117 return This->isImplicit();
3118
3119 return false;
3120}
3121
3122/// hasAnyTypeDependentArguments - Determines if any of the expressions
3123/// in Exprs is type-dependent.
3124bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3125 for (unsigned I = 0; I < Exprs.size(); ++I)
3126 if (Exprs[I]->isTypeDependent())
3127 return true;
3128
3129 return false;
3130}
3131
3132bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3133 const Expr **Culprit) const {
3134 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3135, __PRETTY_FUNCTION__))
3135 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3135, __PRETTY_FUNCTION__))
;
3136
3137 // This function is attempting whether an expression is an initializer
3138 // which can be evaluated at compile-time. It very closely parallels
3139 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3140 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3141 // to isEvaluatable most of the time.
3142 //
3143 // If we ever capture reference-binding directly in the AST, we can
3144 // kill the second parameter.
3145
3146 if (IsForRef) {
3147 EvalResult Result;
3148 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3149 return true;
3150 if (Culprit)
3151 *Culprit = this;
3152 return false;
3153 }
3154
3155 switch (getStmtClass()) {
3156 default: break;
3157 case StringLiteralClass:
3158 case ObjCEncodeExprClass:
3159 return true;
3160 case CXXTemporaryObjectExprClass:
3161 case CXXConstructExprClass: {
3162 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3163
3164 if (CE->getConstructor()->isTrivial() &&
3165 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3166 // Trivial default constructor
3167 if (!CE->getNumArgs()) return true;
3168
3169 // Trivial copy constructor
3170 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument")((CE->getNumArgs() == 1 && "trivial ctor with > 1 argument"
) ? static_cast<void> (0) : __assert_fail ("CE->getNumArgs() == 1 && \"trivial ctor with > 1 argument\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3170, __PRETTY_FUNCTION__))
;
3171 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3172 }
3173
3174 break;
3175 }
3176 case ConstantExprClass: {
3177 // FIXME: We should be able to return "true" here, but it can lead to extra
3178 // error messages. E.g. in Sema/array-init.c.
3179 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3180 return Exp->isConstantInitializer(Ctx, false, Culprit);
3181 }
3182 case CompoundLiteralExprClass: {
3183 // This handles gcc's extension that allows global initializers like
3184 // "struct x {int x;} x = (struct x) {};".
3185 // FIXME: This accepts other cases it shouldn't!
3186 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3187 return Exp->isConstantInitializer(Ctx, false, Culprit);
3188 }
3189 case DesignatedInitUpdateExprClass: {
3190 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3191 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3192 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3193 }
3194 case InitListExprClass: {
3195 const InitListExpr *ILE = cast<InitListExpr>(this);
3196 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form")((ILE->isSemanticForm() && "InitListExpr must be in semantic form"
) ? static_cast<void> (0) : __assert_fail ("ILE->isSemanticForm() && \"InitListExpr must be in semantic form\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3196, __PRETTY_FUNCTION__))
;
3197 if (ILE->getType()->isArrayType()) {
3198 unsigned numInits = ILE->getNumInits();
3199 for (unsigned i = 0; i < numInits; i++) {
3200 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3201 return false;
3202 }
3203 return true;
3204 }
3205
3206 if (ILE->getType()->isRecordType()) {
3207 unsigned ElementNo = 0;
3208 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3209 for (const auto *Field : RD->fields()) {
3210 // If this is a union, skip all the fields that aren't being initialized.
3211 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3212 continue;
3213
3214 // Don't emit anonymous bitfields, they just affect layout.
3215 if (Field->isUnnamedBitfield())
3216 continue;
3217
3218 if (ElementNo < ILE->getNumInits()) {
3219 const Expr *Elt = ILE->getInit(ElementNo++);
3220 if (Field->isBitField()) {
3221 // Bitfields have to evaluate to an integer.
3222 EvalResult Result;
3223 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3224 if (Culprit)
3225 *Culprit = Elt;
3226 return false;
3227 }
3228 } else {
3229 bool RefType = Field->getType()->isReferenceType();
3230 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3231 return false;
3232 }
3233 }
3234 }
3235 return true;
3236 }
3237
3238 break;
3239 }
3240 case ImplicitValueInitExprClass:
3241 case NoInitExprClass:
3242 return true;
3243 case ParenExprClass:
3244 return cast<ParenExpr>(this)->getSubExpr()
3245 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3246 case GenericSelectionExprClass:
3247 return cast<GenericSelectionExpr>(this)->getResultExpr()
3248 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3249 case ChooseExprClass:
3250 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3251 if (Culprit)
3252 *Culprit = this;
3253 return false;
3254 }
3255 return cast<ChooseExpr>(this)->getChosenSubExpr()
3256 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3257 case UnaryOperatorClass: {
3258 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3259 if (Exp->getOpcode() == UO_Extension)
3260 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3261 break;
3262 }
3263 case CXXFunctionalCastExprClass:
3264 case CXXStaticCastExprClass:
3265 case ImplicitCastExprClass:
3266 case CStyleCastExprClass:
3267 case ObjCBridgedCastExprClass:
3268 case CXXDynamicCastExprClass:
3269 case CXXReinterpretCastExprClass:
3270 case CXXConstCastExprClass: {
3271 const CastExpr *CE = cast<CastExpr>(this);
3272
3273 // Handle misc casts we want to ignore.
3274 if (CE->getCastKind() == CK_NoOp ||
3275 CE->getCastKind() == CK_LValueToRValue ||
3276 CE->getCastKind() == CK_ToUnion ||
3277 CE->getCastKind() == CK_ConstructorConversion ||
3278 CE->getCastKind() == CK_NonAtomicToAtomic ||
3279 CE->getCastKind() == CK_AtomicToNonAtomic ||
3280 CE->getCastKind() == CK_IntToOCLSampler)
3281 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3282
3283 break;
3284 }
3285 case MaterializeTemporaryExprClass:
3286 return cast<MaterializeTemporaryExpr>(this)
3287 ->getSubExpr()
3288 ->isConstantInitializer(Ctx, false, Culprit);
3289
3290 case SubstNonTypeTemplateParmExprClass:
3291 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3292 ->isConstantInitializer(Ctx, false, Culprit);
3293 case CXXDefaultArgExprClass:
3294 return cast<CXXDefaultArgExpr>(this)->getExpr()
3295 ->isConstantInitializer(Ctx, false, Culprit);
3296 case CXXDefaultInitExprClass:
3297 return cast<CXXDefaultInitExpr>(this)->getExpr()
3298 ->isConstantInitializer(Ctx, false, Culprit);
3299 }
3300 // Allow certain forms of UB in constant initializers: signed integer
3301 // overflow and floating-point division by zero. We'll give a warning on
3302 // these, but they're common enough that we have to accept them.
3303 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3304 return true;
3305 if (Culprit)
3306 *Culprit = this;
3307 return false;
3308}
3309
3310bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3311 const FunctionDecl* FD = getDirectCallee();
3312 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3313 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3314 return false;
3315
3316 const Expr* Arg = getArg(0);
3317 bool ArgVal;
3318 return !Arg->isValueDependent() &&
3319 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3320}
3321
3322namespace {
3323 /// Look for any side effects within a Stmt.
3324 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3325 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3326 const bool IncludePossibleEffects;
3327 bool HasSideEffects;
3328
3329 public:
3330 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3331 : Inherited(Context),
3332 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3333
3334 bool hasSideEffects() const { return HasSideEffects; }
3335
3336 void VisitExpr(const Expr *E) {
3337 if (!HasSideEffects &&
3338 E->HasSideEffects(Context, IncludePossibleEffects))
3339 HasSideEffects = true;
3340 }
3341 };
3342}
3343
3344bool Expr::HasSideEffects(const ASTContext &Ctx,
3345 bool IncludePossibleEffects) const {
3346 // In circumstances where we care about definite side effects instead of
3347 // potential side effects, we want to ignore expressions that are part of a
3348 // macro expansion as a potential side effect.
3349 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3350 return false;
3351
3352 if (isInstantiationDependent())
3353 return IncludePossibleEffects;
3354
3355 switch (getStmtClass()) {
3356 case NoStmtClass:
3357 #define ABSTRACT_STMT(Type)
3358 #define STMT(Type, Base) case Type##Class:
3359 #define EXPR(Type, Base)
3360 #include "clang/AST/StmtNodes.inc"
3361 llvm_unreachable("unexpected Expr kind")::llvm::llvm_unreachable_internal("unexpected Expr kind", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3361)
;
3362
3363 case DependentScopeDeclRefExprClass:
3364 case CXXUnresolvedConstructExprClass:
3365 case CXXDependentScopeMemberExprClass:
3366 case UnresolvedLookupExprClass:
3367 case UnresolvedMemberExprClass:
3368 case PackExpansionExprClass:
3369 case SubstNonTypeTemplateParmPackExprClass:
3370 case FunctionParmPackExprClass:
3371 case TypoExprClass:
3372 case CXXFoldExprClass:
3373 llvm_unreachable("shouldn't see dependent / unresolved nodes here")::llvm::llvm_unreachable_internal("shouldn't see dependent / unresolved nodes here"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3373)
;
3374
3375 case DeclRefExprClass:
3376 case ObjCIvarRefExprClass:
3377 case PredefinedExprClass:
3378 case IntegerLiteralClass:
3379 case FixedPointLiteralClass:
3380 case FloatingLiteralClass:
3381 case ImaginaryLiteralClass:
3382 case StringLiteralClass:
3383 case CharacterLiteralClass:
3384 case OffsetOfExprClass:
3385 case ImplicitValueInitExprClass:
3386 case UnaryExprOrTypeTraitExprClass:
3387 case AddrLabelExprClass:
3388 case GNUNullExprClass:
3389 case ArrayInitIndexExprClass:
3390 case NoInitExprClass:
3391 case CXXBoolLiteralExprClass:
3392 case CXXNullPtrLiteralExprClass:
3393 case CXXThisExprClass:
3394 case CXXScalarValueInitExprClass:
3395 case TypeTraitExprClass:
3396 case ArrayTypeTraitExprClass:
3397 case ExpressionTraitExprClass:
3398 case CXXNoexceptExprClass:
3399 case SizeOfPackExprClass:
3400 case ObjCStringLiteralClass:
3401 case ObjCEncodeExprClass:
3402 case ObjCBoolLiteralExprClass:
3403 case ObjCAvailabilityCheckExprClass:
3404 case CXXUuidofExprClass:
3405 case OpaqueValueExprClass:
3406 case SourceLocExprClass:
3407 case ConceptSpecializationExprClass:
3408 case RequiresExprClass:
3409 // These never have a side-effect.
3410 return false;
3411
3412 case ConstantExprClass:
3413 // FIXME: Move this into the "return false;" block above.
3414 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3415 Ctx, IncludePossibleEffects);
3416
3417 case CallExprClass:
3418 case CXXOperatorCallExprClass:
3419 case CXXMemberCallExprClass:
3420 case CUDAKernelCallExprClass:
3421 case UserDefinedLiteralClass: {
3422 // We don't know a call definitely has side effects, except for calls
3423 // to pure/const functions that definitely don't.
3424 // If the call itself is considered side-effect free, check the operands.
3425 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3426 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3427 if (IsPure || !IncludePossibleEffects)
3428 break;
3429 return true;
3430 }
3431
3432 case BlockExprClass:
3433 case CXXBindTemporaryExprClass:
3434 if (!IncludePossibleEffects)
3435 break;
3436 return true;
3437
3438 case MSPropertyRefExprClass:
3439 case MSPropertySubscriptExprClass:
3440 case CompoundAssignOperatorClass:
3441 case VAArgExprClass:
3442 case AtomicExprClass:
3443 case CXXThrowExprClass:
3444 case CXXNewExprClass:
3445 case CXXDeleteExprClass:
3446 case CoawaitExprClass:
3447 case DependentCoawaitExprClass:
3448 case CoyieldExprClass:
3449 // These always have a side-effect.
3450 return true;
3451
3452 case StmtExprClass: {
3453 // StmtExprs have a side-effect if any substatement does.
3454 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3455 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3456 return Finder.hasSideEffects();
3457 }
3458
3459 case ExprWithCleanupsClass:
3460 if (IncludePossibleEffects)
3461 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3462 return true;
3463 break;
3464
3465 case ParenExprClass:
3466 case ArraySubscriptExprClass:
3467 case OMPArraySectionExprClass:
3468 case MemberExprClass:
3469 case ConditionalOperatorClass:
3470 case BinaryConditionalOperatorClass:
3471 case CompoundLiteralExprClass:
3472 case ExtVectorElementExprClass:
3473 case DesignatedInitExprClass:
3474 case DesignatedInitUpdateExprClass:
3475 case ArrayInitLoopExprClass:
3476 case ParenListExprClass:
3477 case CXXPseudoDestructorExprClass:
3478 case CXXRewrittenBinaryOperatorClass:
3479 case CXXStdInitializerListExprClass:
3480 case SubstNonTypeTemplateParmExprClass:
3481 case MaterializeTemporaryExprClass:
3482 case ShuffleVectorExprClass:
3483 case ConvertVectorExprClass:
3484 case AsTypeExprClass:
3485 // These have a side-effect if any subexpression does.
3486 break;
3487
3488 case UnaryOperatorClass:
3489 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3490 return true;
3491 break;
3492
3493 case BinaryOperatorClass:
3494 if (cast<BinaryOperator>(this)->isAssignmentOp())
3495 return true;
3496 break;
3497
3498 case InitListExprClass:
3499 // FIXME: The children for an InitListExpr doesn't include the array filler.
3500 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3501 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3502 return true;
3503 break;
3504
3505 case GenericSelectionExprClass:
3506 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3507 HasSideEffects(Ctx, IncludePossibleEffects);
3508
3509 case ChooseExprClass:
3510 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3511 Ctx, IncludePossibleEffects);
3512
3513 case CXXDefaultArgExprClass:
3514 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3515 Ctx, IncludePossibleEffects);
3516
3517 case CXXDefaultInitExprClass: {
3518 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3519 if (const Expr *E = FD->getInClassInitializer())
3520 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3521 // If we've not yet parsed the initializer, assume it has side-effects.
3522 return true;
3523 }
3524
3525 case CXXDynamicCastExprClass: {
3526 // A dynamic_cast expression has side-effects if it can throw.
3527 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3528 if (DCE->getTypeAsWritten()->isReferenceType() &&
3529 DCE->getCastKind() == CK_Dynamic)
3530 return true;
3531 }
3532 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3533 case ImplicitCastExprClass:
3534 case CStyleCastExprClass:
3535 case CXXStaticCastExprClass:
3536 case CXXReinterpretCastExprClass:
3537 case CXXConstCastExprClass:
3538 case CXXFunctionalCastExprClass:
3539 case BuiltinBitCastExprClass: {
3540 // While volatile reads are side-effecting in both C and C++, we treat them
3541 // as having possible (not definite) side-effects. This allows idiomatic
3542 // code to behave without warning, such as sizeof(*v) for a volatile-
3543 // qualified pointer.
3544 if (!IncludePossibleEffects)
3545 break;
3546
3547 const CastExpr *CE = cast<CastExpr>(this);
3548 if (CE->getCastKind() == CK_LValueToRValue &&
3549 CE->getSubExpr()->getType().isVolatileQualified())
3550 return true;
3551 break;
3552 }
3553
3554 case CXXTypeidExprClass:
3555 // typeid might throw if its subexpression is potentially-evaluated, so has
3556 // side-effects in that case whether or not its subexpression does.
3557 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3558
3559 case CXXConstructExprClass:
3560 case CXXTemporaryObjectExprClass: {
3561 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3562 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3563 return true;
3564 // A trivial constructor does not add any side-effects of its own. Just look
3565 // at its arguments.
3566 break;
3567 }
3568
3569 case CXXInheritedCtorInitExprClass: {
3570 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3571 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3572 return true;
3573 break;
3574 }
3575
3576 case LambdaExprClass: {
3577 const LambdaExpr *LE = cast<LambdaExpr>(this);
3578 for (Expr *E : LE->capture_inits())
3579 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3580 return true;
3581 return false;
3582 }
3583
3584 case PseudoObjectExprClass: {
3585 // Only look for side-effects in the semantic form, and look past
3586 // OpaqueValueExpr bindings in that form.
3587 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3588 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3589 E = PO->semantics_end();
3590 I != E; ++I) {
3591 const Expr *Subexpr = *I;
3592 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3593 Subexpr = OVE->getSourceExpr();
3594 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3595 return true;
3596 }
3597 return false;
3598 }
3599
3600 case ObjCBoxedExprClass:
3601 case ObjCArrayLiteralClass:
3602 case ObjCDictionaryLiteralClass:
3603 case ObjCSelectorExprClass:
3604 case ObjCProtocolExprClass:
3605 case ObjCIsaExprClass:
3606 case ObjCIndirectCopyRestoreExprClass:
3607 case ObjCSubscriptRefExprClass:
3608 case ObjCBridgedCastExprClass:
3609 case ObjCMessageExprClass:
3610 case ObjCPropertyRefExprClass:
3611 // FIXME: Classify these cases better.
3612 if (IncludePossibleEffects)
3613 return true;
3614 break;
3615 }
3616
3617 // Recurse to children.
3618 for (const Stmt *SubStmt : children())
3619 if (SubStmt &&
3620 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3621 return true;
3622
3623 return false;
3624}
3625
3626namespace {
3627 /// Look for a call to a non-trivial function within an expression.
3628 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3629 {
3630 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3631
3632 bool NonTrivial;
3633
3634 public:
3635 explicit NonTrivialCallFinder(const ASTContext &Context)
3636 : Inherited(Context), NonTrivial(false) { }
3637
3638 bool hasNonTrivialCall() const { return NonTrivial; }
3639
3640 void VisitCallExpr(const CallExpr *E) {
3641 if (const CXXMethodDecl *Method
3642 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3643 if (Method->isTrivial()) {
3644 // Recurse to children of the call.
3645 Inherited::VisitStmt(E);
3646 return;
3647 }
3648 }
3649
3650 NonTrivial = true;
3651 }
3652
3653 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3654 if (E->getConstructor()->isTrivial()) {
3655 // Recurse to children of the call.
3656 Inherited::VisitStmt(E);
3657 return;
3658 }
3659
3660 NonTrivial = true;
3661 }
3662
3663 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3664 if (E->getTemporary()->getDestructor()->isTrivial()) {
3665 Inherited::VisitStmt(E);
3666 return;
3667 }
3668
3669 NonTrivial = true;
3670 }
3671 };
3672}
3673
3674bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3675 NonTrivialCallFinder Finder(Ctx);
3676 Finder.Visit(this);
3677 return Finder.hasNonTrivialCall();
3678}
3679
3680/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3681/// pointer constant or not, as well as the specific kind of constant detected.
3682/// Null pointer constants can be integer constant expressions with the
3683/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3684/// (a GNU extension).
3685Expr::NullPointerConstantKind
3686Expr::isNullPointerConstant(ASTContext &Ctx,
3687 NullPointerConstantValueDependence NPC) const {
3688 if (isValueDependent() &&
3689 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3690 switch (NPC) {
3691 case NPC_NeverValueDependent:
3692 llvm_unreachable("Unexpected value dependent expression!")::llvm::llvm_unreachable_internal("Unexpected value dependent expression!"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3692)
;
3693 case NPC_ValueDependentIsNull:
3694 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3695 return NPCK_ZeroExpression;
3696 else
3697 return NPCK_NotNull;
3698
3699 case NPC_ValueDependentIsNotNull:
3700 return NPCK_NotNull;
3701 }
3702 }
3703
3704 // Strip off a cast to void*, if it exists. Except in C++.
3705 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3706 if (!Ctx.getLangOpts().CPlusPlus) {
3707 // Check that it is a cast to void*.
3708 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3709 QualType Pointee = PT->getPointeeType();
3710 Qualifiers Qs = Pointee.getQualifiers();
3711 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3712 // has non-default address space it is not treated as nullptr.
3713 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3714 // since it cannot be assigned to a pointer to constant address space.
3715 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3716 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3717 (Ctx.getLangOpts().OpenCL &&
3718 Ctx.getLangOpts().OpenCLVersion < 200 &&
3719 Pointee.getAddressSpace() == LangAS::opencl_private))
3720 Qs.removeAddressSpace();
3721
3722 if (Pointee->isVoidType() && Qs.empty() && // to void*
3723 CE->getSubExpr()->getType()->isIntegerType()) // from int
3724 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3725 }
3726 }
3727 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3728 // Ignore the ImplicitCastExpr type entirely.
3729 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3730 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3731 // Accept ((void*)0) as a null pointer constant, as many other
3732 // implementations do.
3733 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3734 } else if (const GenericSelectionExpr *GE =
3735 dyn_cast<GenericSelectionExpr>(this)) {
3736 if (GE->isResultDependent())
3737 return NPCK_NotNull;
3738 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3739 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3740 if (CE->isConditionDependent())
3741 return NPCK_NotNull;
3742 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3743 } else if (const CXXDefaultArgExpr *DefaultArg
3744 = dyn_cast<CXXDefaultArgExpr>(this)) {
3745 // See through default argument expressions.
3746 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3747 } else if (const CXXDefaultInitExpr *DefaultInit
3748 = dyn_cast<CXXDefaultInitExpr>(this)) {
3749 // See through default initializer expressions.
3750 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3751 } else if (isa<GNUNullExpr>(this)) {
3752 // The GNU __null extension is always a null pointer constant.
3753 return NPCK_GNUNull;
3754 } else if (const MaterializeTemporaryExpr *M
3755 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3756 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3757 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3758 if (const Expr *Source = OVE->getSourceExpr())
3759 return Source->isNullPointerConstant(Ctx, NPC);
3760 }
3761
3762 // C++11 nullptr_t is always a null pointer constant.
3763 if (getType()->isNullPtrType())
3764 return NPCK_CXX11_nullptr;
3765
3766 if (const RecordType *UT = getType()->getAsUnionType())
3767 if (!Ctx.getLangOpts().CPlusPlus11 &&
3768 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3769 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3770 const Expr *InitExpr = CLE->getInitializer();
3771 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3772 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3773 }
3774 // This expression must be an integer type.
3775 if (!getType()->isIntegerType() ||
3776 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3777 return NPCK_NotNull;
3778
3779 if (Ctx.getLangOpts().CPlusPlus11) {
3780 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3781 // value zero or a prvalue of type std::nullptr_t.
3782 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3783 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3784 if (Lit && !Lit->getValue())
3785 return NPCK_ZeroLiteral;
3786 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3787 return NPCK_NotNull;
3788 } else {
3789 // If we have an integer constant expression, we need to *evaluate* it and
3790 // test for the value 0.
3791 if (!isIntegerConstantExpr(Ctx))
3792 return NPCK_NotNull;
3793 }
3794
3795 if (EvaluateKnownConstInt(Ctx) != 0)
3796 return NPCK_NotNull;
3797
3798 if (isa<IntegerLiteral>(this))
3799 return NPCK_ZeroLiteral;
3800 return NPCK_ZeroExpression;
3801}
3802
3803/// If this expression is an l-value for an Objective C
3804/// property, find the underlying property reference expression.
3805const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3806 const Expr *E = this;
3807 while (true) {
3808 assert((E->getValueKind() == VK_LValue &&(((E->getValueKind() == VK_LValue && E->getObjectKind
() == OK_ObjCProperty) && "expression is not a property reference"
) ? static_cast<void> (0) : __assert_fail ("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3810, __PRETTY_FUNCTION__))
3809 E->getObjectKind() == OK_ObjCProperty) &&(((E->getValueKind() == VK_LValue && E->getObjectKind
() == OK_ObjCProperty) && "expression is not a property reference"
) ? static_cast<void> (0) : __assert_fail ("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3810, __PRETTY_FUNCTION__))
3810 "expression is not a property reference")(((E->getValueKind() == VK_LValue && E->getObjectKind
() == OK_ObjCProperty) && "expression is not a property reference"
) ? static_cast<void> (0) : __assert_fail ("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 3810, __PRETTY_FUNCTION__))
;
3811 E = E->IgnoreParenCasts();
3812 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3813 if (BO->getOpcode() == BO_Comma) {
3814 E = BO->getRHS();
3815 continue;
3816 }
3817 }
3818
3819 break;
3820 }
3821
3822 return cast<ObjCPropertyRefExpr>(E);
3823}
3824
3825bool Expr::isObjCSelfExpr() const {
3826 const Expr *E = IgnoreParenImpCasts();
3827
3828 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3829 if (!DRE)
3830 return false;
3831
3832 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3833 if (!Param)
3834 return false;
3835
3836 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3837 if (!M)
3838 return false;
3839
3840 return M->getSelfDecl() == Param;
3841}
3842
3843FieldDecl *Expr::getSourceBitField() {
3844 Expr *E = this->IgnoreParens();
3845
3846 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3847 if (ICE->getCastKind() == CK_LValueToRValue ||
3848 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3849 E = ICE->getSubExpr()->IgnoreParens();
3850 else
3851 break;
3852 }
3853
3854 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3855 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3856 if (Field->isBitField())
3857 return Field;
3858
3859 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3860 FieldDecl *Ivar = IvarRef->getDecl();
3861 if (Ivar->isBitField())
3862 return Ivar;
3863 }
3864
3865 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3866 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3867 if (Field->isBitField())
3868 return Field;
3869
3870 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3871 if (Expr *E = BD->getBinding())
3872 return E->getSourceBitField();
3873 }
3874
3875 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3876 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3877 return BinOp->getLHS()->getSourceBitField();
3878
3879 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3880 return BinOp->getRHS()->getSourceBitField();
3881 }
3882
3883 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3884 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3885 return UnOp->getSubExpr()->getSourceBitField();
3886
3887 return nullptr;
3888}
3889
3890bool Expr::refersToVectorElement() const {
3891 // FIXME: Why do we not just look at the ObjectKind here?
3892 const Expr *E = this->IgnoreParens();
3893
3894 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3895 if (ICE->getValueKind() != VK_RValue &&
3896 ICE->getCastKind() == CK_NoOp)
3897 E = ICE->getSubExpr()->IgnoreParens();
3898 else
3899 break;
3900 }
3901
3902 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3903 return ASE->getBase()->getType()->isVectorType();
3904
3905 if (isa<ExtVectorElementExpr>(E))
3906 return true;
3907
3908 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3909 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3910 if (auto *E = BD->getBinding())
3911 return E->refersToVectorElement();
3912
3913 return false;
3914}
3915
3916bool Expr::refersToGlobalRegisterVar() const {
3917 const Expr *E = this->IgnoreParenImpCasts();
3918
3919 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3920 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3921 if (VD->getStorageClass() == SC_Register &&
3922 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3923 return true;
3924
3925 return false;
3926}
3927
3928bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3929 E1 = E1->IgnoreParens();
3930 E2 = E2->IgnoreParens();
3931
3932 if (E1->getStmtClass() != E2->getStmtClass())
3933 return false;
3934
3935 switch (E1->getStmtClass()) {
3936 default:
3937 return false;
3938 case CXXThisExprClass:
3939 return true;
3940 case DeclRefExprClass: {
3941 // DeclRefExpr without an ImplicitCastExpr can happen for integral
3942 // template parameters.
3943 const auto *DRE1 = cast<DeclRefExpr>(E1);
3944 const auto *DRE2 = cast<DeclRefExpr>(E2);
3945 return DRE1->isRValue() && DRE2->isRValue() &&
3946 DRE1->getDecl() == DRE2->getDecl();
3947 }
3948 case ImplicitCastExprClass: {
3949 // Peel off implicit casts.
3950 while (true) {
3951 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
3952 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
3953 if (!ICE1 || !ICE2)
3954 return false;
3955 if (ICE1->getCastKind() != ICE2->getCastKind())
3956 return false;
3957 E1 = ICE1->getSubExpr()->IgnoreParens();
3958 E2 = ICE2->getSubExpr()->IgnoreParens();
3959 // The final cast must be one of these types.
3960 if (ICE1->getCastKind() == CK_LValueToRValue ||
3961 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
3962 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
3963 break;
3964 }
3965 }
3966
3967 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
3968 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
3969 if (DRE1 && DRE2)
3970 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
3971
3972 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
3973 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
3974 if (Ivar1 && Ivar2) {
3975 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
3976 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
3977 }
3978
3979 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
3980 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
3981 if (Array1 && Array2) {
3982 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
3983 return false;
3984
3985 auto Idx1 = Array1->getIdx();
3986 auto Idx2 = Array2->getIdx();
3987 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
3988 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
3989 if (Integer1 && Integer2) {
3990 if (!llvm::APInt::isSameValue(Integer1->getValue(),
3991 Integer2->getValue()))
3992 return false;
3993 } else {
3994 if (!isSameComparisonOperand(Idx1, Idx2))
3995 return false;
3996 }
3997
3998 return true;
3999 }
4000
4001 // Walk the MemberExpr chain.
4002 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4003 const auto *ME1 = cast<MemberExpr>(E1);
4004 const auto *ME2 = cast<MemberExpr>(E2);
4005 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4006 return false;
4007 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4008 if (D->isStaticDataMember())
4009 return true;
4010 E1 = ME1->getBase()->IgnoreParenImpCasts();
4011 E2 = ME2->getBase()->IgnoreParenImpCasts();
4012 }
4013
4014 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4015 return true;
4016
4017 // A static member variable can end the MemberExpr chain with either
4018 // a MemberExpr or a DeclRefExpr.
4019 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4020 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4021 return DRE->getDecl();
4022 if (const auto *ME = dyn_cast<MemberExpr>(E))
4023 return ME->getMemberDecl();
4024 return nullptr;
4025 };
4026
4027 const ValueDecl *VD1 = getAnyDecl(E1);
4028 const ValueDecl *VD2 = getAnyDecl(E2);
4029 return declaresSameEntity(VD1, VD2);
4030 }
4031 }
4032}
4033
4034/// isArrow - Return true if the base expression is a pointer to vector,
4035/// return false if the base expression is a vector.
4036bool ExtVectorElementExpr::isArrow() const {
4037 return getBase()->getType()->isPointerType();
4038}
4039
4040unsigned ExtVectorElementExpr::getNumElements() const {
4041 if (const VectorType *VT = getType()->getAs<VectorType>())
4042 return VT->getNumElements();
4043 return 1;
4044}
4045
4046/// containsDuplicateElements - Return true if any element access is repeated.
4047bool ExtVectorElementExpr::containsDuplicateElements() const {
4048 // FIXME: Refactor this code to an accessor on the AST node which returns the
4049 // "type" of component access, and share with code below and in Sema.
4050 StringRef Comp = Accessor->getName();
4051
4052 // Halving swizzles do not contain duplicate elements.
4053 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4054 return false;
4055
4056 // Advance past s-char prefix on hex swizzles.
4057 if (Comp[0] == 's' || Comp[0] == 'S')
4058 Comp = Comp.substr(1);
4059
4060 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4061 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4062 return true;
4063
4064 return false;
4065}
4066
4067/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4068void ExtVectorElementExpr::getEncodedElementAccess(
4069 SmallVectorImpl<uint32_t> &Elts) const {
4070 StringRef Comp = Accessor->getName();
4071 bool isNumericAccessor = false;
4072 if (Comp[0] == 's' || Comp[0] == 'S') {
4073 Comp = Comp.substr(1);
4074 isNumericAccessor = true;
4075 }
4076
4077 bool isHi = Comp == "hi";
4078 bool isLo = Comp == "lo";
4079 bool isEven = Comp == "even";
4080 bool isOdd = Comp == "odd";
4081
4082 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4083 uint64_t Index;
4084
4085 if (isHi)
4086 Index = e + i;
4087 else if (isLo)
4088 Index = i;
4089 else if (isEven)
4090 Index = 2 * i;
4091 else if (isOdd)
4092 Index = 2 * i + 1;
4093 else
4094 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4095
4096 Elts.push_back(Index);
4097 }
4098}
4099
4100ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
4101 QualType Type, SourceLocation BLoc,
4102 SourceLocation RP)
4103 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
4104 Type->isDependentType(), Type->isDependentType(),
4105 Type->isInstantiationDependentType(),
4106 Type->containsUnexpandedParameterPack()),
4107 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
4108{
4109 SubExprs = new (C) Stmt*[args.size()];
4110 for (unsigned i = 0; i != args.size(); i++) {
4111 addDependence(args[i]->getDependence());
4112 SubExprs[i] = args[i];
4113 }
4114}
4115
4116void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4117 if (SubExprs) C.Deallocate(SubExprs);
4118
4119 this->NumExprs = Exprs.size();
4120 SubExprs = new (C) Stmt*[NumExprs];
4121 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4122}
4123
4124GenericSelectionExpr::GenericSelectionExpr(
4125 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4126 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4127 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4128 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4129 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4130 AssocExprs[ResultIndex]->getValueKind(),
4131 AssocExprs[ResultIndex]->getObjectKind(),
4132 AssocExprs[ResultIndex]->isTypeDependent(),
4133 AssocExprs[ResultIndex]->isValueDependent(),
4134 AssocExprs[ResultIndex]->isInstantiationDependent(),
4135 ContainsUnexpandedParameterPack),
4136 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4137 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4138 assert(AssocTypes.size() == AssocExprs.size() &&((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4140, __PRETTY_FUNCTION__))
4139 "Must have the same number of association expressions"((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4140, __PRETTY_FUNCTION__))
4140 " and TypeSourceInfo!")((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4140, __PRETTY_FUNCTION__))
;
4141 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!")((ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!"
) ? static_cast<void> (0) : __assert_fail ("ResultIndex < NumAssocs && \"ResultIndex is out-of-bounds!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4141, __PRETTY_FUNCTION__))
;
4142
4143 GenericSelectionExprBits.GenericLoc = GenericLoc;
4144 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4145 std::copy(AssocExprs.begin(), AssocExprs.end(),
4146 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4147 std::copy(AssocTypes.begin(), AssocTypes.end(),
4148 getTrailingObjects<TypeSourceInfo *>());
4149}
4150
4151GenericSelectionExpr::GenericSelectionExpr(
4152 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4153 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4154 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4155 bool ContainsUnexpandedParameterPack)
4156 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4157 OK_Ordinary,
4158 /*isTypeDependent=*/true,
4159 /*isValueDependent=*/true,
4160 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4161 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4162 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4163 assert(AssocTypes.size() == AssocExprs.size() &&((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4165, __PRETTY_FUNCTION__))
4164 "Must have the same number of association expressions"((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4165, __PRETTY_FUNCTION__))
4165 " and TypeSourceInfo!")((AssocTypes.size() == AssocExprs.size() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? static_cast<void> (0) : __assert_fail
("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4165, __PRETTY_FUNCTION__))
;
4166
4167 GenericSelectionExprBits.GenericLoc = GenericLoc;
4168 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4169 std::copy(AssocExprs.begin(), AssocExprs.end(),
4170 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4171 std::copy(AssocTypes.begin(), AssocTypes.end(),
4172 getTrailingObjects<TypeSourceInfo *>());
4173}
4174
4175GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4176 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4177
4178GenericSelectionExpr *GenericSelectionExpr::Create(
4179 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4180 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4181 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4182 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4183 unsigned NumAssocs = AssocExprs.size();
4184 void *Mem = Context.Allocate(
4185 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4186 alignof(GenericSelectionExpr));
4187 return new (Mem) GenericSelectionExpr(
4188 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4189 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4190}
4191
4192GenericSelectionExpr *GenericSelectionExpr::Create(
4193 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4194 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4195 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4196 bool ContainsUnexpandedParameterPack) {
4197 unsigned NumAssocs = AssocExprs.size();
4198 void *Mem = Context.Allocate(
4199 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4200 alignof(GenericSelectionExpr));
4201 return new (Mem) GenericSelectionExpr(
4202 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4203 RParenLoc, ContainsUnexpandedParameterPack);
4204}
4205
4206GenericSelectionExpr *
4207GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4208 unsigned NumAssocs) {
4209 void *Mem = Context.Allocate(
4210 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4211 alignof(GenericSelectionExpr));
4212 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4213}
4214
4215//===----------------------------------------------------------------------===//
4216// DesignatedInitExpr
4217//===----------------------------------------------------------------------===//
4218
4219IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4220 assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator"
) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4220, __PRETTY_FUNCTION__))
;
4221 if (Field.NameOrField & 0x01)
4222 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4223 else
4224 return getField()->getIdentifier();
4225}
4226
4227DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4228 llvm::ArrayRef<Designator> Designators,
4229 SourceLocation EqualOrColonLoc,
4230 bool GNUSyntax,
4231 ArrayRef<Expr*> IndexExprs,
4232 Expr *Init)
4233 : Expr(DesignatedInitExprClass, Ty,
4234 Init->getValueKind(), Init->getObjectKind(),
4235 Init->isTypeDependent(), Init->isValueDependent(),
4236 Init->isInstantiationDependent(),
4237 Init->containsUnexpandedParameterPack()),
4238 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4239 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4240 this->Designators = new (C) Designator[NumDesignators];
4241
4242 // Record the initializer itself.
4243 child_iterator Child = child_begin();
4244 *Child++ = Init;
4245
4246 // Copy the designators and their subexpressions, computing
4247 // value-dependence along the way.
4248 unsigned IndexIdx = 0;
4249 for (unsigned I = 0; I != NumDesignators; ++I) {
4250 this->Designators[I] = Designators[I];
4251
4252 if (this->Designators[I].isArrayDesignator()) {
4253 // Compute type- and value-dependence.
4254 Expr *Index = IndexExprs[IndexIdx];
4255
4256 // Propagate dependence flags.
4257 auto Deps = Index->getDependence();
4258 if (Deps & (ExprDependence::Type | ExprDependence::Value))
4259 Deps |= ExprDependence::Type | ExprDependence::Value;
4260 addDependence(Deps);
4261
4262 // Copy the index expressions into permanent storage.
4263 *Child++ = IndexExprs[IndexIdx++];
4264 } else if (this->Designators[I].isArrayRangeDesignator()) {
4265 // Compute type- and value-dependence.
4266 Expr *Start = IndexExprs[IndexIdx];
4267 Expr *End = IndexExprs[IndexIdx + 1];
4268
4269 auto Deps = Start->getDependence() | End->getDependence();
4270 if (Deps & (ExprDependence::Type | ExprDependence::Value))
4271 Deps |= ExprDependence::TypeValueInstantiation;
4272 addDependence(Deps);
4273
4274 // Copy the start/end expressions into permanent storage.
4275 *Child++ = IndexExprs[IndexIdx++];
4276 *Child++ = IndexExprs[IndexIdx++];
4277 }
4278 }
4279
4280 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions")((IndexIdx == IndexExprs.size() && "Wrong number of index expressions"
) ? static_cast<void> (0) : __assert_fail ("IndexIdx == IndexExprs.size() && \"Wrong number of index expressions\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4280, __PRETTY_FUNCTION__))
;
4281}
4282
4283DesignatedInitExpr *
4284DesignatedInitExpr::Create(const ASTContext &C,
4285 llvm::ArrayRef<Designator> Designators,
4286 ArrayRef<Expr*> IndexExprs,
4287 SourceLocation ColonOrEqualLoc,
4288 bool UsesColonSyntax, Expr *Init) {
4289 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4290 alignof(DesignatedInitExpr));
4291 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4292 ColonOrEqualLoc, UsesColonSyntax,
4293 IndexExprs, Init);
4294}
4295
4296DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4297 unsigned NumIndexExprs) {
4298 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4299 alignof(DesignatedInitExpr));
4300 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4301}
4302
4303void DesignatedInitExpr::setDesignators(const ASTContext &C,
4304 const Designator *Desigs,
4305 unsigned NumDesigs) {
4306 Designators = new (C) Designator[NumDesigs];
4307 NumDesignators = NumDesigs;
4308 for (unsigned I = 0; I != NumDesigs; ++I)
4309 Designators[I] = Desigs[I];
4310}
4311
4312SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4313 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4314 if (size() == 1)
4315 return DIE->getDesignator(0)->getSourceRange();
4316 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4317 DIE->getDesignator(size() - 1)->getEndLoc());
4318}
4319
4320SourceLocation DesignatedInitExpr::getBeginLoc() const {
4321 SourceLocation StartLoc;
4322 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4323 Designator &First = *DIE->getDesignator(0);
4324 if (First.isFieldDesignator()) {
4325 if (GNUSyntax)
4326 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4327 else
4328 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4329 } else
4330 StartLoc =
4331 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
4332 return StartLoc;
4333}
4334
4335SourceLocation DesignatedInitExpr::getEndLoc() const {
4336 return getInit()->getEndLoc();
4337}
4338
4339Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4340 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator")((D.Kind == Designator::ArrayDesignator && "Requires array designator"
) ? static_cast<void> (0) : __assert_fail ("D.Kind == Designator::ArrayDesignator && \"Requires array designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4340, __PRETTY_FUNCTION__))
;
4341 return getSubExpr(D.ArrayOrRange.Index + 1);
4342}
4343
4344Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4345 assert(D.Kind == Designator::ArrayRangeDesignator &&((D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"
) ? static_cast<void> (0) : __assert_fail ("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4346, __PRETTY_FUNCTION__))
4346 "Requires array range designator")((D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"
) ? static_cast<void> (0) : __assert_fail ("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4346, __PRETTY_FUNCTION__))
;
4347 return getSubExpr(D.ArrayOrRange.Index + 1);
4348}
4349
4350Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4351 assert(D.Kind == Designator::ArrayRangeDesignator &&((D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"
) ? static_cast<void> (0) : __assert_fail ("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4352, __PRETTY_FUNCTION__))
4352 "Requires array range designator")((D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"
) ? static_cast<void> (0) : __assert_fail ("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4352, __PRETTY_FUNCTION__))
;
4353 return getSubExpr(D.ArrayOrRange.Index + 2);
4354}
4355
4356/// Replaces the designator at index @p Idx with the series
4357/// of designators in [First, Last).
4358void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4359 const Designator *First,
4360 const Designator *Last) {
4361 unsigned NumNewDesignators = Last - First;
4362 if (NumNewDesignators == 0) {
4363 std::copy_backward(Designators + Idx + 1,
4364 Designators + NumDesignators,
4365 Designators + Idx);
4366 --NumNewDesignators;
4367 return;
4368 } else if (NumNewDesignators == 1) {
4369 Designators[Idx] = *First;
4370 return;
4371 }
4372
4373 Designator *NewDesignators
4374 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4375 std::copy(Designators, Designators + Idx, NewDesignators);
4376 std::copy(First, Last, NewDesignators + Idx);
4377 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4378 NewDesignators + Idx + NumNewDesignators);
4379 Designators = NewDesignators;
4380 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4381}
4382
4383DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4384 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4385 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4386 OK_Ordinary, false, false, false, false) {
4387 BaseAndUpdaterExprs[0] = baseExpr;
4388
4389 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4390 ILE->setType(baseExpr->getType());
4391 BaseAndUpdaterExprs[1] = ILE;
4392}
4393
4394SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4395 return getBase()->getBeginLoc();
4396}
4397
4398SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4399 return getBase()->getEndLoc();
4400}
4401
4402ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4403 SourceLocation RParenLoc)
4404 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4405 false, false),
4406 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4407 ParenListExprBits.NumExprs = Exprs.size();
4408
4409 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4410 addDependence(Exprs[I]->getDependence());
4411 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4412 }
4413}
4414
4415ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4416 : Expr(ParenListExprClass, Empty) {
4417 ParenListExprBits.NumExprs = NumExprs;
4418}
4419
4420ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4421 SourceLocation LParenLoc,
4422 ArrayRef<Expr *> Exprs,
4423 SourceLocation RParenLoc) {
4424 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4425 alignof(ParenListExpr));
4426 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4427}
4428
4429ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4430 unsigned NumExprs) {
4431 void *Mem =
4432 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4433 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4434}
4435
4436const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4437 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4438 e = ewc->getSubExpr();
4439 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4440 e = m->getSubExpr();
4441 e = cast<CXXConstructExpr>(e)->getArg(0);
4442 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4443 e = ice->getSubExpr();
4444 return cast<OpaqueValueExpr>(e);
4445}
4446
4447PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4448 EmptyShell sh,
4449 unsigned numSemanticExprs) {
4450 void *buffer =
4451 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4452 alignof(PseudoObjectExpr));
4453 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4454}
4455
4456PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4457 : Expr(PseudoObjectExprClass, shell) {
4458 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4459}
4460
4461PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4462 ArrayRef<Expr*> semantics,
4463 unsigned resultIndex) {
4464 assert(syntax && "no syntactic expression!")((syntax && "no syntactic expression!") ? static_cast
<void> (0) : __assert_fail ("syntax && \"no syntactic expression!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4464, __PRETTY_FUNCTION__))
;
4465 assert(semantics.size() && "no semantic expressions!")((semantics.size() && "no semantic expressions!") ? static_cast
<void> (0) : __assert_fail ("semantics.size() && \"no semantic expressions!\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4465, __PRETTY_FUNCTION__))
;
4466
4467 QualType type;
4468 ExprValueKind VK;
4469 if (resultIndex == NoResult) {
4470 type = C.VoidTy;
4471 VK = VK_RValue;
4472 } else {
4473 assert(resultIndex < semantics.size())((resultIndex < semantics.size()) ? static_cast<void>
(0) : __assert_fail ("resultIndex < semantics.size()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4473, __PRETTY_FUNCTION__))
;
4474 type = semantics[resultIndex]->getType();
4475 VK = semantics[resultIndex]->getValueKind();
4476 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary)((semantics[resultIndex]->getObjectKind() == OK_Ordinary) ?
static_cast<void> (0) : __assert_fail ("semantics[resultIndex]->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4476, __PRETTY_FUNCTION__))
;
4477 }
4478
4479 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4480 alignof(PseudoObjectExpr));
4481 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4482 resultIndex);
4483}
4484
4485PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4486 Expr *syntax, ArrayRef<Expr*> semantics,
4487 unsigned resultIndex)
4488 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4489 /*filled in at end of ctor*/ false, false, false, false) {
4490 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4491 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4492
4493 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4494 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4495 getSubExprsBuffer()[i] = E;
4496
4497 addDependence(E->getDependence());
4498
4499 if (isa<OpaqueValueExpr>(E))
4500 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&((cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr
&& "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? static_cast<void> (0
) : __assert_fail ("cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4502, __PRETTY_FUNCTION__))
4501 "opaque-value semantic expressions for pseudo-object "((cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr
&& "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? static_cast<void> (0
) : __assert_fail ("cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4502, __PRETTY_FUNCTION__))
4502 "operations must have sources")((cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr
&& "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? static_cast<void> (0
) : __assert_fail ("cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4502, __PRETTY_FUNCTION__))
;
4503 }
4504}
4505
4506//===----------------------------------------------------------------------===//
4507// Child Iterators for iterating over subexpressions/substatements
4508//===----------------------------------------------------------------------===//
4509
4510// UnaryExprOrTypeTraitExpr
4511Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4512 const_child_range CCR =
4513 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4514 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4515}
4516
4517Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4518 // If this is of a type and the type is a VLA type (and not a typedef), the
4519 // size expression of the VLA needs to be treated as an executable expression.
4520 // Why isn't this weirdness documented better in StmtIterator?
4521 if (isArgumentType()) {
4522 if (const VariableArrayType *T =
4523 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4524 return const_child_range(const_child_iterator(T), const_child_iterator());
4525 return const_child_range(const_child_iterator(), const_child_iterator());
4526 }
4527 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4528}
4529
4530AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
4531 QualType t, AtomicOp op, SourceLocation RP)
4532 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4533 false, false, false, false),
4534 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4535{
4536 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions")((args.size() == getNumSubExprs(op) && "wrong number of subexpressions"
) ? static_cast<void> (0) : __assert_fail ("args.size() == getNumSubExprs(op) && \"wrong number of subexpressions\""
, "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4536, __PRETTY_FUNCTION__))
;
4537 for (unsigned i = 0; i != args.size(); i++) {
4538 addDependence(args[i]->getDependence());
4539 SubExprs[i] = args[i];
4540 }
4541}
4542
4543unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4544 switch (Op) {
4545 case AO__c11_atomic_init:
4546 case AO__opencl_atomic_init:
4547 case AO__c11_atomic_load:
4548 case AO__atomic_load_n:
4549 return 2;
4550
4551 case AO__opencl_atomic_load:
4552 case AO__c11_atomic_store:
4553 case AO__c11_atomic_exchange:
4554 case AO__atomic_load:
4555 case AO__atomic_store:
4556 case AO__atomic_store_n:
4557 case AO__atomic_exchange_n:
4558 case AO__c11_atomic_fetch_add:
4559 case AO__c11_atomic_fetch_sub:
4560 case AO__c11_atomic_fetch_and:
4561 case AO__c11_atomic_fetch_or:
4562 case AO__c11_atomic_fetch_xor:
4563 case AO__c11_atomic_fetch_max:
4564 case AO__c11_atomic_fetch_min:
4565 case AO__atomic_fetch_add:
4566 case AO__atomic_fetch_sub:
4567 case AO__atomic_fetch_and:
4568 case AO__atomic_fetch_or:
4569 case AO__atomic_fetch_xor:
4570 case AO__atomic_fetch_nand:
4571 case AO__atomic_add_fetch:
4572 case AO__atomic_sub_fetch:
4573 case AO__atomic_and_fetch:
4574 case AO__atomic_or_fetch:
4575 case AO__atomic_xor_fetch:
4576 case AO__atomic_nand_fetch:
4577 case AO__atomic_min_fetch:
4578 case AO__atomic_max_fetch:
4579 case AO__atomic_fetch_min:
4580 case AO__atomic_fetch_max:
4581 return 3;
4582
4583 case AO__opencl_atomic_store:
4584 case AO__opencl_atomic_exchange:
4585 case AO__opencl_atomic_fetch_add:
4586 case AO__opencl_atomic_fetch_sub:
4587 case AO__opencl_atomic_fetch_and:
4588 case AO__opencl_atomic_fetch_or:
4589 case AO__opencl_atomic_fetch_xor:
4590 case AO__opencl_atomic_fetch_min:
4591 case AO__opencl_atomic_fetch_max:
4592 case AO__atomic_exchange:
4593 return 4;
4594
4595 case AO__c11_atomic_compare_exchange_strong:
4596 case AO__c11_atomic_compare_exchange_weak:
4597 return 5;
4598
4599 case AO__opencl_atomic_compare_exchange_strong:
4600 case AO__opencl_atomic_compare_exchange_weak:
4601 case AO__atomic_compare_exchange:
4602 case AO__atomic_compare_exchange_n:
4603 return 6;
4604 }
4605 llvm_unreachable("unknown atomic op")::llvm::llvm_unreachable_internal("unknown atomic op", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4605)
;
4606}
4607
4608QualType AtomicExpr::getValueType() const {
4609 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4610 if (auto AT = T->getAs<AtomicType>())
4611 return AT->getValueType();
4612 return T;
4613}
4614
4615QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4616 unsigned ArraySectionCount = 0;
4617 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4618 Base = OASE->getBase();
4619 ++ArraySectionCount;
4620 }
4621 while (auto *ASE =
4622 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4623 Base = ASE->getBase();
4624 ++ArraySectionCount;
4625 }
4626 Base = Base->IgnoreParenImpCasts();
4627 auto OriginalTy = Base->getType();
4628 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4629 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4630 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4631
4632 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4633 if (OriginalTy->isAnyPointerType())
4634 OriginalTy = OriginalTy->getPointeeType();
4635 else {
4636 assert (OriginalTy->isArrayType())((OriginalTy->isArrayType()) ? static_cast<void> (0)
: __assert_fail ("OriginalTy->isArrayType()", "/build/llvm-toolchain-snapshot-11~++20200307100611+a5704f92b83/clang/lib/AST/Expr.cpp"
, 4636, __PRETTY_FUNCTION__))
;
4637 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4638 }
4639 }
4640 return OriginalTy;
4641}

/usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/bits/stl_iterator.h

1// Iterators -*- C++ -*-
2
3// Copyright (C) 2001-2016 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
37 *
38 *
39 * Copyright (c) 1996-1998
40 * Silicon Graphics Computer Systems, Inc.
41 *
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
49 */
50
51/** @file bits/stl_iterator.h
52 * This is an internal header file, included by other library headers.
53 * Do not attempt to use it directly. @headername{iterator}
54 *
55 * This file implements reverse_iterator, back_insert_iterator,
56 * front_insert_iterator, insert_iterator, __normal_iterator, and their
57 * supporting functions and overloaded operators.
58 */
59
60#ifndef _STL_ITERATOR_H1
61#define _STL_ITERATOR_H1 1
62
63#include <bits/cpp_type_traits.h>
64#include <ext/type_traits.h>
65#include <bits/move.h>
66#include <bits/ptr_traits.h>
67
68namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
69{
70_GLIBCXX_BEGIN_NAMESPACE_VERSION
71
72 /**
73 * @addtogroup iterators
74 * @{
75 */
76
77 // 24.4.1 Reverse iterators
78 /**
79 * Bidirectional and random access iterators have corresponding reverse
80 * %iterator adaptors that iterate through the data structure in the
81 * opposite direction. They have the same signatures as the corresponding
82 * iterators. The fundamental relation between a reverse %iterator and its
83 * corresponding %iterator @c i is established by the identity:
84 * @code
85 * &*(reverse_iterator(i)) == &*(i - 1)
86 * @endcode
87 *
88 * <em>This mapping is dictated by the fact that while there is always a
89 * pointer past the end of an array, there might not be a valid pointer
90 * before the beginning of an array.</em> [24.4.1]/1,2
91 *
92 * Reverse iterators can be tricky and surprising at first. Their
93 * semantics make sense, however, and the trickiness is a side effect of
94 * the requirement that the iterators must be safe.
95 */
96 template<typename _Iterator>
97 class reverse_iterator
98 : public iterator<typename iterator_traits<_Iterator>::iterator_category,
99 typename iterator_traits<_Iterator>::value_type,
100 typename iterator_traits<_Iterator>::difference_type,
101 typename iterator_traits<_Iterator>::pointer,
102 typename iterator_traits<_Iterator>::reference>
103 {
104 protected:
105 _Iterator current;
106
107 typedef iterator_traits<_Iterator> __traits_type;
108
109 public:
110 typedef _Iterator iterator_type;
111 typedef typename __traits_type::difference_type difference_type;
112 typedef typename __traits_type::pointer pointer;
113 typedef typename __traits_type::reference reference;
114
115 /**
116 * The default constructor value-initializes member @p current.
117 * If it is a pointer, that means it is zero-initialized.
118 */
119 // _GLIBCXX_RESOLVE_LIB_DEFECTS
120 // 235 No specification of default ctor for reverse_iterator
121 reverse_iterator() : current() { }
122
123 /**
124 * This %iterator will move in the opposite direction that @p x does.
125 */
126 explicit
127 reverse_iterator(iterator_type __x) : current(__x) { }
128
129 /**
130 * The copy constructor is normal.
131 */
132 reverse_iterator(const reverse_iterator& __x)
133 : current(__x.current) { }
134
135 /**
136 * A %reverse_iterator across other types can be copied if the
137 * underlying %iterator can be converted to the type of @c current.
138 */
139 template<typename _Iter>
140 reverse_iterator(const reverse_iterator<_Iter>& __x)
141 : current(__x.base()) { }
142
143 /**
144 * @return @c current, the %iterator used for underlying work.
145 */
146 iterator_type
147 base() const
148 { return current; }
149
150 /**
151 * @return A reference to the value at @c --current
152 *
153 * This requires that @c --current is dereferenceable.
154 *
155 * @warning This implementation requires that for an iterator of the
156 * underlying iterator type, @c x, a reference obtained by
157 * @c *x remains valid after @c x has been modified or
158 * destroyed. This is a bug: http://gcc.gnu.org/PR51823
159 */
160 reference
161 operator*() const
162 {
163 _Iterator __tmp = current;
164 return *--__tmp;
165 }
166
167 /**
168 * @return A pointer to the value at @c --current
169 *
170 * This requires that @c --current is dereferenceable.
171 */
172 pointer
173 operator->() const
174 { return &(operator*()); }
175
176 /**
177 * @return @c *this
178 *
179 * Decrements the underlying iterator.
180 */
181 reverse_iterator&
182 operator++()
183 {
184 --current;
185 return *this;
186 }
187
188 /**
189 * @return The original value of @c *this
190 *
191 * Decrements the underlying iterator.
192 */
193 reverse_iterator
194 operator++(int)
195 {
196 reverse_iterator __tmp = *this;
197 --current;
198 return __tmp;
199 }
200
201 /**
202 * @return @c *this
203 *
204 * Increments the underlying iterator.
205 */
206 reverse_iterator&
207 operator--()
208 {
209 ++current;
210 return *this;
211 }
212
213 /**
214 * @return A reverse_iterator with the previous value of @c *this
215 *
216 * Increments the underlying iterator.
217 */
218 reverse_iterator
219 operator--(int)
220 {
221 reverse_iterator __tmp = *this;
222 ++current;
223 return __tmp;
224 }
225
226 /**
227 * @return A reverse_iterator that refers to @c current - @a __n
228 *
229 * The underlying iterator must be a Random Access Iterator.
230 */
231 reverse_iterator
232 operator+(difference_type __n) const
233 { return reverse_iterator(current - __n); }
234
235 /**
236 * @return *this
237 *
238 * Moves the underlying iterator backwards @a __n steps.
239 * The underlying iterator must be a Random Access Iterator.
240 */
241 reverse_iterator&
242 operator+=(difference_type __n)
243 {
244 current -= __n;
245 return *this;
246 }
247
248 /**
249 * @return A reverse_iterator that refers to @c current - @a __n
250 *
251 * The underlying iterator must be a Random Access Iterator.
252 */
253 reverse_iterator
254 operator-(difference_type __n) const
255 { return reverse_iterator(current + __n); }
256
257 /**
258 * @return *this
259 *
260 * Moves the underlying iterator forwards @a __n steps.
261 * The underlying iterator must be a Random Access Iterator.
262 */
263 reverse_iterator&
264 operator-=(difference_type __n)
265 {
266 current += __n;
267 return *this;
268 }
269
270 /**
271 * @return The value at @c current - @a __n - 1
272 *
273 * The underlying iterator must be a Random Access Iterator.
274 */
275 reference
276 operator[](difference_type __n) const
277 { return *(*this + __n); }
278 };
279
280 //@{
281 /**
282 * @param __x A %reverse_iterator.
283 * @param __y A %reverse_iterator.
284 * @return A simple bool.
285 *
286 * Reverse iterators forward many operations to their underlying base()
287 * iterators. Others are implemented in terms of one another.
288 *
289 */
290 template<typename _Iterator>
291 inline bool
292 operator==(const reverse_iterator<_Iterator>& __x,
293 const reverse_iterator<_Iterator>& __y)
294 { return __x.base() == __y.base(); }
23
Assuming the condition is true
24
Returning the value 1, which participates in a condition later
295
296 template<typename _Iterator>
297 inline bool
298 operator<(const reverse_iterator<_Iterator>& __x,
299 const reverse_iterator<_Iterator>& __y)
300 { return __y.base() < __x.base(); }
301
302 template<typename _Iterator>
303 inline bool
304 operator!=(const reverse_iterator<_Iterator>& __x,
305 const reverse_iterator<_Iterator>& __y)
306 { return !(__x == __y); }
22
Calling 'operator==<const clang::ClassTemplateSpecializationDecl **>'
25
Returning from 'operator==<const clang::ClassTemplateSpecializationDecl **>'
26
Returning zero, which participates in a condition later
307
308 template<typename _Iterator>
309 inline bool
310 operator>(const reverse_iterator<_Iterator>& __x,
311 const reverse_iterator<_Iterator>& __y)
312 { return __y < __x; }
313
314 template<typename _Iterator>
315 inline bool
316 operator<=(const reverse_iterator<_Iterator>& __x,
317 const reverse_iterator<_Iterator>& __y)
318 { return !(__y < __x); }
319
320 template<typename _Iterator>
321 inline bool
322 operator>=(const reverse_iterator<_Iterator>& __x,
323 const reverse_iterator<_Iterator>& __y)
324 { return !(__x < __y); }
325
326 template<typename _Iterator>
327#if __cplusplus201402L < 201103L
328 inline typename reverse_iterator<_Iterator>::difference_type
329 operator-(const reverse_iterator<_Iterator>& __x,
330 const reverse_iterator<_Iterator>& __y)
331#else
332 inline auto
333 operator-(const reverse_iterator<_Iterator>& __x,
334 const reverse_iterator<_Iterator>& __y)
335 -> decltype(__x.base() - __y.base())
336#endif
337 { return __y.base() - __x.base(); }
338
339 template<typename _Iterator>
340 inline reverse_iterator<_Iterator>
341 operator+(typename reverse_iterator<_Iterator>::difference_type __n,
342 const reverse_iterator<_Iterator>& __x)
343 { return reverse_iterator<_Iterator>(__x.base() - __n); }
344
345 // _GLIBCXX_RESOLVE_LIB_DEFECTS
346 // DR 280. Comparison of reverse_iterator to const reverse_iterator.
347 template<typename _IteratorL, typename _IteratorR>
348 inline bool
349 operator==(const reverse_iterator<_IteratorL>& __x,
350 const reverse_iterator<_IteratorR>& __y)
351 { return __x.base() == __y.base(); }
352
353 template<typename _IteratorL, typename _IteratorR>
354 inline bool
355 operator<(const reverse_iterator<_IteratorL>& __x,
356 const reverse_iterator<_IteratorR>& __y)
357 { return __y.base() < __x.base(); }
358
359 template<typename _IteratorL, typename _IteratorR>
360 inline bool
361 operator!=(const reverse_iterator<_IteratorL>& __x,
362 const reverse_iterator<_IteratorR>& __y)
363 { return !(__x == __y); }
364
365 template<typename _IteratorL, typename _IteratorR>
366 inline bool
367 operator>(const reverse_iterator<_IteratorL>& __x,
368 const reverse_iterator<_IteratorR>& __y)
369 { return __y < __x; }
370
371 template<typename _IteratorL, typename _IteratorR>
372 inline bool
373 operator<=(const reverse_iterator<_IteratorL>& __x,
374 const reverse_iterator<_IteratorR>& __y)
375 { return !(__y < __x); }
376
377 template<typename _IteratorL, typename _IteratorR>
378 inline bool
379 operator>=(const reverse_iterator<_IteratorL>& __x,
380 const reverse_iterator<_IteratorR>& __y)
381 { return !(__x < __y); }
382
383 template<typename _IteratorL, typename _IteratorR>
384#if __cplusplus201402L >= 201103L
385 // DR 685.
386 inline auto
387 operator-(const reverse_iterator<_IteratorL>& __x,
388 const reverse_iterator<_IteratorR>& __y)
389 -> decltype(__y.base() - __x.base())
390#else
391 inline typename reverse_iterator<_IteratorL>::difference_type
392 operator-(const reverse_iterator<_IteratorL>& __x,
393 const reverse_iterator<_IteratorR>& __y)
394#endif
395 { return __y.base() - __x.base(); }
396 //@}
397
398#if __cplusplus201402L >= 201103L
399 // Same as C++14 make_reverse_iterator but used in C++03 mode too.
400 template<typename _Iterator>
401 inline reverse_iterator<_Iterator>
402 __make_reverse_iterator(_Iterator __i)
403 { return reverse_iterator<_Iterator>(__i); }
404
405# if __cplusplus201402L > 201103L
406# define __cpp_lib_make_reverse_iterator201402 201402
407
408 // _GLIBCXX_RESOLVE_LIB_DEFECTS
409 // DR 2285. make_reverse_iterator
410 /// Generator function for reverse_iterator.
411 template<typename _Iterator>
412 inline reverse_iterator<_Iterator>
413 make_reverse_iterator(_Iterator __i)
414 { return reverse_iterator<_Iterator>(__i); }
415# endif
416#endif
417
418#if __cplusplus201402L >= 201103L
419 template<typename _Iterator>
420 auto
421 __niter_base(reverse_iterator<_Iterator> __it)
422 -> decltype(__make_reverse_iterator(__niter_base(__it.base())))
423 { return __make_reverse_iterator(__niter_base(__it.base())); }
424
425 template<typename _Iterator>
426 struct __is_move_iterator<reverse_iterator<_Iterator> >
427 : __is_move_iterator<_Iterator>
428 { };
429
430 template<typename _Iterator>
431 auto
432 __miter_base(reverse_iterator<_Iterator> __it)
433 -> decltype(__make_reverse_iterator(__miter_base(__it.base())))
434 { return __make_reverse_iterator(__miter_base(__it.base())); }
435#endif
436
437 // 24.4.2.2.1 back_insert_iterator
438 /**
439 * @brief Turns assignment into insertion.
440 *
441 * These are output iterators, constructed from a container-of-T.
442 * Assigning a T to the iterator appends it to the container using
443 * push_back.
444 *
445 * Tip: Using the back_inserter function to create these iterators can
446 * save typing.
447 */
448 template<typename _Container>
449 class back_insert_iterator
450 : public iterator<output_iterator_tag, void, void, void, void>
451 {
452 protected:
453 _Container* container;
454
455 public:
456 /// A nested typedef for the type of whatever container you used.
457 typedef _Container container_type;
458
459 /// The only way to create this %iterator is with a container.
460 explicit
461 back_insert_iterator(_Container& __x)
462 : container(std::__addressof(__x)) { }
463
464 /**
465 * @param __value An instance of whatever type
466 * container_type::const_reference is; presumably a
467 * reference-to-const T for container<T>.
468 * @return This %iterator, for chained operations.
469 *
470 * This kind of %iterator doesn't really have a @a position in the
471 * container (you can think of the position as being permanently at
472 * the end, if you like). Assigning a value to the %iterator will
473 * always append the value to the end of the container.
474 */
475#if __cplusplus201402L < 201103L
476 back_insert_iterator&
477 operator=(typename _Container::const_reference __value)
478 {
479 container->push_back(__value);
480 return *this;
481 }
482#else
483 back_insert_iterator&
484 operator=(const typename _Container::value_type& __value)
485 {
486 container->push_back(__value);
487 return *this;
488 }
489
490 back_insert_iterator&
491 operator=(typename _Container::value_type&& __value)
492 {
493 container->push_back(std::move(__value));
494 return *this;
495 }
496#endif
497
498 /// Simply returns *this.
499 back_insert_iterator&
500 operator*()
501 { return *this; }
502
503 /// Simply returns *this. (This %iterator does not @a move.)
504 back_insert_iterator&
505 operator++()
506 { return *this; }
507
508 /// Simply returns *this. (This %iterator does not @a move.)
509 back_insert_iterator
510 operator++(int)
511 { return *this; }
512 };
513
514 /**
515 * @param __x A container of arbitrary type.
516 * @return An instance of back_insert_iterator working on @p __x.
517 *
518 * This wrapper function helps in creating back_insert_iterator instances.
519 * Typing the name of the %iterator requires knowing the precise full
520 * type of the container, which can be tedious and impedes generic
521 * programming. Using this function lets you take advantage of automatic
522 * template parameter deduction, making the compiler match the correct
523 * types for you.
524 */
525 template<typename _Container>
526 inline back_insert_iterator<_Container>
527 back_inserter(_Container& __x)
528 { return back_insert_iterator<_Container>(__x); }
529
530 /**
531 * @brief Turns assignment into insertion.
532 *
533 * These are output iterators, constructed from a container-of-T.
534 * Assigning a T to the iterator prepends it to the container using
535 * push_front.
536 *
537 * Tip: Using the front_inserter function to create these iterators can
538 * save typing.
539 */
540 template<typename _Container>
541 class front_insert_iterator
542 : public iterator<output_iterator_tag, void, void, void, void>
543 {
544 protected:
545 _Container* container;
546
547 public:
548 /// A nested typedef for the type of whatever container you used.
549 typedef _Container container_type;
550
551 /// The only way to create this %iterator is with a container.
552 explicit front_insert_iterator(_Container& __x)
553 : container(std::__addressof(__x)) { }
554
555 /**
556 * @param __value An instance of whatever type
557 * container_type::const_reference is; presumably a
558 * reference-to-const T for container<T>.
559 * @return This %iterator, for chained operations.
560 *
561 * This kind of %iterator doesn't really have a @a position in the
562 * container (you can think of the position as being permanently at
563 * the front, if you like). Assigning a value to the %iterator will
564 * always prepend the value to the front of the container.
565 */
566#if __cplusplus201402L < 201103L
567 front_insert_iterator&
568 operator=(typename _Container::const_reference __value)
569 {
570 container->push_front(__value);
571 return *this;
572 }
573#else
574 front_insert_iterator&
575 operator=(const typename _Container::value_type& __value)
576 {
577 container->push_front(__value);
578 return *this;
579 }
580
581 front_insert_iterator&
582 operator=(typename _Container::value_type&& __value)
583 {
584 container->push_front(std::move(__value));
585 return *this;
586 }
587#endif
588
589 /// Simply returns *this.
590 front_insert_iterator&
591 operator*()
592 { return *this; }
593
594 /// Simply returns *this. (This %iterator does not @a move.)
595 front_insert_iterator&
596 operator++()
597 { return *this; }
598
599 /// Simply returns *this. (This %iterator does not @a move.)
600 front_insert_iterator
601 operator++(int)
602 { return *this; }
603 };
604
605 /**
606 * @param __x A container of arbitrary type.
607 * @return An instance of front_insert_iterator working on @p x.
608 *
609 * This wrapper function helps in creating front_insert_iterator instances.
610 * Typing the name of the %iterator requires knowing the precise full
611 * type of the container, which can be tedious and impedes generic
612 * programming. Using this function lets you take advantage of automatic
613 * template parameter deduction, making the compiler match the correct
614 * types for you.
615 */
616 template<typename _Container>
617 inline front_insert_iterator<_Container>
618 front_inserter(_Container& __x)
619 { return front_insert_iterator<_Container>(__x); }
620
621 /**
622 * @brief Turns assignment into insertion.
623 *
624 * These are output iterators, constructed from a container-of-T.
625 * Assigning a T to the iterator inserts it in the container at the
626 * %iterator's position, rather than overwriting the value at that
627 * position.
628 *
629 * (Sequences will actually insert a @e copy of the value before the
630 * %iterator's position.)
631 *
632 * Tip: Using the inserter function to create these iterators can
633 * save typing.
634 */
635 template<typename _Container>
636 class insert_iterator
637 : public iterator<output_iterator_tag, void, void, void, void>
638 {
639 protected:
640 _Container* container;
641 typename _Container::iterator iter;
642
643 public:
644 /// A nested typedef for the type of whatever container you used.
645 typedef _Container container_type;
646
647 /**
648 * The only way to create this %iterator is with a container and an
649 * initial position (a normal %iterator into the container).
650 */
651 insert_iterator(_Container& __x, typename _Container::iterator __i)
652 : container(std::__addressof(__x)), iter(__i) {}
653
654 /**
655 * @param __value An instance of whatever type
656 * container_type::const_reference is; presumably a
657 * reference-to-const T for container<T>.
658 * @return This %iterator, for chained operations.
659 *
660 * This kind of %iterator maintains its own position in the
661 * container. Assigning a value to the %iterator will insert the
662 * value into the container at the place before the %iterator.
663 *
664 * The position is maintained such that subsequent assignments will
665 * insert values immediately after one another. For example,
666 * @code
667 * // vector v contains A and Z
668 *
669 * insert_iterator i (v, ++v.begin());
670 * i = 1;
671 * i = 2;
672 * i = 3;
673 *
674 * // vector v contains A, 1, 2, 3, and Z
675 * @endcode
676 */
677#if __cplusplus201402L < 201103L
678 insert_iterator&
679 operator=(typename _Container::const_reference __value)
680 {
681 iter = container->insert(iter, __value);
682 ++iter;
683 return *this;
684 }
685#else
686 insert_iterator&
687 operator=(const typename _Container::value_type& __value)
688 {
689 iter = container->insert(iter, __value);
690 ++iter;
691 return *this;
692 }
693
694 insert_iterator&
695 operator=(typename _Container::value_type&& __value)
696 {
697 iter = container->insert(iter, std::move(__value));
698 ++iter;
699 return *this;
700 }
701#endif
702
703 /// Simply returns *this.
704 insert_iterator&
705 operator*()
706 { return *this; }
707
708 /// Simply returns *this. (This %iterator does not @a move.)
709 insert_iterator&
710 operator++()
711 { return *this; }
712
713 /// Simply returns *this. (This %iterator does not @a move.)
714 insert_iterator&
715 operator++(int)
716 { return *this; }
717 };
718
719 /**
720 * @param __x A container of arbitrary type.
721 * @return An instance of insert_iterator working on @p __x.
722 *
723 * This wrapper function helps in creating insert_iterator instances.
724 * Typing the name of the %iterator requires knowing the precise full
725 * type of the container, which can be tedious and impedes generic
726 * programming. Using this function lets you take advantage of automatic
727 * template parameter deduction, making the compiler match the correct
728 * types for you.
729 */
730 template<typename _Container, typename _Iterator>
731 inline insert_iterator<_Container>
732 inserter(_Container& __x, _Iterator __i)
733 {
734 return insert_iterator<_Container>(__x,
735 typename _Container::iterator(__i));
736 }
737
738 // @} group iterators
739
740_GLIBCXX_END_NAMESPACE_VERSION
741} // namespace
742
743namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
744{
745_GLIBCXX_BEGIN_NAMESPACE_VERSION
746
747 // This iterator adapter is @a normal in the sense that it does not
748 // change the semantics of any of the operators of its iterator
749 // parameter. Its primary purpose is to convert an iterator that is
750 // not a class, e.g. a pointer, into an iterator that is a class.
751 // The _Container parameter exists solely so that different containers
752 // using this template can instantiate different types, even if the
753 // _Iterator parameter is the same.
754 using std::iterator_traits;
755 using std::iterator;
756 template<typename _Iterator, typename _Container>
757 class __normal_iterator
758 {
759 protected:
760 _Iterator _M_current;
761
762 typedef iterator_traits<_Iterator> __traits_type;
763
764 public:
765 typedef _Iterator iterator_type;
766 typedef typename __traits_type::iterator_category iterator_category;
767 typedef typename __traits_type::value_type value_type;
768 typedef typename __traits_type::difference_type difference_type;
769 typedef typename __traits_type::reference reference;
770 typedef typename __traits_type::pointer pointer;
771
772 _GLIBCXX_CONSTEXPRconstexpr __normal_iterator() _GLIBCXX_NOEXCEPTnoexcept
773 : _M_current(_Iterator()) { }
774
775 explicit
776 __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPTnoexcept
777 : _M_current(__i) { }
778
779 // Allow iterator to const_iterator conversion
780 template<typename _Iter>
781 __normal_iterator(const __normal_iterator<_Iter,
782 typename __enable_if<
783 (std::__are_same<_Iter, typename _Container::pointer>::__value),
784 _Container>::__type>& __i) _GLIBCXX_NOEXCEPTnoexcept
785 : _M_current(__i.base()) { }
786
787 // Forward iterator requirements
788 reference
789 operator*() const _GLIBCXX_NOEXCEPTnoexcept
790 { return *_M_current; }
791
792 pointer
793 operator->() const _GLIBCXX_NOEXCEPTnoexcept
794 { return _M_current; }
795
796 __normal_iterator&
797 operator++() _GLIBCXX_NOEXCEPTnoexcept
798 {
799 ++_M_current;
800 return *this;
801 }
802
803 __normal_iterator
804 operator++(int) _GLIBCXX_NOEXCEPTnoexcept
805 { return __normal_iterator(_M_current++); }
806
807 // Bidirectional iterator requirements
808 __normal_iterator&
809 operator--() _GLIBCXX_NOEXCEPTnoexcept
810 {
811 --_M_current;
812 return *this;
813 }
814
815 __normal_iterator
816 operator--(int) _GLIBCXX_NOEXCEPTnoexcept
817 { return __normal_iterator(_M_current--); }
818
819 // Random access iterator requirements
820 reference
821 operator[](difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
822 { return _M_current[__n]; }
823
824 __normal_iterator&
825 operator+=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
826 { _M_current += __n; return *this; }
827
828 __normal_iterator
829 operator+(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
830 { return __normal_iterator(_M_current + __n); }
831
832 __normal_iterator&
833 operator-=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
834 { _M_current -= __n; return *this; }
835
836 __normal_iterator
837 operator-(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
838 { return __normal_iterator(_M_current - __n); }
839
840 const _Iterator&
841 base() const _GLIBCXX_NOEXCEPTnoexcept
842 { return _M_current; }
843 };
844
845 // Note: In what follows, the left- and right-hand-side iterators are
846 // allowed to vary in types (conceptually in cv-qualification) so that
847 // comparison between cv-qualified and non-cv-qualified iterators be
848 // valid. However, the greedy and unfriendly operators in std::rel_ops
849 // will make overload resolution ambiguous (when in scope) if we don't
850 // provide overloads whose operands are of the same type. Can someone
851 // remind me what generic programming is about? -- Gaby
852
853 // Forward iterator requirements
854 template<typename _IteratorL, typename _IteratorR, typename _Container>
855 inline bool
856 operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,
857 const __normal_iterator<_IteratorR, _Container>& __rhs)
858 _GLIBCXX_NOEXCEPTnoexcept
859 { return __lhs.base() == __rhs.base(); }
860
861 template<typename _Iterator, typename _Container>
862 inline bool
863 operator==(const __normal_iterator<_Iterator, _Container>& __lhs,
864 const __normal_iterator<_Iterator, _Container>& __rhs)
865 _GLIBCXX_NOEXCEPTnoexcept
866 { return __lhs.base() == __rhs.base(); }
867
868 template<typename _IteratorL, typename _IteratorR, typename _Container>
869 inline bool
870 operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs,
871 const __normal_iterator<_IteratorR, _Container>& __rhs)
872 _GLIBCXX_NOEXCEPTnoexcept
873 { return __lhs.base() != __rhs.base(); }
874
875 template<typename _Iterator, typename _Container>
876 inline bool
877 operator!=(const __normal_iterator<_Iterator, _Container>& __lhs,
878 const __normal_iterator<_Iterator, _Container>& __rhs)
879 _GLIBCXX_NOEXCEPTnoexcept
880 { return __lhs.base() != __rhs.base(); }
881
882 // Random access iterator requirements
883 template<typename _IteratorL, typename _IteratorR, typename _Container>
884 inline bool
885 operator<(const __normal_iterator<_IteratorL, _Container>& __lhs,
886 const __normal_iterator<_IteratorR, _Container>& __rhs)
887 _GLIBCXX_NOEXCEPTnoexcept
888 { return __lhs.base() < __rhs.base(); }
889
890 template<typename _Iterator, typename _Container>
891 inline bool
892 operator<(const __normal_iterator<_Iterator, _Container>& __lhs,
893 const __normal_iterator<_Iterator, _Container>& __rhs)
894 _GLIBCXX_NOEXCEPTnoexcept
895 { return __lhs.base() < __rhs.base(); }
896
897 template<typename _IteratorL, typename _IteratorR, typename _Container>
898 inline bool
899 operator>(const __normal_iterator<_IteratorL, _Container>& __lhs,
900 const __normal_iterator<_IteratorR, _Container>& __rhs)
901 _GLIBCXX_NOEXCEPTnoexcept
902 { return __lhs.base() > __rhs.base(); }
903
904 template<typename _Iterator, typename _Container>
905 inline bool
906 operator>(const __normal_iterator<_Iterator, _Container>& __lhs,
907 const __normal_iterator<_Iterator, _Container>& __rhs)
908 _GLIBCXX_NOEXCEPTnoexcept
909 { return __lhs.base() > __rhs.base(); }
910
911 template<typename _IteratorL, typename _IteratorR, typename _Container>
912 inline bool
913 operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs,
914 const __normal_iterator<_IteratorR, _Container>& __rhs)
915 _GLIBCXX_NOEXCEPTnoexcept
916 { return __lhs.base() <= __rhs.base(); }
917
918 template<typename _Iterator, typename _Container>
919 inline bool
920 operator<=(const __normal_iterator<_Iterator, _Container>& __lhs,
921 const __normal_iterator<_Iterator, _Container>& __rhs)
922 _GLIBCXX_NOEXCEPTnoexcept
923 { return __lhs.base() <= __rhs.base(); }
924
925 template<typename _IteratorL, typename _IteratorR, typename _Container>
926 inline bool
927 operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs,
928 const __normal_iterator<_IteratorR, _Container>& __rhs)
929 _GLIBCXX_NOEXCEPTnoexcept
930 { return __lhs.base() >= __rhs.base(); }
931
932 template<typename _Iterator, typename _Container>
933 inline bool
934 operator>=(const __normal_iterator<_Iterator, _Container>& __lhs,
935 const __normal_iterator<_Iterator, _Container>& __rhs)
936 _GLIBCXX_NOEXCEPTnoexcept
937 { return __lhs.base() >= __rhs.base(); }
938
939 // _GLIBCXX_RESOLVE_LIB_DEFECTS
940 // According to the resolution of DR179 not only the various comparison
941 // operators but also operator- must accept mixed iterator/const_iterator
942 // parameters.
943 template<typename _IteratorL, typename _IteratorR, typename _Container>
944#if __cplusplus201402L >= 201103L
945 // DR 685.
946 inline auto
947 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
948 const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept
949 -> decltype(__lhs.base() - __rhs.base())
950#else
951 inline typename __normal_iterator<_IteratorL, _Container>::difference_type
952 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
953 const __normal_iterator<_IteratorR, _Container>& __rhs)
954#endif
955 { return __lhs.base() - __rhs.base(); }
956
957 template<typename _Iterator, typename _Container>
958 inline typename __normal_iterator<_Iterator, _Container>::difference_type
959 operator-(const __normal_iterator<_Iterator, _Container>& __lhs,
960 const __normal_iterator<_Iterator, _Container>& __rhs)
961 _GLIBCXX_NOEXCEPTnoexcept
962 { return __lhs.base() - __rhs.base(); }
963
964 template<typename _Iterator, typename _Container>
965 inline __normal_iterator<_Iterator, _Container>
966 operator+(typename __normal_iterator<_Iterator, _Container>::difference_type
967 __n, const __normal_iterator<_Iterator, _Container>& __i)
968 _GLIBCXX_NOEXCEPTnoexcept
969 { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); }
970
971_GLIBCXX_END_NAMESPACE_VERSION
972} // namespace
973
974namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
975{
976_GLIBCXX_BEGIN_NAMESPACE_VERSION
977
978 template<typename _Iterator, typename _Container>
979 _Iterator
980 __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it)
981 { return __it.base(); }
982
983_GLIBCXX_END_NAMESPACE_VERSION
984} // namespace
985
986#if __cplusplus201402L >= 201103L
987
988namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
989{
990_GLIBCXX_BEGIN_NAMESPACE_VERSION
991
992 /**
993 * @addtogroup iterators
994 * @{
995 */
996
997 // 24.4.3 Move iterators
998 /**
999 * Class template move_iterator is an iterator adapter with the same
1000 * behavior as the underlying iterator except that its dereference
1001 * operator implicitly converts the value returned by the underlying
1002 * iterator's dereference operator to an rvalue reference. Some
1003 * generic algorithms can be called with move iterators to replace
1004 * copying with moving.
1005 */
1006 template<typename _Iterator>
1007 class move_iterator
1008 {
1009 protected:
1010 _Iterator _M_current;
1011
1012 typedef iterator_traits<_Iterator> __traits_type;
1013 typedef typename __traits_type::reference __base_ref;
1014
1015 public:
1016 typedef _Iterator iterator_type;
1017 typedef typename __traits_type::iterator_category iterator_category;
1018 typedef typename __traits_type::value_type value_type;
1019 typedef typename __traits_type::difference_type difference_type;
1020 // NB: DR 680.
1021 typedef _Iterator pointer;
1022 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1023 // 2106. move_iterator wrapping iterators returning prvalues
1024 typedef typename conditional<is_reference<__base_ref>::value,
1025 typename remove_reference<__base_ref>::type&&,
1026 __base_ref>::type reference;
1027
1028 move_iterator()
1029 : _M_current() { }
1030
1031 explicit
1032 move_iterator(iterator_type __i)
1033 : _M_current(__i) { }
1034
1035 template<typename _Iter>
1036 move_iterator(const move_iterator<_Iter>& __i)
1037 : _M_current(__i.base()) { }
1038
1039 iterator_type
1040 base() const
1041 { return _M_current; }
1042
1043 reference
1044 operator*() const
1045 { return static_cast<reference>(*_M_current); }
1046
1047 pointer
1048 operator->() const
1049 { return _M_current; }
1050
1051 move_iterator&
1052 operator++()
1053 {
1054 ++_M_current;
1055 return *this;
1056 }
1057
1058 move_iterator
1059 operator++(int)
1060 {
1061 move_iterator __tmp = *this;
1062 ++_M_current;
1063 return __tmp;
1064 }
1065
1066 move_iterator&
1067 operator--()
1068 {
1069 --_M_current;
1070 return *this;
1071 }
1072
1073 move_iterator
1074 operator--(int)
1075 {
1076 move_iterator __tmp = *this;
1077 --_M_current;
1078 return __tmp;
1079 }
1080
1081 move_iterator
1082 operator+(difference_type __n) const
1083 { return move_iterator(_M_current + __n); }
1084
1085 move_iterator&
1086 operator+=(difference_type __n)
1087 {
1088 _M_current += __n;
1089 return *this;
1090 }
1091
1092 move_iterator
1093 operator-(difference_type __n) const
1094 { return move_iterator(_M_current - __n); }
1095
1096 move_iterator&
1097 operator-=(difference_type __n)
1098 {
1099 _M_current -= __n;
1100 return *this;
1101 }
1102
1103 reference
1104 operator[](difference_type __n) const
1105 { return std::move(_M_current[__n]); }
1106 };
1107
1108 // Note: See __normal_iterator operators note from Gaby to understand
1109 // why there are always 2 versions for most of the move_iterator
1110 // operators.
1111 template<typename _IteratorL, typename _IteratorR>
1112 inline bool
1113 operator==(const move_iterator<_IteratorL>& __x,
1114 const move_iterator<_IteratorR>& __y)
1115 { return __x.base() == __y.base(); }
1116
1117 template<typename _Iterator>
1118 inline bool
1119 operator==(const move_iterator<_Iterator>& __x,
1120 const move_iterator<_Iterator>& __y)
1121 { return __x.base() == __y.base(); }
1122
1123 template<typename _IteratorL, typename _IteratorR>
1124 inline bool
1125 operator!=(const move_iterator<_IteratorL>& __x,
1126 const move_iterator<_IteratorR>& __y)
1127 { return !(__x == __y); }
1128
1129 template<typename _Iterator>
1130 inline bool
1131 operator!=(const move_iterator<_Iterator>& __x,
1132 const move_iterator<_Iterator>& __y)
1133 { return !(__x == __y); }
1134
1135 template<typename _IteratorL, typename _IteratorR>
1136 inline bool
1137 operator<(const move_iterator<_IteratorL>& __x,
1138 const move_iterator<_IteratorR>& __y)
1139 { return __x.base() < __y.base(); }
1140
1141 template<typename _Iterator>
1142 inline bool
1143 operator<(const move_iterator<_Iterator>& __x,
1144 const move_iterator<_Iterator>& __y)
1145 { return __x.base() < __y.base(); }
1146
1147 template<typename _IteratorL, typename _IteratorR>
1148 inline bool
1149 operator<=(const move_iterator<_IteratorL>& __x,
1150 const move_iterator<_IteratorR>& __y)
1151 { return !(__y < __x); }
1152
1153 template<typename _Iterator>
1154 inline bool
1155 operator<=(const move_iterator<_Iterator>& __x,
1156 const move_iterator<_Iterator>& __y)
1157 { return !(__y < __x); }
1158
1159 template<typename _IteratorL, typename _IteratorR>
1160 inline bool
1161 operator>(const move_iterator<_IteratorL>& __x,
1162 const move_iterator<_IteratorR>& __y)
1163 { return __y < __x; }
1164
1165 template<typename _Iterator>
1166 inline bool
1167 operator>(const move_iterator<_Iterator>& __x,
1168 const move_iterator<_Iterator>& __y)
1169 { return __y < __x; }
1170
1171 template<typename _IteratorL, typename _IteratorR>
1172 inline bool
1173 operator>=(const move_iterator<_IteratorL>& __x,
1174 const move_iterator<_IteratorR>& __y)
1175 { return !(__x < __y); }
1176
1177 template<typename _Iterator>
1178 inline bool
1179 operator>=(const move_iterator<_Iterator>& __x,
1180 const move_iterator<_Iterator>& __y)
1181 { return !(__x < __y); }
1182
1183 // DR 685.
1184 template<typename _IteratorL, typename _IteratorR>
1185 inline auto
1186 operator-(const move_iterator<_IteratorL>& __x,
1187 const move_iterator<_IteratorR>& __y)
1188 -> decltype(__x.base() - __y.base())
1189 { return __x.base() - __y.base(); }
1190
1191 template<typename _Iterator>
1192 inline auto
1193 operator-(const move_iterator<_Iterator>& __x,
1194 const move_iterator<_Iterator>& __y)
1195 -> decltype(__x.base() - __y.base())
1196 { return __x.base() - __y.base(); }
1197
1198 template<typename _Iterator>
1199 inline move_iterator<_Iterator>
1200 operator+(typename move_iterator<_Iterator>::difference_type __n,
1201 const move_iterator<_Iterator>& __x)
1202 { return __x + __n; }
1203
1204 template<typename _Iterator>
1205 inline move_iterator<_Iterator>
1206 make_move_iterator(_Iterator __i)
1207 { return move_iterator<_Iterator>(__i); }
1208
1209 template<typename _Iterator, typename _ReturnType
1210 = typename conditional<__move_if_noexcept_cond
1211 <typename iterator_traits<_Iterator>::value_type>::value,
1212 _Iterator, move_iterator<_Iterator>>::type>
1213 inline _ReturnType
1214 __make_move_if_noexcept_iterator(_Iterator __i)
1215 { return _ReturnType(__i); }
1216
1217 // Overload for pointers that matches std::move_if_noexcept more closely,
1218 // returning a constant iterator when we don't want to move.
1219 template<typename _Tp, typename _ReturnType
1220 = typename conditional<__move_if_noexcept_cond<_Tp>::value,
1221 const _Tp*, move_iterator<_Tp*>>::type>
1222 inline _ReturnType
1223 __make_move_if_noexcept_iterator(_Tp* __i)
1224 { return _ReturnType(__i); }
1225
1226 // @} group iterators
1227
1228 template<typename _Iterator>
1229 auto
1230 __niter_base(move_iterator<_Iterator> __it)
1231 -> decltype(make_move_iterator(__niter_base(__it.base())))
1232 { return make_move_iterator(__niter_base(__it.base())); }
1233
1234 template<typename _Iterator>
1235 struct __is_move_iterator<move_iterator<_Iterator> >
1236 {
1237 enum { __value = 1 };
1238 typedef __true_type __type;
1239 };
1240
1241 template<typename _Iterator>
1242 auto
1243 __miter_base(move_iterator<_Iterator> __it)
1244 -> decltype(__miter_base(__it.base()))
1245 { return __miter_base(__it.base()); }
1246
1247_GLIBCXX_END_NAMESPACE_VERSION
1248} // namespace
1249
1250#define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) std::make_move_iterator(_Iter)
1251#define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) \
1252 std::__make_move_if_noexcept_iterator(_Iter)
1253#else
1254#define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) (_Iter)
1255#define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) (_Iter)
1256#endif // C++11
1257
1258#ifdef _GLIBCXX_DEBUG
1259# include <debug/stl_iterator.h>
1260#endif
1261
1262#endif