Bug Summary

File:tools/clang/lib/AST/Expr.cpp
Warning:line 3786, 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~svn329677/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/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~svn329677/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-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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~svn329677/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 CoawaitExprClass:
2053 case CoyieldExprClass:
2054 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2055 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2056 case ChooseExprClass:
2057 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2058 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2059 case UnaryOperatorClass: {
2060 const UnaryOperator *UO = cast<UnaryOperator>(this);
2061
2062 switch (UO->getOpcode()) {
2063 case UO_Plus:
2064 case UO_Minus:
2065 case UO_AddrOf:
2066 case UO_Not:
2067 case UO_LNot:
2068 case UO_Deref:
2069 break;
2070 case UO_Coawait:
2071 // This is just the 'operator co_await' call inside the guts of a
2072 // dependent co_await call.
2073 case UO_PostInc:
2074 case UO_PostDec:
2075 case UO_PreInc:
2076 case UO_PreDec: // ++/--
2077 return false; // Not a warning.
2078 case UO_Real:
2079 case UO_Imag:
2080 // accessing a piece of a volatile complex is a side-effect.
2081 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2082 .isVolatileQualified())
2083 return false;
2084 break;
2085 case UO_Extension:
2086 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2087 }
2088 WarnE = this;
2089 Loc = UO->getOperatorLoc();
2090 R1 = UO->getSubExpr()->getSourceRange();
2091 return true;
2092 }
2093 case BinaryOperatorClass: {
2094 const BinaryOperator *BO = cast<BinaryOperator>(this);
2095 switch (BO->getOpcode()) {
2096 default:
2097 break;
2098 // Consider the RHS of comma for side effects. LHS was checked by
2099 // Sema::CheckCommaOperands.
2100 case BO_Comma:
2101 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2102 // lvalue-ness) of an assignment written in a macro.
2103 if (IntegerLiteral *IE =
2104 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2105 if (IE->getValue() == 0)
2106 return false;
2107 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2108 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2109 case BO_LAnd:
2110 case BO_LOr:
2111 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2112 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2113 return false;
2114 break;
2115 }
2116 if (BO->isAssignmentOp())
2117 return false;
2118 WarnE = this;
2119 Loc = BO->getOperatorLoc();
2120 R1 = BO->getLHS()->getSourceRange();
2121 R2 = BO->getRHS()->getSourceRange();
2122 return true;
2123 }
2124 case CompoundAssignOperatorClass:
2125 case VAArgExprClass:
2126 case AtomicExprClass:
2127 return false;
2128
2129 case ConditionalOperatorClass: {
2130 // If only one of the LHS or RHS is a warning, the operator might
2131 // be being used for control flow. Only warn if both the LHS and
2132 // RHS are warnings.
2133 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
2134 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2135 return false;
2136 if (!Exp->getLHS())
2137 return true;
2138 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2139 }
2140
2141 case MemberExprClass:
2142 WarnE = this;
2143 Loc = cast<MemberExpr>(this)->getMemberLoc();
2144 R1 = SourceRange(Loc, Loc);
2145 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2146 return true;
2147
2148 case ArraySubscriptExprClass:
2149 WarnE = this;
2150 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2151 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2152 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2153 return true;
2154
2155 case CXXOperatorCallExprClass: {
2156 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2157 // overloads as there is no reasonable way to define these such that they
2158 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2159 // warning: operators == and != are commonly typo'ed, and so warning on them
2160 // provides additional value as well. If this list is updated,
2161 // DiagnoseUnusedComparison should be as well.
2162 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2163 switch (Op->getOperator()) {
2164 default:
2165 break;
2166 case OO_EqualEqual:
2167 case OO_ExclaimEqual:
2168 case OO_Less:
2169 case OO_Greater:
2170 case OO_GreaterEqual:
2171 case OO_LessEqual:
2172 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2173 Op->getCallReturnType(Ctx)->isVoidType())
2174 break;
2175 WarnE = this;
2176 Loc = Op->getOperatorLoc();
2177 R1 = Op->getSourceRange();
2178 return true;
2179 }
2180
2181 // Fallthrough for generic call handling.
2182 LLVM_FALLTHROUGH[[clang::fallthrough]];
2183 }
2184 case CallExprClass:
2185 case CXXMemberCallExprClass:
2186 case UserDefinedLiteralClass: {
2187 // If this is a direct call, get the callee.
2188 const CallExpr *CE = cast<CallExpr>(this);
2189 if (const Decl *FD = CE->getCalleeDecl()) {
2190 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2191 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2192 : FD->hasAttr<WarnUnusedResultAttr>();
2193
2194 // If the callee has attribute pure, const, or warn_unused_result, warn
2195 // about it. void foo() { strlen("bar"); } should warn.
2196 //
2197 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2198 // updated to match for QoI.
2199 if (HasWarnUnusedResultAttr ||
2200 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2201 WarnE = this;
2202 Loc = CE->getCallee()->getLocStart();
2203 R1 = CE->getCallee()->getSourceRange();
2204
2205 if (unsigned NumArgs = CE->getNumArgs())
2206 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2207 CE->getArg(NumArgs-1)->getLocEnd());
2208 return true;
2209 }
2210 }
2211 return false;
2212 }
2213
2214 // If we don't know precisely what we're looking at, let's not warn.
2215 case UnresolvedLookupExprClass:
2216 case CXXUnresolvedConstructExprClass:
2217 return false;
2218
2219 case CXXTemporaryObjectExprClass:
2220 case CXXConstructExprClass: {
2221 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2222 if (Type->hasAttr<WarnUnusedAttr>()) {
2223 WarnE = this;
2224 Loc = getLocStart();
2225 R1 = getSourceRange();
2226 return true;
2227 }
2228 }
2229 return false;
2230 }
2231
2232 case ObjCMessageExprClass: {
2233 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2234 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2235 ME->isInstanceMessage() &&
2236 !ME->getType()->isVoidType() &&
2237 ME->getMethodFamily() == OMF_init) {
2238 WarnE = this;
2239 Loc = getExprLoc();
2240 R1 = ME->getSourceRange();
2241 return true;
2242 }
2243
2244 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2245 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2246 WarnE = this;
2247 Loc = getExprLoc();
2248 return true;
2249 }
2250
2251 return false;
2252 }
2253
2254 case ObjCPropertyRefExprClass:
2255 WarnE = this;
2256 Loc = getExprLoc();
2257 R1 = getSourceRange();
2258 return true;
2259
2260 case PseudoObjectExprClass: {
2261 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2262
2263 // Only complain about things that have the form of a getter.
2264 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2265 isa<BinaryOperator>(PO->getSyntacticForm()))
2266 return false;
2267
2268 WarnE = this;
2269 Loc = getExprLoc();
2270 R1 = getSourceRange();
2271 return true;
2272 }
2273
2274 case StmtExprClass: {
2275 // Statement exprs don't logically have side effects themselves, but are
2276 // sometimes used in macros in ways that give them a type that is unused.
2277 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2278 // however, if the result of the stmt expr is dead, we don't want to emit a
2279 // warning.
2280 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2281 if (!CS->body_empty()) {
2282 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2283 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2284 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2285 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2286 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2287 }
2288
2289 if (getType()->isVoidType())
2290 return false;
2291 WarnE = this;
2292 Loc = cast<StmtExpr>(this)->getLParenLoc();
2293 R1 = getSourceRange();
2294 return true;
2295 }
2296 case CXXFunctionalCastExprClass:
2297 case CStyleCastExprClass: {
2298 // Ignore an explicit cast to void unless the operand is a non-trivial
2299 // volatile lvalue.
2300 const CastExpr *CE = cast<CastExpr>(this);
2301 if (CE->getCastKind() == CK_ToVoid) {
2302 if (CE->getSubExpr()->isGLValue() &&
2303 CE->getSubExpr()->getType().isVolatileQualified()) {
2304 const DeclRefExpr *DRE =
2305 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2306 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2307 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2308 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2309 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2310 R1, R2, Ctx);
2311 }
2312 }
2313 return false;
2314 }
2315
2316 // If this is a cast to a constructor conversion, check the operand.
2317 // Otherwise, the result of the cast is unused.
2318 if (CE->getCastKind() == CK_ConstructorConversion)
2319 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2320
2321 WarnE = this;
2322 if (const CXXFunctionalCastExpr *CXXCE =
2323 dyn_cast<CXXFunctionalCastExpr>(this)) {
2324 Loc = CXXCE->getLocStart();
2325 R1 = CXXCE->getSubExpr()->getSourceRange();
2326 } else {
2327 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2328 Loc = CStyleCE->getLParenLoc();
2329 R1 = CStyleCE->getSubExpr()->getSourceRange();
2330 }
2331 return true;
2332 }
2333 case ImplicitCastExprClass: {
2334 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2335
2336 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2337 if (ICE->getCastKind() == CK_LValueToRValue &&
2338 ICE->getSubExpr()->getType().isVolatileQualified())
2339 return false;
2340
2341 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2342 }
2343 case CXXDefaultArgExprClass:
2344 return (cast<CXXDefaultArgExpr>(this)
2345 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2346 case CXXDefaultInitExprClass:
2347 return (cast<CXXDefaultInitExpr>(this)
2348 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2349
2350 case CXXNewExprClass:
2351 // FIXME: In theory, there might be new expressions that don't have side
2352 // effects (e.g. a placement new with an uninitialized POD).
2353 case CXXDeleteExprClass:
2354 return false;
2355 case MaterializeTemporaryExprClass:
2356 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2357 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2358 case CXXBindTemporaryExprClass:
2359 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2360 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2361 case ExprWithCleanupsClass:
2362 return cast<ExprWithCleanups>(this)->getSubExpr()
2363 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2364 }
2365}
2366
2367/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2368/// returns true, if it is; false otherwise.
2369bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2370 const Expr *E = IgnoreParens();
2371 switch (E->getStmtClass()) {
2372 default:
2373 return false;
2374 case ObjCIvarRefExprClass:
2375 return true;
2376 case Expr::UnaryOperatorClass:
2377 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2378 case ImplicitCastExprClass:
2379 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2380 case MaterializeTemporaryExprClass:
2381 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2382 ->isOBJCGCCandidate(Ctx);
2383 case CStyleCastExprClass:
2384 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2385 case DeclRefExprClass: {
2386 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2387
2388 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2389 if (VD->hasGlobalStorage())
2390 return true;
2391 QualType T = VD->getType();
2392 // dereferencing to a pointer is always a gc'able candidate,
2393 // unless it is __weak.
2394 return T->isPointerType() &&
2395 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2396 }
2397 return false;
2398 }
2399 case MemberExprClass: {
2400 const MemberExpr *M = cast<MemberExpr>(E);
2401 return M->getBase()->isOBJCGCCandidate(Ctx);
2402 }
2403 case ArraySubscriptExprClass:
2404 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2405 }
2406}
2407
2408bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2409 if (isTypeDependent())
2410 return false;
2411 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2412}
2413
2414QualType Expr::findBoundMemberType(const Expr *expr) {
2415 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2415, __extension__ __PRETTY_FUNCTION__))
;
2416
2417 // Bound member expressions are always one of these possibilities:
2418 // x->m x.m x->*y x.*y
2419 // (possibly parenthesized)
2420
2421 expr = expr->IgnoreParens();
2422 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2423 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2423, __extension__ __PRETTY_FUNCTION__))
;
2424 return mem->getMemberDecl()->getType();
2425 }
2426
2427 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2428 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2429 ->getPointeeType();
2430 assert(type->isFunctionType())(static_cast <bool> (type->isFunctionType()) ? void (
0) : __assert_fail ("type->isFunctionType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2430, __extension__ __PRETTY_FUNCTION__))
;
2431 return type;
2432 }
2433
2434 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2434, __extension__ __PRETTY_FUNCTION__))
;
2435 return QualType();
2436}
2437
2438Expr* Expr::IgnoreParens() {
2439 Expr* E = this;
2440 while (true) {
2441 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2442 E = P->getSubExpr();
2443 continue;
2444 }
2445 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2446 if (P->getOpcode() == UO_Extension) {
2447 E = P->getSubExpr();
2448 continue;
2449 }
2450 }
2451 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2452 if (!P->isResultDependent()) {
2453 E = P->getResultExpr();
2454 continue;
2455 }
2456 }
2457 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2458 if (!P->isConditionDependent()) {
2459 E = P->getChosenSubExpr();
2460 continue;
2461 }
2462 }
2463 return E;
2464 }
2465}
2466
2467/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2468/// or CastExprs or ImplicitCastExprs, returning their operand.
2469Expr *Expr::IgnoreParenCasts() {
2470 Expr *E = this;
2471 while (true) {
2472 E = E->IgnoreParens();
2473 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2474 E = P->getSubExpr();
2475 continue;
2476 }
2477 if (MaterializeTemporaryExpr *Materialize
2478 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2479 E = Materialize->GetTemporaryExpr();
2480 continue;
2481 }
2482 if (SubstNonTypeTemplateParmExpr *NTTP
2483 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2484 E = NTTP->getReplacement();
2485 continue;
2486 }
2487 return E;
2488 }
2489}
2490
2491Expr *Expr::IgnoreCasts() {
2492 Expr *E = this;
2493 while (true) {
2494 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2495 E = P->getSubExpr();
2496 continue;
2497 }
2498 if (MaterializeTemporaryExpr *Materialize
2499 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2500 E = Materialize->GetTemporaryExpr();
2501 continue;
2502 }
2503 if (SubstNonTypeTemplateParmExpr *NTTP
2504 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2505 E = NTTP->getReplacement();
2506 continue;
2507 }
2508 return E;
2509 }
2510}
2511
2512/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2513/// casts. This is intended purely as a temporary workaround for code
2514/// that hasn't yet been rewritten to do the right thing about those
2515/// casts, and may disappear along with the last internal use.
2516Expr *Expr::IgnoreParenLValueCasts() {
2517 Expr *E = this;
2518 while (true) {
2519 E = E->IgnoreParens();
2520 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2521 if (P->getCastKind() == CK_LValueToRValue) {
2522 E = P->getSubExpr();
2523 continue;
2524 }
2525 } else if (MaterializeTemporaryExpr *Materialize
2526 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2527 E = Materialize->GetTemporaryExpr();
2528 continue;
2529 } else if (SubstNonTypeTemplateParmExpr *NTTP
2530 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2531 E = NTTP->getReplacement();
2532 continue;
2533 }
2534 break;
2535 }
2536 return E;
2537}
2538
2539Expr *Expr::ignoreParenBaseCasts() {
2540 Expr *E = this;
2541 while (true) {
2542 E = E->IgnoreParens();
2543 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2544 if (CE->getCastKind() == CK_DerivedToBase ||
2545 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2546 CE->getCastKind() == CK_NoOp) {
2547 E = CE->getSubExpr();
2548 continue;
2549 }
2550 }
2551
2552 return E;
2553 }
2554}
2555
2556Expr *Expr::IgnoreParenImpCasts() {
2557 Expr *E = this;
2558 while (true) {
2559 E = E->IgnoreParens();
2560 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2561 E = P->getSubExpr();
2562 continue;
2563 }
2564 if (MaterializeTemporaryExpr *Materialize
2565 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2566 E = Materialize->GetTemporaryExpr();
2567 continue;
2568 }
2569 if (SubstNonTypeTemplateParmExpr *NTTP
2570 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2571 E = NTTP->getReplacement();
2572 continue;
2573 }
2574 return E;
2575 }
2576}
2577
2578Expr *Expr::IgnoreConversionOperator() {
2579 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2580 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2581 return MCE->getImplicitObjectArgument();
2582 }
2583 return this;
2584}
2585
2586/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2587/// value (including ptr->int casts of the same size). Strip off any
2588/// ParenExpr or CastExprs, returning their operand.
2589Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2590 Expr *E = this;
2591 while (true) {
2592 E = E->IgnoreParens();
2593
2594 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2595 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2596 // ptr<->int casts of the same width. We also ignore all identity casts.
2597 Expr *SE = P->getSubExpr();
2598
2599 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2600 E = SE;
2601 continue;
2602 }
2603
2604 if ((E->getType()->isPointerType() ||
2605 E->getType()->isIntegralType(Ctx)) &&
2606 (SE->getType()->isPointerType() ||
2607 SE->getType()->isIntegralType(Ctx)) &&
2608 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2609 E = SE;
2610 continue;
2611 }
2612 }
2613
2614 if (SubstNonTypeTemplateParmExpr *NTTP
2615 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2616 E = NTTP->getReplacement();
2617 continue;
2618 }
2619
2620 return E;
2621 }
2622}
2623
2624bool Expr::isDefaultArgument() const {
2625 const Expr *E = this;
2626 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2627 E = M->GetTemporaryExpr();
2628
2629 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2630 E = ICE->getSubExprAsWritten();
2631
2632 return isa<CXXDefaultArgExpr>(E);
2633}
2634
2635/// \brief Skip over any no-op casts and any temporary-binding
2636/// expressions.
2637static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2638 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2639 E = M->GetTemporaryExpr();
2640
2641 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2642 if (ICE->getCastKind() == CK_NoOp)
2643 E = ICE->getSubExpr();
2644 else
2645 break;
2646 }
2647
2648 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2649 E = BE->getSubExpr();
2650
2651 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2652 if (ICE->getCastKind() == CK_NoOp)
2653 E = ICE->getSubExpr();
2654 else
2655 break;
2656 }
2657
2658 return E->IgnoreParens();
2659}
2660
2661/// isTemporaryObject - Determines if this expression produces a
2662/// temporary of the given class type.
2663bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2664 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2665 return false;
2666
2667 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2668
2669 // Temporaries are by definition pr-values of class type.
2670 if (!E->Classify(C).isPRValue()) {
2671 // In this context, property reference is a message call and is pr-value.
2672 if (!isa<ObjCPropertyRefExpr>(E))
2673 return false;
2674 }
2675
2676 // Black-list a few cases which yield pr-values of class type that don't
2677 // refer to temporaries of that type:
2678
2679 // - implicit derived-to-base conversions
2680 if (isa<ImplicitCastExpr>(E)) {
2681 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2682 case CK_DerivedToBase:
2683 case CK_UncheckedDerivedToBase:
2684 return false;
2685 default:
2686 break;
2687 }
2688 }
2689
2690 // - member expressions (all)
2691 if (isa<MemberExpr>(E))
2692 return false;
2693
2694 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2695 if (BO->isPtrMemOp())
2696 return false;
2697
2698 // - opaque values (all)
2699 if (isa<OpaqueValueExpr>(E))
2700 return false;
2701
2702 return true;
2703}
2704
2705bool Expr::isImplicitCXXThis() const {
2706 const Expr *E = this;
2707
2708 // Strip away parentheses and casts we don't care about.
2709 while (true) {
2710 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2711 E = Paren->getSubExpr();
2712 continue;
2713 }
2714
2715 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2716 if (ICE->getCastKind() == CK_NoOp ||
2717 ICE->getCastKind() == CK_LValueToRValue ||
2718 ICE->getCastKind() == CK_DerivedToBase ||
2719 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2720 E = ICE->getSubExpr();
2721 continue;
2722 }
2723 }
2724
2725 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2726 if (UnOp->getOpcode() == UO_Extension) {
2727 E = UnOp->getSubExpr();
2728 continue;
2729 }
2730 }
2731
2732 if (const MaterializeTemporaryExpr *M
2733 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2734 E = M->GetTemporaryExpr();
2735 continue;
2736 }
2737
2738 break;
2739 }
2740
2741 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2742 return This->isImplicit();
2743
2744 return false;
2745}
2746
2747/// hasAnyTypeDependentArguments - Determines if any of the expressions
2748/// in Exprs is type-dependent.
2749bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
2750 for (unsigned I = 0; I < Exprs.size(); ++I)
2751 if (Exprs[I]->isTypeDependent())
2752 return true;
2753
2754 return false;
2755}
2756
2757bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2758 const Expr **Culprit) const {
2759 // This function is attempting whether an expression is an initializer
2760 // which can be evaluated at compile-time. It very closely parallels
2761 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2762 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2763 // to isEvaluatable most of the time.
2764 //
2765 // If we ever capture reference-binding directly in the AST, we can
2766 // kill the second parameter.
2767
2768 if (IsForRef) {
2769 EvalResult Result;
2770 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2771 return true;
2772 if (Culprit)
2773 *Culprit = this;
2774 return false;
2775 }
2776
2777 switch (getStmtClass()) {
2778 default: break;
2779 case StringLiteralClass:
2780 case ObjCEncodeExprClass:
2781 return true;
2782 case CXXTemporaryObjectExprClass:
2783 case CXXConstructExprClass: {
2784 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2785
2786 if (CE->getConstructor()->isTrivial() &&
2787 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2788 // Trivial default constructor
2789 if (!CE->getNumArgs()) return true;
2790
2791 // Trivial copy constructor
2792 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2792, __extension__ __PRETTY_FUNCTION__))
;
2793 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
2794 }
2795
2796 break;
2797 }
2798 case CompoundLiteralExprClass: {
2799 // This handles gcc's extension that allows global initializers like
2800 // "struct x {int x;} x = (struct x) {};".
2801 // FIXME: This accepts other cases it shouldn't!
2802 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2803 return Exp->isConstantInitializer(Ctx, false, Culprit);
2804 }
2805 case DesignatedInitUpdateExprClass: {
2806 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2807 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2808 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2809 }
2810 case InitListExprClass: {
2811 const InitListExpr *ILE = cast<InitListExpr>(this);
2812 if (ILE->getType()->isArrayType()) {
2813 unsigned numInits = ILE->getNumInits();
2814 for (unsigned i = 0; i < numInits; i++) {
2815 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
2816 return false;
2817 }
2818 return true;
2819 }
2820
2821 if (ILE->getType()->isRecordType()) {
2822 unsigned ElementNo = 0;
2823 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
2824 for (const auto *Field : RD->fields()) {
2825 // If this is a union, skip all the fields that aren't being initialized.
2826 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
2827 continue;
2828
2829 // Don't emit anonymous bitfields, they just affect layout.
2830 if (Field->isUnnamedBitfield())
2831 continue;
2832
2833 if (ElementNo < ILE->getNumInits()) {
2834 const Expr *Elt = ILE->getInit(ElementNo++);
2835 if (Field->isBitField()) {
2836 // Bitfields have to evaluate to an integer.
2837 llvm::APSInt ResultTmp;
2838 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2839 if (Culprit)
2840 *Culprit = Elt;
2841 return false;
2842 }
2843 } else {
2844 bool RefType = Field->getType()->isReferenceType();
2845 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
2846 return false;
2847 }
2848 }
2849 }
2850 return true;
2851 }
2852
2853 break;
2854 }
2855 case ImplicitValueInitExprClass:
2856 case NoInitExprClass:
2857 return true;
2858 case ParenExprClass:
2859 return cast<ParenExpr>(this)->getSubExpr()
2860 ->isConstantInitializer(Ctx, IsForRef, Culprit);
2861 case GenericSelectionExprClass:
2862 return cast<GenericSelectionExpr>(this)->getResultExpr()
2863 ->isConstantInitializer(Ctx, IsForRef, Culprit);
2864 case ChooseExprClass:
2865 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2866 if (Culprit)
2867 *Culprit = this;
2868 return false;
2869 }
2870 return cast<ChooseExpr>(this)->getChosenSubExpr()
2871 ->isConstantInitializer(Ctx, IsForRef, Culprit);
2872 case UnaryOperatorClass: {
2873 const UnaryOperator* Exp = cast<UnaryOperator>(this);
2874 if (Exp->getOpcode() == UO_Extension)
2875 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2876 break;
2877 }
2878 case CXXFunctionalCastExprClass:
2879 case CXXStaticCastExprClass:
2880 case ImplicitCastExprClass:
2881 case CStyleCastExprClass:
2882 case ObjCBridgedCastExprClass:
2883 case CXXDynamicCastExprClass:
2884 case CXXReinterpretCastExprClass:
2885 case CXXConstCastExprClass: {
2886 const CastExpr *CE = cast<CastExpr>(this);
2887
2888 // Handle misc casts we want to ignore.
2889 if (CE->getCastKind() == CK_NoOp ||
2890 CE->getCastKind() == CK_LValueToRValue ||
2891 CE->getCastKind() == CK_ToUnion ||
2892 CE->getCastKind() == CK_ConstructorConversion ||
2893 CE->getCastKind() == CK_NonAtomicToAtomic ||
2894 CE->getCastKind() == CK_AtomicToNonAtomic ||
2895 CE->getCastKind() == CK_IntToOCLSampler)
2896 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2897
2898 break;
2899 }
2900 case MaterializeTemporaryExprClass:
2901 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2902 ->isConstantInitializer(Ctx, false, Culprit);
2903
2904 case SubstNonTypeTemplateParmExprClass:
2905 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
2906 ->isConstantInitializer(Ctx, false, Culprit);
2907 case CXXDefaultArgExprClass:
2908 return cast<CXXDefaultArgExpr>(this)->getExpr()
2909 ->isConstantInitializer(Ctx, false, Culprit);
2910 case CXXDefaultInitExprClass:
2911 return cast<CXXDefaultInitExpr>(this)->getExpr()
2912 ->isConstantInitializer(Ctx, false, Culprit);
2913 }
2914 // Allow certain forms of UB in constant initializers: signed integer
2915 // overflow and floating-point division by zero. We'll give a warning on
2916 // these, but they're common enough that we have to accept them.
2917 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
2918 return true;
2919 if (Culprit)
2920 *Culprit = this;
2921 return false;
2922}
2923
2924bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
2925 const FunctionDecl* FD = getDirectCallee();
2926 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
2927 FD->getBuiltinID() != Builtin::BI__builtin_assume))
2928 return false;
2929
2930 const Expr* Arg = getArg(0);
2931 bool ArgVal;
2932 return !Arg->isValueDependent() &&
2933 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
2934}
2935
2936namespace {
2937 /// \brief Look for any side effects within a Stmt.
2938 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2939 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2940 const bool IncludePossibleEffects;
2941 bool HasSideEffects;
2942
2943 public:
2944 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2945 : Inherited(Context),
2946 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2947
2948 bool hasSideEffects() const { return HasSideEffects; }
2949
2950 void VisitExpr(const Expr *E) {
2951 if (!HasSideEffects &&
2952 E->HasSideEffects(Context, IncludePossibleEffects))
2953 HasSideEffects = true;
2954 }
2955 };
2956}
2957
2958bool Expr::HasSideEffects(const ASTContext &Ctx,
2959 bool IncludePossibleEffects) const {
2960 // In circumstances where we care about definite side effects instead of
2961 // potential side effects, we want to ignore expressions that are part of a
2962 // macro expansion as a potential side effect.
2963 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2964 return false;
2965
2966 if (isInstantiationDependent())
2967 return IncludePossibleEffects;
2968
2969 switch (getStmtClass()) {
2970 case NoStmtClass:
2971 #define ABSTRACT_STMT(Type)
2972 #define STMT(Type, Base) case Type##Class:
2973 #define EXPR(Type, Base)
2974 #include "clang/AST/StmtNodes.inc"
2975 llvm_unreachable("unexpected Expr kind")::llvm::llvm_unreachable_internal("unexpected Expr kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2975)
;
2976
2977 case DependentScopeDeclRefExprClass:
2978 case CXXUnresolvedConstructExprClass:
2979 case CXXDependentScopeMemberExprClass:
2980 case UnresolvedLookupExprClass:
2981 case UnresolvedMemberExprClass:
2982 case PackExpansionExprClass:
2983 case SubstNonTypeTemplateParmPackExprClass:
2984 case FunctionParmPackExprClass:
2985 case TypoExprClass:
2986 case CXXFoldExprClass:
2987 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 2987)
;
2988
2989 case DeclRefExprClass:
2990 case ObjCIvarRefExprClass:
2991 case PredefinedExprClass:
2992 case IntegerLiteralClass:
2993 case FloatingLiteralClass:
2994 case ImaginaryLiteralClass:
2995 case StringLiteralClass:
2996 case CharacterLiteralClass:
2997 case OffsetOfExprClass:
2998 case ImplicitValueInitExprClass:
2999 case UnaryExprOrTypeTraitExprClass:
3000 case AddrLabelExprClass:
3001 case GNUNullExprClass:
3002 case ArrayInitIndexExprClass:
3003 case NoInitExprClass:
3004 case CXXBoolLiteralExprClass:
3005 case CXXNullPtrLiteralExprClass:
3006 case CXXThisExprClass:
3007 case CXXScalarValueInitExprClass:
3008 case TypeTraitExprClass:
3009 case ArrayTypeTraitExprClass:
3010 case ExpressionTraitExprClass:
3011 case CXXNoexceptExprClass:
3012 case SizeOfPackExprClass:
3013 case ObjCStringLiteralClass:
3014 case ObjCEncodeExprClass:
3015 case ObjCBoolLiteralExprClass:
3016 case ObjCAvailabilityCheckExprClass:
3017 case CXXUuidofExprClass:
3018 case OpaqueValueExprClass:
3019 // These never have a side-effect.
3020 return false;
3021
3022 case CallExprClass:
3023 case CXXOperatorCallExprClass:
3024 case CXXMemberCallExprClass:
3025 case CUDAKernelCallExprClass:
3026 case UserDefinedLiteralClass: {
3027 // We don't know a call definitely has side effects, except for calls
3028 // to pure/const functions that definitely don't.
3029 // If the call itself is considered side-effect free, check the operands.
3030 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3031 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3032 if (IsPure || !IncludePossibleEffects)
3033 break;
3034 return true;
3035 }
3036
3037 case BlockExprClass:
3038 case CXXBindTemporaryExprClass:
3039 if (!IncludePossibleEffects)
3040 break;
3041 return true;
3042
3043 case MSPropertyRefExprClass:
3044 case MSPropertySubscriptExprClass:
3045 case CompoundAssignOperatorClass:
3046 case VAArgExprClass:
3047 case AtomicExprClass:
3048 case CXXThrowExprClass:
3049 case CXXNewExprClass:
3050 case CXXDeleteExprClass:
3051 case CoawaitExprClass:
3052 case DependentCoawaitExprClass:
3053 case CoyieldExprClass:
3054 // These always have a side-effect.
3055 return true;
3056
3057 case StmtExprClass: {
3058 // StmtExprs have a side-effect if any substatement does.
3059 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3060 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3061 return Finder.hasSideEffects();
3062 }
3063
3064 case ExprWithCleanupsClass:
3065 if (IncludePossibleEffects)
3066 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3067 return true;
3068 break;
3069
3070 case ParenExprClass:
3071 case ArraySubscriptExprClass:
3072 case OMPArraySectionExprClass:
3073 case MemberExprClass:
3074 case ConditionalOperatorClass:
3075 case BinaryConditionalOperatorClass:
3076 case CompoundLiteralExprClass:
3077 case ExtVectorElementExprClass:
3078 case DesignatedInitExprClass:
3079 case DesignatedInitUpdateExprClass:
3080 case ArrayInitLoopExprClass:
3081 case ParenListExprClass:
3082 case CXXPseudoDestructorExprClass:
3083 case CXXStdInitializerListExprClass:
3084 case SubstNonTypeTemplateParmExprClass:
3085 case MaterializeTemporaryExprClass:
3086 case ShuffleVectorExprClass:
3087 case ConvertVectorExprClass:
3088 case AsTypeExprClass:
3089 // These have a side-effect if any subexpression does.
3090 break;
3091
3092 case UnaryOperatorClass:
3093 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3094 return true;
3095 break;
3096
3097 case BinaryOperatorClass:
3098 if (cast<BinaryOperator>(this)->isAssignmentOp())
3099 return true;
3100 break;
3101
3102 case InitListExprClass:
3103 // FIXME: The children for an InitListExpr doesn't include the array filler.
3104 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3105 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3106 return true;
3107 break;
3108
3109 case GenericSelectionExprClass:
3110 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3111 HasSideEffects(Ctx, IncludePossibleEffects);
3112
3113 case ChooseExprClass:
3114 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3115 Ctx, IncludePossibleEffects);
3116
3117 case CXXDefaultArgExprClass:
3118 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3119 Ctx, IncludePossibleEffects);
3120
3121 case CXXDefaultInitExprClass: {
3122 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3123 if (const Expr *E = FD->getInClassInitializer())
3124 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3125 // If we've not yet parsed the initializer, assume it has side-effects.
3126 return true;
3127 }
3128
3129 case CXXDynamicCastExprClass: {
3130 // A dynamic_cast expression has side-effects if it can throw.
3131 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3132 if (DCE->getTypeAsWritten()->isReferenceType() &&
3133 DCE->getCastKind() == CK_Dynamic)
3134 return true;
3135 }
3136 LLVM_FALLTHROUGH[[clang::fallthrough]];
3137 case ImplicitCastExprClass:
3138 case CStyleCastExprClass:
3139 case CXXStaticCastExprClass:
3140 case CXXReinterpretCastExprClass:
3141 case CXXConstCastExprClass:
3142 case CXXFunctionalCastExprClass: {
3143 // While volatile reads are side-effecting in both C and C++, we treat them
3144 // as having possible (not definite) side-effects. This allows idiomatic
3145 // code to behave without warning, such as sizeof(*v) for a volatile-
3146 // qualified pointer.
3147 if (!IncludePossibleEffects)
3148 break;
3149
3150 const CastExpr *CE = cast<CastExpr>(this);
3151 if (CE->getCastKind() == CK_LValueToRValue &&
3152 CE->getSubExpr()->getType().isVolatileQualified())
3153 return true;
3154 break;
3155 }
3156
3157 case CXXTypeidExprClass:
3158 // typeid might throw if its subexpression is potentially-evaluated, so has
3159 // side-effects in that case whether or not its subexpression does.
3160 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3161
3162 case CXXConstructExprClass:
3163 case CXXTemporaryObjectExprClass: {
3164 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3165 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3166 return true;
3167 // A trivial constructor does not add any side-effects of its own. Just look
3168 // at its arguments.
3169 break;
3170 }
3171
3172 case CXXInheritedCtorInitExprClass: {
3173 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3174 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3175 return true;
3176 break;
3177 }
3178
3179 case LambdaExprClass: {
3180 const LambdaExpr *LE = cast<LambdaExpr>(this);
3181 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3182 E = LE->capture_end(); I != E; ++I)
3183 if (I->getCaptureKind() == LCK_ByCopy)
3184 // FIXME: Only has a side-effect if the variable is volatile or if
3185 // the copy would invoke a non-trivial copy constructor.
3186 return true;
3187 return false;
3188 }
3189
3190 case PseudoObjectExprClass: {
3191 // Only look for side-effects in the semantic form, and look past
3192 // OpaqueValueExpr bindings in that form.
3193 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3194 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3195 E = PO->semantics_end();
3196 I != E; ++I) {
3197 const Expr *Subexpr = *I;
3198 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3199 Subexpr = OVE->getSourceExpr();
3200 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3201 return true;
3202 }
3203 return false;
3204 }
3205
3206 case ObjCBoxedExprClass:
3207 case ObjCArrayLiteralClass:
3208 case ObjCDictionaryLiteralClass:
3209 case ObjCSelectorExprClass:
3210 case ObjCProtocolExprClass:
3211 case ObjCIsaExprClass:
3212 case ObjCIndirectCopyRestoreExprClass:
3213 case ObjCSubscriptRefExprClass:
3214 case ObjCBridgedCastExprClass:
3215 case ObjCMessageExprClass:
3216 case ObjCPropertyRefExprClass:
3217 // FIXME: Classify these cases better.
3218 if (IncludePossibleEffects)
3219 return true;
3220 break;
3221 }
3222
3223 // Recurse to children.
3224 for (const Stmt *SubStmt : children())
3225 if (SubStmt &&
3226 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3227 return true;
3228
3229 return false;
3230}
3231
3232namespace {
3233 /// \brief Look for a call to a non-trivial function within an expression.
3234 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3235 {
3236 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3237
3238 bool NonTrivial;
3239
3240 public:
3241 explicit NonTrivialCallFinder(const ASTContext &Context)
3242 : Inherited(Context), NonTrivial(false) { }
3243
3244 bool hasNonTrivialCall() const { return NonTrivial; }
3245
3246 void VisitCallExpr(const CallExpr *E) {
3247 if (const CXXMethodDecl *Method
3248 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3249 if (Method->isTrivial()) {
3250 // Recurse to children of the call.
3251 Inherited::VisitStmt(E);
3252 return;
3253 }
3254 }
3255
3256 NonTrivial = true;
3257 }
3258
3259 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3260 if (E->getConstructor()->isTrivial()) {
3261 // Recurse to children of the call.
3262 Inherited::VisitStmt(E);
3263 return;
3264 }
3265
3266 NonTrivial = true;
3267 }
3268
3269 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3270 if (E->getTemporary()->getDestructor()->isTrivial()) {
3271 Inherited::VisitStmt(E);
3272 return;
3273 }
3274
3275 NonTrivial = true;
3276 }
3277 };
3278}
3279
3280bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3281 NonTrivialCallFinder Finder(Ctx);
3282 Finder.Visit(this);
3283 return Finder.hasNonTrivialCall();
3284}
3285
3286/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3287/// pointer constant or not, as well as the specific kind of constant detected.
3288/// Null pointer constants can be integer constant expressions with the
3289/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3290/// (a GNU extension).
3291Expr::NullPointerConstantKind
3292Expr::isNullPointerConstant(ASTContext &Ctx,
3293 NullPointerConstantValueDependence NPC) const {
3294 if (isValueDependent() &&
3295 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3296 switch (NPC) {
3297 case NPC_NeverValueDependent:
3298 llvm_unreachable("Unexpected value dependent expression!")::llvm::llvm_unreachable_internal("Unexpected value dependent expression!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3298)
;
3299 case NPC_ValueDependentIsNull:
3300 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3301 return NPCK_ZeroExpression;
3302 else
3303 return NPCK_NotNull;
3304
3305 case NPC_ValueDependentIsNotNull:
3306 return NPCK_NotNull;
3307 }
3308 }
3309
3310 // Strip off a cast to void*, if it exists. Except in C++.
3311 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3312 if (!Ctx.getLangOpts().CPlusPlus) {
3313 // Check that it is a cast to void*.
3314 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3315 QualType Pointee = PT->getPointeeType();
3316 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3317 // has non-default address space it is not treated as nullptr.
3318 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3319 // since it cannot be assigned to a pointer to constant address space.
3320 bool PointeeHasDefaultAS =
3321 Pointee.getAddressSpace() == LangAS::Default ||
3322 (Ctx.getLangOpts().OpenCLVersion >= 200 &&
3323 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3324 (Ctx.getLangOpts().OpenCL &&
3325 Ctx.getLangOpts().OpenCLVersion < 200 &&
3326 Pointee.getAddressSpace() == LangAS::opencl_private);
3327
3328 if (PointeeHasDefaultAS && Pointee->isVoidType() && // to void*
3329 CE->getSubExpr()->getType()->isIntegerType()) // from int.
3330 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3331 }
3332 }
3333 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3334 // Ignore the ImplicitCastExpr type entirely.
3335 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3336 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3337 // Accept ((void*)0) as a null pointer constant, as many other
3338 // implementations do.
3339 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3340 } else if (const GenericSelectionExpr *GE =
3341 dyn_cast<GenericSelectionExpr>(this)) {
3342 if (GE->isResultDependent())
3343 return NPCK_NotNull;
3344 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3345 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3346 if (CE->isConditionDependent())
3347 return NPCK_NotNull;
3348 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3349 } else if (const CXXDefaultArgExpr *DefaultArg
3350 = dyn_cast<CXXDefaultArgExpr>(this)) {
3351 // See through default argument expressions.
3352 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3353 } else if (const CXXDefaultInitExpr *DefaultInit
3354 = dyn_cast<CXXDefaultInitExpr>(this)) {
3355 // See through default initializer expressions.
3356 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3357 } else if (isa<GNUNullExpr>(this)) {
3358 // The GNU __null extension is always a null pointer constant.
3359 return NPCK_GNUNull;
3360 } else if (const MaterializeTemporaryExpr *M
3361 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3362 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3363 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3364 if (const Expr *Source = OVE->getSourceExpr())
3365 return Source->isNullPointerConstant(Ctx, NPC);
3366 }
3367
3368 // C++11 nullptr_t is always a null pointer constant.
3369 if (getType()->isNullPtrType())
3370 return NPCK_CXX11_nullptr;
3371
3372 if (const RecordType *UT = getType()->getAsUnionType())
3373 if (!Ctx.getLangOpts().CPlusPlus11 &&
3374 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3375 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3376 const Expr *InitExpr = CLE->getInitializer();
3377 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3378 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3379 }
3380 // This expression must be an integer type.
3381 if (!getType()->isIntegerType() ||
3382 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3383 return NPCK_NotNull;
3384
3385 if (Ctx.getLangOpts().CPlusPlus11) {
3386 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3387 // value zero or a prvalue of type std::nullptr_t.
3388 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3389 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3390 if (Lit && !Lit->getValue())
3391 return NPCK_ZeroLiteral;
3392 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3393 return NPCK_NotNull;
3394 } else {
3395 // If we have an integer constant expression, we need to *evaluate* it and
3396 // test for the value 0.
3397 if (!isIntegerConstantExpr(Ctx))
3398 return NPCK_NotNull;
3399 }
3400
3401 if (EvaluateKnownConstInt(Ctx) != 0)
3402 return NPCK_NotNull;
3403
3404 if (isa<IntegerLiteral>(this))
3405 return NPCK_ZeroLiteral;
3406 return NPCK_ZeroExpression;
3407}
3408
3409/// \brief If this expression is an l-value for an Objective C
3410/// property, find the underlying property reference expression.
3411const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3412 const Expr *E = this;
3413 while (true) {
3414 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3416, __extension__ __PRETTY_FUNCTION__))
3415 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3416, __extension__ __PRETTY_FUNCTION__))
3416 "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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3416, __extension__ __PRETTY_FUNCTION__))
;
3417 E = E->IgnoreParenCasts();
3418 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3419 if (BO->getOpcode() == BO_Comma) {
3420 E = BO->getRHS();
3421 continue;
3422 }
3423 }
3424
3425 break;
3426 }
3427
3428 return cast<ObjCPropertyRefExpr>(E);
3429}
3430
3431bool Expr::isObjCSelfExpr() const {
3432 const Expr *E = IgnoreParenImpCasts();
3433
3434 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3435 if (!DRE)
3436 return false;
3437
3438 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3439 if (!Param)
3440 return false;
3441
3442 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3443 if (!M)
3444 return false;
3445
3446 return M->getSelfDecl() == Param;
3447}
3448
3449FieldDecl *Expr::getSourceBitField() {
3450 Expr *E = this->IgnoreParens();
3451
3452 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3453 if (ICE->getCastKind() == CK_LValueToRValue ||
3454 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3455 E = ICE->getSubExpr()->IgnoreParens();
3456 else
3457 break;
3458 }
3459
3460 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3461 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3462 if (Field->isBitField())
3463 return Field;
3464
3465 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3466 FieldDecl *Ivar = IvarRef->getDecl();
3467 if (Ivar->isBitField())
3468 return Ivar;
3469 }
3470
3471 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3472 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3473 if (Field->isBitField())
3474 return Field;
3475
3476 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3477 if (Expr *E = BD->getBinding())
3478 return E->getSourceBitField();
3479 }
3480
3481 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3482 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3483 return BinOp->getLHS()->getSourceBitField();
3484
3485 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3486 return BinOp->getRHS()->getSourceBitField();
3487 }
3488
3489 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3490 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3491 return UnOp->getSubExpr()->getSourceBitField();
3492
3493 return nullptr;
3494}
3495
3496bool Expr::refersToVectorElement() const {
3497 // FIXME: Why do we not just look at the ObjectKind here?
3498 const Expr *E = this->IgnoreParens();
3499
3500 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3501 if (ICE->getValueKind() != VK_RValue &&
3502 ICE->getCastKind() == CK_NoOp)
3503 E = ICE->getSubExpr()->IgnoreParens();
3504 else
3505 break;
3506 }
3507
3508 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3509 return ASE->getBase()->getType()->isVectorType();
3510
3511 if (isa<ExtVectorElementExpr>(E))
3512 return true;
3513
3514 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3515 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3516 if (auto *E = BD->getBinding())
3517 return E->refersToVectorElement();
3518
3519 return false;
3520}
3521
3522bool Expr::refersToGlobalRegisterVar() const {
3523 const Expr *E = this->IgnoreParenImpCasts();
3524
3525 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3526 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3527 if (VD->getStorageClass() == SC_Register &&
3528 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3529 return true;
3530
3531 return false;
3532}
3533
3534/// isArrow - Return true if the base expression is a pointer to vector,
3535/// return false if the base expression is a vector.
3536bool ExtVectorElementExpr::isArrow() const {
3537 return getBase()->getType()->isPointerType();
3538}
3539
3540unsigned ExtVectorElementExpr::getNumElements() const {
3541 if (const VectorType *VT = getType()->getAs<VectorType>())
3542 return VT->getNumElements();
3543 return 1;
3544}
3545
3546/// containsDuplicateElements - Return true if any element access is repeated.
3547bool ExtVectorElementExpr::containsDuplicateElements() const {
3548 // FIXME: Refactor this code to an accessor on the AST node which returns the
3549 // "type" of component access, and share with code below and in Sema.
3550 StringRef Comp = Accessor->getName();
3551
3552 // Halving swizzles do not contain duplicate elements.
3553 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3554 return false;
3555
3556 // Advance past s-char prefix on hex swizzles.
3557 if (Comp[0] == 's' || Comp[0] == 'S')
3558 Comp = Comp.substr(1);
3559
3560 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3561 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3562 return true;
3563
3564 return false;
3565}
3566
3567/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3568void ExtVectorElementExpr::getEncodedElementAccess(
3569 SmallVectorImpl<uint32_t> &Elts) const {
3570 StringRef Comp = Accessor->getName();
3571 bool isNumericAccessor = false;
3572 if (Comp[0] == 's' || Comp[0] == 'S') {
3573 Comp = Comp.substr(1);
3574 isNumericAccessor = true;
3575 }
3576
3577 bool isHi = Comp == "hi";
3578 bool isLo = Comp == "lo";
3579 bool isEven = Comp == "even";
3580 bool isOdd = Comp == "odd";
3581
3582 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3583 uint64_t Index;
3584
3585 if (isHi)
3586 Index = e + i;
3587 else if (isLo)
3588 Index = i;
3589 else if (isEven)
3590 Index = 2 * i;
3591 else if (isOdd)
3592 Index = 2 * i + 1;
3593 else
3594 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3595
3596 Elts.push_back(Index);
3597 }
3598}
3599
3600ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
3601 QualType Type, SourceLocation BLoc,
3602 SourceLocation RP)
3603 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3604 Type->isDependentType(), Type->isDependentType(),
3605 Type->isInstantiationDependentType(),
3606 Type->containsUnexpandedParameterPack()),
3607 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3608{
3609 SubExprs = new (C) Stmt*[args.size()];
3610 for (unsigned i = 0; i != args.size(); i++) {
3611 if (args[i]->isTypeDependent())
3612 ExprBits.TypeDependent = true;
3613 if (args[i]->isValueDependent())
3614 ExprBits.ValueDependent = true;
3615 if (args[i]->isInstantiationDependent())
3616 ExprBits.InstantiationDependent = true;
3617 if (args[i]->containsUnexpandedParameterPack())
3618 ExprBits.ContainsUnexpandedParameterPack = true;
3619
3620 SubExprs[i] = args[i];
3621 }
3622}
3623
3624void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
3625 if (SubExprs) C.Deallocate(SubExprs);
3626
3627 this->NumExprs = Exprs.size();
3628 SubExprs = new (C) Stmt*[NumExprs];
3629 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3630}
3631
3632GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
3633 SourceLocation GenericLoc, Expr *ControllingExpr,
3634 ArrayRef<TypeSourceInfo*> AssocTypes,
3635 ArrayRef<Expr*> AssocExprs,
3636 SourceLocation DefaultLoc,
3637 SourceLocation RParenLoc,
3638 bool ContainsUnexpandedParameterPack,
3639 unsigned ResultIndex)
3640 : Expr(GenericSelectionExprClass,
3641 AssocExprs[ResultIndex]->getType(),
3642 AssocExprs[ResultIndex]->getValueKind(),
3643 AssocExprs[ResultIndex]->getObjectKind(),
3644 AssocExprs[ResultIndex]->isTypeDependent(),
3645 AssocExprs[ResultIndex]->isValueDependent(),
3646 AssocExprs[ResultIndex]->isInstantiationDependent(),
3647 ContainsUnexpandedParameterPack),
3648 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3649 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3650 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3651 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3652 SubExprs[CONTROLLING] = ControllingExpr;
3653 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3653, __extension__ __PRETTY_FUNCTION__))
;
3654 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3655 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3656}
3657
3658GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
3659 SourceLocation GenericLoc, Expr *ControllingExpr,
3660 ArrayRef<TypeSourceInfo*> AssocTypes,
3661 ArrayRef<Expr*> AssocExprs,
3662 SourceLocation DefaultLoc,
3663 SourceLocation RParenLoc,
3664 bool ContainsUnexpandedParameterPack)
3665 : Expr(GenericSelectionExprClass,
3666 Context.DependentTy,
3667 VK_RValue,
3668 OK_Ordinary,
3669 /*isTypeDependent=*/true,
3670 /*isValueDependent=*/true,
3671 /*isInstantiationDependent=*/true,
3672 ContainsUnexpandedParameterPack),
3673 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3674 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3675 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3676 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3677 SubExprs[CONTROLLING] = ControllingExpr;
3678 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3678, __extension__ __PRETTY_FUNCTION__))
;
3679 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3680 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3681}
3682
3683//===----------------------------------------------------------------------===//
3684// DesignatedInitExpr
3685//===----------------------------------------------------------------------===//
3686
3687IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3688 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3688, __extension__ __PRETTY_FUNCTION__))
;
3689 if (Field.NameOrField & 0x01)
3690 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3691 else
3692 return getField()->getIdentifier();
3693}
3694
3695DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
3696 llvm::ArrayRef<Designator> Designators,
3697 SourceLocation EqualOrColonLoc,
3698 bool GNUSyntax,
3699 ArrayRef<Expr*> IndexExprs,
3700 Expr *Init)
3701 : Expr(DesignatedInitExprClass, Ty,
3702 Init->getValueKind(), Init->getObjectKind(),
3703 Init->isTypeDependent(), Init->isValueDependent(),
3704 Init->isInstantiationDependent(),
3705 Init->containsUnexpandedParameterPack()),
3706 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3707 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
3708 this->Designators = new (C) Designator[NumDesignators];
3709
3710 // Record the initializer itself.
3711 child_iterator Child = child_begin();
3712 *Child++ = Init;
3713
3714 // Copy the designators and their subexpressions, computing
3715 // value-dependence along the way.
3716 unsigned IndexIdx = 0;
3717 for (unsigned I = 0; I != NumDesignators; ++I) {
3718 this->Designators[I] = Designators[I];
3719
3720 if (this->Designators[I].isArrayDesignator()) {
3721 // Compute type- and value-dependence.
3722 Expr *Index = IndexExprs[IndexIdx];
3723 if (Index->isTypeDependent() || Index->isValueDependent())
3724 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3725 if (Index->isInstantiationDependent())
3726 ExprBits.InstantiationDependent = true;
3727 // Propagate unexpanded parameter packs.
3728 if (Index->containsUnexpandedParameterPack())
3729 ExprBits.ContainsUnexpandedParameterPack = true;
3730
3731 // Copy the index expressions into permanent storage.
3732 *Child++ = IndexExprs[IndexIdx++];
3733 } else if (this->Designators[I].isArrayRangeDesignator()) {
3734 // Compute type- and value-dependence.
3735 Expr *Start = IndexExprs[IndexIdx];
3736 Expr *End = IndexExprs[IndexIdx + 1];
3737 if (Start->isTypeDependent() || Start->isValueDependent() ||
3738 End->isTypeDependent() || End->isValueDependent()) {
3739 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3740 ExprBits.InstantiationDependent = true;
3741 } else if (Start->isInstantiationDependent() ||
3742 End->isInstantiationDependent()) {
3743 ExprBits.InstantiationDependent = true;
3744 }
3745
3746 // Propagate unexpanded parameter packs.
3747 if (Start->containsUnexpandedParameterPack() ||
3748 End->containsUnexpandedParameterPack())
3749 ExprBits.ContainsUnexpandedParameterPack = true;
3750
3751 // Copy the start/end expressions into permanent storage.
3752 *Child++ = IndexExprs[IndexIdx++];
3753 *Child++ = IndexExprs[IndexIdx++];
3754 }
3755 }
3756
3757 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3757, __extension__ __PRETTY_FUNCTION__))
;
3758}
3759
3760DesignatedInitExpr *
3761DesignatedInitExpr::Create(const ASTContext &C,
3762 llvm::ArrayRef<Designator> Designators,
3763 ArrayRef<Expr*> IndexExprs,
3764 SourceLocation ColonOrEqualLoc,
3765 bool UsesColonSyntax, Expr *Init) {
3766 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
3767 alignof(DesignatedInitExpr));
3768 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
3769 ColonOrEqualLoc, UsesColonSyntax,
3770 IndexExprs, Init);
3771}
3772
3773DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
3774 unsigned NumIndexExprs) {
3775 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3776 alignof(DesignatedInitExpr));
3777 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3778}
3779
3780void DesignatedInitExpr::setDesignators(const ASTContext &C,
3781 const Designator *Desigs,
3782 unsigned NumDesigs) {
3783 Designators = new (C) Designator[NumDesigs];
1
Null pointer value stored to field 'Designators'
3784 NumDesignators = NumDesigs;
3785 for (unsigned I = 0; I != NumDesigs; ++I)
2
Assuming 'I' is not equal to 'NumDesigs'
3
Loop condition is true. Entering loop body
3786 Designators[I] = Desigs[I];
4
Called C++ object pointer is null
3787}
3788
3789SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3790 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3791 if (size() == 1)
3792 return DIE->getDesignator(0)->getSourceRange();
3793 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3794 DIE->getDesignator(size()-1)->getLocEnd());
3795}
3796
3797SourceLocation DesignatedInitExpr::getLocStart() const {
3798 SourceLocation StartLoc;
3799 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3800 Designator &First = *DIE->getDesignator(0);
3801 if (First.isFieldDesignator()) {
3802 if (GNUSyntax)
3803 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3804 else
3805 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3806 } else
3807 StartLoc =
3808 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3809 return StartLoc;
3810}
3811
3812SourceLocation DesignatedInitExpr::getLocEnd() const {
3813 return getInit()->getLocEnd();
3814}
3815
3816Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
3817 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3817, __extension__ __PRETTY_FUNCTION__))
;
3818 return getSubExpr(D.ArrayOrRange.Index + 1);
3819}
3820
3821Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
3822 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3823, __extension__ __PRETTY_FUNCTION__))
3823 "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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3823, __extension__ __PRETTY_FUNCTION__))
;
3824 return getSubExpr(D.ArrayOrRange.Index + 1);
3825}
3826
3827Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
3828 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3829, __extension__ __PRETTY_FUNCTION__))
3829 "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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3829, __extension__ __PRETTY_FUNCTION__))
;
3830 return getSubExpr(D.ArrayOrRange.Index + 2);
3831}
3832
3833/// \brief Replaces the designator at index @p Idx with the series
3834/// of designators in [First, Last).
3835void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
3836 const Designator *First,
3837 const Designator *Last) {
3838 unsigned NumNewDesignators = Last - First;
3839 if (NumNewDesignators == 0) {
3840 std::copy_backward(Designators + Idx + 1,
3841 Designators + NumDesignators,
3842 Designators + Idx);
3843 --NumNewDesignators;
3844 return;
3845 } else if (NumNewDesignators == 1) {
3846 Designators[Idx] = *First;
3847 return;
3848 }
3849
3850 Designator *NewDesignators
3851 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3852 std::copy(Designators, Designators + Idx, NewDesignators);
3853 std::copy(First, Last, NewDesignators + Idx);
3854 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3855 NewDesignators + Idx + NumNewDesignators);
3856 Designators = NewDesignators;
3857 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3858}
3859
3860DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3861 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3862 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3863 OK_Ordinary, false, false, false, false) {
3864 BaseAndUpdaterExprs[0] = baseExpr;
3865
3866 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3867 ILE->setType(baseExpr->getType());
3868 BaseAndUpdaterExprs[1] = ILE;
3869}
3870
3871SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3872 return getBase()->getLocStart();
3873}
3874
3875SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3876 return getBase()->getLocEnd();
3877}
3878
3879ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
3880 ArrayRef<Expr*> exprs,
3881 SourceLocation rparenloc)
3882 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3883 false, false, false, false),
3884 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3885 Exprs = new (C) Stmt*[exprs.size()];
3886 for (unsigned i = 0; i != exprs.size(); ++i) {
3887 if (exprs[i]->isTypeDependent())
3888 ExprBits.TypeDependent = true;
3889 if (exprs[i]->isValueDependent())
3890 ExprBits.ValueDependent = true;
3891 if (exprs[i]->isInstantiationDependent())
3892 ExprBits.InstantiationDependent = true;
3893 if (exprs[i]->containsUnexpandedParameterPack())
3894 ExprBits.ContainsUnexpandedParameterPack = true;
3895
3896 Exprs[i] = exprs[i];
3897 }
3898}
3899
3900const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3901 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3902 e = ewc->getSubExpr();
3903 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3904 e = m->GetTemporaryExpr();
3905 e = cast<CXXConstructExpr>(e)->getArg(0);
3906 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3907 e = ice->getSubExpr();
3908 return cast<OpaqueValueExpr>(e);
3909}
3910
3911PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3912 EmptyShell sh,
3913 unsigned numSemanticExprs) {
3914 void *buffer =
3915 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3916 alignof(PseudoObjectExpr));
3917 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3918}
3919
3920PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3921 : Expr(PseudoObjectExprClass, shell) {
3922 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3923}
3924
3925PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
3926 ArrayRef<Expr*> semantics,
3927 unsigned resultIndex) {
3928 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3928, __extension__ __PRETTY_FUNCTION__))
;
3929 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3929, __extension__ __PRETTY_FUNCTION__))
;
3930
3931 QualType type;
3932 ExprValueKind VK;
3933 if (resultIndex == NoResult) {
3934 type = C.VoidTy;
3935 VK = VK_RValue;
3936 } else {
3937 assert(resultIndex < semantics.size())(static_cast <bool> (resultIndex < semantics.size())
? void (0) : __assert_fail ("resultIndex < semantics.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3937, __extension__ __PRETTY_FUNCTION__))
;
3938 type = semantics[resultIndex]->getType();
3939 VK = semantics[resultIndex]->getValueKind();
3940 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3940, __extension__ __PRETTY_FUNCTION__))
;
3941 }
3942
3943 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
3944 alignof(PseudoObjectExpr));
3945 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3946 resultIndex);
3947}
3948
3949PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3950 Expr *syntax, ArrayRef<Expr*> semantics,
3951 unsigned resultIndex)
3952 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3953 /*filled in at end of ctor*/ false, false, false, false) {
3954 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3955 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3956
3957 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3958 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3959 getSubExprsBuffer()[i] = E;
3960
3961 if (E->isTypeDependent())
3962 ExprBits.TypeDependent = true;
3963 if (E->isValueDependent())
3964 ExprBits.ValueDependent = true;
3965 if (E->isInstantiationDependent())
3966 ExprBits.InstantiationDependent = true;
3967 if (E->containsUnexpandedParameterPack())
3968 ExprBits.ContainsUnexpandedParameterPack = true;
3969
3970 if (isa<OpaqueValueExpr>(E))
3971 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3973, __extension__ __PRETTY_FUNCTION__))
3972 "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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3973, __extension__ __PRETTY_FUNCTION__))
3973 "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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 3973, __extension__ __PRETTY_FUNCTION__))
;
3974 }
3975}
3976
3977//===----------------------------------------------------------------------===//
3978// Child Iterators for iterating over subexpressions/substatements
3979//===----------------------------------------------------------------------===//
3980
3981// UnaryExprOrTypeTraitExpr
3982Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3983 const_child_range CCR =
3984 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
3985 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
3986}
3987
3988Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
3989 // If this is of a type and the type is a VLA type (and not a typedef), the
3990 // size expression of the VLA needs to be treated as an executable expression.
3991 // Why isn't this weirdness documented better in StmtIterator?
3992 if (isArgumentType()) {
3993 if (const VariableArrayType *T =
3994 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
3995 return const_child_range(const_child_iterator(T), const_child_iterator());
3996 return const_child_range(const_child_iterator(), const_child_iterator());
3997 }
3998 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
3999}
4000
4001AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
4002 QualType t, AtomicOp op, SourceLocation RP)
4003 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4004 false, false, false, false),
4005 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4006{
4007 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~svn329677/tools/clang/lib/AST/Expr.cpp"
, 4007, __extension__ __PRETTY_FUNCTION__))
;
4008 for (unsigned i = 0; i != args.size(); i++) {
4009 if (args[i]->isTypeDependent())
4010 ExprBits.TypeDependent = true;
4011 if (args[i]->isValueDependent())
4012 ExprBits.ValueDependent = true;
4013 if (args[i]->isInstantiationDependent())
4014 ExprBits.InstantiationDependent = true;
4015 if (args[i]->containsUnexpandedParameterPack())
4016 ExprBits.ContainsUnexpandedParameterPack = true;
4017
4018 SubExprs[i] = args[i];
4019 }
4020}
4021
4022unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4023 switch (Op) {
4024 case AO__c11_atomic_init:
4025 case AO__opencl_atomic_init:
4026 case AO__c11_atomic_load:
4027 case AO__atomic_load_n:
4028 return 2;
4029
4030 case AO__opencl_atomic_load:
4031 case AO__c11_atomic_store:
4032 case AO__c11_atomic_exchange:
4033 case AO__atomic_load:
4034 case AO__atomic_store:
4035 case AO__atomic_store_n:
4036 case AO__atomic_exchange_n:
4037 case AO__c11_atomic_fetch_add:
4038 case AO__c11_atomic_fetch_sub:
4039 case AO__c11_atomic_fetch_and:
4040 case AO__c11_atomic_fetch_or:
4041 case AO__c11_atomic_fetch_xor:
4042 case AO__atomic_fetch_add:
4043 case AO__atomic_fetch_sub:
4044 case AO__atomic_fetch_and:
4045 case AO__atomic_fetch_or:
4046 case AO__atomic_fetch_xor:
4047 case AO__atomic_fetch_nand:
4048 case AO__atomic_add_fetch:
4049 case AO__atomic_sub_fetch:
4050 case AO__atomic_and_fetch:
4051 case AO__atomic_or_fetch:
4052 case AO__atomic_xor_fetch:
4053 case AO__atomic_nand_fetch:
4054 return 3;
4055
4056 case AO__opencl_atomic_store:
4057 case AO__opencl_atomic_exchange:
4058 case AO__opencl_atomic_fetch_add:
4059 case AO__opencl_atomic_fetch_sub:
4060 case AO__opencl_atomic_fetch_and:
4061 case AO__opencl_atomic_fetch_or:
4062 case AO__opencl_atomic_fetch_xor:
4063 case AO__opencl_atomic_fetch_min:
4064 case AO__opencl_atomic_fetch_max:
4065 case AO__atomic_exchange:
4066 return 4;
4067
4068 case AO__c11_atomic_compare_exchange_strong:
4069 case AO__c11_atomic_compare_exchange_weak:
4070 return 5;
4071
4072 case AO__opencl_atomic_compare_exchange_strong:
4073 case AO__opencl_atomic_compare_exchange_weak:
4074 case AO__atomic_compare_exchange:
4075 case AO__atomic_compare_exchange_n:
4076 return 6;
4077 }
4078 llvm_unreachable("unknown atomic op")::llvm::llvm_unreachable_internal("unknown atomic op", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 4078)
;
4079}
4080
4081QualType AtomicExpr::getValueType() const {
4082 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4083 if (auto AT = T->getAs<AtomicType>())
4084 return AT->getValueType();
4085 return T;
4086}
4087
4088QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4089 unsigned ArraySectionCount = 0;
4090 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4091 Base = OASE->getBase();
4092 ++ArraySectionCount;
4093 }
4094 while (auto *ASE =
4095 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4096 Base = ASE->getBase();
4097 ++ArraySectionCount;
4098 }
4099 Base = Base->IgnoreParenImpCasts();
4100 auto OriginalTy = Base->getType();
4101 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4102 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4103 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4104
4105 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4106 if (OriginalTy->isAnyPointerType())
4107 OriginalTy = OriginalTy->getPointeeType();
4108 else {
4109 assert (OriginalTy->isArrayType())(static_cast <bool> (OriginalTy->isArrayType()) ? void
(0) : __assert_fail ("OriginalTy->isArrayType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/Expr.cpp"
, 4109, __extension__ __PRETTY_FUNCTION__))
;
4110 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4111 }
4112 }
4113 return OriginalTy;
4114}