Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/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-12/lib/clang/12.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-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-24-223304-31662-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/AST/Expr.cpp

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

/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&