Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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