1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expr class and subclasses.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/EvaluatedExprVisitor.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 "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
35 using namespace clang;
37 const Expr *Expr::getBestDynamicClassTypeExpr() const {
40 E = E->ignoreParenBaseCasts();
42 // Follow the RHS of a comma operator.
43 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44 if (BO->getOpcode() == BO_Comma) {
50 // Step into initializer for materialized temporaries.
51 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52 E = MTE->GetTemporaryExpr();
62 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
63 const Expr *E = getBestDynamicClassTypeExpr();
64 QualType DerivedType = E->getType();
65 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66 DerivedType = PTy->getPointeeType();
68 if (DerivedType->isDependentType())
71 const RecordType *Ty = DerivedType->castAs<RecordType>();
72 Decl *D = Ty->getDecl();
73 return cast<CXXRecordDecl>(D);
76 const Expr *Expr::skipRValueSubobjectAdjustments(
77 SmallVectorImpl<const Expr *> &CommaLHSs,
78 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
81 E = E->IgnoreParens();
83 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84 if ((CE->getCastKind() == CK_DerivedToBase ||
85 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86 E->getType()->isRecordType()) {
88 CXXRecordDecl *Derived
89 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
90 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
94 if (CE->getCastKind() == CK_NoOp) {
98 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
100 assert(ME->getBase()->getType()->isRecordType());
101 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
102 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
104 Adjustments.push_back(SubobjectAdjustment(Field));
109 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
110 if (BO->getOpcode() == BO_PtrMemD) {
111 assert(BO->getRHS()->isRValue());
113 const MemberPointerType *MPT =
114 BO->getRHS()->getType()->getAs<MemberPointerType>();
115 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
117 } else if (BO->getOpcode() == BO_Comma) {
118 CommaLHSs.push_back(BO->getLHS());
130 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
131 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
132 /// but also int expressions which are produced by things like comparisons in
134 bool Expr::isKnownToHaveBooleanValue() const {
135 const Expr *E = IgnoreParens();
137 // If this value has _Bool type, it is obvious 0/1.
138 if (E->getType()->isBooleanType()) return true;
139 // If this is a non-scalar-integer type, we don't care enough to try.
140 if (!E->getType()->isIntegralOrEnumerationType()) return false;
142 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
143 switch (UO->getOpcode()) {
145 return UO->getSubExpr()->isKnownToHaveBooleanValue();
153 // Only look through implicit casts. If the user writes
154 // '(int) (a && b)' treat it as an arbitrary int.
155 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
156 return CE->getSubExpr()->isKnownToHaveBooleanValue();
158 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
159 switch (BO->getOpcode()) {
160 default: return false;
161 case BO_LT: // Relational operators.
165 case BO_EQ: // Equality operators.
167 case BO_LAnd: // AND operator.
168 case BO_LOr: // Logical OR operator.
171 case BO_And: // Bitwise AND operator.
172 case BO_Xor: // Bitwise XOR operator.
173 case BO_Or: // Bitwise OR operator.
174 // Handle things like (x==2)|(y==12).
175 return BO->getLHS()->isKnownToHaveBooleanValue() &&
176 BO->getRHS()->isKnownToHaveBooleanValue();
180 return BO->getRHS()->isKnownToHaveBooleanValue();
184 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
185 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
186 CO->getFalseExpr()->isKnownToHaveBooleanValue();
191 // Amusing macro metaprogramming hack: check whether a class provides
192 // a more specific implementation of getExprLoc().
194 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
196 /// This implementation is used when a class provides a custom
197 /// implementation of getExprLoc.
198 template <class E, class T>
199 SourceLocation getExprLocImpl(const Expr *expr,
200 SourceLocation (T::*v)() const) {
201 return static_cast<const E*>(expr)->getExprLoc();
204 /// This implementation is used when a class doesn't provide
205 /// a custom implementation of getExprLoc. Overload resolution
206 /// should pick it over the implementation above because it's
207 /// more specialized according to function template partial ordering.
209 SourceLocation getExprLocImpl(const Expr *expr,
210 SourceLocation (Expr::*v)() const) {
211 return static_cast<const E *>(expr)->getBeginLoc();
215 SourceLocation Expr::getExprLoc() const {
216 switch (getStmtClass()) {
217 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
218 #define ABSTRACT_STMT(type)
219 #define STMT(type, base) \
220 case Stmt::type##Class: break;
221 #define EXPR(type, base) \
222 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
223 #include "clang/AST/StmtNodes.inc"
225 llvm_unreachable("unknown expression kind");
228 //===----------------------------------------------------------------------===//
229 // Primary Expressions.
230 //===----------------------------------------------------------------------===//
232 static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
233 assert((Kind == ConstantExpr::RSK_APValue ||
234 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
235 "Invalid StorageKind Value");
238 ConstantExpr::ResultStorageKind
239 ConstantExpr::getStorageKind(const APValue &Value) {
240 switch (Value.getKind()) {
242 case APValue::Indeterminate:
243 return ConstantExpr::RSK_None;
245 if (!Value.getInt().needsCleanup())
246 return ConstantExpr::RSK_Int64;
249 return ConstantExpr::RSK_APValue;
253 ConstantExpr::ResultStorageKind
254 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
255 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
256 return ConstantExpr::RSK_Int64;
257 return ConstantExpr::RSK_APValue;
260 void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
261 ConstantExprBits.ResultKind = StorageKind;
262 ConstantExprBits.APValueKind = APValue::None;
263 ConstantExprBits.HasCleanup = false;
264 if (StorageKind == ConstantExpr::RSK_APValue)
265 ::new (getTrailingObjects<APValue>()) APValue();
268 ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
269 : FullExpr(ConstantExprClass, subexpr) {
270 DefaultInit(StorageKind);
273 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
274 ResultStorageKind StorageKind) {
275 assert(!isa<ConstantExpr>(E));
276 AssertResultStorageKind(StorageKind);
277 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
278 StorageKind == ConstantExpr::RSK_APValue,
279 StorageKind == ConstantExpr::RSK_Int64);
280 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
281 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
285 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
286 const APValue &Result) {
287 ResultStorageKind StorageKind = getStorageKind(Result);
288 ConstantExpr *Self = Create(Context, E, StorageKind);
289 Self->SetResult(Result, Context);
293 ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
294 : FullExpr(ConstantExprClass, Empty) {
295 DefaultInit(StorageKind);
298 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
299 ResultStorageKind StorageKind,
301 AssertResultStorageKind(StorageKind);
302 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
303 StorageKind == ConstantExpr::RSK_APValue,
304 StorageKind == ConstantExpr::RSK_Int64);
305 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
306 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
310 void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
311 assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
312 "Invalid storage for this value kind");
313 ConstantExprBits.APValueKind = Value.getKind();
314 switch (ConstantExprBits.ResultKind) {
318 Int64Result() = *Value.getInt().getRawData();
319 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
320 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
323 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
324 ConstantExprBits.HasCleanup = true;
325 Context.addDestruction(&APValueResult());
327 APValueResult() = std::move(Value);
330 llvm_unreachable("Invalid ResultKind Bits");
333 llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
334 switch (ConstantExprBits.ResultKind) {
335 case ConstantExpr::RSK_APValue:
336 return APValueResult().getInt();
337 case ConstantExpr::RSK_Int64:
338 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
339 ConstantExprBits.IsUnsigned);
341 llvm_unreachable("invalid Accessor");
345 APValue ConstantExpr::getAPValueResult() const {
346 switch (ConstantExprBits.ResultKind) {
347 case ConstantExpr::RSK_APValue:
348 return APValueResult();
349 case ConstantExpr::RSK_Int64:
351 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
352 ConstantExprBits.IsUnsigned));
353 case ConstantExpr::RSK_None:
356 llvm_unreachable("invalid ResultKind");
359 /// Compute the type-, value-, and instantiation-dependence of a
360 /// declaration reference
361 /// based on the declaration being referenced.
362 static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
363 QualType T, bool &TypeDependent,
364 bool &ValueDependent,
365 bool &InstantiationDependent) {
366 TypeDependent = false;
367 ValueDependent = false;
368 InstantiationDependent = false;
370 // (TD) C++ [temp.dep.expr]p3:
371 // An id-expression is type-dependent if it contains:
375 // (VD) C++ [temp.dep.constexpr]p2:
376 // An identifier is value-dependent if it is:
378 // (TD) - an identifier that was declared with dependent type
379 // (VD) - a name declared with a dependent type,
380 if (T->isDependentType()) {
381 TypeDependent = true;
382 ValueDependent = true;
383 InstantiationDependent = true;
385 } else if (T->isInstantiationDependentType()) {
386 InstantiationDependent = true;
389 // (TD) - a conversion-function-id that specifies a dependent type
390 if (D->getDeclName().getNameKind()
391 == DeclarationName::CXXConversionFunctionName) {
392 QualType T = D->getDeclName().getCXXNameType();
393 if (T->isDependentType()) {
394 TypeDependent = true;
395 ValueDependent = true;
396 InstantiationDependent = true;
400 if (T->isInstantiationDependentType())
401 InstantiationDependent = true;
404 // (VD) - the name of a non-type template parameter,
405 if (isa<NonTypeTemplateParmDecl>(D)) {
406 ValueDependent = true;
407 InstantiationDependent = true;
411 // (VD) - a constant with integral or enumeration type and is
412 // initialized with an expression that is value-dependent.
413 // (VD) - a constant with literal type and is initialized with an
414 // expression that is value-dependent [C++11].
415 // (VD) - FIXME: Missing from the standard:
416 // - an entity with reference type and is initialized with an
417 // expression that is value-dependent [C++11]
418 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
419 if ((Ctx.getLangOpts().CPlusPlus11 ?
420 Var->getType()->isLiteralType(Ctx) :
421 Var->getType()->isIntegralOrEnumerationType()) &&
422 (Var->getType().isConstQualified() ||
423 Var->getType()->isReferenceType())) {
424 if (const Expr *Init = Var->getAnyInitializer())
425 if (Init->isValueDependent()) {
426 ValueDependent = true;
427 InstantiationDependent = true;
431 // (VD) - FIXME: Missing from the standard:
432 // - a member function or a static data member of the current
434 if (Var->isStaticDataMember() &&
435 Var->getDeclContext()->isDependentContext()) {
436 ValueDependent = true;
437 InstantiationDependent = true;
438 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
439 if (TInfo->getType()->isIncompleteArrayType())
440 TypeDependent = true;
446 // (VD) - FIXME: Missing from the standard:
447 // - a member function or a static data member of the current
449 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
450 ValueDependent = true;
451 InstantiationDependent = true;
455 void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
456 bool TypeDependent = false;
457 bool ValueDependent = false;
458 bool InstantiationDependent = false;
459 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
460 ValueDependent, InstantiationDependent);
462 ExprBits.TypeDependent |= TypeDependent;
463 ExprBits.ValueDependent |= ValueDependent;
464 ExprBits.InstantiationDependent |= InstantiationDependent;
466 // Is the declaration a parameter pack?
467 if (getDecl()->isParameterPack())
468 ExprBits.ContainsUnexpandedParameterPack = true;
471 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
472 bool RefersToEnclosingVariableOrCapture, QualType T,
473 ExprValueKind VK, SourceLocation L,
474 const DeclarationNameLoc &LocInfo,
475 NonOdrUseReason NOUR)
476 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
477 D(D), DNLoc(LocInfo) {
478 DeclRefExprBits.HasQualifier = false;
479 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
480 DeclRefExprBits.HasFoundDecl = false;
481 DeclRefExprBits.HadMultipleCandidates = false;
482 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
483 RefersToEnclosingVariableOrCapture;
484 DeclRefExprBits.NonOdrUseReason = NOUR;
485 DeclRefExprBits.Loc = L;
486 computeDependence(Ctx);
489 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
490 NestedNameSpecifierLoc QualifierLoc,
491 SourceLocation TemplateKWLoc, ValueDecl *D,
492 bool RefersToEnclosingVariableOrCapture,
493 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
494 const TemplateArgumentListInfo *TemplateArgs,
495 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
496 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
497 D(D), DNLoc(NameInfo.getInfo()) {
498 DeclRefExprBits.Loc = NameInfo.getLoc();
499 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
501 new (getTrailingObjects<NestedNameSpecifierLoc>())
502 NestedNameSpecifierLoc(QualifierLoc);
503 auto *NNS = QualifierLoc.getNestedNameSpecifier();
504 if (NNS->isInstantiationDependent())
505 ExprBits.InstantiationDependent = true;
506 if (NNS->containsUnexpandedParameterPack())
507 ExprBits.ContainsUnexpandedParameterPack = true;
509 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
511 *getTrailingObjects<NamedDecl *>() = FoundD;
512 DeclRefExprBits.HasTemplateKWAndArgsInfo
513 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
514 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
515 RefersToEnclosingVariableOrCapture;
516 DeclRefExprBits.NonOdrUseReason = NOUR;
518 bool Dependent = false;
519 bool InstantiationDependent = false;
520 bool ContainsUnexpandedParameterPack = false;
521 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
522 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
523 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
524 assert(!Dependent && "built a DeclRefExpr with dependent template args");
525 ExprBits.InstantiationDependent |= InstantiationDependent;
526 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
527 } else if (TemplateKWLoc.isValid()) {
528 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
531 DeclRefExprBits.HadMultipleCandidates = 0;
533 computeDependence(Ctx);
536 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
537 NestedNameSpecifierLoc QualifierLoc,
538 SourceLocation TemplateKWLoc, ValueDecl *D,
539 bool RefersToEnclosingVariableOrCapture,
540 SourceLocation NameLoc, QualType T,
541 ExprValueKind VK, NamedDecl *FoundD,
542 const TemplateArgumentListInfo *TemplateArgs,
543 NonOdrUseReason NOUR) {
544 return Create(Context, QualifierLoc, TemplateKWLoc, D,
545 RefersToEnclosingVariableOrCapture,
546 DeclarationNameInfo(D->getDeclName(), NameLoc),
547 T, VK, FoundD, TemplateArgs, NOUR);
550 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
551 NestedNameSpecifierLoc QualifierLoc,
552 SourceLocation TemplateKWLoc, ValueDecl *D,
553 bool RefersToEnclosingVariableOrCapture,
554 const DeclarationNameInfo &NameInfo,
555 QualType T, ExprValueKind VK,
557 const TemplateArgumentListInfo *TemplateArgs,
558 NonOdrUseReason NOUR) {
559 // Filter out cases where the found Decl is the same as the value refenenced.
563 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
565 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
566 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
567 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
568 HasTemplateKWAndArgsInfo ? 1 : 0,
569 TemplateArgs ? TemplateArgs->size() : 0);
571 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
572 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
573 RefersToEnclosingVariableOrCapture, NameInfo,
574 FoundD, TemplateArgs, T, VK, NOUR);
577 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
580 bool HasTemplateKWAndArgsInfo,
581 unsigned NumTemplateArgs) {
582 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
584 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
585 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
586 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
588 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
589 return new (Mem) DeclRefExpr(EmptyShell());
592 SourceLocation DeclRefExpr::getBeginLoc() const {
594 return getQualifierLoc().getBeginLoc();
595 return getNameInfo().getBeginLoc();
597 SourceLocation DeclRefExpr::getEndLoc() const {
598 if (hasExplicitTemplateArgs())
599 return getRAngleLoc();
600 return getNameInfo().getEndLoc();
603 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
605 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
606 FNTy->isDependentType(), FNTy->isDependentType(),
607 FNTy->isInstantiationDependentType(),
608 /*ContainsUnexpandedParameterPack=*/false) {
609 PredefinedExprBits.Kind = IK;
610 assert((getIdentKind() == IK) &&
611 "IdentKind do not fit in PredefinedExprBitfields!");
612 bool HasFunctionName = SL != nullptr;
613 PredefinedExprBits.HasFunctionName = HasFunctionName;
614 PredefinedExprBits.Loc = L;
619 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
620 : Expr(PredefinedExprClass, Empty) {
621 PredefinedExprBits.HasFunctionName = HasFunctionName;
624 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
625 QualType FNTy, IdentKind IK,
627 bool HasFunctionName = SL != nullptr;
628 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
629 alignof(PredefinedExpr));
630 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
633 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
634 bool HasFunctionName) {
635 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
636 alignof(PredefinedExpr));
637 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
640 StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
645 return "__FUNCTION__";
647 return "__FUNCDNAME__";
649 return "L__FUNCTION__";
651 return "__PRETTY_FUNCTION__";
653 return "__FUNCSIG__";
655 return "L__FUNCSIG__";
656 case PrettyFunctionNoVirtual:
659 llvm_unreachable("Unknown ident kind for PredefinedExpr");
662 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
663 // expr" policy instead.
664 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
665 ASTContext &Context = CurrentDecl->getASTContext();
667 if (IK == PredefinedExpr::FuncDName) {
668 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
669 std::unique_ptr<MangleContext> MC;
670 MC.reset(Context.createMangleContext());
672 if (MC->shouldMangleDeclName(ND)) {
673 SmallString<256> Buffer;
674 llvm::raw_svector_ostream Out(Buffer);
675 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
676 MC->mangleCXXCtor(CD, Ctor_Base, Out);
677 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
678 MC->mangleCXXDtor(DD, Dtor_Base, Out);
680 MC->mangleName(ND, Out);
682 if (!Buffer.empty() && Buffer.front() == '\01')
683 return Buffer.substr(1);
686 return ND->getIdentifier()->getName();
690 if (isa<BlockDecl>(CurrentDecl)) {
691 // For blocks we only emit something if it is enclosed in a function
692 // For top-level block we'd like to include the name of variable, but we
693 // don't have it at this point.
694 auto DC = CurrentDecl->getDeclContext();
695 if (DC->isFileContext())
698 SmallString<256> Buffer;
699 llvm::raw_svector_ostream Out(Buffer);
700 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
701 // For nested blocks, propagate up to the parent.
702 Out << ComputeName(IK, DCBlock);
703 else if (auto *DCDecl = dyn_cast<Decl>(DC))
704 Out << ComputeName(IK, DCDecl) << "_block_invoke";
707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
708 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
709 IK != FuncSig && IK != LFuncSig)
710 return FD->getNameAsString();
712 SmallString<256> Name;
713 llvm::raw_svector_ostream Out(Name);
715 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
716 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
722 PrintingPolicy Policy(Context.getLangOpts());
724 llvm::raw_string_ostream POut(Proto);
726 const FunctionDecl *Decl = FD;
727 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
729 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
730 const FunctionProtoType *FT = nullptr;
731 if (FD->hasWrittenPrototype())
732 FT = dyn_cast<FunctionProtoType>(AFT);
734 if (IK == FuncSig || IK == LFuncSig) {
735 switch (AFT->getCallConv()) {
736 case CC_C: POut << "__cdecl "; break;
737 case CC_X86StdCall: POut << "__stdcall "; break;
738 case CC_X86FastCall: POut << "__fastcall "; break;
739 case CC_X86ThisCall: POut << "__thiscall "; break;
740 case CC_X86VectorCall: POut << "__vectorcall "; break;
741 case CC_X86RegCall: POut << "__regcall "; break;
742 // Only bother printing the conventions that MSVC knows about.
747 FD->printQualifiedName(POut, Policy);
751 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
753 POut << Decl->getParamDecl(i)->getType().stream(Policy);
756 if (FT->isVariadic()) {
757 if (FD->getNumParams()) POut << ", ";
759 } else if ((IK == FuncSig || IK == LFuncSig ||
760 !Context.getLangOpts().CPlusPlus) &&
761 !Decl->getNumParams()) {
767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
768 assert(FT && "We must have a written prototype in this case.");
771 if (FT->isVolatile())
773 RefQualifierKind Ref = MD->getRefQualifier();
774 if (Ref == RQ_LValue)
776 else if (Ref == RQ_RValue)
780 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
782 const DeclContext *Ctx = FD->getDeclContext();
783 while (Ctx && isa<NamedDecl>(Ctx)) {
784 const ClassTemplateSpecializationDecl *Spec
785 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
786 if (Spec && !Spec->isExplicitSpecialization())
787 Specs.push_back(Spec);
788 Ctx = Ctx->getParent();
791 std::string TemplateParams;
792 llvm::raw_string_ostream TOut(TemplateParams);
793 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
795 const TemplateParameterList *Params
796 = (*I)->getSpecializedTemplate()->getTemplateParameters();
797 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
798 assert(Params->size() == Args.size());
799 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
800 StringRef Param = Params->getParam(i)->getName();
801 if (Param.empty()) continue;
802 TOut << Param << " = ";
803 Args.get(i).print(Policy, TOut);
808 FunctionTemplateSpecializationInfo *FSI
809 = FD->getTemplateSpecializationInfo();
810 if (FSI && !FSI->isExplicitSpecialization()) {
811 const TemplateParameterList* Params
812 = FSI->getTemplate()->getTemplateParameters();
813 const TemplateArgumentList* Args = FSI->TemplateArguments;
814 assert(Params->size() == Args->size());
815 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
816 StringRef Param = Params->getParam(i)->getName();
817 if (Param.empty()) continue;
818 TOut << Param << " = ";
819 Args->get(i).print(Policy, TOut);
825 if (!TemplateParams.empty()) {
826 // remove the trailing comma and space
827 TemplateParams.resize(TemplateParams.size() - 2);
828 POut << " [" << TemplateParams << "]";
833 // Print "auto" for all deduced return types. This includes C++1y return
834 // type deduction and lambdas. For trailing return types resolve the
835 // decltype expression. Otherwise print the real type when this is
836 // not a constructor or destructor.
837 if (isa<CXXMethodDecl>(FD) &&
838 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
839 Proto = "auto " + Proto;
840 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
842 ->getAs<DecltypeType>()
843 ->getUnderlyingType()
844 .getAsStringInternal(Proto, Policy);
845 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
846 AFT->getReturnType().getAsStringInternal(Proto, Policy);
850 return Name.str().str();
852 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
853 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
854 // Skip to its enclosing function or method, but not its enclosing
856 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
857 const Decl *D = Decl::castFromDeclContext(DC);
858 return ComputeName(IK, D);
860 llvm_unreachable("CapturedDecl not inside a function or method");
862 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
863 SmallString<256> Name;
864 llvm::raw_svector_ostream Out(Name);
865 Out << (MD->isInstanceMethod() ? '-' : '+');
868 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
869 // a null check to avoid a crash.
870 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
873 if (const ObjCCategoryImplDecl *CID =
874 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
875 Out << '(' << *CID << ')';
878 MD->getSelector().print(Out);
881 return Name.str().str();
883 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
884 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
890 void APNumericStorage::setIntValue(const ASTContext &C,
891 const llvm::APInt &Val) {
895 BitWidth = Val.getBitWidth();
896 unsigned NumWords = Val.getNumWords();
897 const uint64_t* Words = Val.getRawData();
899 pVal = new (C) uint64_t[NumWords];
900 std::copy(Words, Words + NumWords, pVal);
901 } else if (NumWords == 1)
907 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
908 QualType type, SourceLocation l)
909 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
912 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
913 assert(V.getBitWidth() == C.getIntWidth(type) &&
914 "Integer type is not the correct size for constant.");
919 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
920 QualType type, SourceLocation l) {
921 return new (C) IntegerLiteral(C, V, type, l);
925 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
926 return new (C) IntegerLiteral(Empty);
929 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
930 QualType type, SourceLocation l,
932 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
934 Loc(l), Scale(Scale) {
935 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
936 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
937 "Fixed point type is not the correct size for constant.");
941 FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
942 const llvm::APInt &V,
946 return new (C) FixedPointLiteral(C, V, type, l, Scale);
949 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
950 // Currently the longest decimal number that can be printed is the max for an
951 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
952 // which is 43 characters.
954 FixedPointValueToString(
955 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
959 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
960 bool isexact, QualType Type, SourceLocation L)
961 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
962 false, false), Loc(L) {
963 setSemantics(V.getSemantics());
964 FloatingLiteralBits.IsExact = isexact;
968 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
969 : Expr(FloatingLiteralClass, Empty) {
970 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
971 FloatingLiteralBits.IsExact = false;
975 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
976 bool isexact, QualType Type, SourceLocation L) {
977 return new (C) FloatingLiteral(C, V, isexact, Type, L);
981 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
982 return new (C) FloatingLiteral(C, Empty);
985 /// getValueAsApproximateDouble - This returns the value as an inaccurate
986 /// double. Note that this may cause loss of precision, but is useful for
987 /// debugging dumps, etc.
988 double FloatingLiteral::getValueAsApproximateDouble() const {
989 llvm::APFloat V = getValue();
991 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
993 return V.convertToDouble();
996 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
998 unsigned CharByteWidth = 0;
1002 CharByteWidth = Target.getCharWidth();
1005 CharByteWidth = Target.getWCharWidth();
1008 CharByteWidth = Target.getChar16Width();
1011 CharByteWidth = Target.getChar32Width();
1014 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1016 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1017 "The only supported character byte widths are 1,2 and 4!");
1018 return CharByteWidth;
1021 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1022 StringKind Kind, bool Pascal, QualType Ty,
1023 const SourceLocation *Loc,
1024 unsigned NumConcatenated)
1025 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1027 assert(Ctx.getAsConstantArrayType(Ty) &&
1028 "StringLiteral must be of constant array type!");
1029 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1030 unsigned ByteLength = Str.size();
1031 assert((ByteLength % CharByteWidth == 0) &&
1032 "The size of the data must be a multiple of CharByteWidth!");
1034 // Avoid the expensive division. The compiler should be able to figure it
1035 // out by itself. However as of clang 7, even with the appropriate
1036 // llvm_unreachable added just here, it is not able to do so.
1038 switch (CharByteWidth) {
1040 Length = ByteLength;
1043 Length = ByteLength / 2;
1046 Length = ByteLength / 4;
1049 llvm_unreachable("Unsupported character width!");
1052 StringLiteralBits.Kind = Kind;
1053 StringLiteralBits.CharByteWidth = CharByteWidth;
1054 StringLiteralBits.IsPascal = Pascal;
1055 StringLiteralBits.NumConcatenated = NumConcatenated;
1056 *getTrailingObjects<unsigned>() = Length;
1058 // Initialize the trailing array of SourceLocation.
1059 // This is safe since SourceLocation is POD-like.
1060 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1061 NumConcatenated * sizeof(SourceLocation));
1063 // Initialize the trailing array of char holding the string data.
1064 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1067 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1068 unsigned Length, unsigned CharByteWidth)
1069 : Expr(StringLiteralClass, Empty) {
1070 StringLiteralBits.CharByteWidth = CharByteWidth;
1071 StringLiteralBits.NumConcatenated = NumConcatenated;
1072 *getTrailingObjects<unsigned>() = Length;
1075 StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1076 StringKind Kind, bool Pascal, QualType Ty,
1077 const SourceLocation *Loc,
1078 unsigned NumConcatenated) {
1079 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1080 1, NumConcatenated, Str.size()),
1081 alignof(StringLiteral));
1083 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1086 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1087 unsigned NumConcatenated,
1089 unsigned CharByteWidth) {
1090 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1091 1, NumConcatenated, Length * CharByteWidth),
1092 alignof(StringLiteral));
1094 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1097 void StringLiteral::outputString(raw_ostream &OS) const {
1098 switch (getKind()) {
1099 case Ascii: break; // no prefix.
1100 case Wide: OS << 'L'; break;
1101 case UTF8: OS << "u8"; break;
1102 case UTF16: OS << 'u'; break;
1103 case UTF32: OS << 'U'; break;
1106 static const char Hex[] = "0123456789ABCDEF";
1108 unsigned LastSlashX = getLength();
1109 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1110 switch (uint32_t Char = getCodeUnit(I)) {
1112 // FIXME: Convert UTF-8 back to codepoints before rendering.
1114 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1115 // Leave invalid surrogates alone; we'll use \x for those.
1116 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1118 uint32_t Trail = getCodeUnit(I + 1);
1119 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1120 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1126 // If this is a wide string, output characters over 0xff using \x
1127 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1128 // codepoint: use \x escapes for invalid codepoints.
1129 if (getKind() == Wide ||
1130 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1131 // FIXME: Is this the best way to print wchar_t?
1134 while ((Char >> Shift) == 0)
1136 for (/**/; Shift >= 0; Shift -= 4)
1137 OS << Hex[(Char >> Shift) & 15];
1144 << Hex[(Char >> 20) & 15]
1145 << Hex[(Char >> 16) & 15];
1148 OS << Hex[(Char >> 12) & 15]
1149 << Hex[(Char >> 8) & 15]
1150 << Hex[(Char >> 4) & 15]
1151 << Hex[(Char >> 0) & 15];
1155 // If we used \x... for the previous character, and this character is a
1156 // hexadecimal digit, prevent it being slurped as part of the \x.
1157 if (LastSlashX + 1 == I) {
1159 case '0': case '1': case '2': case '3': case '4':
1160 case '5': case '6': case '7': case '8': case '9':
1161 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1162 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1167 assert(Char <= 0xff &&
1168 "Characters above 0xff should already have been handled.");
1170 if (isPrintable(Char))
1172 else // Output anything hard as an octal escape.
1174 << (char)('0' + ((Char >> 6) & 7))
1175 << (char)('0' + ((Char >> 3) & 7))
1176 << (char)('0' + ((Char >> 0) & 7));
1178 // Handle some common non-printable cases to make dumps prettier.
1179 case '\\': OS << "\\\\"; break;
1180 case '"': OS << "\\\""; break;
1181 case '\a': OS << "\\a"; break;
1182 case '\b': OS << "\\b"; break;
1183 case '\f': OS << "\\f"; break;
1184 case '\n': OS << "\\n"; break;
1185 case '\r': OS << "\\r"; break;
1186 case '\t': OS << "\\t"; break;
1187 case '\v': OS << "\\v"; break;
1193 /// getLocationOfByte - Return a source location that points to the specified
1194 /// byte of this string literal.
1196 /// Strings are amazingly complex. They can be formed from multiple tokens and
1197 /// can have escape sequences in them in addition to the usual trigraph and
1198 /// escaped newline business. This routine handles this complexity.
1200 /// The *StartToken sets the first token to be searched in this function and
1201 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1202 /// returning, it updates the *StartToken to the TokNo of the token being found
1203 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1205 /// Using these two parameters can reduce the time complexity from O(n^2) to
1206 /// O(n) if one wants to get the location of byte for all the tokens in a
1210 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1211 const LangOptions &Features,
1212 const TargetInfo &Target, unsigned *StartToken,
1213 unsigned *StartTokenByteOffset) const {
1214 assert((getKind() == StringLiteral::Ascii ||
1215 getKind() == StringLiteral::UTF8) &&
1216 "Only narrow string literals are currently supported");
1218 // Loop over all of the tokens in this string until we find the one that
1219 // contains the byte we're looking for.
1221 unsigned StringOffset = 0;
1223 TokNo = *StartToken;
1224 if (StartTokenByteOffset) {
1225 StringOffset = *StartTokenByteOffset;
1226 ByteNo -= StringOffset;
1229 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1230 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1232 // Get the spelling of the string so that we can get the data that makes up
1233 // the string literal, not the identifier for the macro it is potentially
1234 // expanded through.
1235 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1237 // Re-lex the token to get its length and original spelling.
1238 std::pair<FileID, unsigned> LocInfo =
1239 SM.getDecomposedLoc(StrTokSpellingLoc);
1240 bool Invalid = false;
1241 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1243 if (StartTokenByteOffset != nullptr)
1244 *StartTokenByteOffset = StringOffset;
1245 if (StartToken != nullptr)
1246 *StartToken = TokNo;
1247 return StrTokSpellingLoc;
1250 const char *StrData = Buffer.data()+LocInfo.second;
1252 // Create a lexer starting at the beginning of this token.
1253 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1254 Buffer.begin(), StrData, Buffer.end());
1256 TheLexer.LexFromRawLexer(TheTok);
1258 // Use the StringLiteralParser to compute the length of the string in bytes.
1259 StringLiteralParser SLP(TheTok, SM, Features, Target);
1260 unsigned TokNumBytes = SLP.GetStringLength();
1262 // If the byte is in this token, return the location of the byte.
1263 if (ByteNo < TokNumBytes ||
1264 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1265 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1267 // Now that we know the offset of the token in the spelling, use the
1268 // preprocessor to get the offset in the original source.
1269 if (StartTokenByteOffset != nullptr)
1270 *StartTokenByteOffset = StringOffset;
1271 if (StartToken != nullptr)
1272 *StartToken = TokNo;
1273 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1276 // Move to the next string token.
1277 StringOffset += TokNumBytes;
1279 ByteNo -= TokNumBytes;
1283 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1284 /// corresponds to, e.g. "sizeof" or "[pre]++".
1285 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1287 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1288 #include "clang/AST/OperationKinds.def"
1290 llvm_unreachable("Unknown unary operator");
1294 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1296 default: llvm_unreachable("No unary operator for overloaded function");
1297 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1298 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1299 case OO_Amp: return UO_AddrOf;
1300 case OO_Star: return UO_Deref;
1301 case OO_Plus: return UO_Plus;
1302 case OO_Minus: return UO_Minus;
1303 case OO_Tilde: return UO_Not;
1304 case OO_Exclaim: return UO_LNot;
1305 case OO_Coawait: return UO_Coawait;
1309 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1311 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1312 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1313 case UO_AddrOf: return OO_Amp;
1314 case UO_Deref: return OO_Star;
1315 case UO_Plus: return OO_Plus;
1316 case UO_Minus: return OO_Minus;
1317 case UO_Not: return OO_Tilde;
1318 case UO_LNot: return OO_Exclaim;
1319 case UO_Coawait: return OO_Coawait;
1320 default: return OO_None;
1325 //===----------------------------------------------------------------------===//
1326 // Postfix Operators.
1327 //===----------------------------------------------------------------------===//
1329 CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1330 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1331 SourceLocation RParenLoc, unsigned MinNumArgs,
1332 ADLCallKind UsesADL)
1333 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1334 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1335 Fn->containsUnexpandedParameterPack()),
1336 RParenLoc(RParenLoc) {
1337 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1338 unsigned NumPreArgs = PreArgs.size();
1339 CallExprBits.NumPreArgs = NumPreArgs;
1340 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1342 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1343 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1344 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1345 "OffsetToTrailingObjects overflow!");
1347 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1350 for (unsigned I = 0; I != NumPreArgs; ++I) {
1351 updateDependenciesFromArg(PreArgs[I]);
1352 setPreArg(I, PreArgs[I]);
1354 for (unsigned I = 0; I != Args.size(); ++I) {
1355 updateDependenciesFromArg(Args[I]);
1358 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1363 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1365 : Expr(SC, Empty), NumArgs(NumArgs) {
1366 CallExprBits.NumPreArgs = NumPreArgs;
1367 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1369 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1370 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1371 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1372 "OffsetToTrailingObjects overflow!");
1375 CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1376 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1377 SourceLocation RParenLoc, unsigned MinNumArgs,
1378 ADLCallKind UsesADL) {
1379 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1380 unsigned SizeOfTrailingObjects =
1381 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1383 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1384 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1385 RParenLoc, MinNumArgs, UsesADL);
1388 CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1389 ExprValueKind VK, SourceLocation RParenLoc,
1390 ADLCallKind UsesADL) {
1391 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1392 "Misaligned memory in CallExpr::CreateTemporary!");
1393 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1394 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1397 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1399 unsigned SizeOfTrailingObjects =
1400 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1402 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1403 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1406 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1409 return sizeof(CallExpr);
1410 case CXXOperatorCallExprClass:
1411 return sizeof(CXXOperatorCallExpr);
1412 case CXXMemberCallExprClass:
1413 return sizeof(CXXMemberCallExpr);
1414 case UserDefinedLiteralClass:
1415 return sizeof(UserDefinedLiteral);
1416 case CUDAKernelCallExprClass:
1417 return sizeof(CUDAKernelCallExpr);
1419 llvm_unreachable("unexpected class deriving from CallExpr!");
1423 void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1424 if (Arg->isTypeDependent())
1425 ExprBits.TypeDependent = true;
1426 if (Arg->isValueDependent())
1427 ExprBits.ValueDependent = true;
1428 if (Arg->isInstantiationDependent())
1429 ExprBits.InstantiationDependent = true;
1430 if (Arg->containsUnexpandedParameterPack())
1431 ExprBits.ContainsUnexpandedParameterPack = true;
1434 Decl *Expr::getReferencedDeclOfCallee() {
1435 Expr *CEE = IgnoreParenImpCasts();
1437 while (SubstNonTypeTemplateParmExpr *NTTP
1438 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1439 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1442 // If we're calling a dereference, look at the pointer instead.
1443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1444 if (BO->isPtrMemOp())
1445 CEE = BO->getRHS()->IgnoreParenCasts();
1446 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1447 if (UO->getOpcode() == UO_Deref)
1448 CEE = UO->getSubExpr()->IgnoreParenCasts();
1450 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1451 return DRE->getDecl();
1452 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1453 return ME->getMemberDecl();
1454 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1455 return BE->getBlockDecl();
1460 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1462 unsigned CallExpr::getBuiltinCallee() const {
1463 // All simple function calls (e.g. func()) are implicitly cast to pointer to
1464 // function. As a result, we try and obtain the DeclRefExpr from the
1465 // ImplicitCastExpr.
1466 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1467 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1470 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1474 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1478 if (!FDecl->getIdentifier())
1481 return FDecl->getBuiltinID();
1484 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1485 if (unsigned BI = getBuiltinCallee())
1486 return Ctx.BuiltinInfo.isUnevaluated(BI);
1490 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1491 const Expr *Callee = getCallee();
1492 QualType CalleeType = Callee->getType();
1493 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1494 CalleeType = FnTypePtr->getPointeeType();
1495 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1496 CalleeType = BPT->getPointeeType();
1497 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1498 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1501 // This should never be overloaded and so should never return null.
1502 CalleeType = Expr::findBoundMemberType(Callee);
1505 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1506 return FnType->getReturnType();
1509 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1510 // If the return type is a struct, union, or enum that is marked nodiscard,
1511 // then return the return type attribute.
1512 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1513 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1516 // Otherwise, see if the callee is marked nodiscard and return that attribute
1518 const Decl *D = getCalleeDecl();
1519 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1522 SourceLocation CallExpr::getBeginLoc() const {
1523 if (isa<CXXOperatorCallExpr>(this))
1524 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1526 SourceLocation begin = getCallee()->getBeginLoc();
1527 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1528 begin = getArg(0)->getBeginLoc();
1531 SourceLocation CallExpr::getEndLoc() const {
1532 if (isa<CXXOperatorCallExpr>(this))
1533 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1535 SourceLocation end = getRParenLoc();
1536 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1537 end = getArg(getNumArgs() - 1)->getEndLoc();
1541 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1542 SourceLocation OperatorLoc,
1543 TypeSourceInfo *tsi,
1544 ArrayRef<OffsetOfNode> comps,
1545 ArrayRef<Expr*> exprs,
1546 SourceLocation RParenLoc) {
1547 void *Mem = C.Allocate(
1548 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1550 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1554 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1555 unsigned numComps, unsigned numExprs) {
1557 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1558 return new (Mem) OffsetOfExpr(numComps, numExprs);
1561 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1562 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1563 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1564 SourceLocation RParenLoc)
1565 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1566 /*TypeDependent=*/false,
1567 /*ValueDependent=*/tsi->getType()->isDependentType(),
1568 tsi->getType()->isInstantiationDependentType(),
1569 tsi->getType()->containsUnexpandedParameterPack()),
1570 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1571 NumComps(comps.size()), NumExprs(exprs.size())
1573 for (unsigned i = 0; i != comps.size(); ++i) {
1574 setComponent(i, comps[i]);
1577 for (unsigned i = 0; i != exprs.size(); ++i) {
1578 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1579 ExprBits.ValueDependent = true;
1580 if (exprs[i]->containsUnexpandedParameterPack())
1581 ExprBits.ContainsUnexpandedParameterPack = true;
1583 setIndexExpr(i, exprs[i]);
1587 IdentifierInfo *OffsetOfNode::getFieldName() const {
1588 assert(getKind() == Field || getKind() == Identifier);
1589 if (getKind() == Field)
1590 return getField()->getIdentifier();
1592 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1595 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1596 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1597 SourceLocation op, SourceLocation rp)
1598 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1599 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1600 // Value-dependent if the argument is type-dependent.
1601 E->isTypeDependent(), E->isInstantiationDependent(),
1602 E->containsUnexpandedParameterPack()),
1603 OpLoc(op), RParenLoc(rp) {
1604 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1605 UnaryExprOrTypeTraitExprBits.IsType = false;
1608 // Check to see if we are in the situation where alignof(decl) should be
1609 // dependent because decl's alignment is dependent.
1610 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
1611 if (!isValueDependent() || !isInstantiationDependent()) {
1612 E = E->IgnoreParens();
1614 const ValueDecl *D = nullptr;
1615 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1617 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1618 D = ME->getMemberDecl();
1621 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1622 if (I->isAlignmentDependent()) {
1623 setValueDependent(true);
1624 setInstantiationDependent(true);
1633 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1634 ValueDecl *MemberDecl,
1635 const DeclarationNameInfo &NameInfo, QualType T,
1636 ExprValueKind VK, ExprObjectKind OK,
1637 NonOdrUseReason NOUR)
1638 : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1639 Base->isValueDependent(), Base->isInstantiationDependent(),
1640 Base->containsUnexpandedParameterPack()),
1641 Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1642 MemberLoc(NameInfo.getLoc()) {
1643 assert(!NameInfo.getName() ||
1644 MemberDecl->getDeclName() == NameInfo.getName());
1645 MemberExprBits.IsArrow = IsArrow;
1646 MemberExprBits.HasQualifierOrFoundDecl = false;
1647 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1648 MemberExprBits.HadMultipleCandidates = false;
1649 MemberExprBits.NonOdrUseReason = NOUR;
1650 MemberExprBits.OperatorLoc = OperatorLoc;
1653 MemberExpr *MemberExpr::Create(
1654 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1655 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1656 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1657 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1658 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1659 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1660 FoundDecl.getAccess() != MemberDecl->getAccess();
1661 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1663 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1664 TemplateArgumentLoc>(
1665 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1666 TemplateArgs ? TemplateArgs->size() : 0);
1668 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1669 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1670 NameInfo, T, VK, OK, NOUR);
1672 if (HasQualOrFound) {
1673 // FIXME: Wrong. We should be looking at the member declaration we found.
1674 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1675 E->setValueDependent(true);
1676 E->setTypeDependent(true);
1677 E->setInstantiationDependent(true);
1679 else if (QualifierLoc &&
1680 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1681 E->setInstantiationDependent(true);
1683 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1685 MemberExprNameQualifier *NQ =
1686 E->getTrailingObjects<MemberExprNameQualifier>();
1687 NQ->QualifierLoc = QualifierLoc;
1688 NQ->FoundDecl = FoundDecl;
1691 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1692 TemplateArgs || TemplateKWLoc.isValid();
1695 bool Dependent = false;
1696 bool InstantiationDependent = false;
1697 bool ContainsUnexpandedParameterPack = false;
1698 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1699 TemplateKWLoc, *TemplateArgs,
1700 E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1701 InstantiationDependent, ContainsUnexpandedParameterPack);
1702 if (InstantiationDependent)
1703 E->setInstantiationDependent(true);
1704 } else if (TemplateKWLoc.isValid()) {
1705 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1712 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1713 bool HasQualifier, bool HasFoundDecl,
1714 bool HasTemplateKWAndArgsInfo,
1715 unsigned NumTemplateArgs) {
1716 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1717 "template args but no template arg info?");
1718 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1720 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1721 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1722 HasTemplateKWAndArgsInfo ? 1 : 0,
1724 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1725 return new (Mem) MemberExpr(EmptyShell());
1728 SourceLocation MemberExpr::getBeginLoc() const {
1729 if (isImplicitAccess()) {
1731 return getQualifierLoc().getBeginLoc();
1735 // FIXME: We don't want this to happen. Rather, we should be able to
1736 // detect all kinds of implicit accesses more cleanly.
1737 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1738 if (BaseStartLoc.isValid())
1739 return BaseStartLoc;
1742 SourceLocation MemberExpr::getEndLoc() const {
1743 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1744 if (hasExplicitTemplateArgs())
1745 EndLoc = getRAngleLoc();
1746 else if (EndLoc.isInvalid())
1747 EndLoc = getBase()->getEndLoc();
1751 bool CastExpr::CastConsistency() const {
1752 switch (getCastKind()) {
1753 case CK_DerivedToBase:
1754 case CK_UncheckedDerivedToBase:
1755 case CK_DerivedToBaseMemberPointer:
1756 case CK_BaseToDerived:
1757 case CK_BaseToDerivedMemberPointer:
1758 assert(!path_empty() && "Cast kind should have a base path!");
1761 case CK_CPointerToObjCPointerCast:
1762 assert(getType()->isObjCObjectPointerType());
1763 assert(getSubExpr()->getType()->isPointerType());
1764 goto CheckNoBasePath;
1766 case CK_BlockPointerToObjCPointerCast:
1767 assert(getType()->isObjCObjectPointerType());
1768 assert(getSubExpr()->getType()->isBlockPointerType());
1769 goto CheckNoBasePath;
1771 case CK_ReinterpretMemberPointer:
1772 assert(getType()->isMemberPointerType());
1773 assert(getSubExpr()->getType()->isMemberPointerType());
1774 goto CheckNoBasePath;
1777 // Arbitrary casts to C pointer types count as bitcasts.
1778 // Otherwise, we should only have block and ObjC pointer casts
1779 // here if they stay within the type kind.
1780 if (!getType()->isPointerType()) {
1781 assert(getType()->isObjCObjectPointerType() ==
1782 getSubExpr()->getType()->isObjCObjectPointerType());
1783 assert(getType()->isBlockPointerType() ==
1784 getSubExpr()->getType()->isBlockPointerType());
1786 goto CheckNoBasePath;
1788 case CK_AnyPointerToBlockPointerCast:
1789 assert(getType()->isBlockPointerType());
1790 assert(getSubExpr()->getType()->isAnyPointerType() &&
1791 !getSubExpr()->getType()->isBlockPointerType());
1792 goto CheckNoBasePath;
1794 case CK_CopyAndAutoreleaseBlockObject:
1795 assert(getType()->isBlockPointerType());
1796 assert(getSubExpr()->getType()->isBlockPointerType());
1797 goto CheckNoBasePath;
1799 case CK_FunctionToPointerDecay:
1800 assert(getType()->isPointerType());
1801 assert(getSubExpr()->getType()->isFunctionType());
1802 goto CheckNoBasePath;
1804 case CK_AddressSpaceConversion: {
1805 auto Ty = getType();
1806 auto SETy = getSubExpr()->getType();
1807 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1808 if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
1809 Ty = Ty->getPointeeType();
1810 SETy = SETy->getPointeeType();
1812 assert(!Ty.isNull() && !SETy.isNull() &&
1813 Ty.getAddressSpace() != SETy.getAddressSpace());
1814 goto CheckNoBasePath;
1816 // These should not have an inheritance path.
1819 case CK_ArrayToPointerDecay:
1820 case CK_NullToMemberPointer:
1821 case CK_NullToPointer:
1822 case CK_ConstructorConversion:
1823 case CK_IntegralToPointer:
1824 case CK_PointerToIntegral:
1826 case CK_VectorSplat:
1827 case CK_IntegralCast:
1828 case CK_BooleanToSignedIntegral:
1829 case CK_IntegralToFloating:
1830 case CK_FloatingToIntegral:
1831 case CK_FloatingCast:
1832 case CK_ObjCObjectLValueCast:
1833 case CK_FloatingRealToComplex:
1834 case CK_FloatingComplexToReal:
1835 case CK_FloatingComplexCast:
1836 case CK_FloatingComplexToIntegralComplex:
1837 case CK_IntegralRealToComplex:
1838 case CK_IntegralComplexToReal:
1839 case CK_IntegralComplexCast:
1840 case CK_IntegralComplexToFloatingComplex:
1841 case CK_ARCProduceObject:
1842 case CK_ARCConsumeObject:
1843 case CK_ARCReclaimReturnedObject:
1844 case CK_ARCExtendBlockObject:
1845 case CK_ZeroToOCLOpaqueType:
1846 case CK_IntToOCLSampler:
1847 case CK_FixedPointCast:
1848 case CK_FixedPointToIntegral:
1849 case CK_IntegralToFixedPoint:
1850 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1851 goto CheckNoBasePath;
1854 case CK_LValueToRValue:
1856 case CK_AtomicToNonAtomic:
1857 case CK_NonAtomicToAtomic:
1858 case CK_PointerToBoolean:
1859 case CK_IntegralToBoolean:
1860 case CK_FloatingToBoolean:
1861 case CK_MemberPointerToBoolean:
1862 case CK_FloatingComplexToBoolean:
1863 case CK_IntegralComplexToBoolean:
1864 case CK_LValueBitCast: // -> bool&
1865 case CK_LValueToRValueBitCast:
1866 case CK_UserDefinedConversion: // operator bool()
1867 case CK_BuiltinFnToFnPtr:
1868 case CK_FixedPointToBoolean:
1870 assert(path_empty() && "Cast kind should not have a base path!");
1876 const char *CastExpr::getCastKindName(CastKind CK) {
1878 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1879 #include "clang/AST/OperationKinds.def"
1881 llvm_unreachable("Unhandled cast kind!");
1885 const Expr *skipImplicitTemporary(const Expr *E) {
1886 // Skip through reference binding to temporary.
1887 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1888 E = Materialize->GetTemporaryExpr();
1890 // Skip any temporary bindings; they're implicit.
1891 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1892 E = Binder->getSubExpr();
1898 Expr *CastExpr::getSubExprAsWritten() {
1899 const Expr *SubExpr = nullptr;
1900 const CastExpr *E = this;
1902 SubExpr = skipImplicitTemporary(E->getSubExpr());
1904 // Conversions by constructor and conversion functions have a
1905 // subexpression describing the call; strip it off.
1906 if (E->getCastKind() == CK_ConstructorConversion)
1908 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1909 else if (E->getCastKind() == CK_UserDefinedConversion) {
1910 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1911 isa<BlockExpr>(SubExpr)) &&
1912 "Unexpected SubExpr for CK_UserDefinedConversion.");
1913 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1914 SubExpr = MCE->getImplicitObjectArgument();
1917 // If the subexpression we're left with is an implicit cast, look
1918 // through that, too.
1919 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1921 return const_cast<Expr*>(SubExpr);
1924 NamedDecl *CastExpr::getConversionFunction() const {
1925 const Expr *SubExpr = nullptr;
1927 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1928 SubExpr = skipImplicitTemporary(E->getSubExpr());
1930 if (E->getCastKind() == CK_ConstructorConversion)
1931 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1933 if (E->getCastKind() == CK_UserDefinedConversion) {
1934 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1935 return MCE->getMethodDecl();
1942 CXXBaseSpecifier **CastExpr::path_buffer() {
1943 switch (getStmtClass()) {
1944 #define ABSTRACT_STMT(x)
1945 #define CASTEXPR(Type, Base) \
1946 case Stmt::Type##Class: \
1947 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1948 #define STMT(Type, Base)
1949 #include "clang/AST/StmtNodes.inc"
1951 llvm_unreachable("non-cast expressions not possible here");
1955 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1957 auto RD = unionType->castAs<RecordType>()->getDecl();
1958 return getTargetFieldForToUnionCast(RD, opType);
1961 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1963 auto &Ctx = RD->getASTContext();
1964 RecordDecl::field_iterator Field, FieldEnd;
1965 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1966 Field != FieldEnd; ++Field) {
1967 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1968 !Field->isUnnamedBitfield()) {
1975 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1976 CastKind Kind, Expr *Operand,
1977 const CXXCastPath *BasePath,
1979 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1980 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1981 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1982 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1983 assert((Kind != CK_LValueToRValue ||
1984 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1985 "invalid type for lvalue-to-rvalue conversion");
1986 ImplicitCastExpr *E =
1987 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1989 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1990 E->getTrailingObjects<CXXBaseSpecifier *>());
1994 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1995 unsigned PathSize) {
1996 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1997 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
2001 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2002 ExprValueKind VK, CastKind K, Expr *Op,
2003 const CXXCastPath *BasePath,
2004 TypeSourceInfo *WrittenTy,
2005 SourceLocation L, SourceLocation R) {
2006 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2007 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2009 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
2011 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2012 E->getTrailingObjects<CXXBaseSpecifier *>());
2016 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2017 unsigned PathSize) {
2018 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2019 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2022 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2023 /// corresponds to, e.g. "<<=".
2024 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2026 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2027 #include "clang/AST/OperationKinds.def"
2029 llvm_unreachable("Invalid OpCode!");
2033 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2035 default: llvm_unreachable("Not an overloadable binary operator");
2036 case OO_Plus: return BO_Add;
2037 case OO_Minus: return BO_Sub;
2038 case OO_Star: return BO_Mul;
2039 case OO_Slash: return BO_Div;
2040 case OO_Percent: return BO_Rem;
2041 case OO_Caret: return BO_Xor;
2042 case OO_Amp: return BO_And;
2043 case OO_Pipe: return BO_Or;
2044 case OO_Equal: return BO_Assign;
2045 case OO_Spaceship: return BO_Cmp;
2046 case OO_Less: return BO_LT;
2047 case OO_Greater: return BO_GT;
2048 case OO_PlusEqual: return BO_AddAssign;
2049 case OO_MinusEqual: return BO_SubAssign;
2050 case OO_StarEqual: return BO_MulAssign;
2051 case OO_SlashEqual: return BO_DivAssign;
2052 case OO_PercentEqual: return BO_RemAssign;
2053 case OO_CaretEqual: return BO_XorAssign;
2054 case OO_AmpEqual: return BO_AndAssign;
2055 case OO_PipeEqual: return BO_OrAssign;
2056 case OO_LessLess: return BO_Shl;
2057 case OO_GreaterGreater: return BO_Shr;
2058 case OO_LessLessEqual: return BO_ShlAssign;
2059 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2060 case OO_EqualEqual: return BO_EQ;
2061 case OO_ExclaimEqual: return BO_NE;
2062 case OO_LessEqual: return BO_LE;
2063 case OO_GreaterEqual: return BO_GE;
2064 case OO_AmpAmp: return BO_LAnd;
2065 case OO_PipePipe: return BO_LOr;
2066 case OO_Comma: return BO_Comma;
2067 case OO_ArrowStar: return BO_PtrMemI;
2071 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2072 static const OverloadedOperatorKind OverOps[] = {
2073 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2074 OO_Star, OO_Slash, OO_Percent,
2076 OO_LessLess, OO_GreaterGreater,
2078 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2079 OO_EqualEqual, OO_ExclaimEqual,
2085 OO_Equal, OO_StarEqual,
2086 OO_SlashEqual, OO_PercentEqual,
2087 OO_PlusEqual, OO_MinusEqual,
2088 OO_LessLessEqual, OO_GreaterGreaterEqual,
2089 OO_AmpEqual, OO_CaretEqual,
2093 return OverOps[Opc];
2096 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2098 Expr *LHS, Expr *RHS) {
2102 // Check that we have one pointer and one integer operand.
2104 if (LHS->getType()->isPointerType()) {
2105 if (!RHS->getType()->isIntegerType())
2108 } else if (RHS->getType()->isPointerType()) {
2109 if (!LHS->getType()->isIntegerType())
2116 // Check that the pointer is a nullptr.
2117 if (!PExp->IgnoreParenCasts()
2118 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2121 // Check that the pointee type is char-sized.
2122 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2123 if (!PTy || !PTy->getPointeeType()->isCharType())
2129 static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2130 SourceLocExpr::IdentKind Kind) {
2132 case SourceLocExpr::File:
2133 case SourceLocExpr::Function: {
2134 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2135 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2137 case SourceLocExpr::Line:
2138 case SourceLocExpr::Column:
2139 return Ctx.UnsignedIntTy;
2141 llvm_unreachable("unhandled case");
2144 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2145 SourceLocation BLoc, SourceLocation RParenLoc,
2146 DeclContext *ParentContext)
2147 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2148 VK_RValue, OK_Ordinary, false, false, false, false),
2149 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2150 SourceLocExprBits.Kind = Kind;
2153 StringRef SourceLocExpr::getBuiltinStr() const {
2154 switch (getIdentKind()) {
2156 return "__builtin_FILE";
2158 return "__builtin_FUNCTION";
2160 return "__builtin_LINE";
2162 return "__builtin_COLUMN";
2164 llvm_unreachable("unexpected IdentKind!");
2167 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2168 const Expr *DefaultExpr) const {
2170 const DeclContext *Context;
2173 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2174 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2175 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2176 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2177 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2178 return {this->getLocation(), this->getParentContext()};
2181 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2182 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2184 auto MakeStringLiteral = [&](StringRef Tmp) {
2185 using LValuePathEntry = APValue::LValuePathEntry;
2186 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2187 // Decay the string to a pointer to the first character.
2188 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2189 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2192 switch (getIdentKind()) {
2193 case SourceLocExpr::File:
2194 return MakeStringLiteral(PLoc.getFilename());
2195 case SourceLocExpr::Function: {
2196 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2197 return MakeStringLiteral(
2198 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2201 case SourceLocExpr::Line:
2202 case SourceLocExpr::Column: {
2203 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2204 /*isUnsigned=*/true);
2205 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2207 return APValue(IntVal);
2210 llvm_unreachable("unhandled case");
2213 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2214 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
2215 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2217 InitExprs(C, initExprs.size()),
2218 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2220 sawArrayRangeDesignator(false);
2221 for (unsigned I = 0; I != initExprs.size(); ++I) {
2222 if (initExprs[I]->isTypeDependent())
2223 ExprBits.TypeDependent = true;
2224 if (initExprs[I]->isValueDependent())
2225 ExprBits.ValueDependent = true;
2226 if (initExprs[I]->isInstantiationDependent())
2227 ExprBits.InstantiationDependent = true;
2228 if (initExprs[I]->containsUnexpandedParameterPack())
2229 ExprBits.ContainsUnexpandedParameterPack = true;
2232 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2235 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2236 if (NumInits > InitExprs.size())
2237 InitExprs.reserve(C, NumInits);
2240 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2241 InitExprs.resize(C, NumInits, nullptr);
2244 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2245 if (Init >= InitExprs.size()) {
2246 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2247 setInit(Init, expr);
2251 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2252 setInit(Init, expr);
2256 void InitListExpr::setArrayFiller(Expr *filler) {
2257 assert(!hasArrayFiller() && "Filler already set!");
2258 ArrayFillerOrUnionFieldInit = filler;
2259 // Fill out any "holes" in the array due to designated initializers.
2260 Expr **inits = getInits();
2261 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2262 if (inits[i] == nullptr)
2266 bool InitListExpr::isStringLiteralInit() const {
2267 if (getNumInits() != 1)
2269 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2270 if (!AT || !AT->getElementType()->isIntegerType())
2272 // It is possible for getInit() to return null.
2273 const Expr *Init = getInit(0);
2276 Init = Init->IgnoreParens();
2277 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2280 bool InitListExpr::isTransparent() const {
2281 assert(isSemanticForm() && "syntactic form never semantically transparent");
2283 // A glvalue InitListExpr is always just sugar.
2285 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2289 // Otherwise, we're sugar if and only if we have exactly one initializer that
2290 // is of the same type.
2291 if (getNumInits() != 1 || !getInit(0))
2294 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2295 // transparent struct copy.
2296 if (!getInit(0)->isRValue() && getType()->isRecordType())
2299 return getType().getCanonicalType() ==
2300 getInit(0)->getType().getCanonicalType();
2303 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2304 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2306 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2310 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2311 return Lit && Lit->getValue() == 0;
2314 SourceLocation InitListExpr::getBeginLoc() const {
2315 if (InitListExpr *SyntacticForm = getSyntacticForm())
2316 return SyntacticForm->getBeginLoc();
2317 SourceLocation Beg = LBraceLoc;
2318 if (Beg.isInvalid()) {
2319 // Find the first non-null initializer.
2320 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2321 E = InitExprs.end();
2324 Beg = S->getBeginLoc();
2332 SourceLocation InitListExpr::getEndLoc() const {
2333 if (InitListExpr *SyntacticForm = getSyntacticForm())
2334 return SyntacticForm->getEndLoc();
2335 SourceLocation End = RBraceLoc;
2336 if (End.isInvalid()) {
2337 // Find the first non-null initializer from the end.
2338 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2339 E = InitExprs.rend();
2342 End = S->getEndLoc();
2350 /// getFunctionType - Return the underlying function type for this block.
2352 const FunctionProtoType *BlockExpr::getFunctionType() const {
2353 // The block pointer is never sugared, but the function type might be.
2354 return cast<BlockPointerType>(getType())
2355 ->getPointeeType()->castAs<FunctionProtoType>();
2358 SourceLocation BlockExpr::getCaretLocation() const {
2359 return TheBlock->getCaretLocation();
2361 const Stmt *BlockExpr::getBody() const {
2362 return TheBlock->getBody();
2364 Stmt *BlockExpr::getBody() {
2365 return TheBlock->getBody();
2369 //===----------------------------------------------------------------------===//
2370 // Generic Expression Routines
2371 //===----------------------------------------------------------------------===//
2373 /// isUnusedResultAWarning - Return true if this immediate expression should
2374 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2375 /// with location to warn on and the source range[s] to report with the
2377 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2378 SourceRange &R1, SourceRange &R2,
2379 ASTContext &Ctx) const {
2380 // Don't warn if the expr is type dependent. The type could end up
2381 // instantiating to void.
2382 if (isTypeDependent())
2385 switch (getStmtClass()) {
2387 if (getType()->isVoidType())
2391 R1 = getSourceRange();
2393 case ParenExprClass:
2394 return cast<ParenExpr>(this)->getSubExpr()->
2395 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2396 case GenericSelectionExprClass:
2397 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2398 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2399 case CoawaitExprClass:
2400 case CoyieldExprClass:
2401 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2402 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2403 case ChooseExprClass:
2404 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2405 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2406 case UnaryOperatorClass: {
2407 const UnaryOperator *UO = cast<UnaryOperator>(this);
2409 switch (UO->getOpcode()) {
2418 // This is just the 'operator co_await' call inside the guts of a
2419 // dependent co_await call.
2423 case UO_PreDec: // ++/--
2424 return false; // Not a warning.
2427 // accessing a piece of a volatile complex is a side-effect.
2428 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2429 .isVolatileQualified())
2433 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2436 Loc = UO->getOperatorLoc();
2437 R1 = UO->getSubExpr()->getSourceRange();
2440 case BinaryOperatorClass: {
2441 const BinaryOperator *BO = cast<BinaryOperator>(this);
2442 switch (BO->getOpcode()) {
2445 // Consider the RHS of comma for side effects. LHS was checked by
2446 // Sema::CheckCommaOperands.
2448 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2449 // lvalue-ness) of an assignment written in a macro.
2450 if (IntegerLiteral *IE =
2451 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2452 if (IE->getValue() == 0)
2454 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2455 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2458 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2459 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2463 if (BO->isAssignmentOp())
2466 Loc = BO->getOperatorLoc();
2467 R1 = BO->getLHS()->getSourceRange();
2468 R2 = BO->getRHS()->getSourceRange();
2471 case CompoundAssignOperatorClass:
2472 case VAArgExprClass:
2473 case AtomicExprClass:
2476 case ConditionalOperatorClass: {
2477 // If only one of the LHS or RHS is a warning, the operator might
2478 // be being used for control flow. Only warn if both the LHS and
2479 // RHS are warnings.
2480 const auto *Exp = cast<ConditionalOperator>(this);
2481 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2482 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2484 case BinaryConditionalOperatorClass: {
2485 const auto *Exp = cast<BinaryConditionalOperator>(this);
2486 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2489 case MemberExprClass:
2491 Loc = cast<MemberExpr>(this)->getMemberLoc();
2492 R1 = SourceRange(Loc, Loc);
2493 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2496 case ArraySubscriptExprClass:
2498 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2499 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2500 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2503 case CXXOperatorCallExprClass: {
2504 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2505 // overloads as there is no reasonable way to define these such that they
2506 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2507 // warning: operators == and != are commonly typo'ed, and so warning on them
2508 // provides additional value as well. If this list is updated,
2509 // DiagnoseUnusedComparison should be as well.
2510 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2511 switch (Op->getOperator()) {
2515 case OO_ExclaimEqual:
2518 case OO_GreaterEqual:
2520 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2521 Op->getCallReturnType(Ctx)->isVoidType())
2524 Loc = Op->getOperatorLoc();
2525 R1 = Op->getSourceRange();
2529 // Fallthrough for generic call handling.
2533 case CXXMemberCallExprClass:
2534 case UserDefinedLiteralClass: {
2535 // If this is a direct call, get the callee.
2536 const CallExpr *CE = cast<CallExpr>(this);
2537 if (const Decl *FD = CE->getCalleeDecl()) {
2538 // If the callee has attribute pure, const, or warn_unused_result, warn
2539 // about it. void foo() { strlen("bar"); } should warn.
2541 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2542 // updated to match for QoI.
2543 if (CE->hasUnusedResultAttr(Ctx) ||
2544 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2546 Loc = CE->getCallee()->getBeginLoc();
2547 R1 = CE->getCallee()->getSourceRange();
2549 if (unsigned NumArgs = CE->getNumArgs())
2550 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2551 CE->getArg(NumArgs - 1)->getEndLoc());
2558 // If we don't know precisely what we're looking at, let's not warn.
2559 case UnresolvedLookupExprClass:
2560 case CXXUnresolvedConstructExprClass:
2563 case CXXTemporaryObjectExprClass:
2564 case CXXConstructExprClass: {
2565 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2566 if (Type->hasAttr<WarnUnusedAttr>()) {
2568 Loc = getBeginLoc();
2569 R1 = getSourceRange();
2576 case ObjCMessageExprClass: {
2577 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2578 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2579 ME->isInstanceMessage() &&
2580 !ME->getType()->isVoidType() &&
2581 ME->getMethodFamily() == OMF_init) {
2584 R1 = ME->getSourceRange();
2588 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2589 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2598 case ObjCPropertyRefExprClass:
2601 R1 = getSourceRange();
2604 case PseudoObjectExprClass: {
2605 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2607 // Only complain about things that have the form of a getter.
2608 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2609 isa<BinaryOperator>(PO->getSyntacticForm()))
2614 R1 = getSourceRange();
2618 case StmtExprClass: {
2619 // Statement exprs don't logically have side effects themselves, but are
2620 // sometimes used in macros in ways that give them a type that is unused.
2621 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2622 // however, if the result of the stmt expr is dead, we don't want to emit a
2624 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2625 if (!CS->body_empty()) {
2626 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2627 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2628 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2629 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2630 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2633 if (getType()->isVoidType())
2636 Loc = cast<StmtExpr>(this)->getLParenLoc();
2637 R1 = getSourceRange();
2640 case CXXFunctionalCastExprClass:
2641 case CStyleCastExprClass: {
2642 // Ignore an explicit cast to void unless the operand is a non-trivial
2644 const CastExpr *CE = cast<CastExpr>(this);
2645 if (CE->getCastKind() == CK_ToVoid) {
2646 if (CE->getSubExpr()->isGLValue() &&
2647 CE->getSubExpr()->getType().isVolatileQualified()) {
2648 const DeclRefExpr *DRE =
2649 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2650 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2651 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2652 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2653 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2660 // If this is a cast to a constructor conversion, check the operand.
2661 // Otherwise, the result of the cast is unused.
2662 if (CE->getCastKind() == CK_ConstructorConversion)
2663 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2666 if (const CXXFunctionalCastExpr *CXXCE =
2667 dyn_cast<CXXFunctionalCastExpr>(this)) {
2668 Loc = CXXCE->getBeginLoc();
2669 R1 = CXXCE->getSubExpr()->getSourceRange();
2671 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2672 Loc = CStyleCE->getLParenLoc();
2673 R1 = CStyleCE->getSubExpr()->getSourceRange();
2677 case ImplicitCastExprClass: {
2678 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2680 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2681 if (ICE->getCastKind() == CK_LValueToRValue &&
2682 ICE->getSubExpr()->getType().isVolatileQualified())
2685 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2687 case CXXDefaultArgExprClass:
2688 return (cast<CXXDefaultArgExpr>(this)
2689 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2690 case CXXDefaultInitExprClass:
2691 return (cast<CXXDefaultInitExpr>(this)
2692 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2694 case CXXNewExprClass:
2695 // FIXME: In theory, there might be new expressions that don't have side
2696 // effects (e.g. a placement new with an uninitialized POD).
2697 case CXXDeleteExprClass:
2699 case MaterializeTemporaryExprClass:
2700 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2701 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2702 case CXXBindTemporaryExprClass:
2703 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2704 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2705 case ExprWithCleanupsClass:
2706 return cast<ExprWithCleanups>(this)->getSubExpr()
2707 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2711 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2712 /// returns true, if it is; false otherwise.
2713 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2714 const Expr *E = IgnoreParens();
2715 switch (E->getStmtClass()) {
2718 case ObjCIvarRefExprClass:
2720 case Expr::UnaryOperatorClass:
2721 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2722 case ImplicitCastExprClass:
2723 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2724 case MaterializeTemporaryExprClass:
2725 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2726 ->isOBJCGCCandidate(Ctx);
2727 case CStyleCastExprClass:
2728 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2729 case DeclRefExprClass: {
2730 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2732 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2733 if (VD->hasGlobalStorage())
2735 QualType T = VD->getType();
2736 // dereferencing to a pointer is always a gc'able candidate,
2737 // unless it is __weak.
2738 return T->isPointerType() &&
2739 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2743 case MemberExprClass: {
2744 const MemberExpr *M = cast<MemberExpr>(E);
2745 return M->getBase()->isOBJCGCCandidate(Ctx);
2747 case ArraySubscriptExprClass:
2748 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2752 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2753 if (isTypeDependent())
2755 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2758 QualType Expr::findBoundMemberType(const Expr *expr) {
2759 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2761 // Bound member expressions are always one of these possibilities:
2762 // x->m x.m x->*y x.*y
2763 // (possibly parenthesized)
2765 expr = expr->IgnoreParens();
2766 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2767 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2768 return mem->getMemberDecl()->getType();
2771 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2772 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2774 assert(type->isFunctionType());
2778 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2782 static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2783 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2784 return ICE->getSubExpr();
2786 if (auto *FE = dyn_cast<FullExpr>(E))
2787 return FE->getSubExpr();
2792 static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2793 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2794 // addition to what IgnoreImpCasts() skips to account for the current
2795 // behaviour of IgnoreParenImpCasts().
2796 Expr *SubE = IgnoreImpCastsSingleStep(E);
2800 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2801 return MTE->GetTemporaryExpr();
2803 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2804 return NTTP->getReplacement();
2809 static Expr *IgnoreCastsSingleStep(Expr *E) {
2810 if (auto *CE = dyn_cast<CastExpr>(E))
2811 return CE->getSubExpr();
2813 if (auto *FE = dyn_cast<FullExpr>(E))
2814 return FE->getSubExpr();
2816 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2817 return MTE->GetTemporaryExpr();
2819 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2820 return NTTP->getReplacement();
2825 static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2826 // Skip what IgnoreCastsSingleStep skips, except that only
2827 // lvalue-to-rvalue casts are skipped.
2828 if (auto *CE = dyn_cast<CastExpr>(E))
2829 if (CE->getCastKind() != CK_LValueToRValue)
2832 return IgnoreCastsSingleStep(E);
2835 static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2836 if (auto *CE = dyn_cast<CastExpr>(E))
2837 if (CE->getCastKind() == CK_DerivedToBase ||
2838 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2839 CE->getCastKind() == CK_NoOp)
2840 return CE->getSubExpr();
2845 static Expr *IgnoreImplicitSingleStep(Expr *E) {
2846 Expr *SubE = IgnoreImpCastsSingleStep(E);
2850 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2851 return MTE->GetTemporaryExpr();
2853 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2854 return BTE->getSubExpr();
2859 static Expr *IgnoreParensSingleStep(Expr *E) {
2860 if (auto *PE = dyn_cast<ParenExpr>(E))
2861 return PE->getSubExpr();
2863 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2864 if (UO->getOpcode() == UO_Extension)
2865 return UO->getSubExpr();
2868 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2869 if (!GSE->isResultDependent())
2870 return GSE->getResultExpr();
2873 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2874 if (!CE->isConditionDependent())
2875 return CE->getChosenSubExpr();
2878 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2879 return CE->getSubExpr();
2884 static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2885 if (auto *CE = dyn_cast<CastExpr>(E)) {
2886 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2887 // ptr<->int casts of the same width. We also ignore all identity casts.
2888 Expr *SubExpr = CE->getSubExpr();
2889 bool IsIdentityCast =
2890 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2891 bool IsSameWidthCast =
2892 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2893 (SubExpr->getType()->isPointerType() ||
2894 SubExpr->getType()->isIntegralType(Ctx)) &&
2895 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2897 if (IsIdentityCast || IsSameWidthCast)
2901 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2902 return NTTP->getReplacement();
2907 static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2908 template <typename FnTy, typename... FnTys>
2909 static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2910 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2913 /// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2914 /// Recursively apply each of the functions to E until reaching a fixed point.
2915 /// Note that a null E is valid; in this case nothing is done.
2916 template <typename... FnTys>
2917 static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2918 Expr *LastE = nullptr;
2919 while (E != LastE) {
2921 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2926 Expr *Expr::IgnoreImpCasts() {
2927 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
2930 Expr *Expr::IgnoreCasts() {
2931 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2934 Expr *Expr::IgnoreImplicit() {
2935 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2938 Expr *Expr::IgnoreParens() {
2939 return IgnoreExprNodes(this, IgnoreParensSingleStep);
2942 Expr *Expr::IgnoreParenImpCasts() {
2943 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2944 IgnoreImpCastsExtraSingleStep);
2947 Expr *Expr::IgnoreParenCasts() {
2948 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2951 Expr *Expr::IgnoreConversionOperator() {
2952 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2953 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2954 return MCE->getImplicitObjectArgument();
2959 Expr *Expr::IgnoreParenLValueCasts() {
2960 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2961 IgnoreLValueCastsSingleStep);
2964 Expr *Expr::ignoreParenBaseCasts() {
2965 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2966 IgnoreBaseCastsSingleStep);
2969 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2970 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2971 return IgnoreNoopCastsSingleStep(Ctx, E);
2975 bool Expr::isDefaultArgument() const {
2976 const Expr *E = this;
2977 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2978 E = M->GetTemporaryExpr();
2980 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2981 E = ICE->getSubExprAsWritten();
2983 return isa<CXXDefaultArgExpr>(E);
2986 /// Skip over any no-op casts and any temporary-binding
2988 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2989 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2990 E = M->GetTemporaryExpr();
2992 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2993 if (ICE->getCastKind() == CK_NoOp)
2994 E = ICE->getSubExpr();
2999 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3000 E = BE->getSubExpr();
3002 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3003 if (ICE->getCastKind() == CK_NoOp)
3004 E = ICE->getSubExpr();
3009 return E->IgnoreParens();
3012 /// isTemporaryObject - Determines if this expression produces a
3013 /// temporary of the given class type.
3014 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3015 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3018 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3020 // Temporaries are by definition pr-values of class type.
3021 if (!E->Classify(C).isPRValue()) {
3022 // In this context, property reference is a message call and is pr-value.
3023 if (!isa<ObjCPropertyRefExpr>(E))
3027 // Black-list a few cases which yield pr-values of class type that don't
3028 // refer to temporaries of that type:
3030 // - implicit derived-to-base conversions
3031 if (isa<ImplicitCastExpr>(E)) {
3032 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3033 case CK_DerivedToBase:
3034 case CK_UncheckedDerivedToBase:
3041 // - member expressions (all)
3042 if (isa<MemberExpr>(E))
3045 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3046 if (BO->isPtrMemOp())
3049 // - opaque values (all)
3050 if (isa<OpaqueValueExpr>(E))
3056 bool Expr::isImplicitCXXThis() const {
3057 const Expr *E = this;
3059 // Strip away parentheses and casts we don't care about.
3061 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3062 E = Paren->getSubExpr();
3066 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3067 if (ICE->getCastKind() == CK_NoOp ||
3068 ICE->getCastKind() == CK_LValueToRValue ||
3069 ICE->getCastKind() == CK_DerivedToBase ||
3070 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3071 E = ICE->getSubExpr();
3076 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3077 if (UnOp->getOpcode() == UO_Extension) {
3078 E = UnOp->getSubExpr();
3083 if (const MaterializeTemporaryExpr *M
3084 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3085 E = M->GetTemporaryExpr();
3092 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3093 return This->isImplicit();
3098 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3099 /// in Exprs is type-dependent.
3100 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3101 for (unsigned I = 0; I < Exprs.size(); ++I)
3102 if (Exprs[I]->isTypeDependent())
3108 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3109 const Expr **Culprit) const {
3110 assert(!isValueDependent() &&
3111 "Expression evaluator can't be called on a dependent expression.");
3113 // This function is attempting whether an expression is an initializer
3114 // which can be evaluated at compile-time. It very closely parallels
3115 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3116 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3117 // to isEvaluatable most of the time.
3119 // If we ever capture reference-binding directly in the AST, we can
3120 // kill the second parameter.
3124 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3131 switch (getStmtClass()) {
3133 case StringLiteralClass:
3134 case ObjCEncodeExprClass:
3136 case CXXTemporaryObjectExprClass:
3137 case CXXConstructExprClass: {
3138 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3140 if (CE->getConstructor()->isTrivial() &&
3141 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3142 // Trivial default constructor
3143 if (!CE->getNumArgs()) return true;
3145 // Trivial copy constructor
3146 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3147 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3152 case ConstantExprClass: {
3153 // FIXME: We should be able to return "true" here, but it can lead to extra
3154 // error messages. E.g. in Sema/array-init.c.
3155 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3156 return Exp->isConstantInitializer(Ctx, false, Culprit);
3158 case CompoundLiteralExprClass: {
3159 // This handles gcc's extension that allows global initializers like
3160 // "struct x {int x;} x = (struct x) {};".
3161 // FIXME: This accepts other cases it shouldn't!
3162 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3163 return Exp->isConstantInitializer(Ctx, false, Culprit);
3165 case DesignatedInitUpdateExprClass: {
3166 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3167 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3168 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3170 case InitListExprClass: {
3171 const InitListExpr *ILE = cast<InitListExpr>(this);
3172 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3173 if (ILE->getType()->isArrayType()) {
3174 unsigned numInits = ILE->getNumInits();
3175 for (unsigned i = 0; i < numInits; i++) {
3176 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3182 if (ILE->getType()->isRecordType()) {
3183 unsigned ElementNo = 0;
3184 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
3185 for (const auto *Field : RD->fields()) {
3186 // If this is a union, skip all the fields that aren't being initialized.
3187 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3190 // Don't emit anonymous bitfields, they just affect layout.
3191 if (Field->isUnnamedBitfield())
3194 if (ElementNo < ILE->getNumInits()) {
3195 const Expr *Elt = ILE->getInit(ElementNo++);
3196 if (Field->isBitField()) {
3197 // Bitfields have to evaluate to an integer.
3199 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3205 bool RefType = Field->getType()->isReferenceType();
3206 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3216 case ImplicitValueInitExprClass:
3217 case NoInitExprClass:
3219 case ParenExprClass:
3220 return cast<ParenExpr>(this)->getSubExpr()
3221 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3222 case GenericSelectionExprClass:
3223 return cast<GenericSelectionExpr>(this)->getResultExpr()
3224 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3225 case ChooseExprClass:
3226 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3231 return cast<ChooseExpr>(this)->getChosenSubExpr()
3232 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3233 case UnaryOperatorClass: {
3234 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3235 if (Exp->getOpcode() == UO_Extension)
3236 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3239 case CXXFunctionalCastExprClass:
3240 case CXXStaticCastExprClass:
3241 case ImplicitCastExprClass:
3242 case CStyleCastExprClass:
3243 case ObjCBridgedCastExprClass:
3244 case CXXDynamicCastExprClass:
3245 case CXXReinterpretCastExprClass:
3246 case CXXConstCastExprClass: {
3247 const CastExpr *CE = cast<CastExpr>(this);
3249 // Handle misc casts we want to ignore.
3250 if (CE->getCastKind() == CK_NoOp ||
3251 CE->getCastKind() == CK_LValueToRValue ||
3252 CE->getCastKind() == CK_ToUnion ||
3253 CE->getCastKind() == CK_ConstructorConversion ||
3254 CE->getCastKind() == CK_NonAtomicToAtomic ||
3255 CE->getCastKind() == CK_AtomicToNonAtomic ||
3256 CE->getCastKind() == CK_IntToOCLSampler)
3257 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3261 case MaterializeTemporaryExprClass:
3262 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
3263 ->isConstantInitializer(Ctx, false, Culprit);
3265 case SubstNonTypeTemplateParmExprClass:
3266 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3267 ->isConstantInitializer(Ctx, false, Culprit);
3268 case CXXDefaultArgExprClass:
3269 return cast<CXXDefaultArgExpr>(this)->getExpr()
3270 ->isConstantInitializer(Ctx, false, Culprit);
3271 case CXXDefaultInitExprClass:
3272 return cast<CXXDefaultInitExpr>(this)->getExpr()
3273 ->isConstantInitializer(Ctx, false, Culprit);
3275 // Allow certain forms of UB in constant initializers: signed integer
3276 // overflow and floating-point division by zero. We'll give a warning on
3277 // these, but they're common enough that we have to accept them.
3278 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3285 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3286 const FunctionDecl* FD = getDirectCallee();
3287 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3288 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3291 const Expr* Arg = getArg(0);
3293 return !Arg->isValueDependent() &&
3294 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3298 /// Look for any side effects within a Stmt.
3299 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3300 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3301 const bool IncludePossibleEffects;
3302 bool HasSideEffects;
3305 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3306 : Inherited(Context),
3307 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3309 bool hasSideEffects() const { return HasSideEffects; }
3311 void VisitExpr(const Expr *E) {
3312 if (!HasSideEffects &&
3313 E->HasSideEffects(Context, IncludePossibleEffects))
3314 HasSideEffects = true;
3319 bool Expr::HasSideEffects(const ASTContext &Ctx,
3320 bool IncludePossibleEffects) const {
3321 // In circumstances where we care about definite side effects instead of
3322 // potential side effects, we want to ignore expressions that are part of a
3323 // macro expansion as a potential side effect.
3324 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3327 if (isInstantiationDependent())
3328 return IncludePossibleEffects;
3330 switch (getStmtClass()) {
3332 #define ABSTRACT_STMT(Type)
3333 #define STMT(Type, Base) case Type##Class:
3334 #define EXPR(Type, Base)
3335 #include "clang/AST/StmtNodes.inc"
3336 llvm_unreachable("unexpected Expr kind");
3338 case DependentScopeDeclRefExprClass:
3339 case CXXUnresolvedConstructExprClass:
3340 case CXXDependentScopeMemberExprClass:
3341 case UnresolvedLookupExprClass:
3342 case UnresolvedMemberExprClass:
3343 case PackExpansionExprClass:
3344 case SubstNonTypeTemplateParmPackExprClass:
3345 case FunctionParmPackExprClass:
3347 case CXXFoldExprClass:
3348 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3350 case DeclRefExprClass:
3351 case ObjCIvarRefExprClass:
3352 case PredefinedExprClass:
3353 case IntegerLiteralClass:
3354 case FixedPointLiteralClass:
3355 case FloatingLiteralClass:
3356 case ImaginaryLiteralClass:
3357 case StringLiteralClass:
3358 case CharacterLiteralClass:
3359 case OffsetOfExprClass:
3360 case ImplicitValueInitExprClass:
3361 case UnaryExprOrTypeTraitExprClass:
3362 case AddrLabelExprClass:
3363 case GNUNullExprClass:
3364 case ArrayInitIndexExprClass:
3365 case NoInitExprClass:
3366 case CXXBoolLiteralExprClass:
3367 case CXXNullPtrLiteralExprClass:
3368 case CXXThisExprClass:
3369 case CXXScalarValueInitExprClass:
3370 case TypeTraitExprClass:
3371 case ArrayTypeTraitExprClass:
3372 case ExpressionTraitExprClass:
3373 case CXXNoexceptExprClass:
3374 case SizeOfPackExprClass:
3375 case ObjCStringLiteralClass:
3376 case ObjCEncodeExprClass:
3377 case ObjCBoolLiteralExprClass:
3378 case ObjCAvailabilityCheckExprClass:
3379 case CXXUuidofExprClass:
3380 case OpaqueValueExprClass:
3381 case SourceLocExprClass:
3382 // These never have a side-effect.
3385 case ConstantExprClass:
3386 // FIXME: Move this into the "return false;" block above.
3387 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3388 Ctx, IncludePossibleEffects);
3391 case CXXOperatorCallExprClass:
3392 case CXXMemberCallExprClass:
3393 case CUDAKernelCallExprClass:
3394 case UserDefinedLiteralClass: {
3395 // We don't know a call definitely has side effects, except for calls
3396 // to pure/const functions that definitely don't.
3397 // If the call itself is considered side-effect free, check the operands.
3398 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3399 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3400 if (IsPure || !IncludePossibleEffects)
3405 case BlockExprClass:
3406 case CXXBindTemporaryExprClass:
3407 if (!IncludePossibleEffects)
3411 case MSPropertyRefExprClass:
3412 case MSPropertySubscriptExprClass:
3413 case CompoundAssignOperatorClass:
3414 case VAArgExprClass:
3415 case AtomicExprClass:
3416 case CXXThrowExprClass:
3417 case CXXNewExprClass:
3418 case CXXDeleteExprClass:
3419 case CoawaitExprClass:
3420 case DependentCoawaitExprClass:
3421 case CoyieldExprClass:
3422 // These always have a side-effect.
3425 case StmtExprClass: {
3426 // StmtExprs have a side-effect if any substatement does.
3427 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3428 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3429 return Finder.hasSideEffects();
3432 case ExprWithCleanupsClass:
3433 if (IncludePossibleEffects)
3434 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3438 case ParenExprClass:
3439 case ArraySubscriptExprClass:
3440 case OMPArraySectionExprClass:
3441 case MemberExprClass:
3442 case ConditionalOperatorClass:
3443 case BinaryConditionalOperatorClass:
3444 case CompoundLiteralExprClass:
3445 case ExtVectorElementExprClass:
3446 case DesignatedInitExprClass:
3447 case DesignatedInitUpdateExprClass:
3448 case ArrayInitLoopExprClass:
3449 case ParenListExprClass:
3450 case CXXPseudoDestructorExprClass:
3451 case CXXStdInitializerListExprClass:
3452 case SubstNonTypeTemplateParmExprClass:
3453 case MaterializeTemporaryExprClass:
3454 case ShuffleVectorExprClass:
3455 case ConvertVectorExprClass:
3456 case AsTypeExprClass:
3457 // These have a side-effect if any subexpression does.
3460 case UnaryOperatorClass:
3461 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3465 case BinaryOperatorClass:
3466 if (cast<BinaryOperator>(this)->isAssignmentOp())
3470 case InitListExprClass:
3471 // FIXME: The children for an InitListExpr doesn't include the array filler.
3472 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3473 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3477 case GenericSelectionExprClass:
3478 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3479 HasSideEffects(Ctx, IncludePossibleEffects);
3481 case ChooseExprClass:
3482 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3483 Ctx, IncludePossibleEffects);
3485 case CXXDefaultArgExprClass:
3486 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3487 Ctx, IncludePossibleEffects);
3489 case CXXDefaultInitExprClass: {
3490 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3491 if (const Expr *E = FD->getInClassInitializer())
3492 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3493 // If we've not yet parsed the initializer, assume it has side-effects.
3497 case CXXDynamicCastExprClass: {
3498 // A dynamic_cast expression has side-effects if it can throw.
3499 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3500 if (DCE->getTypeAsWritten()->isReferenceType() &&
3501 DCE->getCastKind() == CK_Dynamic)
3505 case ImplicitCastExprClass:
3506 case CStyleCastExprClass:
3507 case CXXStaticCastExprClass:
3508 case CXXReinterpretCastExprClass:
3509 case CXXConstCastExprClass:
3510 case CXXFunctionalCastExprClass:
3511 case BuiltinBitCastExprClass: {
3512 // While volatile reads are side-effecting in both C and C++, we treat them
3513 // as having possible (not definite) side-effects. This allows idiomatic
3514 // code to behave without warning, such as sizeof(*v) for a volatile-
3515 // qualified pointer.
3516 if (!IncludePossibleEffects)
3519 const CastExpr *CE = cast<CastExpr>(this);
3520 if (CE->getCastKind() == CK_LValueToRValue &&
3521 CE->getSubExpr()->getType().isVolatileQualified())
3526 case CXXTypeidExprClass:
3527 // typeid might throw if its subexpression is potentially-evaluated, so has
3528 // side-effects in that case whether or not its subexpression does.
3529 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3531 case CXXConstructExprClass:
3532 case CXXTemporaryObjectExprClass: {
3533 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3534 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3536 // A trivial constructor does not add any side-effects of its own. Just look
3537 // at its arguments.
3541 case CXXInheritedCtorInitExprClass: {
3542 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3543 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3548 case LambdaExprClass: {
3549 const LambdaExpr *LE = cast<LambdaExpr>(this);
3550 for (Expr *E : LE->capture_inits())
3551 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3556 case PseudoObjectExprClass: {
3557 // Only look for side-effects in the semantic form, and look past
3558 // OpaqueValueExpr bindings in that form.
3559 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3560 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3561 E = PO->semantics_end();
3563 const Expr *Subexpr = *I;
3564 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3565 Subexpr = OVE->getSourceExpr();
3566 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3572 case ObjCBoxedExprClass:
3573 case ObjCArrayLiteralClass:
3574 case ObjCDictionaryLiteralClass:
3575 case ObjCSelectorExprClass:
3576 case ObjCProtocolExprClass:
3577 case ObjCIsaExprClass:
3578 case ObjCIndirectCopyRestoreExprClass:
3579 case ObjCSubscriptRefExprClass:
3580 case ObjCBridgedCastExprClass:
3581 case ObjCMessageExprClass:
3582 case ObjCPropertyRefExprClass:
3583 // FIXME: Classify these cases better.
3584 if (IncludePossibleEffects)
3589 // Recurse to children.
3590 for (const Stmt *SubStmt : children())
3592 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3599 /// Look for a call to a non-trivial function within an expression.
3600 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3602 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3607 explicit NonTrivialCallFinder(const ASTContext &Context)
3608 : Inherited(Context), NonTrivial(false) { }
3610 bool hasNonTrivialCall() const { return NonTrivial; }
3612 void VisitCallExpr(const CallExpr *E) {
3613 if (const CXXMethodDecl *Method
3614 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3615 if (Method->isTrivial()) {
3616 // Recurse to children of the call.
3617 Inherited::VisitStmt(E);
3625 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3626 if (E->getConstructor()->isTrivial()) {
3627 // Recurse to children of the call.
3628 Inherited::VisitStmt(E);
3635 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3636 if (E->getTemporary()->getDestructor()->isTrivial()) {
3637 Inherited::VisitStmt(E);
3646 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3647 NonTrivialCallFinder Finder(Ctx);
3649 return Finder.hasNonTrivialCall();
3652 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3653 /// pointer constant or not, as well as the specific kind of constant detected.
3654 /// Null pointer constants can be integer constant expressions with the
3655 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3656 /// (a GNU extension).
3657 Expr::NullPointerConstantKind
3658 Expr::isNullPointerConstant(ASTContext &Ctx,
3659 NullPointerConstantValueDependence NPC) const {
3660 if (isValueDependent() &&
3661 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3663 case NPC_NeverValueDependent:
3664 llvm_unreachable("Unexpected value dependent expression!");
3665 case NPC_ValueDependentIsNull:
3666 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3667 return NPCK_ZeroExpression;
3669 return NPCK_NotNull;
3671 case NPC_ValueDependentIsNotNull:
3672 return NPCK_NotNull;
3676 // Strip off a cast to void*, if it exists. Except in C++.
3677 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3678 if (!Ctx.getLangOpts().CPlusPlus) {
3679 // Check that it is a cast to void*.
3680 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3681 QualType Pointee = PT->getPointeeType();
3682 Qualifiers Qs = Pointee.getQualifiers();
3683 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3684 // has non-default address space it is not treated as nullptr.
3685 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3686 // since it cannot be assigned to a pointer to constant address space.
3687 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3688 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3689 (Ctx.getLangOpts().OpenCL &&
3690 Ctx.getLangOpts().OpenCLVersion < 200 &&
3691 Pointee.getAddressSpace() == LangAS::opencl_private))
3692 Qs.removeAddressSpace();
3694 if (Pointee->isVoidType() && Qs.empty() && // to void*
3695 CE->getSubExpr()->getType()->isIntegerType()) // from int
3696 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3699 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3700 // Ignore the ImplicitCastExpr type entirely.
3701 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3702 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3703 // Accept ((void*)0) as a null pointer constant, as many other
3704 // implementations do.
3705 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3706 } else if (const GenericSelectionExpr *GE =
3707 dyn_cast<GenericSelectionExpr>(this)) {
3708 if (GE->isResultDependent())
3709 return NPCK_NotNull;
3710 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3711 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3712 if (CE->isConditionDependent())
3713 return NPCK_NotNull;
3714 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3715 } else if (const CXXDefaultArgExpr *DefaultArg
3716 = dyn_cast<CXXDefaultArgExpr>(this)) {
3717 // See through default argument expressions.
3718 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3719 } else if (const CXXDefaultInitExpr *DefaultInit
3720 = dyn_cast<CXXDefaultInitExpr>(this)) {
3721 // See through default initializer expressions.
3722 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3723 } else if (isa<GNUNullExpr>(this)) {
3724 // The GNU __null extension is always a null pointer constant.
3725 return NPCK_GNUNull;
3726 } else if (const MaterializeTemporaryExpr *M
3727 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3728 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3729 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3730 if (const Expr *Source = OVE->getSourceExpr())
3731 return Source->isNullPointerConstant(Ctx, NPC);
3734 // C++11 nullptr_t is always a null pointer constant.
3735 if (getType()->isNullPtrType())
3736 return NPCK_CXX11_nullptr;
3738 if (const RecordType *UT = getType()->getAsUnionType())
3739 if (!Ctx.getLangOpts().CPlusPlus11 &&
3740 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3741 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3742 const Expr *InitExpr = CLE->getInitializer();
3743 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3744 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3746 // This expression must be an integer type.
3747 if (!getType()->isIntegerType() ||
3748 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3749 return NPCK_NotNull;
3751 if (Ctx.getLangOpts().CPlusPlus11) {
3752 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3753 // value zero or a prvalue of type std::nullptr_t.
3754 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3755 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3756 if (Lit && !Lit->getValue())
3757 return NPCK_ZeroLiteral;
3758 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3759 return NPCK_NotNull;
3761 // If we have an integer constant expression, we need to *evaluate* it and
3762 // test for the value 0.
3763 if (!isIntegerConstantExpr(Ctx))
3764 return NPCK_NotNull;
3767 if (EvaluateKnownConstInt(Ctx) != 0)
3768 return NPCK_NotNull;
3770 if (isa<IntegerLiteral>(this))
3771 return NPCK_ZeroLiteral;
3772 return NPCK_ZeroExpression;
3775 /// If this expression is an l-value for an Objective C
3776 /// property, find the underlying property reference expression.
3777 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3778 const Expr *E = this;
3780 assert((E->getValueKind() == VK_LValue &&
3781 E->getObjectKind() == OK_ObjCProperty) &&
3782 "expression is not a property reference");
3783 E = E->IgnoreParenCasts();
3784 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3785 if (BO->getOpcode() == BO_Comma) {
3794 return cast<ObjCPropertyRefExpr>(E);
3797 bool Expr::isObjCSelfExpr() const {
3798 const Expr *E = IgnoreParenImpCasts();
3800 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3804 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3808 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3812 return M->getSelfDecl() == Param;
3815 FieldDecl *Expr::getSourceBitField() {
3816 Expr *E = this->IgnoreParens();
3818 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3819 if (ICE->getCastKind() == CK_LValueToRValue ||
3820 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3821 E = ICE->getSubExpr()->IgnoreParens();
3826 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3827 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3828 if (Field->isBitField())
3831 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3832 FieldDecl *Ivar = IvarRef->getDecl();
3833 if (Ivar->isBitField())
3837 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3838 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3839 if (Field->isBitField())
3842 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3843 if (Expr *E = BD->getBinding())
3844 return E->getSourceBitField();
3847 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3848 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3849 return BinOp->getLHS()->getSourceBitField();
3851 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3852 return BinOp->getRHS()->getSourceBitField();
3855 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3856 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3857 return UnOp->getSubExpr()->getSourceBitField();
3862 bool Expr::refersToVectorElement() const {
3863 // FIXME: Why do we not just look at the ObjectKind here?
3864 const Expr *E = this->IgnoreParens();
3866 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3867 if (ICE->getValueKind() != VK_RValue &&
3868 ICE->getCastKind() == CK_NoOp)
3869 E = ICE->getSubExpr()->IgnoreParens();
3874 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3875 return ASE->getBase()->getType()->isVectorType();
3877 if (isa<ExtVectorElementExpr>(E))
3880 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3881 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3882 if (auto *E = BD->getBinding())
3883 return E->refersToVectorElement();
3888 bool Expr::refersToGlobalRegisterVar() const {
3889 const Expr *E = this->IgnoreParenImpCasts();
3891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3892 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3893 if (VD->getStorageClass() == SC_Register &&
3894 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3900 /// isArrow - Return true if the base expression is a pointer to vector,
3901 /// return false if the base expression is a vector.
3902 bool ExtVectorElementExpr::isArrow() const {
3903 return getBase()->getType()->isPointerType();
3906 unsigned ExtVectorElementExpr::getNumElements() const {
3907 if (const VectorType *VT = getType()->getAs<VectorType>())
3908 return VT->getNumElements();
3912 /// containsDuplicateElements - Return true if any element access is repeated.
3913 bool ExtVectorElementExpr::containsDuplicateElements() const {
3914 // FIXME: Refactor this code to an accessor on the AST node which returns the
3915 // "type" of component access, and share with code below and in Sema.
3916 StringRef Comp = Accessor->getName();
3918 // Halving swizzles do not contain duplicate elements.
3919 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3922 // Advance past s-char prefix on hex swizzles.
3923 if (Comp[0] == 's' || Comp[0] == 'S')
3924 Comp = Comp.substr(1);
3926 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3927 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3933 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3934 void ExtVectorElementExpr::getEncodedElementAccess(
3935 SmallVectorImpl<uint32_t> &Elts) const {
3936 StringRef Comp = Accessor->getName();
3937 bool isNumericAccessor = false;
3938 if (Comp[0] == 's' || Comp[0] == 'S') {
3939 Comp = Comp.substr(1);
3940 isNumericAccessor = true;
3943 bool isHi = Comp == "hi";
3944 bool isLo = Comp == "lo";
3945 bool isEven = Comp == "even";
3946 bool isOdd = Comp == "odd";
3948 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3960 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3962 Elts.push_back(Index);
3966 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
3967 QualType Type, SourceLocation BLoc,
3969 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3970 Type->isDependentType(), Type->isDependentType(),
3971 Type->isInstantiationDependentType(),
3972 Type->containsUnexpandedParameterPack()),
3973 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3975 SubExprs = new (C) Stmt*[args.size()];
3976 for (unsigned i = 0; i != args.size(); i++) {
3977 if (args[i]->isTypeDependent())
3978 ExprBits.TypeDependent = true;
3979 if (args[i]->isValueDependent())
3980 ExprBits.ValueDependent = true;
3981 if (args[i]->isInstantiationDependent())
3982 ExprBits.InstantiationDependent = true;
3983 if (args[i]->containsUnexpandedParameterPack())
3984 ExprBits.ContainsUnexpandedParameterPack = true;
3986 SubExprs[i] = args[i];
3990 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
3991 if (SubExprs) C.Deallocate(SubExprs);
3993 this->NumExprs = Exprs.size();
3994 SubExprs = new (C) Stmt*[NumExprs];
3995 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3998 GenericSelectionExpr::GenericSelectionExpr(
3999 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4000 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4001 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4002 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4003 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4004 AssocExprs[ResultIndex]->getValueKind(),
4005 AssocExprs[ResultIndex]->getObjectKind(),
4006 AssocExprs[ResultIndex]->isTypeDependent(),
4007 AssocExprs[ResultIndex]->isValueDependent(),
4008 AssocExprs[ResultIndex]->isInstantiationDependent(),
4009 ContainsUnexpandedParameterPack),
4010 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4011 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4012 assert(AssocTypes.size() == AssocExprs.size() &&
4013 "Must have the same number of association expressions"
4014 " and TypeSourceInfo!");
4015 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4017 GenericSelectionExprBits.GenericLoc = GenericLoc;
4018 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4019 std::copy(AssocExprs.begin(), AssocExprs.end(),
4020 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4021 std::copy(AssocTypes.begin(), AssocTypes.end(),
4022 getTrailingObjects<TypeSourceInfo *>());
4025 GenericSelectionExpr::GenericSelectionExpr(
4026 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4027 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4028 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4029 bool ContainsUnexpandedParameterPack)
4030 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4032 /*isTypeDependent=*/true,
4033 /*isValueDependent=*/true,
4034 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4035 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4036 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4037 assert(AssocTypes.size() == AssocExprs.size() &&
4038 "Must have the same number of association expressions"
4039 " and TypeSourceInfo!");
4041 GenericSelectionExprBits.GenericLoc = GenericLoc;
4042 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4043 std::copy(AssocExprs.begin(), AssocExprs.end(),
4044 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4045 std::copy(AssocTypes.begin(), AssocTypes.end(),
4046 getTrailingObjects<TypeSourceInfo *>());
4049 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4050 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4052 GenericSelectionExpr *GenericSelectionExpr::Create(
4053 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4054 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4055 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4056 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4057 unsigned NumAssocs = AssocExprs.size();
4058 void *Mem = Context.Allocate(
4059 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4060 alignof(GenericSelectionExpr));
4061 return new (Mem) GenericSelectionExpr(
4062 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4063 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4066 GenericSelectionExpr *GenericSelectionExpr::Create(
4067 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4068 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4069 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4070 bool ContainsUnexpandedParameterPack) {
4071 unsigned NumAssocs = AssocExprs.size();
4072 void *Mem = Context.Allocate(
4073 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4074 alignof(GenericSelectionExpr));
4075 return new (Mem) GenericSelectionExpr(
4076 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4077 RParenLoc, ContainsUnexpandedParameterPack);
4080 GenericSelectionExpr *
4081 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4082 unsigned NumAssocs) {
4083 void *Mem = Context.Allocate(
4084 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4085 alignof(GenericSelectionExpr));
4086 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4089 //===----------------------------------------------------------------------===//
4090 // DesignatedInitExpr
4091 //===----------------------------------------------------------------------===//
4093 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4094 assert(Kind == FieldDesignator && "Only valid on a field designator");
4095 if (Field.NameOrField & 0x01)
4096 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4098 return getField()->getIdentifier();
4101 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4102 llvm::ArrayRef<Designator> Designators,
4103 SourceLocation EqualOrColonLoc,
4105 ArrayRef<Expr*> IndexExprs,
4107 : Expr(DesignatedInitExprClass, Ty,
4108 Init->getValueKind(), Init->getObjectKind(),
4109 Init->isTypeDependent(), Init->isValueDependent(),
4110 Init->isInstantiationDependent(),
4111 Init->containsUnexpandedParameterPack()),
4112 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4113 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4114 this->Designators = new (C) Designator[NumDesignators];
4116 // Record the initializer itself.
4117 child_iterator Child = child_begin();
4120 // Copy the designators and their subexpressions, computing
4121 // value-dependence along the way.
4122 unsigned IndexIdx = 0;
4123 for (unsigned I = 0; I != NumDesignators; ++I) {
4124 this->Designators[I] = Designators[I];
4126 if (this->Designators[I].isArrayDesignator()) {
4127 // Compute type- and value-dependence.
4128 Expr *Index = IndexExprs[IndexIdx];
4129 if (Index->isTypeDependent() || Index->isValueDependent())
4130 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4131 if (Index->isInstantiationDependent())
4132 ExprBits.InstantiationDependent = true;
4133 // Propagate unexpanded parameter packs.
4134 if (Index->containsUnexpandedParameterPack())
4135 ExprBits.ContainsUnexpandedParameterPack = true;
4137 // Copy the index expressions into permanent storage.
4138 *Child++ = IndexExprs[IndexIdx++];
4139 } else if (this->Designators[I].isArrayRangeDesignator()) {
4140 // Compute type- and value-dependence.
4141 Expr *Start = IndexExprs[IndexIdx];
4142 Expr *End = IndexExprs[IndexIdx + 1];
4143 if (Start->isTypeDependent() || Start->isValueDependent() ||
4144 End->isTypeDependent() || End->isValueDependent()) {
4145 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4146 ExprBits.InstantiationDependent = true;
4147 } else if (Start->isInstantiationDependent() ||
4148 End->isInstantiationDependent()) {
4149 ExprBits.InstantiationDependent = true;
4152 // Propagate unexpanded parameter packs.
4153 if (Start->containsUnexpandedParameterPack() ||
4154 End->containsUnexpandedParameterPack())
4155 ExprBits.ContainsUnexpandedParameterPack = true;
4157 // Copy the start/end expressions into permanent storage.
4158 *Child++ = IndexExprs[IndexIdx++];
4159 *Child++ = IndexExprs[IndexIdx++];
4163 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4166 DesignatedInitExpr *
4167 DesignatedInitExpr::Create(const ASTContext &C,
4168 llvm::ArrayRef<Designator> Designators,
4169 ArrayRef<Expr*> IndexExprs,
4170 SourceLocation ColonOrEqualLoc,
4171 bool UsesColonSyntax, Expr *Init) {
4172 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4173 alignof(DesignatedInitExpr));
4174 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4175 ColonOrEqualLoc, UsesColonSyntax,
4179 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4180 unsigned NumIndexExprs) {
4181 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4182 alignof(DesignatedInitExpr));
4183 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4186 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4187 const Designator *Desigs,
4188 unsigned NumDesigs) {
4189 Designators = new (C) Designator[NumDesigs];
4190 NumDesignators = NumDesigs;
4191 for (unsigned I = 0; I != NumDesigs; ++I)
4192 Designators[I] = Desigs[I];
4195 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4196 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4198 return DIE->getDesignator(0)->getSourceRange();
4199 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4200 DIE->getDesignator(size() - 1)->getEndLoc());
4203 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4204 SourceLocation StartLoc;
4205 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4206 Designator &First = *DIE->getDesignator(0);
4207 if (First.isFieldDesignator()) {
4209 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4211 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4214 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
4218 SourceLocation DesignatedInitExpr::getEndLoc() const {
4219 return getInit()->getEndLoc();
4222 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4223 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4224 return getSubExpr(D.ArrayOrRange.Index + 1);
4227 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4228 assert(D.Kind == Designator::ArrayRangeDesignator &&
4229 "Requires array range designator");
4230 return getSubExpr(D.ArrayOrRange.Index + 1);
4233 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4234 assert(D.Kind == Designator::ArrayRangeDesignator &&
4235 "Requires array range designator");
4236 return getSubExpr(D.ArrayOrRange.Index + 2);
4239 /// Replaces the designator at index @p Idx with the series
4240 /// of designators in [First, Last).
4241 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4242 const Designator *First,
4243 const Designator *Last) {
4244 unsigned NumNewDesignators = Last - First;
4245 if (NumNewDesignators == 0) {
4246 std::copy_backward(Designators + Idx + 1,
4247 Designators + NumDesignators,
4249 --NumNewDesignators;
4251 } else if (NumNewDesignators == 1) {
4252 Designators[Idx] = *First;
4256 Designator *NewDesignators
4257 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4258 std::copy(Designators, Designators + Idx, NewDesignators);
4259 std::copy(First, Last, NewDesignators + Idx);
4260 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4261 NewDesignators + Idx + NumNewDesignators);
4262 Designators = NewDesignators;
4263 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4266 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4267 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4268 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4269 OK_Ordinary, false, false, false, false) {
4270 BaseAndUpdaterExprs[0] = baseExpr;
4272 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4273 ILE->setType(baseExpr->getType());
4274 BaseAndUpdaterExprs[1] = ILE;
4277 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4278 return getBase()->getBeginLoc();
4281 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4282 return getBase()->getEndLoc();
4285 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4286 SourceLocation RParenLoc)
4287 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4289 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4290 ParenListExprBits.NumExprs = Exprs.size();
4292 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4293 if (Exprs[I]->isTypeDependent())
4294 ExprBits.TypeDependent = true;
4295 if (Exprs[I]->isValueDependent())
4296 ExprBits.ValueDependent = true;
4297 if (Exprs[I]->isInstantiationDependent())
4298 ExprBits.InstantiationDependent = true;
4299 if (Exprs[I]->containsUnexpandedParameterPack())
4300 ExprBits.ContainsUnexpandedParameterPack = true;
4302 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4306 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4307 : Expr(ParenListExprClass, Empty) {
4308 ParenListExprBits.NumExprs = NumExprs;
4311 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4312 SourceLocation LParenLoc,
4313 ArrayRef<Expr *> Exprs,
4314 SourceLocation RParenLoc) {
4315 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4316 alignof(ParenListExpr));
4317 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4320 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4321 unsigned NumExprs) {
4323 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4324 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4327 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4328 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4329 e = ewc->getSubExpr();
4330 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4331 e = m->GetTemporaryExpr();
4332 e = cast<CXXConstructExpr>(e)->getArg(0);
4333 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4334 e = ice->getSubExpr();
4335 return cast<OpaqueValueExpr>(e);
4338 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4340 unsigned numSemanticExprs) {
4342 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4343 alignof(PseudoObjectExpr));
4344 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4347 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4348 : Expr(PseudoObjectExprClass, shell) {
4349 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4352 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4353 ArrayRef<Expr*> semantics,
4354 unsigned resultIndex) {
4355 assert(syntax && "no syntactic expression!");
4356 assert(semantics.size() && "no semantic expressions!");
4360 if (resultIndex == NoResult) {
4364 assert(resultIndex < semantics.size());
4365 type = semantics[resultIndex]->getType();
4366 VK = semantics[resultIndex]->getValueKind();
4367 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4370 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4371 alignof(PseudoObjectExpr));
4372 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4376 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4377 Expr *syntax, ArrayRef<Expr*> semantics,
4378 unsigned resultIndex)
4379 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4380 /*filled in at end of ctor*/ false, false, false, false) {
4381 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4382 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4384 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4385 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4386 getSubExprsBuffer()[i] = E;
4388 if (E->isTypeDependent())
4389 ExprBits.TypeDependent = true;
4390 if (E->isValueDependent())
4391 ExprBits.ValueDependent = true;
4392 if (E->isInstantiationDependent())
4393 ExprBits.InstantiationDependent = true;
4394 if (E->containsUnexpandedParameterPack())
4395 ExprBits.ContainsUnexpandedParameterPack = true;
4397 if (isa<OpaqueValueExpr>(E))
4398 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4399 "opaque-value semantic expressions for pseudo-object "
4400 "operations must have sources");
4404 //===----------------------------------------------------------------------===//
4405 // Child Iterators for iterating over subexpressions/substatements
4406 //===----------------------------------------------------------------------===//
4408 // UnaryExprOrTypeTraitExpr
4409 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4410 const_child_range CCR =
4411 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4412 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4415 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4416 // If this is of a type and the type is a VLA type (and not a typedef), the
4417 // size expression of the VLA needs to be treated as an executable expression.
4418 // Why isn't this weirdness documented better in StmtIterator?
4419 if (isArgumentType()) {
4420 if (const VariableArrayType *T =
4421 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4422 return const_child_range(const_child_iterator(T), const_child_iterator());
4423 return const_child_range(const_child_iterator(), const_child_iterator());
4425 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4428 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
4429 QualType t, AtomicOp op, SourceLocation RP)
4430 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4431 false, false, false, false),
4432 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4434 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4435 for (unsigned i = 0; i != args.size(); i++) {
4436 if (args[i]->isTypeDependent())
4437 ExprBits.TypeDependent = true;
4438 if (args[i]->isValueDependent())
4439 ExprBits.ValueDependent = true;
4440 if (args[i]->isInstantiationDependent())
4441 ExprBits.InstantiationDependent = true;
4442 if (args[i]->containsUnexpandedParameterPack())
4443 ExprBits.ContainsUnexpandedParameterPack = true;
4445 SubExprs[i] = args[i];
4449 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4451 case AO__c11_atomic_init:
4452 case AO__opencl_atomic_init:
4453 case AO__c11_atomic_load:
4454 case AO__atomic_load_n:
4457 case AO__opencl_atomic_load:
4458 case AO__c11_atomic_store:
4459 case AO__c11_atomic_exchange:
4460 case AO__atomic_load:
4461 case AO__atomic_store:
4462 case AO__atomic_store_n:
4463 case AO__atomic_exchange_n:
4464 case AO__c11_atomic_fetch_add:
4465 case AO__c11_atomic_fetch_sub:
4466 case AO__c11_atomic_fetch_and:
4467 case AO__c11_atomic_fetch_or:
4468 case AO__c11_atomic_fetch_xor:
4469 case AO__atomic_fetch_add:
4470 case AO__atomic_fetch_sub:
4471 case AO__atomic_fetch_and:
4472 case AO__atomic_fetch_or:
4473 case AO__atomic_fetch_xor:
4474 case AO__atomic_fetch_nand:
4475 case AO__atomic_add_fetch:
4476 case AO__atomic_sub_fetch:
4477 case AO__atomic_and_fetch:
4478 case AO__atomic_or_fetch:
4479 case AO__atomic_xor_fetch:
4480 case AO__atomic_nand_fetch:
4481 case AO__atomic_fetch_min:
4482 case AO__atomic_fetch_max:
4485 case AO__opencl_atomic_store:
4486 case AO__opencl_atomic_exchange:
4487 case AO__opencl_atomic_fetch_add:
4488 case AO__opencl_atomic_fetch_sub:
4489 case AO__opencl_atomic_fetch_and:
4490 case AO__opencl_atomic_fetch_or:
4491 case AO__opencl_atomic_fetch_xor:
4492 case AO__opencl_atomic_fetch_min:
4493 case AO__opencl_atomic_fetch_max:
4494 case AO__atomic_exchange:
4497 case AO__c11_atomic_compare_exchange_strong:
4498 case AO__c11_atomic_compare_exchange_weak:
4501 case AO__opencl_atomic_compare_exchange_strong:
4502 case AO__opencl_atomic_compare_exchange_weak:
4503 case AO__atomic_compare_exchange:
4504 case AO__atomic_compare_exchange_n:
4507 llvm_unreachable("unknown atomic op");
4510 QualType AtomicExpr::getValueType() const {
4511 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4512 if (auto AT = T->getAs<AtomicType>())
4513 return AT->getValueType();
4517 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4518 unsigned ArraySectionCount = 0;
4519 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4520 Base = OASE->getBase();
4521 ++ArraySectionCount;
4524 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4525 Base = ASE->getBase();
4526 ++ArraySectionCount;
4528 Base = Base->IgnoreParenImpCasts();
4529 auto OriginalTy = Base->getType();
4530 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4531 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4532 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4534 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4535 if (OriginalTy->isAnyPointerType())
4536 OriginalTy = OriginalTy->getPointeeType();
4538 assert (OriginalTy->isArrayType());
4539 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();