1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8// 9// This file defines the Expr interface and subclasses. 10// 11//===----------------------------------------------------------------------===// 12 13#ifndef LLVM_CLANG_AST_EXPR_H 14#define LLVM_CLANG_AST_EXPR_H 15 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTVector.h" 18#include "clang/AST/ComputeDependence.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclAccessPair.h" 21#include "clang/AST/DependenceFlags.h" 22#include "clang/AST/OperationKinds.h" 23#include "clang/AST/Stmt.h" 24#include "clang/AST/TemplateBase.h" 25#include "clang/AST/Type.h" 26#include "clang/Basic/CharInfo.h" 27#include "clang/Basic/FixedPoint.h" 28#include "clang/Basic/LangOptions.h" 29#include "clang/Basic/SyncScope.h" 30#include "clang/Basic/TypeTraits.h" 31#include "llvm/ADT/APFloat.h" 32#include "llvm/ADT/APSInt.h" 33#include "llvm/ADT/SmallVector.h" 34#include "llvm/ADT/StringRef.h" 35#include "llvm/ADT/iterator.h" 36#include "llvm/ADT/iterator_range.h" 37#include "llvm/Support/AtomicOrdering.h" 38#include "llvm/Support/Compiler.h" 39#include "llvm/Support/TrailingObjects.h" 40 41namespace clang { 42 class APValue; 43 class ASTContext; 44 class BlockDecl; 45 class CXXBaseSpecifier; 46 class CXXMemberCallExpr; 47 class CXXOperatorCallExpr; 48 class CastExpr; 49 class Decl; 50 class IdentifierInfo; 51 class MaterializeTemporaryExpr; 52 class NamedDecl; 53 class ObjCPropertyRefExpr; 54 class OpaqueValueExpr; 55 class ParmVarDecl; 56 class StringLiteral; 57 class TargetInfo; 58 class ValueDecl; 59 60/// A simple array of base specifiers. 61typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 62 63/// An adjustment to be made to the temporary created when emitting a 64/// reference binding, which accesses a particular subobject of that temporary. 65struct SubobjectAdjustment { 66 enum { 67 DerivedToBaseAdjustment, 68 FieldAdjustment, 69 MemberPointerAdjustment 70 } Kind; 71 72 struct DTB { 73 const CastExpr *BasePath; 74 const CXXRecordDecl *DerivedClass; 75 }; 76 77 struct P { 78 const MemberPointerType *MPT; 79 Expr *RHS; 80 }; 81 82 union { 83 struct DTB DerivedToBase; 84 FieldDecl *Field; 85 struct P Ptr; 86 }; 87 88 SubobjectAdjustment(const CastExpr *BasePath, 89 const CXXRecordDecl *DerivedClass) 90 : Kind(DerivedToBaseAdjustment) { 91 DerivedToBase.BasePath = BasePath; 92 DerivedToBase.DerivedClass = DerivedClass; 93 } 94 95 SubobjectAdjustment(FieldDecl *Field) 96 : Kind(FieldAdjustment) { 97 this->Field = Field; 98 } 99 100 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) 101 : Kind(MemberPointerAdjustment) { 102 this->Ptr.MPT = MPT; 103 this->Ptr.RHS = RHS; 104 } 105}; 106 107/// This represents one expression. Note that Expr's are subclasses of Stmt. 108/// This allows an expression to be transparently used any place a Stmt is 109/// required. 110class Expr : public ValueStmt { 111 QualType TR; 112 113public: 114 Expr() = delete; 115 Expr(const Expr&) = delete; 116 Expr(Expr &&) = delete; 117 Expr &operator=(const Expr&) = delete; 118 Expr &operator=(Expr&&) = delete; 119 120protected: 121 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK) 122 : ValueStmt(SC) { 123 ExprBits.Dependent = 0; 124 ExprBits.ValueKind = VK; 125 ExprBits.ObjectKind = OK; 126 assert(ExprBits.ObjectKind == OK && "truncated kind"); 127 setType(T); 128 } 129 130 /// Construct an empty expression. 131 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { } 132 133 /// Each concrete expr subclass is expected to compute its dependence and call 134 /// this in the constructor. 135 void setDependence(ExprDependence Deps) { 136 ExprBits.Dependent = static_cast<unsigned>(Deps); 137 } 138 friend class ASTImporter; // Sets dependence dircetly. 139 friend class ASTStmtReader; // Sets dependence dircetly. 140 141public: 142 QualType getType() const { return TR; } 143 void setType(QualType t) { 144 // In C++, the type of an expression is always adjusted so that it 145 // will not have reference type (C++ [expr]p6). Use 146 // QualType::getNonReferenceType() to retrieve the non-reference 147 // type. Additionally, inspect Expr::isLvalue to determine whether 148 // an expression that is adjusted in this manner should be 149 // considered an lvalue. 150 assert((t.isNull() || !t->isReferenceType()) && 151 "Expressions can't have reference type"); 152 153 TR = t; 154 } 155 156 ExprDependence getDependence() const { 157 return static_cast<ExprDependence>(ExprBits.Dependent); 158 } 159 160 /// Determines whether the value of this expression depends on 161 /// - a template parameter (C++ [temp.dep.constexpr]) 162 /// - or an error, whose resolution is unknown 163 /// 164 /// For example, the array bound of "Chars" in the following example is 165 /// value-dependent. 166 /// @code 167 /// template<int Size, char (&Chars)[Size]> struct meta_string; 168 /// @endcode 169 bool isValueDependent() const { 170 return static_cast<bool>(getDependence() & ExprDependence::Value); 171 } 172 173 /// Determines whether the type of this expression depends on 174 /// - a template paramter (C++ [temp.dep.expr], which means that its type 175 /// could change from one template instantiation to the next) 176 /// - or an error 177 /// 178 /// For example, the expressions "x" and "x + y" are type-dependent in 179 /// the following code, but "y" is not type-dependent: 180 /// @code 181 /// template<typename T> 182 /// void add(T x, int y) { 183 /// x + y; 184 /// } 185 /// @endcode 186 bool isTypeDependent() const { 187 return static_cast<bool>(getDependence() & ExprDependence::Type); 188 } 189 190 /// Whether this expression is instantiation-dependent, meaning that 191 /// it depends in some way on 192 /// - a template parameter (even if neither its type nor (constant) value 193 /// can change due to the template instantiation) 194 /// - or an error 195 /// 196 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 197 /// instantiation-dependent (since it involves a template parameter \c T), but 198 /// is neither type- nor value-dependent, since the type of the inner 199 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 200 /// \c sizeof is known. 201 /// 202 /// \code 203 /// template<typename T> 204 /// void f(T x, T y) { 205 /// sizeof(sizeof(T() + T()); 206 /// } 207 /// \endcode 208 /// 209 /// \code 210 /// void func(int) { 211 /// func(); // the expression is instantiation-dependent, because it depends 212 /// // on an error. 213 /// } 214 /// \endcode 215 bool isInstantiationDependent() const { 216 return static_cast<bool>(getDependence() & ExprDependence::Instantiation); 217 } 218 219 /// Whether this expression contains an unexpanded parameter 220 /// pack (for C++11 variadic templates). 221 /// 222 /// Given the following function template: 223 /// 224 /// \code 225 /// template<typename F, typename ...Types> 226 /// void forward(const F &f, Types &&...args) { 227 /// f(static_cast<Types&&>(args)...); 228 /// } 229 /// \endcode 230 /// 231 /// The expressions \c args and \c static_cast<Types&&>(args) both 232 /// contain parameter packs. 233 bool containsUnexpandedParameterPack() const { 234 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack); 235 } 236 237 /// Whether this expression contains subexpressions which had errors, e.g. a 238 /// TypoExpr. 239 bool containsErrors() const { 240 return static_cast<bool>(getDependence() & ExprDependence::Error); 241 } 242 243 /// getExprLoc - Return the preferred location for the arrow when diagnosing 244 /// a problem with a generic expression. 245 SourceLocation getExprLoc() const LLVM_READONLY; 246 247 /// Determine whether an lvalue-to-rvalue conversion should implicitly be 248 /// applied to this expression if it appears as a discarded-value expression 249 /// in C++11 onwards. This applies to certain forms of volatile glvalues. 250 bool isReadIfDiscardedInCPlusPlus11() const; 251 252 /// isUnusedResultAWarning - Return true if this immediate expression should 253 /// be warned about if the result is unused. If so, fill in expr, location, 254 /// and ranges with expr to warn on and source locations/ranges appropriate 255 /// for a warning. 256 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, 257 SourceRange &R1, SourceRange &R2, 258 ASTContext &Ctx) const; 259 260 /// isLValue - True if this expression is an "l-value" according to 261 /// the rules of the current language. C and C++ give somewhat 262 /// different rules for this concept, but in general, the result of 263 /// an l-value expression identifies a specific object whereas the 264 /// result of an r-value expression is a value detached from any 265 /// specific storage. 266 /// 267 /// C++11 divides the concept of "r-value" into pure r-values 268 /// ("pr-values") and so-called expiring values ("x-values"), which 269 /// identify specific objects that can be safely cannibalized for 270 /// their resources. This is an unfortunate abuse of terminology on 271 /// the part of the C++ committee. In Clang, when we say "r-value", 272 /// we generally mean a pr-value. 273 bool isLValue() const { return getValueKind() == VK_LValue; } 274 bool isRValue() const { return getValueKind() == VK_RValue; } 275 bool isXValue() const { return getValueKind() == VK_XValue; } 276 bool isGLValue() const { return getValueKind() != VK_RValue; } 277 278 enum LValueClassification { 279 LV_Valid, 280 LV_NotObjectType, 281 LV_IncompleteVoidType, 282 LV_DuplicateVectorComponents, 283 LV_InvalidExpression, 284 LV_InvalidMessageExpression, 285 LV_MemberFunction, 286 LV_SubObjCPropertySetting, 287 LV_ClassTemporary, 288 LV_ArrayTemporary 289 }; 290 /// Reasons why an expression might not be an l-value. 291 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 292 293 enum isModifiableLvalueResult { 294 MLV_Valid, 295 MLV_NotObjectType, 296 MLV_IncompleteVoidType, 297 MLV_DuplicateVectorComponents, 298 MLV_InvalidExpression, 299 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 300 MLV_IncompleteType, 301 MLV_ConstQualified, 302 MLV_ConstQualifiedField, 303 MLV_ConstAddrSpace, 304 MLV_ArrayType, 305 MLV_NoSetterProperty, 306 MLV_MemberFunction, 307 MLV_SubObjCPropertySetting, 308 MLV_InvalidMessageExpression, 309 MLV_ClassTemporary, 310 MLV_ArrayTemporary 311 }; 312 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 313 /// does not have an incomplete type, does not have a const-qualified type, 314 /// and if it is a structure or union, does not have any member (including, 315 /// recursively, any member or element of all contained aggregates or unions) 316 /// with a const-qualified type. 317 /// 318 /// \param Loc [in,out] - A source location which *may* be filled 319 /// in with the location of the expression making this a 320 /// non-modifiable lvalue, if specified. 321 isModifiableLvalueResult 322 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; 323 324 /// The return type of classify(). Represents the C++11 expression 325 /// taxonomy. 326 class Classification { 327 public: 328 /// The various classification results. Most of these mean prvalue. 329 enum Kinds { 330 CL_LValue, 331 CL_XValue, 332 CL_Function, // Functions cannot be lvalues in C. 333 CL_Void, // Void cannot be an lvalue in C. 334 CL_AddressableVoid, // Void expression whose address can be taken in C. 335 CL_DuplicateVectorComponents, // A vector shuffle with dupes. 336 CL_MemberFunction, // An expression referring to a member function 337 CL_SubObjCPropertySetting, 338 CL_ClassTemporary, // A temporary of class type, or subobject thereof. 339 CL_ArrayTemporary, // A temporary of array type. 340 CL_ObjCMessageRValue, // ObjC message is an rvalue 341 CL_PRValue // A prvalue for any other reason, of any other type 342 }; 343 /// The results of modification testing. 344 enum ModifiableType { 345 CM_Untested, // testModifiable was false. 346 CM_Modifiable, 347 CM_RValue, // Not modifiable because it's an rvalue 348 CM_Function, // Not modifiable because it's a function; C++ only 349 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext 350 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter 351 CM_ConstQualified, 352 CM_ConstQualifiedField, 353 CM_ConstAddrSpace, 354 CM_ArrayType, 355 CM_IncompleteType 356 }; 357 358 private: 359 friend class Expr; 360 361 unsigned short Kind; 362 unsigned short Modifiable; 363 364 explicit Classification(Kinds k, ModifiableType m) 365 : Kind(k), Modifiable(m) 366 {} 367 368 public: 369 Classification() {} 370 371 Kinds getKind() const { return static_cast<Kinds>(Kind); } 372 ModifiableType getModifiable() const { 373 assert(Modifiable != CM_Untested && "Did not test for modifiability."); 374 return static_cast<ModifiableType>(Modifiable); 375 } 376 bool isLValue() const { return Kind == CL_LValue; } 377 bool isXValue() const { return Kind == CL_XValue; } 378 bool isGLValue() const { return Kind <= CL_XValue; } 379 bool isPRValue() const { return Kind >= CL_Function; } 380 bool isRValue() const { return Kind >= CL_XValue; } 381 bool isModifiable() const { return getModifiable() == CM_Modifiable; } 382 383 /// Create a simple, modifiably lvalue 384 static Classification makeSimpleLValue() { 385 return Classification(CL_LValue, CM_Modifiable); 386 } 387 388 }; 389 /// Classify - Classify this expression according to the C++11 390 /// expression taxonomy. 391 /// 392 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the 393 /// old lvalue vs rvalue. This function determines the type of expression this 394 /// is. There are three expression types: 395 /// - lvalues are classical lvalues as in C++03. 396 /// - prvalues are equivalent to rvalues in C++03. 397 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a 398 /// function returning an rvalue reference. 399 /// lvalues and xvalues are collectively referred to as glvalues, while 400 /// prvalues and xvalues together form rvalues. 401 Classification Classify(ASTContext &Ctx) const { 402 return ClassifyImpl(Ctx, nullptr); 403 } 404 405 /// ClassifyModifiable - Classify this expression according to the 406 /// C++11 expression taxonomy, and see if it is valid on the left side 407 /// of an assignment. 408 /// 409 /// This function extends classify in that it also tests whether the 410 /// expression is modifiable (C99 6.3.2.1p1). 411 /// \param Loc A source location that might be filled with a relevant location 412 /// if the expression is not modifiable. 413 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ 414 return ClassifyImpl(Ctx, &Loc); 415 } 416 417 /// getValueKindForType - Given a formal return or parameter type, 418 /// give its value kind. 419 static ExprValueKind getValueKindForType(QualType T) { 420 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 421 return (isa<LValueReferenceType>(RT) 422 ? VK_LValue 423 : (RT->getPointeeType()->isFunctionType() 424 ? VK_LValue : VK_XValue)); 425 return VK_RValue; 426 } 427 428 /// getValueKind - The value kind that this expression produces. 429 ExprValueKind getValueKind() const { 430 return static_cast<ExprValueKind>(ExprBits.ValueKind); 431 } 432 433 /// getObjectKind - The object kind that this expression produces. 434 /// Object kinds are meaningful only for expressions that yield an 435 /// l-value or x-value. 436 ExprObjectKind getObjectKind() const { 437 return static_cast<ExprObjectKind>(ExprBits.ObjectKind); 438 } 439 440 bool isOrdinaryOrBitFieldObject() const { 441 ExprObjectKind OK = getObjectKind(); 442 return (OK == OK_Ordinary || OK == OK_BitField); 443 } 444 445 /// setValueKind - Set the value kind produced by this expression. 446 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } 447 448 /// setObjectKind - Set the object kind produced by this expression. 449 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } 450 451private: 452 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 453 454public: 455 456 /// Returns true if this expression is a gl-value that 457 /// potentially refers to a bit-field. 458 /// 459 /// In C++, whether a gl-value refers to a bitfield is essentially 460 /// an aspect of the value-kind type system. 461 bool refersToBitField() const { return getObjectKind() == OK_BitField; } 462 463 /// If this expression refers to a bit-field, retrieve the 464 /// declaration of that bit-field. 465 /// 466 /// Note that this returns a non-null pointer in subtly different 467 /// places than refersToBitField returns true. In particular, this can 468 /// return a non-null pointer even for r-values loaded from 469 /// bit-fields, but it will return null for a conditional bit-field. 470 FieldDecl *getSourceBitField(); 471 472 const FieldDecl *getSourceBitField() const { 473 return const_cast<Expr*>(this)->getSourceBitField(); 474 } 475 476 Decl *getReferencedDeclOfCallee(); 477 const Decl *getReferencedDeclOfCallee() const { 478 return const_cast<Expr*>(this)->getReferencedDeclOfCallee(); 479 } 480 481 /// If this expression is an l-value for an Objective C 482 /// property, find the underlying property reference expression. 483 const ObjCPropertyRefExpr *getObjCProperty() const; 484 485 /// Check if this expression is the ObjC 'self' implicit parameter. 486 bool isObjCSelfExpr() const; 487 488 /// Returns whether this expression refers to a vector element. 489 bool refersToVectorElement() const; 490 491 /// Returns whether this expression refers to a matrix element. 492 bool refersToMatrixElement() const { 493 return getObjectKind() == OK_MatrixComponent; 494 } 495 496 /// Returns whether this expression refers to a global register 497 /// variable. 498 bool refersToGlobalRegisterVar() const; 499 500 /// Returns whether this expression has a placeholder type. 501 bool hasPlaceholderType() const { 502 return getType()->isPlaceholderType(); 503 } 504 505 /// Returns whether this expression has a specific placeholder type. 506 bool hasPlaceholderType(BuiltinType::Kind K) const { 507 assert(BuiltinType::isPlaceholderTypeKind(K)); 508 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) 509 return BT->getKind() == K; 510 return false; 511 } 512 513 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 514 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 515 /// but also int expressions which are produced by things like comparisons in 516 /// C. 517 /// 518 /// \param Semantic If true, only return true for expressions that are known 519 /// to be semantically boolean, which might not be true even for expressions 520 /// that are known to evaluate to 0/1. For instance, reading an unsigned 521 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily 522 /// semantically correspond to a bool. 523 bool isKnownToHaveBooleanValue(bool Semantic = true) const; 524 525 /// isIntegerConstantExpr - Return true if this expression is a valid integer 526 /// constant expression, and, if so, return its value in Result. If not a 527 /// valid i-c-e, return false and fill in Loc (if specified) with the location 528 /// of the invalid expression. 529 /// 530 /// Note: This does not perform the implicit conversions required by C++11 531 /// [expr.const]p5. 532 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, 533 SourceLocation *Loc = nullptr, 534 bool isEvaluated = true) const; 535 bool isIntegerConstantExpr(const ASTContext &Ctx, 536 SourceLocation *Loc = nullptr) const; 537 538 /// isCXX98IntegralConstantExpr - Return true if this expression is an 539 /// integral constant expression in C++98. Can only be used in C++. 540 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; 541 542 /// isCXX11ConstantExpr - Return true if this expression is a constant 543 /// expression in C++11. Can only be used in C++. 544 /// 545 /// Note: This does not perform the implicit conversions required by C++11 546 /// [expr.const]p5. 547 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, 548 SourceLocation *Loc = nullptr) const; 549 550 /// isPotentialConstantExpr - Return true if this function's definition 551 /// might be usable in a constant expression in C++11, if it were marked 552 /// constexpr. Return false if the function can never produce a constant 553 /// expression, along with diagnostics describing why not. 554 static bool isPotentialConstantExpr(const FunctionDecl *FD, 555 SmallVectorImpl< 556 PartialDiagnosticAt> &Diags); 557 558 /// isPotentialConstantExprUnevaluted - Return true if this expression might 559 /// be usable in a constant expression in C++11 in an unevaluated context, if 560 /// it were in function FD marked constexpr. Return false if the function can 561 /// never produce a constant expression, along with diagnostics describing 562 /// why not. 563 static bool isPotentialConstantExprUnevaluated(Expr *E, 564 const FunctionDecl *FD, 565 SmallVectorImpl< 566 PartialDiagnosticAt> &Diags); 567 568 /// isConstantInitializer - Returns true if this expression can be emitted to 569 /// IR as a constant, and thus can be used as a constant initializer in C. 570 /// If this expression is not constant and Culprit is non-null, 571 /// it is used to store the address of first non constant expr. 572 bool isConstantInitializer(ASTContext &Ctx, bool ForRef, 573 const Expr **Culprit = nullptr) const; 574 575 /// EvalStatus is a struct with detailed info about an evaluation in progress. 576 struct EvalStatus { 577 /// Whether the evaluated expression has side effects. 578 /// For example, (f() && 0) can be folded, but it still has side effects. 579 bool HasSideEffects; 580 581 /// Whether the evaluation hit undefined behavior. 582 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. 583 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. 584 bool HasUndefinedBehavior; 585 586 /// Diag - If this is non-null, it will be filled in with a stack of notes 587 /// indicating why evaluation failed (or why it failed to produce a constant 588 /// expression). 589 /// If the expression is unfoldable, the notes will indicate why it's not 590 /// foldable. If the expression is foldable, but not a constant expression, 591 /// the notes will describes why it isn't a constant expression. If the 592 /// expression *is* a constant expression, no notes will be produced. 593 SmallVectorImpl<PartialDiagnosticAt> *Diag; 594 595 EvalStatus() 596 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {} 597 598 // hasSideEffects - Return true if the evaluated expression has 599 // side effects. 600 bool hasSideEffects() const { 601 return HasSideEffects; 602 } 603 }; 604 605 /// EvalResult is a struct with detailed info about an evaluated expression. 606 struct EvalResult : EvalStatus { 607 /// Val - This is the value the expression can be folded to. 608 APValue Val; 609 610 // isGlobalLValue - Return true if the evaluated lvalue expression 611 // is global. 612 bool isGlobalLValue() const; 613 }; 614 615 /// EvaluateAsRValue - Return true if this is a constant which we can fold to 616 /// an rvalue using any crazy technique (that has nothing to do with language 617 /// standards) that we want to, even if the expression has side-effects. If 618 /// this function returns true, it returns the folded constant in Result. If 619 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be 620 /// applied. 621 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 622 bool InConstantContext = false) const; 623 624 /// EvaluateAsBooleanCondition - Return true if this is a constant 625 /// which we can fold and convert to a boolean condition using 626 /// any crazy technique that we want to, even if the expression has 627 /// side-effects. 628 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 629 bool InConstantContext = false) const; 630 631 enum SideEffectsKind { 632 SE_NoSideEffects, ///< Strictly evaluate the expression. 633 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not 634 ///< arbitrary unmodeled side effects. 635 SE_AllowSideEffects ///< Allow any unmodeled side effect. 636 }; 637 638 /// EvaluateAsInt - Return true if this is a constant which we can fold and 639 /// convert to an integer, using any crazy technique that we want to. 640 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 641 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 642 bool InConstantContext = false) const; 643 644 /// EvaluateAsFloat - Return true if this is a constant which we can fold and 645 /// convert to a floating point value, using any crazy technique that we 646 /// want to. 647 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, 648 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 649 bool InConstantContext = false) const; 650 651 /// EvaluateAsFloat - Return true if this is a constant which we can fold and 652 /// convert to a fixed point value. 653 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 654 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 655 bool InConstantContext = false) const; 656 657 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 658 /// constant folded without side-effects, but discard the result. 659 bool isEvaluatable(const ASTContext &Ctx, 660 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; 661 662 /// HasSideEffects - This routine returns true for all those expressions 663 /// which have any effect other than producing a value. Example is a function 664 /// call, volatile variable read, or throwing an exception. If 665 /// IncludePossibleEffects is false, this call treats certain expressions with 666 /// potential side effects (such as function call-like expressions, 667 /// instantiation-dependent expressions, or invocations from a macro) as not 668 /// having side effects. 669 bool HasSideEffects(const ASTContext &Ctx, 670 bool IncludePossibleEffects = true) const; 671 672 /// Determine whether this expression involves a call to any function 673 /// that is not trivial. 674 bool hasNonTrivialCall(const ASTContext &Ctx) const; 675 676 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded 677 /// integer. This must be called on an expression that constant folds to an 678 /// integer. 679 llvm::APSInt EvaluateKnownConstInt( 680 const ASTContext &Ctx, 681 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 682 683 llvm::APSInt EvaluateKnownConstIntCheckOverflow( 684 const ASTContext &Ctx, 685 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 686 687 void EvaluateForOverflow(const ASTContext &Ctx) const; 688 689 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an 690 /// lvalue with link time known address, with no side-effects. 691 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 692 bool InConstantContext = false) const; 693 694 /// EvaluateAsInitializer - Evaluate an expression as if it were the 695 /// initializer of the given declaration. Returns true if the initializer 696 /// can be folded to a constant, and produces any relevant notes. In C++11, 697 /// notes will be produced if the expression is not a constant expression. 698 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, 699 const VarDecl *VD, 700 SmallVectorImpl<PartialDiagnosticAt> &Notes) const; 701 702 /// EvaluateWithSubstitution - Evaluate an expression as if from the context 703 /// of a call to the given function with the given arguments, inside an 704 /// unevaluated context. Returns true if the expression could be folded to a 705 /// constant. 706 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 707 const FunctionDecl *Callee, 708 ArrayRef<const Expr*> Args, 709 const Expr *This = nullptr) const; 710 711 /// Indicates how the constant expression will be used. 712 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling }; 713 714 /// Evaluate an expression that is required to be a constant expression. 715 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 716 const ASTContext &Ctx, 717 bool InPlace = false) const; 718 719 /// If the current Expr is a pointer, this will try to statically 720 /// determine the number of bytes available where the pointer is pointing. 721 /// Returns true if all of the above holds and we were able to figure out the 722 /// size, false otherwise. 723 /// 724 /// \param Type - How to evaluate the size of the Expr, as defined by the 725 /// "type" parameter of __builtin_object_size 726 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 727 unsigned Type) const; 728 729 /// Enumeration used to describe the kind of Null pointer constant 730 /// returned from \c isNullPointerConstant(). 731 enum NullPointerConstantKind { 732 /// Expression is not a Null pointer constant. 733 NPCK_NotNull = 0, 734 735 /// Expression is a Null pointer constant built from a zero integer 736 /// expression that is not a simple, possibly parenthesized, zero literal. 737 /// C++ Core Issue 903 will classify these expressions as "not pointers" 738 /// once it is adopted. 739 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 740 NPCK_ZeroExpression, 741 742 /// Expression is a Null pointer constant built from a literal zero. 743 NPCK_ZeroLiteral, 744 745 /// Expression is a C++11 nullptr. 746 NPCK_CXX11_nullptr, 747 748 /// Expression is a GNU-style __null constant. 749 NPCK_GNUNull 750 }; 751 752 /// Enumeration used to describe how \c isNullPointerConstant() 753 /// should cope with value-dependent expressions. 754 enum NullPointerConstantValueDependence { 755 /// Specifies that the expression should never be value-dependent. 756 NPC_NeverValueDependent = 0, 757 758 /// Specifies that a value-dependent expression of integral or 759 /// dependent type should be considered a null pointer constant. 760 NPC_ValueDependentIsNull, 761 762 /// Specifies that a value-dependent expression should be considered 763 /// to never be a null pointer constant. 764 NPC_ValueDependentIsNotNull 765 }; 766 767 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 768 /// a Null pointer constant. The return value can further distinguish the 769 /// kind of NULL pointer constant that was detected. 770 NullPointerConstantKind isNullPointerConstant( 771 ASTContext &Ctx, 772 NullPointerConstantValueDependence NPC) const; 773 774 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 775 /// write barrier. 776 bool isOBJCGCCandidate(ASTContext &Ctx) const; 777 778 /// Returns true if this expression is a bound member function. 779 bool isBoundMemberFunction(ASTContext &Ctx) const; 780 781 /// Given an expression of bound-member type, find the type 782 /// of the member. Returns null if this is an *overloaded* bound 783 /// member expression. 784 static QualType findBoundMemberType(const Expr *expr); 785 786 /// Skip past any invisble AST nodes which might surround this 787 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes, 788 /// but also injected CXXMemberExpr and CXXConstructExpr which represent 789 /// implicit conversions. 790 Expr *IgnoreUnlessSpelledInSource(); 791 const Expr *IgnoreUnlessSpelledInSource() const { 792 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource(); 793 } 794 795 /// Skip past any implicit casts which might surround this expression until 796 /// reaching a fixed point. Skips: 797 /// * ImplicitCastExpr 798 /// * FullExpr 799 Expr *IgnoreImpCasts() LLVM_READONLY; 800 const Expr *IgnoreImpCasts() const { 801 return const_cast<Expr *>(this)->IgnoreImpCasts(); 802 } 803 804 /// Skip past any casts which might surround this expression until reaching 805 /// a fixed point. Skips: 806 /// * CastExpr 807 /// * FullExpr 808 /// * MaterializeTemporaryExpr 809 /// * SubstNonTypeTemplateParmExpr 810 Expr *IgnoreCasts() LLVM_READONLY; 811 const Expr *IgnoreCasts() const { 812 return const_cast<Expr *>(this)->IgnoreCasts(); 813 } 814 815 /// Skip past any implicit AST nodes which might surround this expression 816 /// until reaching a fixed point. Skips: 817 /// * What IgnoreImpCasts() skips 818 /// * MaterializeTemporaryExpr 819 /// * CXXBindTemporaryExpr 820 Expr *IgnoreImplicit() LLVM_READONLY; 821 const Expr *IgnoreImplicit() const { 822 return const_cast<Expr *>(this)->IgnoreImplicit(); 823 } 824 825 /// Skip past any implicit AST nodes which might surround this expression 826 /// until reaching a fixed point. Same as IgnoreImplicit, except that it 827 /// also skips over implicit calls to constructors and conversion functions. 828 /// 829 /// FIXME: Should IgnoreImplicit do this? 830 Expr *IgnoreImplicitAsWritten() LLVM_READONLY; 831 const Expr *IgnoreImplicitAsWritten() const { 832 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten(); 833 } 834 835 /// Skip past any parentheses which might surround this expression until 836 /// reaching a fixed point. Skips: 837 /// * ParenExpr 838 /// * UnaryOperator if `UO_Extension` 839 /// * GenericSelectionExpr if `!isResultDependent()` 840 /// * ChooseExpr if `!isConditionDependent()` 841 /// * ConstantExpr 842 Expr *IgnoreParens() LLVM_READONLY; 843 const Expr *IgnoreParens() const { 844 return const_cast<Expr *>(this)->IgnoreParens(); 845 } 846 847 /// Skip past any parentheses and implicit casts which might surround this 848 /// expression until reaching a fixed point. 849 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to 850 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However 851 /// this is currently not the case. Instead IgnoreParenImpCasts() skips: 852 /// * What IgnoreParens() skips 853 /// * What IgnoreImpCasts() skips 854 /// * MaterializeTemporaryExpr 855 /// * SubstNonTypeTemplateParmExpr 856 Expr *IgnoreParenImpCasts() LLVM_READONLY; 857 const Expr *IgnoreParenImpCasts() const { 858 return const_cast<Expr *>(this)->IgnoreParenImpCasts(); 859 } 860 861 /// Skip past any parentheses and casts which might surround this expression 862 /// until reaching a fixed point. Skips: 863 /// * What IgnoreParens() skips 864 /// * What IgnoreCasts() skips 865 Expr *IgnoreParenCasts() LLVM_READONLY; 866 const Expr *IgnoreParenCasts() const { 867 return const_cast<Expr *>(this)->IgnoreParenCasts(); 868 } 869 870 /// Skip conversion operators. If this Expr is a call to a conversion 871 /// operator, return the argument. 872 Expr *IgnoreConversionOperator() LLVM_READONLY; 873 const Expr *IgnoreConversionOperator() const { 874 return const_cast<Expr *>(this)->IgnoreConversionOperator(); 875 } 876 877 /// Skip past any parentheses and lvalue casts which might surround this 878 /// expression until reaching a fixed point. Skips: 879 /// * What IgnoreParens() skips 880 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue 881 /// casts are skipped 882 /// FIXME: This is intended purely as a temporary workaround for code 883 /// that hasn't yet been rewritten to do the right thing about those 884 /// casts, and may disappear along with the last internal use. 885 Expr *IgnoreParenLValueCasts() LLVM_READONLY; 886 const Expr *IgnoreParenLValueCasts() const { 887 return const_cast<Expr *>(this)->IgnoreParenLValueCasts(); 888 } 889 890 /// Skip past any parenthese and casts which do not change the value 891 /// (including ptr->int casts of the same size) until reaching a fixed point. 892 /// Skips: 893 /// * What IgnoreParens() skips 894 /// * CastExpr which do not change the value 895 /// * SubstNonTypeTemplateParmExpr 896 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY; 897 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const { 898 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx); 899 } 900 901 /// Skip past any parentheses and derived-to-base casts until reaching a 902 /// fixed point. Skips: 903 /// * What IgnoreParens() skips 904 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase, 905 /// CK_UncheckedDerivedToBase and CK_NoOp) 906 Expr *ignoreParenBaseCasts() LLVM_READONLY; 907 const Expr *ignoreParenBaseCasts() const { 908 return const_cast<Expr *>(this)->ignoreParenBaseCasts(); 909 } 910 911 /// Determine whether this expression is a default function argument. 912 /// 913 /// Default arguments are implicitly generated in the abstract syntax tree 914 /// by semantic analysis for function calls, object constructions, etc. in 915 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 916 /// this routine also looks through any implicit casts to determine whether 917 /// the expression is a default argument. 918 bool isDefaultArgument() const; 919 920 /// Determine whether the result of this expression is a 921 /// temporary object of the given class type. 922 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 923 924 /// Whether this expression is an implicit reference to 'this' in C++. 925 bool isImplicitCXXThis() const; 926 927 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); 928 929 /// For an expression of class type or pointer to class type, 930 /// return the most derived class decl the expression is known to refer to. 931 /// 932 /// If this expression is a cast, this method looks through it to find the 933 /// most derived decl that can be inferred from the expression. 934 /// This is valid because derived-to-base conversions have undefined 935 /// behavior if the object isn't dynamically of the derived type. 936 const CXXRecordDecl *getBestDynamicClassType() const; 937 938 /// Get the inner expression that determines the best dynamic class. 939 /// If this is a prvalue, we guarantee that it is of the most-derived type 940 /// for the object itself. 941 const Expr *getBestDynamicClassTypeExpr() const; 942 943 /// Walk outwards from an expression we want to bind a reference to and 944 /// find the expression whose lifetime needs to be extended. Record 945 /// the LHSs of comma expressions and adjustments needed along the path. 946 const Expr *skipRValueSubobjectAdjustments( 947 SmallVectorImpl<const Expr *> &CommaLHS, 948 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; 949 const Expr *skipRValueSubobjectAdjustments() const { 950 SmallVector<const Expr *, 8> CommaLHSs; 951 SmallVector<SubobjectAdjustment, 8> Adjustments; 952 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 953 } 954 955 /// Checks that the two Expr's will refer to the same value as a comparison 956 /// operand. The caller must ensure that the values referenced by the Expr's 957 /// are not modified between E1 and E2 or the result my be invalid. 958 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2); 959 960 static bool classof(const Stmt *T) { 961 return T->getStmtClass() >= firstExprConstant && 962 T->getStmtClass() <= lastExprConstant; 963 } 964}; 965 966//===----------------------------------------------------------------------===// 967// Wrapper Expressions. 968//===----------------------------------------------------------------------===// 969 970/// FullExpr - Represents a "full-expression" node. 971class FullExpr : public Expr { 972protected: 973 Stmt *SubExpr; 974 975 FullExpr(StmtClass SC, Expr *subexpr) 976 : Expr(SC, subexpr->getType(), subexpr->getValueKind(), 977 subexpr->getObjectKind()), 978 SubExpr(subexpr) { 979 setDependence(computeDependence(this)); 980 } 981 FullExpr(StmtClass SC, EmptyShell Empty) 982 : Expr(SC, Empty) {} 983public: 984 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } 985 Expr *getSubExpr() { return cast<Expr>(SubExpr); } 986 987 /// As with any mutator of the AST, be very careful when modifying an 988 /// existing AST to preserve its invariants. 989 void setSubExpr(Expr *E) { SubExpr = E; } 990 991 static bool classof(const Stmt *T) { 992 return T->getStmtClass() >= firstFullExprConstant && 993 T->getStmtClass() <= lastFullExprConstant; 994 } 995}; 996 997/// ConstantExpr - An expression that occurs in a constant context and 998/// optionally the result of evaluating the expression. 999class ConstantExpr final 1000 : public FullExpr, 1001 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> { 1002 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value, 1003 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t " 1004 "for tail-allocated storage"); 1005 friend TrailingObjects; 1006 friend class ASTStmtReader; 1007 friend class ASTStmtWriter; 1008 1009public: 1010 /// Describes the kind of result that can be tail-allocated. 1011 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue }; 1012 1013private: 1014 size_t numTrailingObjects(OverloadToken<APValue>) const { 1015 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue; 1016 } 1017 size_t numTrailingObjects(OverloadToken<uint64_t>) const { 1018 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64; 1019 } 1020 1021 uint64_t &Int64Result() { 1022 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && 1023 "invalid accessor"); 1024 return *getTrailingObjects<uint64_t>(); 1025 } 1026 const uint64_t &Int64Result() const { 1027 return const_cast<ConstantExpr *>(this)->Int64Result(); 1028 } 1029 APValue &APValueResult() { 1030 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && 1031 "invalid accessor"); 1032 return *getTrailingObjects<APValue>(); 1033 } 1034 APValue &APValueResult() const { 1035 return const_cast<ConstantExpr *>(this)->APValueResult(); 1036 } 1037 1038 ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind, 1039 bool IsImmediateInvocation); 1040 ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind); 1041 1042public: 1043 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 1044 const APValue &Result); 1045 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 1046 ResultStorageKind Storage = RSK_None, 1047 bool IsImmediateInvocation = false); 1048 static ConstantExpr *CreateEmpty(const ASTContext &Context, 1049 ResultStorageKind StorageKind); 1050 1051 static ResultStorageKind getStorageKind(const APValue &Value); 1052 static ResultStorageKind getStorageKind(const Type *T, 1053 const ASTContext &Context); 1054 1055 SourceLocation getBeginLoc() const LLVM_READONLY { 1056 return SubExpr->getBeginLoc(); 1057 } 1058 SourceLocation getEndLoc() const LLVM_READONLY { 1059 return SubExpr->getEndLoc(); 1060 } 1061 1062 static bool classof(const Stmt *T) { 1063 return T->getStmtClass() == ConstantExprClass; 1064 } 1065 1066 void SetResult(APValue Value, const ASTContext &Context) { 1067 MoveIntoResult(Value, Context); 1068 } 1069 void MoveIntoResult(APValue &Value, const ASTContext &Context); 1070 1071 APValue::ValueKind getResultAPValueKind() const { 1072 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind); 1073 } 1074 ResultStorageKind getResultStorageKind() const { 1075 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind); 1076 } 1077 bool isImmediateInvocation() const { 1078 return ConstantExprBits.IsImmediateInvocation; 1079 } 1080 bool hasAPValueResult() const { 1081 return ConstantExprBits.APValueKind != APValue::None; 1082 } 1083 APValue getAPValueResult() const; 1084 APValue &getResultAsAPValue() const { return APValueResult(); } 1085 llvm::APSInt getResultAsAPSInt() const; 1086 // Iterators 1087 child_range children() { return child_range(&SubExpr, &SubExpr+1); } 1088 const_child_range children() const { 1089 return const_child_range(&SubExpr, &SubExpr + 1); 1090 } 1091}; 1092 1093//===----------------------------------------------------------------------===// 1094// Primary Expressions. 1095//===----------------------------------------------------------------------===// 1096 1097/// OpaqueValueExpr - An expression referring to an opaque object of a 1098/// fixed type and value class. These don't correspond to concrete 1099/// syntax; instead they're used to express operations (usually copy 1100/// operations) on values whose source is generally obvious from 1101/// context. 1102class OpaqueValueExpr : public Expr { 1103 friend class ASTStmtReader; 1104 Expr *SourceExpr; 1105 1106public: 1107 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 1108 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr) 1109 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) { 1110 setIsUnique(false); 1111 OpaqueValueExprBits.Loc = Loc; 1112 setDependence(computeDependence(this)); 1113 } 1114 1115 /// Given an expression which invokes a copy constructor --- i.e. a 1116 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 1117 /// find the OpaqueValueExpr that's the source of the construction. 1118 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 1119 1120 explicit OpaqueValueExpr(EmptyShell Empty) 1121 : Expr(OpaqueValueExprClass, Empty) {} 1122 1123 /// Retrieve the location of this expression. 1124 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; } 1125 1126 SourceLocation getBeginLoc() const LLVM_READONLY { 1127 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation(); 1128 } 1129 SourceLocation getEndLoc() const LLVM_READONLY { 1130 return SourceExpr ? SourceExpr->getEndLoc() : getLocation(); 1131 } 1132 SourceLocation getExprLoc() const LLVM_READONLY { 1133 return SourceExpr ? SourceExpr->getExprLoc() : getLocation(); 1134 } 1135 1136 child_range children() { 1137 return child_range(child_iterator(), child_iterator()); 1138 } 1139 1140 const_child_range children() const { 1141 return const_child_range(const_child_iterator(), const_child_iterator()); 1142 } 1143 1144 /// The source expression of an opaque value expression is the 1145 /// expression which originally generated the value. This is 1146 /// provided as a convenience for analyses that don't wish to 1147 /// precisely model the execution behavior of the program. 1148 /// 1149 /// The source expression is typically set when building the 1150 /// expression which binds the opaque value expression in the first 1151 /// place. 1152 Expr *getSourceExpr() const { return SourceExpr; } 1153 1154 void setIsUnique(bool V) { 1155 assert((!V || SourceExpr) && 1156 "unique OVEs are expected to have source expressions"); 1157 OpaqueValueExprBits.IsUnique = V; 1158 } 1159 1160 bool isUnique() const { return OpaqueValueExprBits.IsUnique; } 1161 1162 static bool classof(const Stmt *T) { 1163 return T->getStmtClass() == OpaqueValueExprClass; 1164 } 1165}; 1166 1167/// A reference to a declared variable, function, enum, etc. 1168/// [C99 6.5.1p2] 1169/// 1170/// This encodes all the information about how a declaration is referenced 1171/// within an expression. 1172/// 1173/// There are several optional constructs attached to DeclRefExprs only when 1174/// they apply in order to conserve memory. These are laid out past the end of 1175/// the object, and flags in the DeclRefExprBitfield track whether they exist: 1176/// 1177/// DeclRefExprBits.HasQualifier: 1178/// Specifies when this declaration reference expression has a C++ 1179/// nested-name-specifier. 1180/// DeclRefExprBits.HasFoundDecl: 1181/// Specifies when this declaration reference expression has a record of 1182/// a NamedDecl (different from the referenced ValueDecl) which was found 1183/// during name lookup and/or overload resolution. 1184/// DeclRefExprBits.HasTemplateKWAndArgsInfo: 1185/// Specifies when this declaration reference expression has an explicit 1186/// C++ template keyword and/or template argument list. 1187/// DeclRefExprBits.RefersToEnclosingVariableOrCapture 1188/// Specifies when this declaration reference expression (validly) 1189/// refers to an enclosed local or a captured variable. 1190class DeclRefExpr final 1191 : public Expr, 1192 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc, 1193 NamedDecl *, ASTTemplateKWAndArgsInfo, 1194 TemplateArgumentLoc> { 1195 friend class ASTStmtReader; 1196 friend class ASTStmtWriter; 1197 friend TrailingObjects; 1198 1199 /// The declaration that we are referencing. 1200 ValueDecl *D; 1201 1202 /// Provides source/type location info for the declaration name 1203 /// embedded in D. 1204 DeclarationNameLoc DNLoc; 1205 1206 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const { 1207 return hasQualifier(); 1208 } 1209 1210 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const { 1211 return hasFoundDecl(); 1212 } 1213 1214 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 1215 return hasTemplateKWAndArgsInfo(); 1216 } 1217 1218 /// Test whether there is a distinct FoundDecl attached to the end of 1219 /// this DRE. 1220 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 1221 1222 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, 1223 SourceLocation TemplateKWLoc, ValueDecl *D, 1224 bool RefersToEnlosingVariableOrCapture, 1225 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, 1226 const TemplateArgumentListInfo *TemplateArgs, QualType T, 1227 ExprValueKind VK, NonOdrUseReason NOUR); 1228 1229 /// Construct an empty declaration reference expression. 1230 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {} 1231 1232public: 1233 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, 1234 bool RefersToEnclosingVariableOrCapture, QualType T, 1235 ExprValueKind VK, SourceLocation L, 1236 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(), 1237 NonOdrUseReason NOUR = NOUR_None); 1238 1239 static DeclRefExpr * 1240 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1241 SourceLocation TemplateKWLoc, ValueDecl *D, 1242 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, 1243 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, 1244 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1245 NonOdrUseReason NOUR = NOUR_None); 1246 1247 static DeclRefExpr * 1248 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1249 SourceLocation TemplateKWLoc, ValueDecl *D, 1250 bool RefersToEnclosingVariableOrCapture, 1251 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, 1252 NamedDecl *FoundD = nullptr, 1253 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1254 NonOdrUseReason NOUR = NOUR_None); 1255 1256 /// Construct an empty declaration reference expression. 1257 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 1258 bool HasFoundDecl, 1259 bool HasTemplateKWAndArgsInfo, 1260 unsigned NumTemplateArgs); 1261 1262 ValueDecl *getDecl() { return D; } 1263 const ValueDecl *getDecl() const { return D; } 1264 void setDecl(ValueDecl *NewD) { D = NewD; } 1265 1266 DeclarationNameInfo getNameInfo() const { 1267 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc); 1268 } 1269 1270 SourceLocation getLocation() const { return DeclRefExprBits.Loc; } 1271 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; } 1272 SourceLocation getBeginLoc() const LLVM_READONLY; 1273 SourceLocation getEndLoc() const LLVM_READONLY; 1274 1275 /// Determine whether this declaration reference was preceded by a 1276 /// C++ nested-name-specifier, e.g., \c N::foo. 1277 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 1278 1279 /// If the name was qualified, retrieves the nested-name-specifier 1280 /// that precedes the name, with source-location information. 1281 NestedNameSpecifierLoc getQualifierLoc() const { 1282 if (!hasQualifier()) 1283 return NestedNameSpecifierLoc(); 1284 return *getTrailingObjects<NestedNameSpecifierLoc>(); 1285 } 1286 1287 /// If the name was qualified, retrieves the nested-name-specifier 1288 /// that precedes the name. Otherwise, returns NULL. 1289 NestedNameSpecifier *getQualifier() const { 1290 return getQualifierLoc().getNestedNameSpecifier(); 1291 } 1292 1293 /// Get the NamedDecl through which this reference occurred. 1294 /// 1295 /// This Decl may be different from the ValueDecl actually referred to in the 1296 /// presence of using declarations, etc. It always returns non-NULL, and may 1297 /// simple return the ValueDecl when appropriate. 1298 1299 NamedDecl *getFoundDecl() { 1300 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1301 } 1302 1303 /// Get the NamedDecl through which this reference occurred. 1304 /// See non-const variant. 1305 const NamedDecl *getFoundDecl() const { 1306 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1307 } 1308 1309 bool hasTemplateKWAndArgsInfo() const { 1310 return DeclRefExprBits.HasTemplateKWAndArgsInfo; 1311 } 1312 1313 /// Retrieve the location of the template keyword preceding 1314 /// this name, if any. 1315 SourceLocation getTemplateKeywordLoc() const { 1316 if (!hasTemplateKWAndArgsInfo()) 1317 return SourceLocation(); 1318 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 1319 } 1320 1321 /// Retrieve the location of the left angle bracket starting the 1322 /// explicit template argument list following the name, if any. 1323 SourceLocation getLAngleLoc() const { 1324 if (!hasTemplateKWAndArgsInfo()) 1325 return SourceLocation(); 1326 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 1327 } 1328 1329 /// Retrieve the location of the right angle bracket ending the 1330 /// explicit template argument list following the name, if any. 1331 SourceLocation getRAngleLoc() const { 1332 if (!hasTemplateKWAndArgsInfo()) 1333 return SourceLocation(); 1334 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 1335 } 1336 1337 /// Determines whether the name in this declaration reference 1338 /// was preceded by the template keyword. 1339 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 1340 1341 /// Determines whether this declaration reference was followed by an 1342 /// explicit template argument list. 1343 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 1344 1345 /// Copies the template arguments (if present) into the given 1346 /// structure. 1347 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 1348 if (hasExplicitTemplateArgs()) 1349 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 1350 getTrailingObjects<TemplateArgumentLoc>(), List); 1351 } 1352 1353 /// Retrieve the template arguments provided as part of this 1354 /// template-id. 1355 const TemplateArgumentLoc *getTemplateArgs() const { 1356 if (!hasExplicitTemplateArgs()) 1357 return nullptr; 1358 return getTrailingObjects<TemplateArgumentLoc>(); 1359 } 1360 1361 /// Retrieve the number of template arguments provided as part of this 1362 /// template-id. 1363 unsigned getNumTemplateArgs() const { 1364 if (!hasExplicitTemplateArgs()) 1365 return 0; 1366 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 1367 } 1368 1369 ArrayRef<TemplateArgumentLoc> template_arguments() const { 1370 return {getTemplateArgs(), getNumTemplateArgs()}; 1371 } 1372 1373 /// Returns true if this expression refers to a function that 1374 /// was resolved from an overloaded set having size greater than 1. 1375 bool hadMultipleCandidates() const { 1376 return DeclRefExprBits.HadMultipleCandidates; 1377 } 1378 /// Sets the flag telling whether this expression refers to 1379 /// a function that was resolved from an overloaded set having size 1380 /// greater than 1. 1381 void setHadMultipleCandidates(bool V = true) { 1382 DeclRefExprBits.HadMultipleCandidates = V; 1383 } 1384 1385 /// Is this expression a non-odr-use reference, and if so, why? 1386 NonOdrUseReason isNonOdrUse() const { 1387 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason); 1388 } 1389 1390 /// Does this DeclRefExpr refer to an enclosing local or a captured 1391 /// variable? 1392 bool refersToEnclosingVariableOrCapture() const { 1393 return DeclRefExprBits.RefersToEnclosingVariableOrCapture; 1394 } 1395 1396 static bool classof(const Stmt *T) { 1397 return T->getStmtClass() == DeclRefExprClass; 1398 } 1399 1400 // Iterators 1401 child_range children() { 1402 return child_range(child_iterator(), child_iterator()); 1403 } 1404 1405 const_child_range children() const { 1406 return const_child_range(const_child_iterator(), const_child_iterator()); 1407 } 1408}; 1409 1410/// Used by IntegerLiteral/FloatingLiteral to store the numeric without 1411/// leaking memory. 1412/// 1413/// For large floats/integers, APFloat/APInt will allocate memory from the heap 1414/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1415/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1416/// the APFloat/APInt values will never get freed. APNumericStorage uses 1417/// ASTContext's allocator for memory allocation. 1418class APNumericStorage { 1419 union { 1420 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1421 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1422 }; 1423 unsigned BitWidth; 1424 1425 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1426 1427 APNumericStorage(const APNumericStorage &) = delete; 1428 void operator=(const APNumericStorage &) = delete; 1429 1430protected: 1431 APNumericStorage() : VAL(0), BitWidth(0) { } 1432 1433 llvm::APInt getIntValue() const { 1434 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1435 if (NumWords > 1) 1436 return llvm::APInt(BitWidth, NumWords, pVal); 1437 else 1438 return llvm::APInt(BitWidth, VAL); 1439 } 1440 void setIntValue(const ASTContext &C, const llvm::APInt &Val); 1441}; 1442 1443class APIntStorage : private APNumericStorage { 1444public: 1445 llvm::APInt getValue() const { return getIntValue(); } 1446 void setValue(const ASTContext &C, const llvm::APInt &Val) { 1447 setIntValue(C, Val); 1448 } 1449}; 1450 1451class APFloatStorage : private APNumericStorage { 1452public: 1453 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1454 return llvm::APFloat(Semantics, getIntValue()); 1455 } 1456 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1457 setIntValue(C, Val.bitcastToAPInt()); 1458 } 1459}; 1460 1461class IntegerLiteral : public Expr, public APIntStorage { 1462 SourceLocation Loc; 1463 1464 /// Construct an empty integer literal. 1465 explicit IntegerLiteral(EmptyShell Empty) 1466 : Expr(IntegerLiteralClass, Empty) { } 1467 1468public: 1469 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1470 // or UnsignedLongLongTy 1471 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1472 SourceLocation l); 1473 1474 /// Returns a new integer literal with value 'V' and type 'type'. 1475 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1476 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1477 /// \param V - the value that the returned integer literal contains. 1478 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, 1479 QualType type, SourceLocation l); 1480 /// Returns a new empty integer literal. 1481 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); 1482 1483 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1484 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1485 1486 /// Retrieve the location of the literal. 1487 SourceLocation getLocation() const { return Loc; } 1488 1489 void setLocation(SourceLocation Location) { Loc = Location; } 1490 1491 static bool classof(const Stmt *T) { 1492 return T->getStmtClass() == IntegerLiteralClass; 1493 } 1494 1495 // Iterators 1496 child_range children() { 1497 return child_range(child_iterator(), child_iterator()); 1498 } 1499 const_child_range children() const { 1500 return const_child_range(const_child_iterator(), const_child_iterator()); 1501 } 1502}; 1503 1504class FixedPointLiteral : public Expr, public APIntStorage { 1505 SourceLocation Loc; 1506 unsigned Scale; 1507 1508 /// \brief Construct an empty fixed-point literal. 1509 explicit FixedPointLiteral(EmptyShell Empty) 1510 : Expr(FixedPointLiteralClass, Empty) {} 1511 1512 public: 1513 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1514 SourceLocation l, unsigned Scale); 1515 1516 // Store the int as is without any bit shifting. 1517 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C, 1518 const llvm::APInt &V, 1519 QualType type, SourceLocation l, 1520 unsigned Scale); 1521 1522 /// Returns an empty fixed-point literal. 1523 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty); 1524 1525 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1526 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1527 1528 /// \brief Retrieve the location of the literal. 1529 SourceLocation getLocation() const { return Loc; } 1530 1531 void setLocation(SourceLocation Location) { Loc = Location; } 1532 1533 unsigned getScale() const { return Scale; } 1534 void setScale(unsigned S) { Scale = S; } 1535 1536 static bool classof(const Stmt *T) { 1537 return T->getStmtClass() == FixedPointLiteralClass; 1538 } 1539 1540 std::string getValueAsString(unsigned Radix) const; 1541 1542 // Iterators 1543 child_range children() { 1544 return child_range(child_iterator(), child_iterator()); 1545 } 1546 const_child_range children() const { 1547 return const_child_range(const_child_iterator(), const_child_iterator()); 1548 } 1549}; 1550 1551class CharacterLiteral : public Expr { 1552public: 1553 enum CharacterKind { 1554 Ascii, 1555 Wide, 1556 UTF8, 1557 UTF16, 1558 UTF32 1559 }; 1560 1561private: 1562 unsigned Value; 1563 SourceLocation Loc; 1564public: 1565 // type should be IntTy 1566 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1567 SourceLocation l) 1568 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary), Value(value), 1569 Loc(l) { 1570 CharacterLiteralBits.Kind = kind; 1571 setDependence(ExprDependence::None); 1572 } 1573 1574 /// Construct an empty character literal. 1575 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1576 1577 SourceLocation getLocation() const { return Loc; } 1578 CharacterKind getKind() const { 1579 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1580 } 1581 1582 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1583 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1584 1585 unsigned getValue() const { return Value; } 1586 1587 void setLocation(SourceLocation Location) { Loc = Location; } 1588 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1589 void setValue(unsigned Val) { Value = Val; } 1590 1591 static bool classof(const Stmt *T) { 1592 return T->getStmtClass() == CharacterLiteralClass; 1593 } 1594 1595 // Iterators 1596 child_range children() { 1597 return child_range(child_iterator(), child_iterator()); 1598 } 1599 const_child_range children() const { 1600 return const_child_range(const_child_iterator(), const_child_iterator()); 1601 } 1602}; 1603 1604class FloatingLiteral : public Expr, private APFloatStorage { 1605 SourceLocation Loc; 1606 1607 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, 1608 QualType Type, SourceLocation L); 1609 1610 /// Construct an empty floating-point literal. 1611 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); 1612 1613public: 1614 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, 1615 bool isexact, QualType Type, SourceLocation L); 1616 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); 1617 1618 llvm::APFloat getValue() const { 1619 return APFloatStorage::getValue(getSemantics()); 1620 } 1621 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1622 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1623 APFloatStorage::setValue(C, Val); 1624 } 1625 1626 /// Get a raw enumeration value representing the floating-point semantics of 1627 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1628 llvm::APFloatBase::Semantics getRawSemantics() const { 1629 return static_cast<llvm::APFloatBase::Semantics>( 1630 FloatingLiteralBits.Semantics); 1631 } 1632 1633 /// Set the raw enumeration value representing the floating-point semantics of 1634 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1635 void setRawSemantics(llvm::APFloatBase::Semantics Sem) { 1636 FloatingLiteralBits.Semantics = Sem; 1637 } 1638 1639 /// Return the APFloat semantics this literal uses. 1640 const llvm::fltSemantics &getSemantics() const { 1641 return llvm::APFloatBase::EnumToSemantics( 1642 static_cast<llvm::APFloatBase::Semantics>( 1643 FloatingLiteralBits.Semantics)); 1644 } 1645 1646 /// Set the APFloat semantics this literal uses. 1647 void setSemantics(const llvm::fltSemantics &Sem) { 1648 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem); 1649 } 1650 1651 bool isExact() const { return FloatingLiteralBits.IsExact; } 1652 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1653 1654 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1655 /// double. Note that this may cause loss of precision, but is useful for 1656 /// debugging dumps, etc. 1657 double getValueAsApproximateDouble() const; 1658 1659 SourceLocation getLocation() const { return Loc; } 1660 void setLocation(SourceLocation L) { Loc = L; } 1661 1662 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1663 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1664 1665 static bool classof(const Stmt *T) { 1666 return T->getStmtClass() == FloatingLiteralClass; 1667 } 1668 1669 // Iterators 1670 child_range children() { 1671 return child_range(child_iterator(), child_iterator()); 1672 } 1673 const_child_range children() const { 1674 return const_child_range(const_child_iterator(), const_child_iterator()); 1675 } 1676}; 1677 1678/// ImaginaryLiteral - We support imaginary integer and floating point literals, 1679/// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1680/// IntegerLiteral classes. Instances of this class always have a Complex type 1681/// whose element type matches the subexpression. 1682/// 1683class ImaginaryLiteral : public Expr { 1684 Stmt *Val; 1685public: 1686 ImaginaryLiteral(Expr *val, QualType Ty) 1687 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary), Val(val) { 1688 setDependence(ExprDependence::None); 1689 } 1690 1691 /// Build an empty imaginary literal. 1692 explicit ImaginaryLiteral(EmptyShell Empty) 1693 : Expr(ImaginaryLiteralClass, Empty) { } 1694 1695 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1696 Expr *getSubExpr() { return cast<Expr>(Val); } 1697 void setSubExpr(Expr *E) { Val = E; } 1698 1699 SourceLocation getBeginLoc() const LLVM_READONLY { 1700 return Val->getBeginLoc(); 1701 } 1702 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); } 1703 1704 static bool classof(const Stmt *T) { 1705 return T->getStmtClass() == ImaginaryLiteralClass; 1706 } 1707 1708 // Iterators 1709 child_range children() { return child_range(&Val, &Val+1); } 1710 const_child_range children() const { 1711 return const_child_range(&Val, &Val + 1); 1712 } 1713}; 1714 1715/// StringLiteral - This represents a string literal expression, e.g. "foo" 1716/// or L"bar" (wide strings). The actual string data can be obtained with 1717/// getBytes() and is NOT null-terminated. The length of the string data is 1718/// determined by calling getByteLength(). 1719/// 1720/// The C type for a string is always a ConstantArrayType. In C++, the char 1721/// type is const qualified, in C it is not. 1722/// 1723/// Note that strings in C can be formed by concatenation of multiple string 1724/// literal pptokens in translation phase #6. This keeps track of the locations 1725/// of each of these pieces. 1726/// 1727/// Strings in C can also be truncated and extended by assigning into arrays, 1728/// e.g. with constructs like: 1729/// char X[2] = "foobar"; 1730/// In this case, getByteLength() will return 6, but the string literal will 1731/// have type "char[2]". 1732class StringLiteral final 1733 : public Expr, 1734 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation, 1735 char> { 1736 friend class ASTStmtReader; 1737 friend TrailingObjects; 1738 1739 /// StringLiteral is followed by several trailing objects. They are in order: 1740 /// 1741 /// * A single unsigned storing the length in characters of this string. The 1742 /// length in bytes is this length times the width of a single character. 1743 /// Always present and stored as a trailing objects because storing it in 1744 /// StringLiteral would increase the size of StringLiteral by sizeof(void *) 1745 /// due to alignment requirements. If you add some data to StringLiteral, 1746 /// consider moving it inside StringLiteral. 1747 /// 1748 /// * An array of getNumConcatenated() SourceLocation, one for each of the 1749 /// token this string is made of. 1750 /// 1751 /// * An array of getByteLength() char used to store the string data. 1752 1753public: 1754 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 }; 1755 1756private: 1757 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; } 1758 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { 1759 return getNumConcatenated(); 1760 } 1761 1762 unsigned numTrailingObjects(OverloadToken<char>) const { 1763 return getByteLength(); 1764 } 1765 1766 char *getStrDataAsChar() { return getTrailingObjects<char>(); } 1767 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); } 1768 1769 const uint16_t *getStrDataAsUInt16() const { 1770 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>()); 1771 } 1772 1773 const uint32_t *getStrDataAsUInt32() const { 1774 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>()); 1775 } 1776 1777 /// Build a string literal. 1778 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind, 1779 bool Pascal, QualType Ty, const SourceLocation *Loc, 1780 unsigned NumConcatenated); 1781 1782 /// Build an empty string literal. 1783 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length, 1784 unsigned CharByteWidth); 1785 1786 /// Map a target and string kind to the appropriate character width. 1787 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK); 1788 1789 /// Set one of the string literal token. 1790 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1791 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1792 getTrailingObjects<SourceLocation>()[TokNum] = L; 1793 } 1794 1795public: 1796 /// This is the "fully general" constructor that allows representation of 1797 /// strings formed from multiple concatenated tokens. 1798 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1799 StringKind Kind, bool Pascal, QualType Ty, 1800 const SourceLocation *Loc, 1801 unsigned NumConcatenated); 1802 1803 /// Simple constructor for string literals made from one token. 1804 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1805 StringKind Kind, bool Pascal, QualType Ty, 1806 SourceLocation Loc) { 1807 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1); 1808 } 1809 1810 /// Construct an empty string literal. 1811 static StringLiteral *CreateEmpty(const ASTContext &Ctx, 1812 unsigned NumConcatenated, unsigned Length, 1813 unsigned CharByteWidth); 1814 1815 StringRef getString() const { 1816 assert(getCharByteWidth() == 1 && 1817 "This function is used in places that assume strings use char"); 1818 return StringRef(getStrDataAsChar(), getByteLength()); 1819 } 1820 1821 /// Allow access to clients that need the byte representation, such as 1822 /// ASTWriterStmt::VisitStringLiteral(). 1823 StringRef getBytes() const { 1824 // FIXME: StringRef may not be the right type to use as a result for this. 1825 return StringRef(getStrDataAsChar(), getByteLength()); 1826 } 1827 1828 void outputString(raw_ostream &OS) const; 1829 1830 uint32_t getCodeUnit(size_t i) const { 1831 assert(i < getLength() && "out of bounds access"); 1832 switch (getCharByteWidth()) { 1833 case 1: 1834 return static_cast<unsigned char>(getStrDataAsChar()[i]); 1835 case 2: 1836 return getStrDataAsUInt16()[i]; 1837 case 4: 1838 return getStrDataAsUInt32()[i]; 1839 } 1840 llvm_unreachable("Unsupported character width!"); 1841 } 1842 1843 unsigned getByteLength() const { return getCharByteWidth() * getLength(); } 1844 unsigned getLength() const { return *getTrailingObjects<unsigned>(); } 1845 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; } 1846 1847 StringKind getKind() const { 1848 return static_cast<StringKind>(StringLiteralBits.Kind); 1849 } 1850 1851 bool isAscii() const { return getKind() == Ascii; } 1852 bool isWide() const { return getKind() == Wide; } 1853 bool isUTF8() const { return getKind() == UTF8; } 1854 bool isUTF16() const { return getKind() == UTF16; } 1855 bool isUTF32() const { return getKind() == UTF32; } 1856 bool isPascal() const { return StringLiteralBits.IsPascal; } 1857 1858 bool containsNonAscii() const { 1859 for (auto c : getString()) 1860 if (!isASCII(c)) 1861 return true; 1862 return false; 1863 } 1864 1865 bool containsNonAsciiOrNull() const { 1866 for (auto c : getString()) 1867 if (!isASCII(c) || !c) 1868 return true; 1869 return false; 1870 } 1871 1872 /// getNumConcatenated - Get the number of string literal tokens that were 1873 /// concatenated in translation phase #6 to form this string literal. 1874 unsigned getNumConcatenated() const { 1875 return StringLiteralBits.NumConcatenated; 1876 } 1877 1878 /// Get one of the string literal token. 1879 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1880 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1881 return getTrailingObjects<SourceLocation>()[TokNum]; 1882 } 1883 1884 /// getLocationOfByte - Return a source location that points to the specified 1885 /// byte of this string literal. 1886 /// 1887 /// Strings are amazingly complex. They can be formed from multiple tokens 1888 /// and can have escape sequences in them in addition to the usual trigraph 1889 /// and escaped newline business. This routine handles this complexity. 1890 /// 1891 SourceLocation 1892 getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1893 const LangOptions &Features, const TargetInfo &Target, 1894 unsigned *StartToken = nullptr, 1895 unsigned *StartTokenByteOffset = nullptr) const; 1896 1897 typedef const SourceLocation *tokloc_iterator; 1898 1899 tokloc_iterator tokloc_begin() const { 1900 return getTrailingObjects<SourceLocation>(); 1901 } 1902 1903 tokloc_iterator tokloc_end() const { 1904 return getTrailingObjects<SourceLocation>() + getNumConcatenated(); 1905 } 1906 1907 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); } 1908 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); } 1909 1910 static bool classof(const Stmt *T) { 1911 return T->getStmtClass() == StringLiteralClass; 1912 } 1913 1914 // Iterators 1915 child_range children() { 1916 return child_range(child_iterator(), child_iterator()); 1917 } 1918 const_child_range children() const { 1919 return const_child_range(const_child_iterator(), const_child_iterator()); 1920 } 1921}; 1922 1923/// [C99 6.4.2.2] - A predefined identifier such as __func__. 1924class PredefinedExpr final 1925 : public Expr, 1926 private llvm::TrailingObjects<PredefinedExpr, Stmt *, Expr *, 1927 TypeSourceInfo *> { 1928 friend class ASTStmtReader; 1929 friend TrailingObjects; 1930 1931 // PredefinedExpr is optionally followed by a single trailing 1932 // "Stmt *" for the predefined identifier. It is present if and only if 1933 // hasFunctionName() is true and is always a "StringLiteral *". 1934 // It can also be followed by a Expr* in the case of a 1935 // __builtin_unique_stable_name with an expression, or TypeSourceInfo * if 1936 // __builtin_unique_stable_name with a type. 1937 1938public: 1939 enum IdentKind { 1940 Func, 1941 Function, 1942 LFunction, // Same as Function, but as wide string. 1943 FuncDName, 1944 FuncSig, 1945 LFuncSig, // Same as FuncSig, but as as wide string 1946 PrettyFunction, 1947 /// The same as PrettyFunction, except that the 1948 /// 'virtual' keyword is omitted for virtual member functions. 1949 PrettyFunctionNoVirtual, 1950 UniqueStableNameType, 1951 UniqueStableNameExpr, 1952 }; 1953 1954private: 1955 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, 1956 StringLiteral *SL); 1957 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, 1958 TypeSourceInfo *Info); 1959 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, 1960 Expr *E); 1961 1962 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName); 1963 1964 /// True if this PredefinedExpr has storage for a function name. 1965 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; } 1966 1967 void setFunctionName(StringLiteral *SL) { 1968 assert(hasFunctionName() && 1969 "This PredefinedExpr has no storage for a function name!"); 1970 *getTrailingObjects<Stmt *>() = SL; 1971 } 1972 1973 void setTypeSourceInfo(TypeSourceInfo *Info) { 1974 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType && 1975 "TypeSourceInfo only valid for UniqueStableName of a Type"); 1976 *getTrailingObjects<TypeSourceInfo *>() = Info; 1977 } 1978 1979 void setExpr(Expr *E) { 1980 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr && 1981 "TypeSourceInfo only valid for UniqueStableName of n Expression."); 1982 *getTrailingObjects<Expr *>() = E; 1983 } 1984 1985 size_t numTrailingObjects(OverloadToken<Stmt *>) const { 1986 return hasFunctionName(); 1987 } 1988 1989 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { 1990 return getIdentKind() == UniqueStableNameType && !hasFunctionName(); 1991 } 1992 size_t numTrailingObjects(OverloadToken<Expr *>) const { 1993 return getIdentKind() == UniqueStableNameExpr && !hasFunctionName(); 1994 } 1995 1996public: 1997 /// Create a PredefinedExpr. 1998 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, 1999 QualType FNTy, IdentKind IK, StringLiteral *SL); 2000 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, 2001 QualType FNTy, IdentKind IK, StringLiteral *SL, 2002 TypeSourceInfo *Info); 2003 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, 2004 QualType FNTy, IdentKind IK, StringLiteral *SL, 2005 Expr *E); 2006 2007 /// Create an empty PredefinedExpr. 2008 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx, 2009 bool HasFunctionName); 2010 2011 IdentKind getIdentKind() const { 2012 return static_cast<IdentKind>(PredefinedExprBits.Kind); 2013 } 2014 2015 SourceLocation getLocation() const { return PredefinedExprBits.Loc; } 2016 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; } 2017 2018 StringLiteral *getFunctionName() { 2019 return hasFunctionName() 2020 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 2021 : nullptr; 2022 } 2023 2024 const StringLiteral *getFunctionName() const { 2025 return hasFunctionName() 2026 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 2027 : nullptr; 2028 } 2029 2030 TypeSourceInfo *getTypeSourceInfo() { 2031 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType && 2032 "TypeSourceInfo only valid for UniqueStableName of a Type"); 2033 return *getTrailingObjects<TypeSourceInfo *>(); 2034 } 2035 2036 const TypeSourceInfo *getTypeSourceInfo() const { 2037 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType && 2038 "TypeSourceInfo only valid for UniqueStableName of a Type"); 2039 return *getTrailingObjects<TypeSourceInfo *>(); 2040 } 2041 2042 Expr *getExpr() { 2043 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr && 2044 "TypeSourceInfo only valid for UniqueStableName of n Expression."); 2045 return *getTrailingObjects<Expr *>(); 2046 } 2047 2048 const Expr *getExpr() const { 2049 assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr && 2050 "TypeSourceInfo only valid for UniqueStableName of n Expression."); 2051 return *getTrailingObjects<Expr *>(); 2052 } 2053 2054 static StringRef getIdentKindName(IdentKind IK); 2055 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl); 2056 static std::string ComputeName(ASTContext &Context, IdentKind IK, 2057 const QualType Ty); 2058 2059 SourceLocation getBeginLoc() const { return getLocation(); } 2060 SourceLocation getEndLoc() const { return getLocation(); } 2061 2062 static bool classof(const Stmt *T) { 2063 return T->getStmtClass() == PredefinedExprClass; 2064 } 2065 2066 // Iterators 2067 child_range children() { 2068 return child_range(getTrailingObjects<Stmt *>(), 2069 getTrailingObjects<Stmt *>() + hasFunctionName()); 2070 } 2071 2072 const_child_range children() const { 2073 return const_child_range(getTrailingObjects<Stmt *>(), 2074 getTrailingObjects<Stmt *>() + hasFunctionName()); 2075 } 2076}; 2077 2078/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 2079/// AST node is only formed if full location information is requested. 2080class ParenExpr : public Expr { 2081 SourceLocation L, R; 2082 Stmt *Val; 2083public: 2084 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 2085 : Expr(ParenExprClass, val->getType(), val->getValueKind(), 2086 val->getObjectKind()), 2087 L(l), R(r), Val(val) { 2088 setDependence(computeDependence(this)); 2089 } 2090 2091 /// Construct an empty parenthesized expression. 2092 explicit ParenExpr(EmptyShell Empty) 2093 : Expr(ParenExprClass, Empty) { } 2094 2095 const Expr *getSubExpr() const { return cast<Expr>(Val); } 2096 Expr *getSubExpr() { return cast<Expr>(Val); } 2097 void setSubExpr(Expr *E) { Val = E; } 2098 2099 SourceLocation getBeginLoc() const LLVM_READONLY { return L; } 2100 SourceLocation getEndLoc() const LLVM_READONLY { return R; } 2101 2102 /// Get the location of the left parentheses '('. 2103 SourceLocation getLParen() const { return L; } 2104 void setLParen(SourceLocation Loc) { L = Loc; } 2105 2106 /// Get the location of the right parentheses ')'. 2107 SourceLocation getRParen() const { return R; } 2108 void setRParen(SourceLocation Loc) { R = Loc; } 2109 2110 static bool classof(const Stmt *T) { 2111 return T->getStmtClass() == ParenExprClass; 2112 } 2113 2114 // Iterators 2115 child_range children() { return child_range(&Val, &Val+1); } 2116 const_child_range children() const { 2117 return const_child_range(&Val, &Val + 1); 2118 } 2119}; 2120 2121/// UnaryOperator - This represents the unary-expression's (except sizeof and 2122/// alignof), the postinc/postdec operators from postfix-expression, and various 2123/// extensions. 2124/// 2125/// Notes on various nodes: 2126/// 2127/// Real/Imag - These return the real/imag part of a complex operand. If 2128/// applied to a non-complex value, the former returns its operand and the 2129/// later returns zero in the type of the operand. 2130/// 2131class UnaryOperator final 2132 : public Expr, 2133 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> { 2134 Stmt *Val; 2135 2136 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const { 2137 return UnaryOperatorBits.HasFPFeatures ? 1 : 0; 2138 } 2139 2140 FPOptionsOverride &getTrailingFPFeatures() { 2141 assert(UnaryOperatorBits.HasFPFeatures); 2142 return *getTrailingObjects<FPOptionsOverride>(); 2143 } 2144 2145 const FPOptionsOverride &getTrailingFPFeatures() const { 2146 assert(UnaryOperatorBits.HasFPFeatures); 2147 return *getTrailingObjects<FPOptionsOverride>(); 2148 } 2149 2150public: 2151 typedef UnaryOperatorKind Opcode; 2152 2153protected: 2154 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type, 2155 ExprValueKind VK, ExprObjectKind OK, SourceLocation l, 2156 bool CanOverflow, FPOptionsOverride FPFeatures); 2157 2158 /// Build an empty unary operator. 2159 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty) 2160 : Expr(UnaryOperatorClass, Empty) { 2161 UnaryOperatorBits.Opc = UO_AddrOf; 2162 UnaryOperatorBits.HasFPFeatures = HasFPFeatures; 2163 } 2164 2165public: 2166 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures); 2167 2168 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc, 2169 QualType type, ExprValueKind VK, 2170 ExprObjectKind OK, SourceLocation l, 2171 bool CanOverflow, FPOptionsOverride FPFeatures); 2172 2173 Opcode getOpcode() const { 2174 return static_cast<Opcode>(UnaryOperatorBits.Opc); 2175 } 2176 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; } 2177 2178 Expr *getSubExpr() const { return cast<Expr>(Val); } 2179 void setSubExpr(Expr *E) { Val = E; } 2180 2181 /// getOperatorLoc - Return the location of the operator. 2182 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; } 2183 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; } 2184 2185 /// Returns true if the unary operator can cause an overflow. For instance, 2186 /// signed int i = INT_MAX; i++; 2187 /// signed char c = CHAR_MAX; c++; 2188 /// Due to integer promotions, c++ is promoted to an int before the postfix 2189 /// increment, and the result is an int that cannot overflow. However, i++ 2190 /// can overflow. 2191 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; } 2192 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; } 2193 2194 // Get the FP contractability status of this operator. Only meaningful for 2195 // operations on floating point types. 2196 bool isFPContractableWithinStatement(const LangOptions &LO) const { 2197 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement(); 2198 } 2199 2200 // Get the FENV_ACCESS status of this operator. Only meaningful for 2201 // operations on floating point types. 2202 bool isFEnvAccessOn(const LangOptions &LO) const { 2203 return getFPFeaturesInEffect(LO).getAllowFEnvAccess(); 2204 } 2205 2206 /// isPostfix - Return true if this is a postfix operation, like x++. 2207 static bool isPostfix(Opcode Op) { 2208 return Op == UO_PostInc || Op == UO_PostDec; 2209 } 2210 2211 /// isPrefix - Return true if this is a prefix operation, like --x. 2212 static bool isPrefix(Opcode Op) { 2213 return Op == UO_PreInc || Op == UO_PreDec; 2214 } 2215 2216 bool isPrefix() const { return isPrefix(getOpcode()); } 2217 bool isPostfix() const { return isPostfix(getOpcode()); } 2218 2219 static bool isIncrementOp(Opcode Op) { 2220 return Op == UO_PreInc || Op == UO_PostInc; 2221 } 2222 bool isIncrementOp() const { 2223 return isIncrementOp(getOpcode()); 2224 } 2225 2226 static bool isDecrementOp(Opcode Op) { 2227 return Op == UO_PreDec || Op == UO_PostDec; 2228 } 2229 bool isDecrementOp() const { 2230 return isDecrementOp(getOpcode()); 2231 } 2232 2233 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 2234 bool isIncrementDecrementOp() const { 2235 return isIncrementDecrementOp(getOpcode()); 2236 } 2237 2238 static bool isArithmeticOp(Opcode Op) { 2239 return Op >= UO_Plus && Op <= UO_LNot; 2240 } 2241 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 2242 2243 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2244 /// corresponds to, e.g. "sizeof" or "[pre]++" 2245 static StringRef getOpcodeStr(Opcode Op); 2246 2247 /// Retrieve the unary opcode that corresponds to the given 2248 /// overloaded operator. 2249 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 2250 2251 /// Retrieve the overloaded operator kind that corresponds to 2252 /// the given unary opcode. 2253 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2254 2255 SourceLocation getBeginLoc() const LLVM_READONLY { 2256 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc(); 2257 } 2258 SourceLocation getEndLoc() const LLVM_READONLY { 2259 return isPostfix() ? getOperatorLoc() : Val->getEndLoc(); 2260 } 2261 SourceLocation getExprLoc() const { return getOperatorLoc(); } 2262 2263 static bool classof(const Stmt *T) { 2264 return T->getStmtClass() == UnaryOperatorClass; 2265 } 2266 2267 // Iterators 2268 child_range children() { return child_range(&Val, &Val+1); } 2269 const_child_range children() const { 2270 return const_child_range(&Val, &Val + 1); 2271 } 2272 2273 /// Is FPFeatures in Trailing Storage? 2274 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; } 2275 2276protected: 2277 /// Get FPFeatures from trailing storage 2278 FPOptionsOverride getStoredFPFeatures() const { 2279 return getTrailingFPFeatures(); 2280 } 2281 2282 /// Set FPFeatures in trailing storage, used only by Serialization 2283 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; } 2284 2285public: 2286 // Get the FP features status of this operator. Only meaningful for 2287 // operations on floating point types. 2288 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 2289 if (UnaryOperatorBits.HasFPFeatures) 2290 return getStoredFPFeatures().applyOverrides(LO); 2291 return FPOptions::defaultWithoutTrailingStorage(LO); 2292 } 2293 FPOptionsOverride getFPOptionsOverride() const { 2294 if (UnaryOperatorBits.HasFPFeatures) 2295 return getStoredFPFeatures(); 2296 return FPOptionsOverride(); 2297 } 2298 2299 friend TrailingObjects; 2300 friend class ASTReader; 2301 friend class ASTStmtReader; 2302 friend class ASTStmtWriter; 2303}; 2304 2305/// Helper class for OffsetOfExpr. 2306 2307// __builtin_offsetof(type, identifier(.identifier|[expr])*) 2308class OffsetOfNode { 2309public: 2310 /// The kind of offsetof node we have. 2311 enum Kind { 2312 /// An index into an array. 2313 Array = 0x00, 2314 /// A field. 2315 Field = 0x01, 2316 /// A field in a dependent type, known only by its name. 2317 Identifier = 0x02, 2318 /// An implicit indirection through a C++ base class, when the 2319 /// field found is in a base class. 2320 Base = 0x03 2321 }; 2322 2323private: 2324 enum { MaskBits = 2, Mask = 0x03 }; 2325 2326 /// The source range that covers this part of the designator. 2327 SourceRange Range; 2328 2329 /// The data describing the designator, which comes in three 2330 /// different forms, depending on the lower two bits. 2331 /// - An unsigned index into the array of Expr*'s stored after this node 2332 /// in memory, for [constant-expression] designators. 2333 /// - A FieldDecl*, for references to a known field. 2334 /// - An IdentifierInfo*, for references to a field with a given name 2335 /// when the class type is dependent. 2336 /// - A CXXBaseSpecifier*, for references that look at a field in a 2337 /// base class. 2338 uintptr_t Data; 2339 2340public: 2341 /// Create an offsetof node that refers to an array element. 2342 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 2343 SourceLocation RBracketLoc) 2344 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} 2345 2346 /// Create an offsetof node that refers to a field. 2347 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) 2348 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2349 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {} 2350 2351 /// Create an offsetof node that refers to an identifier. 2352 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 2353 SourceLocation NameLoc) 2354 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2355 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {} 2356 2357 /// Create an offsetof node that refers into a C++ base class. 2358 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 2359 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 2360 2361 /// Determine what kind of offsetof node this is. 2362 Kind getKind() const { return static_cast<Kind>(Data & Mask); } 2363 2364 /// For an array element node, returns the index into the array 2365 /// of expressions. 2366 unsigned getArrayExprIndex() const { 2367 assert(getKind() == Array); 2368 return Data >> 2; 2369 } 2370 2371 /// For a field offsetof node, returns the field. 2372 FieldDecl *getField() const { 2373 assert(getKind() == Field); 2374 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 2375 } 2376 2377 /// For a field or identifier offsetof node, returns the name of 2378 /// the field. 2379 IdentifierInfo *getFieldName() const; 2380 2381 /// For a base class node, returns the base specifier. 2382 CXXBaseSpecifier *getBase() const { 2383 assert(getKind() == Base); 2384 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 2385 } 2386 2387 /// Retrieve the source range that covers this offsetof node. 2388 /// 2389 /// For an array element node, the source range contains the locations of 2390 /// the square brackets. For a field or identifier node, the source range 2391 /// contains the location of the period (if there is one) and the 2392 /// identifier. 2393 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 2394 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); } 2395 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); } 2396}; 2397 2398/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 2399/// offsetof(record-type, member-designator). For example, given: 2400/// @code 2401/// struct S { 2402/// float f; 2403/// double d; 2404/// }; 2405/// struct T { 2406/// int i; 2407/// struct S s[10]; 2408/// }; 2409/// @endcode 2410/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 2411 2412class OffsetOfExpr final 2413 : public Expr, 2414 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> { 2415 SourceLocation OperatorLoc, RParenLoc; 2416 // Base type; 2417 TypeSourceInfo *TSInfo; 2418 // Number of sub-components (i.e. instances of OffsetOfNode). 2419 unsigned NumComps; 2420 // Number of sub-expressions (i.e. array subscript expressions). 2421 unsigned NumExprs; 2422 2423 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const { 2424 return NumComps; 2425 } 2426 2427 OffsetOfExpr(const ASTContext &C, QualType type, 2428 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2429 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 2430 SourceLocation RParenLoc); 2431 2432 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 2433 : Expr(OffsetOfExprClass, EmptyShell()), 2434 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} 2435 2436public: 2437 2438 static OffsetOfExpr *Create(const ASTContext &C, QualType type, 2439 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2440 ArrayRef<OffsetOfNode> comps, 2441 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 2442 2443 static OffsetOfExpr *CreateEmpty(const ASTContext &C, 2444 unsigned NumComps, unsigned NumExprs); 2445 2446 /// getOperatorLoc - Return the location of the operator. 2447 SourceLocation getOperatorLoc() const { return OperatorLoc; } 2448 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 2449 2450 /// Return the location of the right parentheses. 2451 SourceLocation getRParenLoc() const { return RParenLoc; } 2452 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 2453 2454 TypeSourceInfo *getTypeSourceInfo() const { 2455 return TSInfo; 2456 } 2457 void setTypeSourceInfo(TypeSourceInfo *tsi) { 2458 TSInfo = tsi; 2459 } 2460 2461 const OffsetOfNode &getComponent(unsigned Idx) const { 2462 assert(Idx < NumComps && "Subscript out of range"); 2463 return getTrailingObjects<OffsetOfNode>()[Idx]; 2464 } 2465 2466 void setComponent(unsigned Idx, OffsetOfNode ON) { 2467 assert(Idx < NumComps && "Subscript out of range"); 2468 getTrailingObjects<OffsetOfNode>()[Idx] = ON; 2469 } 2470 2471 unsigned getNumComponents() const { 2472 return NumComps; 2473 } 2474 2475 Expr* getIndexExpr(unsigned Idx) { 2476 assert(Idx < NumExprs && "Subscript out of range"); 2477 return getTrailingObjects<Expr *>()[Idx]; 2478 } 2479 2480 const Expr *getIndexExpr(unsigned Idx) const { 2481 assert(Idx < NumExprs && "Subscript out of range"); 2482 return getTrailingObjects<Expr *>()[Idx]; 2483 } 2484 2485 void setIndexExpr(unsigned Idx, Expr* E) { 2486 assert(Idx < NumComps && "Subscript out of range"); 2487 getTrailingObjects<Expr *>()[Idx] = E; 2488 } 2489 2490 unsigned getNumExpressions() const { 2491 return NumExprs; 2492 } 2493 2494 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; } 2495 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2496 2497 static bool classof(const Stmt *T) { 2498 return T->getStmtClass() == OffsetOfExprClass; 2499 } 2500 2501 // Iterators 2502 child_range children() { 2503 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); 2504 return child_range(begin, begin + NumExprs); 2505 } 2506 const_child_range children() const { 2507 Stmt *const *begin = 2508 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); 2509 return const_child_range(begin, begin + NumExprs); 2510 } 2511 friend TrailingObjects; 2512}; 2513 2514/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 2515/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 2516/// vec_step (OpenCL 1.1 6.11.12). 2517class UnaryExprOrTypeTraitExpr : public Expr { 2518 union { 2519 TypeSourceInfo *Ty; 2520 Stmt *Ex; 2521 } Argument; 2522 SourceLocation OpLoc, RParenLoc; 2523 2524public: 2525 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 2526 QualType resultType, SourceLocation op, 2527 SourceLocation rp) 2528 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary), 2529 OpLoc(op), RParenLoc(rp) { 2530 assert(ExprKind <= UETT_Last && "invalid enum value!"); 2531 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 2532 assert(static_cast<unsigned>(ExprKind) == 2533 UnaryExprOrTypeTraitExprBits.Kind && 2534 "UnaryExprOrTypeTraitExprBits.Kind overflow!"); 2535 UnaryExprOrTypeTraitExprBits.IsType = true; 2536 Argument.Ty = TInfo; 2537 setDependence(computeDependence(this)); 2538 } 2539 2540 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 2541 QualType resultType, SourceLocation op, 2542 SourceLocation rp); 2543 2544 /// Construct an empty sizeof/alignof expression. 2545 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 2546 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 2547 2548 UnaryExprOrTypeTrait getKind() const { 2549 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 2550 } 2551 void setKind(UnaryExprOrTypeTrait K) { 2552 assert(K <= UETT_Last && "invalid enum value!"); 2553 UnaryExprOrTypeTraitExprBits.Kind = K; 2554 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind && 2555 "UnaryExprOrTypeTraitExprBits.Kind overflow!"); 2556 } 2557 2558 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 2559 QualType getArgumentType() const { 2560 return getArgumentTypeInfo()->getType(); 2561 } 2562 TypeSourceInfo *getArgumentTypeInfo() const { 2563 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 2564 return Argument.Ty; 2565 } 2566 Expr *getArgumentExpr() { 2567 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 2568 return static_cast<Expr*>(Argument.Ex); 2569 } 2570 const Expr *getArgumentExpr() const { 2571 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 2572 } 2573 2574 void setArgument(Expr *E) { 2575 Argument.Ex = E; 2576 UnaryExprOrTypeTraitExprBits.IsType = false; 2577 } 2578 void setArgument(TypeSourceInfo *TInfo) { 2579 Argument.Ty = TInfo; 2580 UnaryExprOrTypeTraitExprBits.IsType = true; 2581 } 2582 2583 /// Gets the argument type, or the type of the argument expression, whichever 2584 /// is appropriate. 2585 QualType getTypeOfArgument() const { 2586 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2587 } 2588 2589 SourceLocation getOperatorLoc() const { return OpLoc; } 2590 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2591 2592 SourceLocation getRParenLoc() const { return RParenLoc; } 2593 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2594 2595 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; } 2596 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2597 2598 static bool classof(const Stmt *T) { 2599 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2600 } 2601 2602 // Iterators 2603 child_range children(); 2604 const_child_range children() const; 2605}; 2606 2607//===----------------------------------------------------------------------===// 2608// Postfix Operators. 2609//===----------------------------------------------------------------------===// 2610 2611/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2612class ArraySubscriptExpr : public Expr { 2613 enum { LHS, RHS, END_EXPR }; 2614 Stmt *SubExprs[END_EXPR]; 2615 2616 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); } 2617 2618public: 2619 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK, 2620 ExprObjectKind OK, SourceLocation rbracketloc) 2621 : Expr(ArraySubscriptExprClass, t, VK, OK) { 2622 SubExprs[LHS] = lhs; 2623 SubExprs[RHS] = rhs; 2624 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc; 2625 setDependence(computeDependence(this)); 2626 } 2627 2628 /// Create an empty array subscript expression. 2629 explicit ArraySubscriptExpr(EmptyShell Shell) 2630 : Expr(ArraySubscriptExprClass, Shell) { } 2631 2632 /// An array access can be written A[4] or 4[A] (both are equivalent). 2633 /// - getBase() and getIdx() always present the normalized view: A[4]. 2634 /// In this case getBase() returns "A" and getIdx() returns "4". 2635 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2636 /// 4[A] getLHS() returns "4". 2637 /// Note: Because vector element access is also written A[4] we must 2638 /// predicate the format conversion in getBase and getIdx only on the 2639 /// the type of the RHS, as it is possible for the LHS to be a vector of 2640 /// integer type 2641 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2642 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2643 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2644 2645 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2646 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2647 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2648 2649 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); } 2650 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); } 2651 2652 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); } 2653 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); } 2654 2655 SourceLocation getBeginLoc() const LLVM_READONLY { 2656 return getLHS()->getBeginLoc(); 2657 } 2658 SourceLocation getEndLoc() const { return getRBracketLoc(); } 2659 2660 SourceLocation getRBracketLoc() const { 2661 return ArrayOrMatrixSubscriptExprBits.RBracketLoc; 2662 } 2663 void setRBracketLoc(SourceLocation L) { 2664 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L; 2665 } 2666 2667 SourceLocation getExprLoc() const LLVM_READONLY { 2668 return getBase()->getExprLoc(); 2669 } 2670 2671 static bool classof(const Stmt *T) { 2672 return T->getStmtClass() == ArraySubscriptExprClass; 2673 } 2674 2675 // Iterators 2676 child_range children() { 2677 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2678 } 2679 const_child_range children() const { 2680 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2681 } 2682}; 2683 2684/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType 2685/// extension. 2686/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set 2687/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and 2688/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only 2689/// exist during the initial construction of the AST. 2690class MatrixSubscriptExpr : public Expr { 2691 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR }; 2692 Stmt *SubExprs[END_EXPR]; 2693 2694public: 2695 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T, 2696 SourceLocation RBracketLoc) 2697 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(), 2698 OK_MatrixComponent) { 2699 SubExprs[BASE] = Base; 2700 SubExprs[ROW_IDX] = RowIdx; 2701 SubExprs[COLUMN_IDX] = ColumnIdx; 2702 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc; 2703 setDependence(computeDependence(this)); 2704 } 2705 2706 /// Create an empty matrix subscript expression. 2707 explicit MatrixSubscriptExpr(EmptyShell Shell) 2708 : Expr(MatrixSubscriptExprClass, Shell) {} 2709 2710 bool isIncomplete() const { 2711 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx); 2712 assert((SubExprs[COLUMN_IDX] || IsIncomplete) && 2713 "expressions without column index must be marked as incomplete"); 2714 return IsIncomplete; 2715 } 2716 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); } 2717 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); } 2718 void setBase(Expr *E) { SubExprs[BASE] = E; } 2719 2720 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); } 2721 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); } 2722 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; } 2723 2724 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); } 2725 const Expr *getColumnIdx() const { 2726 assert(!isIncomplete() && 2727 "cannot get the column index of an incomplete expression"); 2728 return cast<Expr>(SubExprs[COLUMN_IDX]); 2729 } 2730 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; } 2731 2732 SourceLocation getBeginLoc() const LLVM_READONLY { 2733 return getBase()->getBeginLoc(); 2734 } 2735 2736 SourceLocation getEndLoc() const { return getRBracketLoc(); } 2737 2738 SourceLocation getExprLoc() const LLVM_READONLY { 2739 return getBase()->getExprLoc(); 2740 } 2741 2742 SourceLocation getRBracketLoc() const { 2743 return ArrayOrMatrixSubscriptExprBits.RBracketLoc; 2744 } 2745 void setRBracketLoc(SourceLocation L) { 2746 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L; 2747 } 2748 2749 static bool classof(const Stmt *T) { 2750 return T->getStmtClass() == MatrixSubscriptExprClass; 2751 } 2752 2753 // Iterators 2754 child_range children() { 2755 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2756 } 2757 const_child_range children() const { 2758 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2759 } 2760}; 2761 2762/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2763/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2764/// while its subclasses may represent alternative syntax that (semantically) 2765/// results in a function call. For example, CXXOperatorCallExpr is 2766/// a subclass for overloaded operator calls that use operator syntax, e.g., 2767/// "str1 + str2" to resolve to a function call. 2768class CallExpr : public Expr { 2769 enum { FN = 0, PREARGS_START = 1 }; 2770 2771 /// The number of arguments in the call expression. 2772 unsigned NumArgs; 2773 2774 /// The location of the right parenthese. This has a different meaning for 2775 /// the derived classes of CallExpr. 2776 SourceLocation RParenLoc; 2777 2778 // CallExpr store some data in trailing objects. However since CallExpr 2779 // is used a base of other expression classes we cannot use 2780 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic 2781 // and casts. 2782 // 2783 // The trailing objects are in order: 2784 // 2785 // * A single "Stmt *" for the callee expression. 2786 // 2787 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions. 2788 // 2789 // * An array of getNumArgs() "Stmt *" for the argument expressions. 2790 // 2791 // Note that we store the offset in bytes from the this pointer to the start 2792 // of the trailing objects. It would be perfectly possible to compute it 2793 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of 2794 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to 2795 // compute this once and then load the offset from the bit-fields of Stmt, 2796 // instead of re-computing the offset each time the trailing objects are 2797 // accessed. 2798 2799 /// Return a pointer to the start of the trailing array of "Stmt *". 2800 Stmt **getTrailingStmts() { 2801 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) + 2802 CallExprBits.OffsetToTrailingObjects); 2803 } 2804 Stmt *const *getTrailingStmts() const { 2805 return const_cast<CallExpr *>(this)->getTrailingStmts(); 2806 } 2807 2808 /// Map a statement class to the appropriate offset in bytes from the 2809 /// this pointer to the trailing objects. 2810 static unsigned offsetToTrailingObjects(StmtClass SC); 2811 2812public: 2813 enum class ADLCallKind : bool { NotADL, UsesADL }; 2814 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL; 2815 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL; 2816 2817protected: 2818 /// Build a call expression, assuming that appropriate storage has been 2819 /// allocated for the trailing objects. 2820 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, 2821 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2822 SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL); 2823 2824 /// Build an empty call expression, for deserialization. 2825 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, 2826 EmptyShell Empty); 2827 2828 /// Return the size in bytes needed for the trailing objects. 2829 /// Used by the derived classes to allocate the right amount of storage. 2830 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) { 2831 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *); 2832 } 2833 2834 Stmt *getPreArg(unsigned I) { 2835 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2836 return getTrailingStmts()[PREARGS_START + I]; 2837 } 2838 const Stmt *getPreArg(unsigned I) const { 2839 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2840 return getTrailingStmts()[PREARGS_START + I]; 2841 } 2842 void setPreArg(unsigned I, Stmt *PreArg) { 2843 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2844 getTrailingStmts()[PREARGS_START + I] = PreArg; 2845 } 2846 2847 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2848 2849public: 2850 /// Create a call expression. Fn is the callee expression, Args is the 2851 /// argument array, Ty is the type of the call expression (which is *not* 2852 /// the return type in general), VK is the value kind of the call expression 2853 /// (lvalue, rvalue, ...), and RParenLoc is the location of the right 2854 /// parenthese in the call expression. MinNumArgs specifies the minimum 2855 /// number of arguments. The actual number of arguments will be the greater 2856 /// of Args.size() and MinNumArgs. This is used in a few places to allocate 2857 /// enough storage for the default arguments. UsesADL specifies whether the 2858 /// callee was found through argument-dependent lookup. 2859 /// 2860 /// Note that you can use CreateTemporary if you need a temporary call 2861 /// expression on the stack. 2862 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn, 2863 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2864 SourceLocation RParenLoc, unsigned MinNumArgs = 0, 2865 ADLCallKind UsesADL = NotADL); 2866 2867 /// Create a temporary call expression with no arguments in the memory 2868 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr) 2869 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr): 2870 /// 2871 /// \code{.cpp} 2872 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 2873 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc); 2874 /// \endcode 2875 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty, 2876 ExprValueKind VK, SourceLocation RParenLoc, 2877 ADLCallKind UsesADL = NotADL); 2878 2879 /// Create an empty call expression, for deserialization. 2880 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, 2881 EmptyShell Empty); 2882 2883 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); } 2884 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); } 2885 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; } 2886 2887 ADLCallKind getADLCallKind() const { 2888 return static_cast<ADLCallKind>(CallExprBits.UsesADL); 2889 } 2890 void setADLCallKind(ADLCallKind V = UsesADL) { 2891 CallExprBits.UsesADL = static_cast<bool>(V); 2892 } 2893 bool usesADL() const { return getADLCallKind() == UsesADL; } 2894 2895 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } 2896 const Decl *getCalleeDecl() const { 2897 return getCallee()->getReferencedDeclOfCallee(); 2898 } 2899 2900 /// If the callee is a FunctionDecl, return it. Otherwise return null. 2901 FunctionDecl *getDirectCallee() { 2902 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 2903 } 2904 const FunctionDecl *getDirectCallee() const { 2905 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 2906 } 2907 2908 /// getNumArgs - Return the number of actual arguments to this call. 2909 unsigned getNumArgs() const { return NumArgs; } 2910 2911 /// Retrieve the call arguments. 2912 Expr **getArgs() { 2913 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START + 2914 getNumPreArgs()); 2915 } 2916 const Expr *const *getArgs() const { 2917 return reinterpret_cast<const Expr *const *>( 2918 getTrailingStmts() + PREARGS_START + getNumPreArgs()); 2919 } 2920 2921 /// getArg - Return the specified argument. 2922 Expr *getArg(unsigned Arg) { 2923 assert(Arg < getNumArgs() && "Arg access out of range!"); 2924 return getArgs()[Arg]; 2925 } 2926 const Expr *getArg(unsigned Arg) const { 2927 assert(Arg < getNumArgs() && "Arg access out of range!"); 2928 return getArgs()[Arg]; 2929 } 2930 2931 /// setArg - Set the specified argument. 2932 void setArg(unsigned Arg, Expr *ArgExpr) { 2933 assert(Arg < getNumArgs() && "Arg access out of range!"); 2934 getArgs()[Arg] = ArgExpr; 2935 } 2936 2937 /// Reduce the number of arguments in this call expression. This is used for 2938 /// example during error recovery to drop extra arguments. There is no way 2939 /// to perform the opposite because: 1.) We don't track how much storage 2940 /// we have for the argument array 2.) This would potentially require growing 2941 /// the argument array, something we cannot support since the arguments are 2942 /// stored in a trailing array. 2943 void shrinkNumArgs(unsigned NewNumArgs) { 2944 assert((NewNumArgs <= getNumArgs()) && 2945 "shrinkNumArgs cannot increase the number of arguments!"); 2946 NumArgs = NewNumArgs; 2947 } 2948 2949 /// Bluntly set a new number of arguments without doing any checks whatsoever. 2950 /// Only used during construction of a CallExpr in a few places in Sema. 2951 /// FIXME: Find a way to remove it. 2952 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; } 2953 2954 typedef ExprIterator arg_iterator; 2955 typedef ConstExprIterator const_arg_iterator; 2956 typedef llvm::iterator_range<arg_iterator> arg_range; 2957 typedef llvm::iterator_range<const_arg_iterator> const_arg_range; 2958 2959 arg_range arguments() { return arg_range(arg_begin(), arg_end()); } 2960 const_arg_range arguments() const { 2961 return const_arg_range(arg_begin(), arg_end()); 2962 } 2963 2964 arg_iterator arg_begin() { 2965 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 2966 } 2967 arg_iterator arg_end() { return arg_begin() + getNumArgs(); } 2968 2969 const_arg_iterator arg_begin() const { 2970 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 2971 } 2972 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); } 2973 2974 /// This method provides fast access to all the subexpressions of 2975 /// a CallExpr without going through the slower virtual child_iterator 2976 /// interface. This provides efficient reverse iteration of the 2977 /// subexpressions. This is currently used for CFG construction. 2978 ArrayRef<Stmt *> getRawSubExprs() { 2979 return llvm::makeArrayRef(getTrailingStmts(), 2980 PREARGS_START + getNumPreArgs() + getNumArgs()); 2981 } 2982 2983 /// getNumCommas - Return the number of commas that must have been present in 2984 /// this function call. 2985 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; } 2986 2987 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID 2988 /// of the callee. If not, return 0. 2989 unsigned getBuiltinCallee() const; 2990 2991 /// Returns \c true if this is a call to a builtin which does not 2992 /// evaluate side-effects within its arguments. 2993 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; 2994 2995 /// getCallReturnType - Get the return type of the call expr. This is not 2996 /// always the type of the expr itself, if the return type is a reference 2997 /// type. 2998 QualType getCallReturnType(const ASTContext &Ctx) const; 2999 3000 /// Returns the WarnUnusedResultAttr that is either declared on the called 3001 /// function, or its return type declaration. 3002 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const; 3003 3004 /// Returns true if this call expression should warn on unused results. 3005 bool hasUnusedResultAttr(const ASTContext &Ctx) const { 3006 return getUnusedResultAttr(Ctx) != nullptr; 3007 } 3008 3009 SourceLocation getRParenLoc() const { return RParenLoc; } 3010 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3011 3012 SourceLocation getBeginLoc() const LLVM_READONLY; 3013 SourceLocation getEndLoc() const LLVM_READONLY; 3014 3015 /// Return true if this is a call to __assume() or __builtin_assume() with 3016 /// a non-value-dependent constant parameter evaluating as false. 3017 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const; 3018 3019 /// Used by Sema to implement MSVC-compatible delayed name lookup. 3020 /// (Usually Exprs themselves should set dependence). 3021 void markDependentForPostponedNameLookup() { 3022 setDependence(getDependence() | ExprDependence::TypeValueInstantiation); 3023 } 3024 3025 bool isCallToStdMove() const { 3026 const FunctionDecl *FD = getDirectCallee(); 3027 return getNumArgs() == 1 && FD && FD->isInStdNamespace() && 3028 FD->getIdentifier() && FD->getIdentifier()->isStr("move"); 3029 } 3030 3031 static bool classof(const Stmt *T) { 3032 return T->getStmtClass() >= firstCallExprConstant && 3033 T->getStmtClass() <= lastCallExprConstant; 3034 } 3035 3036 // Iterators 3037 child_range children() { 3038 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START + 3039 getNumPreArgs() + getNumArgs()); 3040 } 3041 3042 const_child_range children() const { 3043 return const_child_range(getTrailingStmts(), 3044 getTrailingStmts() + PREARGS_START + 3045 getNumPreArgs() + getNumArgs()); 3046 } 3047}; 3048 3049/// Extra data stored in some MemberExpr objects. 3050struct MemberExprNameQualifier { 3051 /// The nested-name-specifier that qualifies the name, including 3052 /// source-location information. 3053 NestedNameSpecifierLoc QualifierLoc; 3054 3055 /// The DeclAccessPair through which the MemberDecl was found due to 3056 /// name qualifiers. 3057 DeclAccessPair FoundDecl; 3058}; 3059 3060/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 3061/// 3062class MemberExpr final 3063 : public Expr, 3064 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier, 3065 ASTTemplateKWAndArgsInfo, 3066 TemplateArgumentLoc> { 3067 friend class ASTReader; 3068 friend class ASTStmtReader; 3069 friend class ASTStmtWriter; 3070 friend TrailingObjects; 3071 3072 /// Base - the expression for the base pointer or structure references. In 3073 /// X.F, this is "X". 3074 Stmt *Base; 3075 3076 /// MemberDecl - This is the decl being referenced by the field/member name. 3077 /// In X.F, this is the decl referenced by F. 3078 ValueDecl *MemberDecl; 3079 3080 /// MemberDNLoc - Provides source/type location info for the 3081 /// declaration name embedded in MemberDecl. 3082 DeclarationNameLoc MemberDNLoc; 3083 3084 /// MemberLoc - This is the location of the member name. 3085 SourceLocation MemberLoc; 3086 3087 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const { 3088 return hasQualifierOrFoundDecl(); 3089 } 3090 3091 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 3092 return hasTemplateKWAndArgsInfo(); 3093 } 3094 3095 bool hasQualifierOrFoundDecl() const { 3096 return MemberExprBits.HasQualifierOrFoundDecl; 3097 } 3098 3099 bool hasTemplateKWAndArgsInfo() const { 3100 return MemberExprBits.HasTemplateKWAndArgsInfo; 3101 } 3102 3103 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, 3104 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo, 3105 QualType T, ExprValueKind VK, ExprObjectKind OK, 3106 NonOdrUseReason NOUR); 3107 MemberExpr(EmptyShell Empty) 3108 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {} 3109 3110public: 3111 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow, 3112 SourceLocation OperatorLoc, 3113 NestedNameSpecifierLoc QualifierLoc, 3114 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, 3115 DeclAccessPair FoundDecl, 3116 DeclarationNameInfo MemberNameInfo, 3117 const TemplateArgumentListInfo *TemplateArgs, 3118 QualType T, ExprValueKind VK, ExprObjectKind OK, 3119 NonOdrUseReason NOUR); 3120 3121 /// Create an implicit MemberExpr, with no location, qualifier, template 3122 /// arguments, and so on. Suitable only for non-static member access. 3123 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base, 3124 bool IsArrow, ValueDecl *MemberDecl, 3125 QualType T, ExprValueKind VK, 3126 ExprObjectKind OK) { 3127 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(), 3128 SourceLocation(), MemberDecl, 3129 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()), 3130 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None); 3131 } 3132 3133 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 3134 bool HasFoundDecl, 3135 bool HasTemplateKWAndArgsInfo, 3136 unsigned NumTemplateArgs); 3137 3138 void setBase(Expr *E) { Base = E; } 3139 Expr *getBase() const { return cast<Expr>(Base); } 3140 3141 /// Retrieve the member declaration to which this expression refers. 3142 /// 3143 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for 3144 /// static data members), a CXXMethodDecl, or an EnumConstantDecl. 3145 ValueDecl *getMemberDecl() const { return MemberDecl; } 3146 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 3147 3148 /// Retrieves the declaration found by lookup. 3149 DeclAccessPair getFoundDecl() const { 3150 if (!hasQualifierOrFoundDecl()) 3151 return DeclAccessPair::make(getMemberDecl(), 3152 getMemberDecl()->getAccess()); 3153 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl; 3154 } 3155 3156 /// Determines whether this member expression actually had 3157 /// a C++ nested-name-specifier prior to the name of the member, e.g., 3158 /// x->Base::foo. 3159 bool hasQualifier() const { return getQualifier() != nullptr; } 3160 3161 /// If the member name was qualified, retrieves the 3162 /// nested-name-specifier that precedes the member name, with source-location 3163 /// information. 3164 NestedNameSpecifierLoc getQualifierLoc() const { 3165 if (!hasQualifierOrFoundDecl()) 3166 return NestedNameSpecifierLoc(); 3167 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc; 3168 } 3169 3170 /// If the member name was qualified, retrieves the 3171 /// nested-name-specifier that precedes the member name. Otherwise, returns 3172 /// NULL. 3173 NestedNameSpecifier *getQualifier() const { 3174 return getQualifierLoc().getNestedNameSpecifier(); 3175 } 3176 3177 /// Retrieve the location of the template keyword preceding 3178 /// the member name, if any. 3179 SourceLocation getTemplateKeywordLoc() const { 3180 if (!hasTemplateKWAndArgsInfo()) 3181 return SourceLocation(); 3182 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 3183 } 3184 3185 /// Retrieve the location of the left angle bracket starting the 3186 /// explicit template argument list following the member name, if any. 3187 SourceLocation getLAngleLoc() const { 3188 if (!hasTemplateKWAndArgsInfo()) 3189 return SourceLocation(); 3190 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 3191 } 3192 3193 /// Retrieve the location of the right angle bracket ending the 3194 /// explicit template argument list following the member name, if any. 3195 SourceLocation getRAngleLoc() const { 3196 if (!hasTemplateKWAndArgsInfo()) 3197 return SourceLocation(); 3198 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 3199 } 3200 3201 /// Determines whether the member name was preceded by the template keyword. 3202 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 3203 3204 /// Determines whether the member name was followed by an 3205 /// explicit template argument list. 3206 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 3207 3208 /// Copies the template arguments (if present) into the given 3209 /// structure. 3210 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 3211 if (hasExplicitTemplateArgs()) 3212 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 3213 getTrailingObjects<TemplateArgumentLoc>(), List); 3214 } 3215 3216 /// Retrieve the template arguments provided as part of this 3217 /// template-id. 3218 const TemplateArgumentLoc *getTemplateArgs() const { 3219 if (!hasExplicitTemplateArgs()) 3220 return nullptr; 3221 3222 return getTrailingObjects<TemplateArgumentLoc>(); 3223 } 3224 3225 /// Retrieve the number of template arguments provided as part of this 3226 /// template-id. 3227 unsigned getNumTemplateArgs() const { 3228 if (!hasExplicitTemplateArgs()) 3229 return 0; 3230 3231 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 3232 } 3233 3234 ArrayRef<TemplateArgumentLoc> template_arguments() const { 3235 return {getTemplateArgs(), getNumTemplateArgs()}; 3236 } 3237 3238 /// Retrieve the member declaration name info. 3239 DeclarationNameInfo getMemberNameInfo() const { 3240 return DeclarationNameInfo(MemberDecl->getDeclName(), 3241 MemberLoc, MemberDNLoc); 3242 } 3243 3244 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; } 3245 3246 bool isArrow() const { return MemberExprBits.IsArrow; } 3247 void setArrow(bool A) { MemberExprBits.IsArrow = A; } 3248 3249 /// getMemberLoc - Return the location of the "member", in X->F, it is the 3250 /// location of 'F'. 3251 SourceLocation getMemberLoc() const { return MemberLoc; } 3252 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 3253 3254 SourceLocation getBeginLoc() const LLVM_READONLY; 3255 SourceLocation getEndLoc() const LLVM_READONLY; 3256 3257 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 3258 3259 /// Determine whether the base of this explicit is implicit. 3260 bool isImplicitAccess() const { 3261 return getBase() && getBase()->isImplicitCXXThis(); 3262 } 3263 3264 /// Returns true if this member expression refers to a method that 3265 /// was resolved from an overloaded set having size greater than 1. 3266 bool hadMultipleCandidates() const { 3267 return MemberExprBits.HadMultipleCandidates; 3268 } 3269 /// Sets the flag telling whether this expression refers to 3270 /// a method that was resolved from an overloaded set having size 3271 /// greater than 1. 3272 void setHadMultipleCandidates(bool V = true) { 3273 MemberExprBits.HadMultipleCandidates = V; 3274 } 3275 3276 /// Returns true if virtual dispatch is performed. 3277 /// If the member access is fully qualified, (i.e. X::f()), virtual 3278 /// dispatching is not performed. In -fapple-kext mode qualified 3279 /// calls to virtual method will still go through the vtable. 3280 bool performsVirtualDispatch(const LangOptions &LO) const { 3281 return LO.AppleKext || !hasQualifier(); 3282 } 3283 3284 /// Is this expression a non-odr-use reference, and if so, why? 3285 /// This is only meaningful if the named member is a static member. 3286 NonOdrUseReason isNonOdrUse() const { 3287 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason); 3288 } 3289 3290 static bool classof(const Stmt *T) { 3291 return T->getStmtClass() == MemberExprClass; 3292 } 3293 3294 // Iterators 3295 child_range children() { return child_range(&Base, &Base+1); } 3296 const_child_range children() const { 3297 return const_child_range(&Base, &Base + 1); 3298 } 3299}; 3300 3301/// CompoundLiteralExpr - [C99 6.5.2.5] 3302/// 3303class CompoundLiteralExpr : public Expr { 3304 /// LParenLoc - If non-null, this is the location of the left paren in a 3305 /// compound literal like "(int){4}". This can be null if this is a 3306 /// synthesized compound expression. 3307 SourceLocation LParenLoc; 3308 3309 /// The type as written. This can be an incomplete array type, in 3310 /// which case the actual expression type will be different. 3311 /// The int part of the pair stores whether this expr is file scope. 3312 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 3313 Stmt *Init; 3314public: 3315 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 3316 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 3317 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary), 3318 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) { 3319 setDependence(computeDependence(this)); 3320 } 3321 3322 /// Construct an empty compound literal. 3323 explicit CompoundLiteralExpr(EmptyShell Empty) 3324 : Expr(CompoundLiteralExprClass, Empty) { } 3325 3326 const Expr *getInitializer() const { return cast<Expr>(Init); } 3327 Expr *getInitializer() { return cast<Expr>(Init); } 3328 void setInitializer(Expr *E) { Init = E; } 3329 3330 bool isFileScope() const { return TInfoAndScope.getInt(); } 3331 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 3332 3333 SourceLocation getLParenLoc() const { return LParenLoc; } 3334 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3335 3336 TypeSourceInfo *getTypeSourceInfo() const { 3337 return TInfoAndScope.getPointer(); 3338 } 3339 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 3340 TInfoAndScope.setPointer(tinfo); 3341 } 3342 3343 SourceLocation getBeginLoc() const LLVM_READONLY { 3344 // FIXME: Init should never be null. 3345 if (!Init) 3346 return SourceLocation(); 3347 if (LParenLoc.isInvalid()) 3348 return Init->getBeginLoc(); 3349 return LParenLoc; 3350 } 3351 SourceLocation getEndLoc() const LLVM_READONLY { 3352 // FIXME: Init should never be null. 3353 if (!Init) 3354 return SourceLocation(); 3355 return Init->getEndLoc(); 3356 } 3357 3358 static bool classof(const Stmt *T) { 3359 return T->getStmtClass() == CompoundLiteralExprClass; 3360 } 3361 3362 // Iterators 3363 child_range children() { return child_range(&Init, &Init+1); } 3364 const_child_range children() const { 3365 return const_child_range(&Init, &Init + 1); 3366 } 3367}; 3368 3369/// CastExpr - Base class for type casts, including both implicit 3370/// casts (ImplicitCastExpr) and explicit casts that have some 3371/// representation in the source code (ExplicitCastExpr's derived 3372/// classes). 3373class CastExpr : public Expr { 3374 Stmt *Op; 3375 3376 bool CastConsistency() const; 3377 3378 const CXXBaseSpecifier * const *path_buffer() const { 3379 return const_cast<CastExpr*>(this)->path_buffer(); 3380 } 3381 CXXBaseSpecifier **path_buffer(); 3382 3383protected: 3384 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, 3385 Expr *op, unsigned BasePathSize) 3386 : Expr(SC, ty, VK, OK_Ordinary), Op(op) { 3387 CastExprBits.Kind = kind; 3388 CastExprBits.PartOfExplicitCast = false; 3389 CastExprBits.BasePathSize = BasePathSize; 3390 assert((CastExprBits.BasePathSize == BasePathSize) && 3391 "BasePathSize overflow!"); 3392 setDependence(computeDependence(this)); 3393 assert(CastConsistency()); 3394 } 3395 3396 /// Construct an empty cast. 3397 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 3398 : Expr(SC, Empty) { 3399 CastExprBits.PartOfExplicitCast = false; 3400 CastExprBits.BasePathSize = BasePathSize; 3401 assert((CastExprBits.BasePathSize == BasePathSize) && 3402 "BasePathSize overflow!"); 3403 } 3404 3405public: 3406 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 3407 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 3408 3409 static const char *getCastKindName(CastKind CK); 3410 const char *getCastKindName() const { return getCastKindName(getCastKind()); } 3411 3412 Expr *getSubExpr() { return cast<Expr>(Op); } 3413 const Expr *getSubExpr() const { return cast<Expr>(Op); } 3414 void setSubExpr(Expr *E) { Op = E; } 3415 3416 /// Retrieve the cast subexpression as it was written in the source 3417 /// code, looking through any implicit casts or other intermediate nodes 3418 /// introduced by semantic analysis. 3419 Expr *getSubExprAsWritten(); 3420 const Expr *getSubExprAsWritten() const { 3421 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 3422 } 3423 3424 /// If this cast applies a user-defined conversion, retrieve the conversion 3425 /// function that it invokes. 3426 NamedDecl *getConversionFunction() const; 3427 3428 typedef CXXBaseSpecifier **path_iterator; 3429 typedef const CXXBaseSpecifier *const *path_const_iterator; 3430 bool path_empty() const { return path_size() == 0; } 3431 unsigned path_size() const { return CastExprBits.BasePathSize; } 3432 path_iterator path_begin() { return path_buffer(); } 3433 path_iterator path_end() { return path_buffer() + path_size(); } 3434 path_const_iterator path_begin() const { return path_buffer(); } 3435 path_const_iterator path_end() const { return path_buffer() + path_size(); } 3436 3437 llvm::iterator_range<path_iterator> path() { 3438 return llvm::make_range(path_begin(), path_end()); 3439 } 3440 llvm::iterator_range<path_const_iterator> path() const { 3441 return llvm::make_range(path_begin(), path_end()); 3442 } 3443 3444 const FieldDecl *getTargetUnionField() const { 3445 assert(getCastKind() == CK_ToUnion); 3446 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType()); 3447 } 3448 3449 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType, 3450 QualType opType); 3451 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD, 3452 QualType opType); 3453 3454 static bool classof(const Stmt *T) { 3455 return T->getStmtClass() >= firstCastExprConstant && 3456 T->getStmtClass() <= lastCastExprConstant; 3457 } 3458 3459 // Iterators 3460 child_range children() { return child_range(&Op, &Op+1); } 3461 const_child_range children() const { return const_child_range(&Op, &Op + 1); } 3462}; 3463 3464/// ImplicitCastExpr - Allows us to explicitly represent implicit type 3465/// conversions, which have no direct representation in the original 3466/// source code. For example: converting T[]->T*, void f()->void 3467/// (*f)(), float->double, short->int, etc. 3468/// 3469/// In C, implicit casts always produce rvalues. However, in C++, an 3470/// implicit cast whose result is being bound to a reference will be 3471/// an lvalue or xvalue. For example: 3472/// 3473/// @code 3474/// class Base { }; 3475/// class Derived : public Base { }; 3476/// Derived &&ref(); 3477/// void f(Derived d) { 3478/// Base& b = d; // initializer is an ImplicitCastExpr 3479/// // to an lvalue of type Base 3480/// Base&& r = ref(); // initializer is an ImplicitCastExpr 3481/// // to an xvalue of type Base 3482/// } 3483/// @endcode 3484class ImplicitCastExpr final 3485 : public CastExpr, 3486 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> { 3487 3488 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 3489 unsigned BasePathLength, ExprValueKind VK) 3490 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { } 3491 3492 /// Construct an empty implicit cast. 3493 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 3494 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 3495 3496public: 3497 enum OnStack_t { OnStack }; 3498 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 3499 ExprValueKind VK) 3500 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 3501 } 3502 3503 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; } 3504 void setIsPartOfExplicitCast(bool PartOfExplicitCast) { 3505 CastExprBits.PartOfExplicitCast = PartOfExplicitCast; 3506 } 3507 3508 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, 3509 CastKind Kind, Expr *Operand, 3510 const CXXCastPath *BasePath, 3511 ExprValueKind Cat); 3512 3513 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, 3514 unsigned PathSize); 3515 3516 SourceLocation getBeginLoc() const LLVM_READONLY { 3517 return getSubExpr()->getBeginLoc(); 3518 } 3519 SourceLocation getEndLoc() const LLVM_READONLY { 3520 return getSubExpr()->getEndLoc(); 3521 } 3522 3523 static bool classof(const Stmt *T) { 3524 return T->getStmtClass() == ImplicitCastExprClass; 3525 } 3526 3527 friend TrailingObjects; 3528 friend class CastExpr; 3529}; 3530 3531/// ExplicitCastExpr - An explicit cast written in the source 3532/// code. 3533/// 3534/// This class is effectively an abstract class, because it provides 3535/// the basic representation of an explicitly-written cast without 3536/// specifying which kind of cast (C cast, functional cast, static 3537/// cast, etc.) was written; specific derived classes represent the 3538/// particular style of cast and its location information. 3539/// 3540/// Unlike implicit casts, explicit cast nodes have two different 3541/// types: the type that was written into the source code, and the 3542/// actual type of the expression as determined by semantic 3543/// analysis. These types may differ slightly. For example, in C++ one 3544/// can cast to a reference type, which indicates that the resulting 3545/// expression will be an lvalue or xvalue. The reference type, however, 3546/// will not be used as the type of the expression. 3547class ExplicitCastExpr : public CastExpr { 3548 /// TInfo - Source type info for the (written) type 3549 /// this expression is casting to. 3550 TypeSourceInfo *TInfo; 3551 3552protected: 3553 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 3554 CastKind kind, Expr *op, unsigned PathSize, 3555 TypeSourceInfo *writtenTy) 3556 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 3557 3558 /// Construct an empty explicit cast. 3559 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 3560 : CastExpr(SC, Shell, PathSize) { } 3561 3562public: 3563 /// getTypeInfoAsWritten - Returns the type source info for the type 3564 /// that this expression is casting to. 3565 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 3566 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 3567 3568 /// getTypeAsWritten - Returns the type that this expression is 3569 /// casting to, as written in the source code. 3570 QualType getTypeAsWritten() const { return TInfo->getType(); } 3571 3572 static bool classof(const Stmt *T) { 3573 return T->getStmtClass() >= firstExplicitCastExprConstant && 3574 T->getStmtClass() <= lastExplicitCastExprConstant; 3575 } 3576}; 3577 3578/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 3579/// cast in C++ (C++ [expr.cast]), which uses the syntax 3580/// (Type)expr. For example: @c (int)f. 3581class CStyleCastExpr final 3582 : public ExplicitCastExpr, 3583 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> { 3584 SourceLocation LPLoc; // the location of the left paren 3585 SourceLocation RPLoc; // the location of the right paren 3586 3587 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 3588 unsigned PathSize, TypeSourceInfo *writtenTy, 3589 SourceLocation l, SourceLocation r) 3590 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 3591 writtenTy), LPLoc(l), RPLoc(r) {} 3592 3593 /// Construct an empty C-style explicit cast. 3594 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 3595 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 3596 3597public: 3598 static CStyleCastExpr *Create(const ASTContext &Context, QualType T, 3599 ExprValueKind VK, CastKind K, 3600 Expr *Op, const CXXCastPath *BasePath, 3601 TypeSourceInfo *WrittenTy, SourceLocation L, 3602 SourceLocation R); 3603 3604 static CStyleCastExpr *CreateEmpty(const ASTContext &Context, 3605 unsigned PathSize); 3606 3607 SourceLocation getLParenLoc() const { return LPLoc; } 3608 void setLParenLoc(SourceLocation L) { LPLoc = L; } 3609 3610 SourceLocation getRParenLoc() const { return RPLoc; } 3611 void setRParenLoc(SourceLocation L) { RPLoc = L; } 3612 3613 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; } 3614 SourceLocation getEndLoc() const LLVM_READONLY { 3615 return getSubExpr()->getEndLoc(); 3616 } 3617 3618 static bool classof(const Stmt *T) { 3619 return T->getStmtClass() == CStyleCastExprClass; 3620 } 3621 3622 friend TrailingObjects; 3623 friend class CastExpr; 3624}; 3625 3626/// A builtin binary operation expression such as "x + y" or "x <= y". 3627/// 3628/// This expression node kind describes a builtin binary operation, 3629/// such as "x + y" for integer values "x" and "y". The operands will 3630/// already have been converted to appropriate types (e.g., by 3631/// performing promotions or conversions). 3632/// 3633/// In C++, where operators may be overloaded, a different kind of 3634/// expression node (CXXOperatorCallExpr) is used to express the 3635/// invocation of an overloaded operator with operator syntax. Within 3636/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 3637/// used to store an expression "x + y" depends on the subexpressions 3638/// for x and y. If neither x or y is type-dependent, and the "+" 3639/// operator resolves to a built-in operation, BinaryOperator will be 3640/// used to express the computation (x and y may still be 3641/// value-dependent). If either x or y is type-dependent, or if the 3642/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 3643/// be used to express the computation. 3644class BinaryOperator : public Expr { 3645 enum { LHS, RHS, END_EXPR }; 3646 Stmt *SubExprs[END_EXPR]; 3647 3648public: 3649 typedef BinaryOperatorKind Opcode; 3650 3651protected: 3652 size_t offsetOfTrailingStorage() const; 3653 3654 /// Return a pointer to the trailing FPOptions 3655 FPOptionsOverride *getTrailingFPFeatures() { 3656 assert(BinaryOperatorBits.HasFPFeatures); 3657 return reinterpret_cast<FPOptionsOverride *>( 3658 reinterpret_cast<char *>(this) + offsetOfTrailingStorage()); 3659 } 3660 const FPOptionsOverride *getTrailingFPFeatures() const { 3661 assert(BinaryOperatorBits.HasFPFeatures); 3662 return reinterpret_cast<const FPOptionsOverride *>( 3663 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage()); 3664 } 3665 3666 /// Build a binary operator, assuming that appropriate storage has been 3667 /// allocated for the trailing objects when needed. 3668 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc, 3669 QualType ResTy, ExprValueKind VK, ExprObjectKind OK, 3670 SourceLocation opLoc, FPOptionsOverride FPFeatures); 3671 3672 /// Construct an empty binary operator. 3673 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) { 3674 BinaryOperatorBits.Opc = BO_Comma; 3675 } 3676 3677public: 3678 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures); 3679 3680 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs, 3681 Opcode opc, QualType ResTy, ExprValueKind VK, 3682 ExprObjectKind OK, SourceLocation opLoc, 3683 FPOptionsOverride FPFeatures); 3684 SourceLocation getExprLoc() const { return getOperatorLoc(); } 3685 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; } 3686 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; } 3687 3688 Opcode getOpcode() const { 3689 return static_cast<Opcode>(BinaryOperatorBits.Opc); 3690 } 3691 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; } 3692 3693 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3694 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3695 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3696 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3697 3698 SourceLocation getBeginLoc() const LLVM_READONLY { 3699 return getLHS()->getBeginLoc(); 3700 } 3701 SourceLocation getEndLoc() const LLVM_READONLY { 3702 return getRHS()->getEndLoc(); 3703 } 3704 3705 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 3706 /// corresponds to, e.g. "<<=". 3707 static StringRef getOpcodeStr(Opcode Op); 3708 3709 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 3710 3711 /// Retrieve the binary opcode that corresponds to the given 3712 /// overloaded operator. 3713 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 3714 3715 /// Retrieve the overloaded operator kind that corresponds to 3716 /// the given binary opcode. 3717 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 3718 3719 /// predicates to categorize the respective opcodes. 3720 static bool isPtrMemOp(Opcode Opc) { 3721 return Opc == BO_PtrMemD || Opc == BO_PtrMemI; 3722 } 3723 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); } 3724 3725 static bool isMultiplicativeOp(Opcode Opc) { 3726 return Opc >= BO_Mul && Opc <= BO_Rem; 3727 } 3728 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } 3729 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 3730 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 3731 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 3732 bool isShiftOp() const { return isShiftOp(getOpcode()); } 3733 3734 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 3735 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 3736 3737 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 3738 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 3739 3740 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 3741 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 3742 3743 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; } 3744 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 3745 3746 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; } 3747 bool isCommaOp() const { return isCommaOp(getOpcode()); } 3748 3749 static Opcode negateComparisonOp(Opcode Opc) { 3750 switch (Opc) { 3751 default: 3752 llvm_unreachable("Not a comparison operator."); 3753 case BO_LT: return BO_GE; 3754 case BO_GT: return BO_LE; 3755 case BO_LE: return BO_GT; 3756 case BO_GE: return BO_LT; 3757 case BO_EQ: return BO_NE; 3758 case BO_NE: return BO_EQ; 3759 } 3760 } 3761 3762 static Opcode reverseComparisonOp(Opcode Opc) { 3763 switch (Opc) { 3764 default: 3765 llvm_unreachable("Not a comparison operator."); 3766 case BO_LT: return BO_GT; 3767 case BO_GT: return BO_LT; 3768 case BO_LE: return BO_GE; 3769 case BO_GE: return BO_LE; 3770 case BO_EQ: 3771 case BO_NE: 3772 return Opc; 3773 } 3774 } 3775 3776 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 3777 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 3778 3779 static bool isAssignmentOp(Opcode Opc) { 3780 return Opc >= BO_Assign && Opc <= BO_OrAssign; 3781 } 3782 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 3783 3784 static bool isCompoundAssignmentOp(Opcode Opc) { 3785 return Opc > BO_Assign && Opc <= BO_OrAssign; 3786 } 3787 bool isCompoundAssignmentOp() const { 3788 return isCompoundAssignmentOp(getOpcode()); 3789 } 3790 static Opcode getOpForCompoundAssignment(Opcode Opc) { 3791 assert(isCompoundAssignmentOp(Opc)); 3792 if (Opc >= BO_AndAssign) 3793 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 3794 else 3795 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 3796 } 3797 3798 static bool isShiftAssignOp(Opcode Opc) { 3799 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 3800 } 3801 bool isShiftAssignOp() const { 3802 return isShiftAssignOp(getOpcode()); 3803 } 3804 3805 // Return true if a binary operator using the specified opcode and operands 3806 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized 3807 // integer to a pointer. 3808 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, 3809 Expr *LHS, Expr *RHS); 3810 3811 static bool classof(const Stmt *S) { 3812 return S->getStmtClass() >= firstBinaryOperatorConstant && 3813 S->getStmtClass() <= lastBinaryOperatorConstant; 3814 } 3815 3816 // Iterators 3817 child_range children() { 3818 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3819 } 3820 const_child_range children() const { 3821 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 3822 } 3823 3824 /// Set and fetch the bit that shows whether FPFeatures needs to be 3825 /// allocated in Trailing Storage 3826 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; } 3827 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; } 3828 3829 /// Get FPFeatures from trailing storage 3830 FPOptionsOverride getStoredFPFeatures() const { 3831 assert(hasStoredFPFeatures()); 3832 return *getTrailingFPFeatures(); 3833 } 3834 /// Set FPFeatures in trailing storage, used only by Serialization 3835 void setStoredFPFeatures(FPOptionsOverride F) { 3836 assert(BinaryOperatorBits.HasFPFeatures); 3837 *getTrailingFPFeatures() = F; 3838 } 3839 3840 // Get the FP features status of this operator. Only meaningful for 3841 // operations on floating point types. 3842 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const { 3843 if (BinaryOperatorBits.HasFPFeatures) 3844 return getStoredFPFeatures().applyOverrides(LO); 3845 return FPOptions::defaultWithoutTrailingStorage(LO); 3846 } 3847 3848 // This is used in ASTImporter 3849 FPOptionsOverride getFPFeatures(const LangOptions &LO) const { 3850 if (BinaryOperatorBits.HasFPFeatures) 3851 return getStoredFPFeatures(); 3852 return FPOptionsOverride(); 3853 } 3854 3855 // Get the FP contractability status of this operator. Only meaningful for 3856 // operations on floating point types. 3857 bool isFPContractableWithinStatement(const LangOptions &LO) const { 3858 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement(); 3859 } 3860 3861 // Get the FENV_ACCESS status of this operator. Only meaningful for 3862 // operations on floating point types. 3863 bool isFEnvAccessOn(const LangOptions &LO) const { 3864 return getFPFeaturesInEffect(LO).getAllowFEnvAccess(); 3865 } 3866 3867protected: 3868 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc, 3869 QualType ResTy, ExprValueKind VK, ExprObjectKind OK, 3870 SourceLocation opLoc, FPOptionsOverride FPFeatures, 3871 bool dead2); 3872 3873 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator. 3874 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { 3875 BinaryOperatorBits.Opc = BO_MulAssign; 3876 } 3877 3878 /// Return the size in bytes needed for the trailing objects. 3879 /// Used to allocate the right amount of storage. 3880 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) { 3881 return HasFPFeatures * sizeof(FPOptionsOverride); 3882 } 3883}; 3884 3885/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 3886/// track of the type the operation is performed in. Due to the semantics of 3887/// these operators, the operands are promoted, the arithmetic performed, an 3888/// implicit conversion back to the result type done, then the assignment takes 3889/// place. This captures the intermediate type which the computation is done 3890/// in. 3891class CompoundAssignOperator : public BinaryOperator { 3892 QualType ComputationLHSType; 3893 QualType ComputationResultType; 3894 3895 /// Construct an empty CompoundAssignOperator. 3896 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty, 3897 bool hasFPFeatures) 3898 : BinaryOperator(CompoundAssignOperatorClass, Empty) {} 3899 3900protected: 3901 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, 3902 QualType ResType, ExprValueKind VK, ExprObjectKind OK, 3903 SourceLocation OpLoc, FPOptionsOverride FPFeatures, 3904 QualType CompLHSType, QualType CompResultType) 3905 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, 3906 true), 3907 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) { 3908 assert(isCompoundAssignmentOp() && 3909 "Only should be used for compound assignments"); 3910 } 3911 3912public: 3913 static CompoundAssignOperator *CreateEmpty(const ASTContext &C, 3914 bool hasFPFeatures); 3915 3916 static CompoundAssignOperator * 3917 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3918 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, 3919 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(), 3920 QualType CompResultType = QualType()); 3921 3922 // The two computation types are the type the LHS is converted 3923 // to for the computation and the type of the result; the two are 3924 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 3925 QualType getComputationLHSType() const { return ComputationLHSType; } 3926 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 3927 3928 QualType getComputationResultType() const { return ComputationResultType; } 3929 void setComputationResultType(QualType T) { ComputationResultType = T; } 3930 3931 static bool classof(const Stmt *S) { 3932 return S->getStmtClass() == CompoundAssignOperatorClass; 3933 } 3934}; 3935 3936inline size_t BinaryOperator::offsetOfTrailingStorage() const { 3937 assert(BinaryOperatorBits.HasFPFeatures); 3938 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator) 3939 : sizeof(BinaryOperator); 3940} 3941 3942/// AbstractConditionalOperator - An abstract base class for 3943/// ConditionalOperator and BinaryConditionalOperator. 3944class AbstractConditionalOperator : public Expr { 3945 SourceLocation QuestionLoc, ColonLoc; 3946 friend class ASTStmtReader; 3947 3948protected: 3949 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK, 3950 ExprObjectKind OK, SourceLocation qloc, 3951 SourceLocation cloc) 3952 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {} 3953 3954 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 3955 : Expr(SC, Empty) { } 3956 3957public: 3958 // getCond - Return the expression representing the condition for 3959 // the ?: operator. 3960 Expr *getCond() const; 3961 3962 // getTrueExpr - Return the subexpression representing the value of 3963 // the expression if the condition evaluates to true. 3964 Expr *getTrueExpr() const; 3965 3966 // getFalseExpr - Return the subexpression representing the value of 3967 // the expression if the condition evaluates to false. This is 3968 // the same as getRHS. 3969 Expr *getFalseExpr() const; 3970 3971 SourceLocation getQuestionLoc() const { return QuestionLoc; } 3972 SourceLocation getColonLoc() const { return ColonLoc; } 3973 3974 static bool classof(const Stmt *T) { 3975 return T->getStmtClass() == ConditionalOperatorClass || 3976 T->getStmtClass() == BinaryConditionalOperatorClass; 3977 } 3978}; 3979 3980/// ConditionalOperator - The ?: ternary operator. The GNU "missing 3981/// middle" extension is a BinaryConditionalOperator. 3982class ConditionalOperator : public AbstractConditionalOperator { 3983 enum { COND, LHS, RHS, END_EXPR }; 3984 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3985 3986 friend class ASTStmtReader; 3987public: 3988 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 3989 SourceLocation CLoc, Expr *rhs, QualType t, 3990 ExprValueKind VK, ExprObjectKind OK) 3991 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc, 3992 CLoc) { 3993 SubExprs[COND] = cond; 3994 SubExprs[LHS] = lhs; 3995 SubExprs[RHS] = rhs; 3996 setDependence(computeDependence(this)); 3997 } 3998 3999 /// Build an empty conditional operator. 4000 explicit ConditionalOperator(EmptyShell Empty) 4001 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 4002 4003 // getCond - Return the expression representing the condition for 4004 // the ?: operator. 4005 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4006 4007 // getTrueExpr - Return the subexpression representing the value of 4008 // the expression if the condition evaluates to true. 4009 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 4010 4011 // getFalseExpr - Return the subexpression representing the value of 4012 // the expression if the condition evaluates to false. This is 4013 // the same as getRHS. 4014 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 4015 4016 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 4017 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 4018 4019 SourceLocation getBeginLoc() const LLVM_READONLY { 4020 return getCond()->getBeginLoc(); 4021 } 4022 SourceLocation getEndLoc() const LLVM_READONLY { 4023 return getRHS()->getEndLoc(); 4024 } 4025 4026 static bool classof(const Stmt *T) { 4027 return T->getStmtClass() == ConditionalOperatorClass; 4028 } 4029 4030 // Iterators 4031 child_range children() { 4032 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4033 } 4034 const_child_range children() const { 4035 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4036 } 4037}; 4038 4039/// BinaryConditionalOperator - The GNU extension to the conditional 4040/// operator which allows the middle operand to be omitted. 4041/// 4042/// This is a different expression kind on the assumption that almost 4043/// every client ends up needing to know that these are different. 4044class BinaryConditionalOperator : public AbstractConditionalOperator { 4045 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 4046 4047 /// - the common condition/left-hand-side expression, which will be 4048 /// evaluated as the opaque value 4049 /// - the condition, expressed in terms of the opaque value 4050 /// - the left-hand-side, expressed in terms of the opaque value 4051 /// - the right-hand-side 4052 Stmt *SubExprs[NUM_SUBEXPRS]; 4053 OpaqueValueExpr *OpaqueValue; 4054 4055 friend class ASTStmtReader; 4056public: 4057 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 4058 Expr *cond, Expr *lhs, Expr *rhs, 4059 SourceLocation qloc, SourceLocation cloc, 4060 QualType t, ExprValueKind VK, ExprObjectKind OK) 4061 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 4062 qloc, cloc), 4063 OpaqueValue(opaqueValue) { 4064 SubExprs[COMMON] = common; 4065 SubExprs[COND] = cond; 4066 SubExprs[LHS] = lhs; 4067 SubExprs[RHS] = rhs; 4068 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); 4069 setDependence(computeDependence(this)); 4070 } 4071 4072 /// Build an empty conditional operator. 4073 explicit BinaryConditionalOperator(EmptyShell Empty) 4074 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 4075 4076 /// getCommon - Return the common expression, written to the 4077 /// left of the condition. The opaque value will be bound to the 4078 /// result of this expression. 4079 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 4080 4081 /// getOpaqueValue - Return the opaque value placeholder. 4082 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 4083 4084 /// getCond - Return the condition expression; this is defined 4085 /// in terms of the opaque value. 4086 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4087 4088 /// getTrueExpr - Return the subexpression which will be 4089 /// evaluated if the condition evaluates to true; this is defined 4090 /// in terms of the opaque value. 4091 Expr *getTrueExpr() const { 4092 return cast<Expr>(SubExprs[LHS]); 4093 } 4094 4095 /// getFalseExpr - Return the subexpression which will be 4096 /// evaluated if the condnition evaluates to false; this is 4097 /// defined in terms of the opaque value. 4098 Expr *getFalseExpr() const { 4099 return cast<Expr>(SubExprs[RHS]); 4100 } 4101 4102 SourceLocation getBeginLoc() const LLVM_READONLY { 4103 return getCommon()->getBeginLoc(); 4104 } 4105 SourceLocation getEndLoc() const LLVM_READONLY { 4106 return getFalseExpr()->getEndLoc(); 4107 } 4108 4109 static bool classof(const Stmt *T) { 4110 return T->getStmtClass() == BinaryConditionalOperatorClass; 4111 } 4112 4113 // Iterators 4114 child_range children() { 4115 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 4116 } 4117 const_child_range children() const { 4118 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 4119 } 4120}; 4121 4122inline Expr *AbstractConditionalOperator::getCond() const { 4123 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4124 return co->getCond(); 4125 return cast<BinaryConditionalOperator>(this)->getCond(); 4126} 4127 4128inline Expr *AbstractConditionalOperator::getTrueExpr() const { 4129 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4130 return co->getTrueExpr(); 4131 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 4132} 4133 4134inline Expr *AbstractConditionalOperator::getFalseExpr() const { 4135 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 4136 return co->getFalseExpr(); 4137 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 4138} 4139 4140/// AddrLabelExpr - The GNU address of label extension, representing &&label. 4141class AddrLabelExpr : public Expr { 4142 SourceLocation AmpAmpLoc, LabelLoc; 4143 LabelDecl *Label; 4144public: 4145 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 4146 QualType t) 4147 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary), AmpAmpLoc(AALoc), 4148 LabelLoc(LLoc), Label(L) { 4149 setDependence(ExprDependence::None); 4150 } 4151 4152 /// Build an empty address of a label expression. 4153 explicit AddrLabelExpr(EmptyShell Empty) 4154 : Expr(AddrLabelExprClass, Empty) { } 4155 4156 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 4157 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 4158 SourceLocation getLabelLoc() const { return LabelLoc; } 4159 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 4160 4161 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; } 4162 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; } 4163 4164 LabelDecl *getLabel() const { return Label; } 4165 void setLabel(LabelDecl *L) { Label = L; } 4166 4167 static bool classof(const Stmt *T) { 4168 return T->getStmtClass() == AddrLabelExprClass; 4169 } 4170 4171 // Iterators 4172 child_range children() { 4173 return child_range(child_iterator(), child_iterator()); 4174 } 4175 const_child_range children() const { 4176 return const_child_range(const_child_iterator(), const_child_iterator()); 4177 } 4178}; 4179 4180/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 4181/// The StmtExpr contains a single CompoundStmt node, which it evaluates and 4182/// takes the value of the last subexpression. 4183/// 4184/// A StmtExpr is always an r-value; values "returned" out of a 4185/// StmtExpr will be copied. 4186class StmtExpr : public Expr { 4187 Stmt *SubStmt; 4188 SourceLocation LParenLoc, RParenLoc; 4189public: 4190 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc, 4191 SourceLocation RParenLoc, unsigned TemplateDepth) 4192 : Expr(StmtExprClass, T, VK_RValue, OK_Ordinary), SubStmt(SubStmt), 4193 LParenLoc(LParenLoc), RParenLoc(RParenLoc) { 4194 setDependence(computeDependence(this, TemplateDepth)); 4195 // FIXME: A templated statement expression should have an associated 4196 // DeclContext so that nested declarations always have a dependent context. 4197 StmtExprBits.TemplateDepth = TemplateDepth; 4198 } 4199 4200 /// Build an empty statement expression. 4201 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 4202 4203 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 4204 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 4205 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 4206 4207 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; } 4208 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4209 4210 SourceLocation getLParenLoc() const { return LParenLoc; } 4211 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 4212 SourceLocation getRParenLoc() const { return RParenLoc; } 4213 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4214 4215 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; } 4216 4217 static bool classof(const Stmt *T) { 4218 return T->getStmtClass() == StmtExprClass; 4219 } 4220 4221 // Iterators 4222 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 4223 const_child_range children() const { 4224 return const_child_range(&SubStmt, &SubStmt + 1); 4225 } 4226}; 4227 4228/// ShuffleVectorExpr - clang-specific builtin-in function 4229/// __builtin_shufflevector. 4230/// This AST node represents a operator that does a constant 4231/// shuffle, similar to LLVM's shufflevector instruction. It takes 4232/// two vectors and a variable number of constant indices, 4233/// and returns the appropriately shuffled vector. 4234class ShuffleVectorExpr : public Expr { 4235 SourceLocation BuiltinLoc, RParenLoc; 4236 4237 // SubExprs - the list of values passed to the __builtin_shufflevector 4238 // function. The first two are vectors, and the rest are constant 4239 // indices. The number of values in this list is always 4240 // 2+the number of indices in the vector type. 4241 Stmt **SubExprs; 4242 unsigned NumExprs; 4243 4244public: 4245 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, 4246 SourceLocation BLoc, SourceLocation RP); 4247 4248 /// Build an empty vector-shuffle expression. 4249 explicit ShuffleVectorExpr(EmptyShell Empty) 4250 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } 4251 4252 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4253 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4254 4255 SourceLocation getRParenLoc() const { return RParenLoc; } 4256 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4257 4258 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4259 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4260 4261 static bool classof(const Stmt *T) { 4262 return T->getStmtClass() == ShuffleVectorExprClass; 4263 } 4264 4265 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 4266 /// constant expression, the actual arguments passed in, and the function 4267 /// pointers. 4268 unsigned getNumSubExprs() const { return NumExprs; } 4269 4270 /// Retrieve the array of expressions. 4271 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4272 4273 /// getExpr - Return the Expr at the specified index. 4274 Expr *getExpr(unsigned Index) { 4275 assert((Index < NumExprs) && "Arg access out of range!"); 4276 return cast<Expr>(SubExprs[Index]); 4277 } 4278 const Expr *getExpr(unsigned Index) const { 4279 assert((Index < NumExprs) && "Arg access out of range!"); 4280 return cast<Expr>(SubExprs[Index]); 4281 } 4282 4283 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); 4284 4285 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { 4286 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 4287 return getExpr(N+2)->EvaluateKnownConstInt(Ctx); 4288 } 4289 4290 // Iterators 4291 child_range children() { 4292 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 4293 } 4294 const_child_range children() const { 4295 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); 4296 } 4297}; 4298 4299/// ConvertVectorExpr - Clang builtin function __builtin_convertvector 4300/// This AST node provides support for converting a vector type to another 4301/// vector type of the same arity. 4302class ConvertVectorExpr : public Expr { 4303private: 4304 Stmt *SrcExpr; 4305 TypeSourceInfo *TInfo; 4306 SourceLocation BuiltinLoc, RParenLoc; 4307 4308 friend class ASTReader; 4309 friend class ASTStmtReader; 4310 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} 4311 4312public: 4313 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, 4314 ExprValueKind VK, ExprObjectKind OK, 4315 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4316 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr), 4317 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) { 4318 setDependence(computeDependence(this)); 4319 } 4320 4321 /// getSrcExpr - Return the Expr to be converted. 4322 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4323 4324 /// getTypeSourceInfo - Return the destination type. 4325 TypeSourceInfo *getTypeSourceInfo() const { 4326 return TInfo; 4327 } 4328 void setTypeSourceInfo(TypeSourceInfo *ti) { 4329 TInfo = ti; 4330 } 4331 4332 /// getBuiltinLoc - Return the location of the __builtin_convertvector token. 4333 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4334 4335 /// getRParenLoc - Return the location of final right parenthesis. 4336 SourceLocation getRParenLoc() const { return RParenLoc; } 4337 4338 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4339 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4340 4341 static bool classof(const Stmt *T) { 4342 return T->getStmtClass() == ConvertVectorExprClass; 4343 } 4344 4345 // Iterators 4346 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4347 const_child_range children() const { 4348 return const_child_range(&SrcExpr, &SrcExpr + 1); 4349 } 4350}; 4351 4352/// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 4353/// This AST node is similar to the conditional operator (?:) in C, with 4354/// the following exceptions: 4355/// - the test expression must be a integer constant expression. 4356/// - the expression returned acts like the chosen subexpression in every 4357/// visible way: the type is the same as that of the chosen subexpression, 4358/// and all predicates (whether it's an l-value, whether it's an integer 4359/// constant expression, etc.) return the same result as for the chosen 4360/// sub-expression. 4361class ChooseExpr : public Expr { 4362 enum { COND, LHS, RHS, END_EXPR }; 4363 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 4364 SourceLocation BuiltinLoc, RParenLoc; 4365 bool CondIsTrue; 4366public: 4367 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t, 4368 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP, 4369 bool condIsTrue) 4370 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP), 4371 CondIsTrue(condIsTrue) { 4372 SubExprs[COND] = cond; 4373 SubExprs[LHS] = lhs; 4374 SubExprs[RHS] = rhs; 4375 4376 setDependence(computeDependence(this)); 4377 } 4378 4379 /// Build an empty __builtin_choose_expr. 4380 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 4381 4382 /// isConditionTrue - Return whether the condition is true (i.e. not 4383 /// equal to zero). 4384 bool isConditionTrue() const { 4385 assert(!isConditionDependent() && 4386 "Dependent condition isn't true or false"); 4387 return CondIsTrue; 4388 } 4389 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } 4390 4391 bool isConditionDependent() const { 4392 return getCond()->isTypeDependent() || getCond()->isValueDependent(); 4393 } 4394 4395 /// getChosenSubExpr - Return the subexpression chosen according to the 4396 /// condition. 4397 Expr *getChosenSubExpr() const { 4398 return isConditionTrue() ? getLHS() : getRHS(); 4399 } 4400 4401 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4402 void setCond(Expr *E) { SubExprs[COND] = E; } 4403 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 4404 void setLHS(Expr *E) { SubExprs[LHS] = E; } 4405 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 4406 void setRHS(Expr *E) { SubExprs[RHS] = E; } 4407 4408 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4409 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4410 4411 SourceLocation getRParenLoc() const { return RParenLoc; } 4412 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4413 4414 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4415 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4416 4417 static bool classof(const Stmt *T) { 4418 return T->getStmtClass() == ChooseExprClass; 4419 } 4420 4421 // Iterators 4422 child_range children() { 4423 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4424 } 4425 const_child_range children() const { 4426 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4427 } 4428}; 4429 4430/// GNUNullExpr - Implements the GNU __null extension, which is a name 4431/// for a null pointer constant that has integral type (e.g., int or 4432/// long) and is the same size and alignment as a pointer. The __null 4433/// extension is typically only used by system headers, which define 4434/// NULL as __null in C++ rather than using 0 (which is an integer 4435/// that may not match the size of a pointer). 4436class GNUNullExpr : public Expr { 4437 /// TokenLoc - The location of the __null keyword. 4438 SourceLocation TokenLoc; 4439 4440public: 4441 GNUNullExpr(QualType Ty, SourceLocation Loc) 4442 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary), TokenLoc(Loc) { 4443 setDependence(ExprDependence::None); 4444 } 4445 4446 /// Build an empty GNU __null expression. 4447 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 4448 4449 /// getTokenLocation - The location of the __null token. 4450 SourceLocation getTokenLocation() const { return TokenLoc; } 4451 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 4452 4453 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; } 4454 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; } 4455 4456 static bool classof(const Stmt *T) { 4457 return T->getStmtClass() == GNUNullExprClass; 4458 } 4459 4460 // Iterators 4461 child_range children() { 4462 return child_range(child_iterator(), child_iterator()); 4463 } 4464 const_child_range children() const { 4465 return const_child_range(const_child_iterator(), const_child_iterator()); 4466 } 4467}; 4468 4469/// Represents a call to the builtin function \c __builtin_va_arg. 4470class VAArgExpr : public Expr { 4471 Stmt *Val; 4472 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo; 4473 SourceLocation BuiltinLoc, RParenLoc; 4474public: 4475 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, 4476 SourceLocation RPLoc, QualType t, bool IsMS) 4477 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary), Val(e), 4478 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) { 4479 setDependence(computeDependence(this)); 4480 } 4481 4482 /// Create an empty __builtin_va_arg expression. 4483 explicit VAArgExpr(EmptyShell Empty) 4484 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} 4485 4486 const Expr *getSubExpr() const { return cast<Expr>(Val); } 4487 Expr *getSubExpr() { return cast<Expr>(Val); } 4488 void setSubExpr(Expr *E) { Val = E; } 4489 4490 /// Returns whether this is really a Win64 ABI va_arg expression. 4491 bool isMicrosoftABI() const { return TInfo.getInt(); } 4492 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } 4493 4494 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } 4495 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } 4496 4497 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4498 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4499 4500 SourceLocation getRParenLoc() const { return RParenLoc; } 4501 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4502 4503 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4504 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4505 4506 static bool classof(const Stmt *T) { 4507 return T->getStmtClass() == VAArgExprClass; 4508 } 4509 4510 // Iterators 4511 child_range children() { return child_range(&Val, &Val+1); } 4512 const_child_range children() const { 4513 return const_child_range(&Val, &Val + 1); 4514 } 4515}; 4516 4517/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), 4518/// __builtin_FUNCTION(), or __builtin_FILE(). 4519class SourceLocExpr final : public Expr { 4520 SourceLocation BuiltinLoc, RParenLoc; 4521 DeclContext *ParentContext; 4522 4523public: 4524 enum IdentKind { Function, File, Line, Column }; 4525 4526 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, 4527 SourceLocation RParenLoc, DeclContext *Context); 4528 4529 /// Build an empty call expression. 4530 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {} 4531 4532 /// Return the result of evaluating this SourceLocExpr in the specified 4533 /// (and possibly null) default argument or initialization context. 4534 APValue EvaluateInContext(const ASTContext &Ctx, 4535 const Expr *DefaultExpr) const; 4536 4537 /// Return a string representing the name of the specific builtin function. 4538 StringRef getBuiltinStr() const; 4539 4540 IdentKind getIdentKind() const { 4541 return static_cast<IdentKind>(SourceLocExprBits.Kind); 4542 } 4543 4544 bool isStringType() const { 4545 switch (getIdentKind()) { 4546 case File: 4547 case Function: 4548 return true; 4549 case Line: 4550 case Column: 4551 return false; 4552 } 4553 llvm_unreachable("unknown source location expression kind"); 4554 } 4555 bool isIntType() const LLVM_READONLY { return !isStringType(); } 4556 4557 /// If the SourceLocExpr has been resolved return the subexpression 4558 /// representing the resolved value. Otherwise return null. 4559 const DeclContext *getParentContext() const { return ParentContext; } 4560 DeclContext *getParentContext() { return ParentContext; } 4561 4562 SourceLocation getLocation() const { return BuiltinLoc; } 4563 SourceLocation getBeginLoc() const { return BuiltinLoc; } 4564 SourceLocation getEndLoc() const { return RParenLoc; } 4565 4566 child_range children() { 4567 return child_range(child_iterator(), child_iterator()); 4568 } 4569 4570 const_child_range children() const { 4571 return const_child_range(child_iterator(), child_iterator()); 4572 } 4573 4574 static bool classof(const Stmt *T) { 4575 return T->getStmtClass() == SourceLocExprClass; 4576 } 4577 4578private: 4579 friend class ASTStmtReader; 4580}; 4581 4582/// Describes an C or C++ initializer list. 4583/// 4584/// InitListExpr describes an initializer list, which can be used to 4585/// initialize objects of different types, including 4586/// struct/class/union types, arrays, and vectors. For example: 4587/// 4588/// @code 4589/// struct foo x = { 1, { 2, 3 } }; 4590/// @endcode 4591/// 4592/// Prior to semantic analysis, an initializer list will represent the 4593/// initializer list as written by the user, but will have the 4594/// placeholder type "void". This initializer list is called the 4595/// syntactic form of the initializer, and may contain C99 designated 4596/// initializers (represented as DesignatedInitExprs), initializations 4597/// of subobject members without explicit braces, and so on. Clients 4598/// interested in the original syntax of the initializer list should 4599/// use the syntactic form of the initializer list. 4600/// 4601/// After semantic analysis, the initializer list will represent the 4602/// semantic form of the initializer, where the initializations of all 4603/// subobjects are made explicit with nested InitListExpr nodes and 4604/// C99 designators have been eliminated by placing the designated 4605/// initializations into the subobject they initialize. Additionally, 4606/// any "holes" in the initialization, where no initializer has been 4607/// specified for a particular subobject, will be replaced with 4608/// implicitly-generated ImplicitValueInitExpr expressions that 4609/// value-initialize the subobjects. Note, however, that the 4610/// initializer lists may still have fewer initializers than there are 4611/// elements to initialize within the object. 4612/// 4613/// After semantic analysis has completed, given an initializer list, 4614/// method isSemanticForm() returns true if and only if this is the 4615/// semantic form of the initializer list (note: the same AST node 4616/// may at the same time be the syntactic form). 4617/// Given the semantic form of the initializer list, one can retrieve 4618/// the syntactic form of that initializer list (when different) 4619/// using method getSyntacticForm(); the method returns null if applied 4620/// to a initializer list which is already in syntactic form. 4621/// Similarly, given the syntactic form (i.e., an initializer list such 4622/// that isSemanticForm() returns false), one can retrieve the semantic 4623/// form using method getSemanticForm(). 4624/// Since many initializer lists have the same syntactic and semantic forms, 4625/// getSyntacticForm() may return NULL, indicating that the current 4626/// semantic initializer list also serves as its syntactic form. 4627class InitListExpr : public Expr { 4628 // FIXME: Eliminate this vector in favor of ASTContext allocation 4629 typedef ASTVector<Stmt *> InitExprsTy; 4630 InitExprsTy InitExprs; 4631 SourceLocation LBraceLoc, RBraceLoc; 4632 4633 /// The alternative form of the initializer list (if it exists). 4634 /// The int part of the pair stores whether this initializer list is 4635 /// in semantic form. If not null, the pointer points to: 4636 /// - the syntactic form, if this is in semantic form; 4637 /// - the semantic form, if this is in syntactic form. 4638 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; 4639 4640 /// Either: 4641 /// If this initializer list initializes an array with more elements than 4642 /// there are initializers in the list, specifies an expression to be used 4643 /// for value initialization of the rest of the elements. 4644 /// Or 4645 /// If this initializer list initializes a union, specifies which 4646 /// field within the union will be initialized. 4647 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 4648 4649public: 4650 InitListExpr(const ASTContext &C, SourceLocation lbraceloc, 4651 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); 4652 4653 /// Build an empty initializer list. 4654 explicit InitListExpr(EmptyShell Empty) 4655 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } 4656 4657 unsigned getNumInits() const { return InitExprs.size(); } 4658 4659 /// Retrieve the set of initializers. 4660 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 4661 4662 /// Retrieve the set of initializers. 4663 Expr * const *getInits() const { 4664 return reinterpret_cast<Expr * const *>(InitExprs.data()); 4665 } 4666 4667 ArrayRef<Expr *> inits() { 4668 return llvm::makeArrayRef(getInits(), getNumInits()); 4669 } 4670 4671 ArrayRef<Expr *> inits() const { 4672 return llvm::makeArrayRef(getInits(), getNumInits()); 4673 } 4674 4675 const Expr *getInit(unsigned Init) const { 4676 assert(Init < getNumInits() && "Initializer access out of range!"); 4677 return cast_or_null<Expr>(InitExprs[Init]); 4678 } 4679 4680 Expr *getInit(unsigned Init) { 4681 assert(Init < getNumInits() && "Initializer access out of range!"); 4682 return cast_or_null<Expr>(InitExprs[Init]); 4683 } 4684 4685 void setInit(unsigned Init, Expr *expr) { 4686 assert(Init < getNumInits() && "Initializer access out of range!"); 4687 InitExprs[Init] = expr; 4688 4689 if (expr) 4690 setDependence(getDependence() | expr->getDependence()); 4691 } 4692 4693 /// Reserve space for some number of initializers. 4694 void reserveInits(const ASTContext &C, unsigned NumInits); 4695 4696 /// Specify the number of initializers 4697 /// 4698 /// If there are more than @p NumInits initializers, the remaining 4699 /// initializers will be destroyed. If there are fewer than @p 4700 /// NumInits initializers, NULL expressions will be added for the 4701 /// unknown initializers. 4702 void resizeInits(const ASTContext &Context, unsigned NumInits); 4703 4704 /// Updates the initializer at index @p Init with the new 4705 /// expression @p expr, and returns the old expression at that 4706 /// location. 4707 /// 4708 /// When @p Init is out of range for this initializer list, the 4709 /// initializer list will be extended with NULL expressions to 4710 /// accommodate the new entry. 4711 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); 4712 4713 /// If this initializer list initializes an array with more elements 4714 /// than there are initializers in the list, specifies an expression to be 4715 /// used for value initialization of the rest of the elements. 4716 Expr *getArrayFiller() { 4717 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 4718 } 4719 const Expr *getArrayFiller() const { 4720 return const_cast<InitListExpr *>(this)->getArrayFiller(); 4721 } 4722 void setArrayFiller(Expr *filler); 4723 4724 /// Return true if this is an array initializer and its array "filler" 4725 /// has been set. 4726 bool hasArrayFiller() const { return getArrayFiller(); } 4727 4728 /// If this initializes a union, specifies which field in the 4729 /// union to initialize. 4730 /// 4731 /// Typically, this field is the first named field within the 4732 /// union. However, a designated initializer can specify the 4733 /// initialization of a different field within the union. 4734 FieldDecl *getInitializedFieldInUnion() { 4735 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 4736 } 4737 const FieldDecl *getInitializedFieldInUnion() const { 4738 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 4739 } 4740 void setInitializedFieldInUnion(FieldDecl *FD) { 4741 assert((FD == nullptr 4742 || getInitializedFieldInUnion() == nullptr 4743 || getInitializedFieldInUnion() == FD) 4744 && "Only one field of a union may be initialized at a time!"); 4745 ArrayFillerOrUnionFieldInit = FD; 4746 } 4747 4748 // Explicit InitListExpr's originate from source code (and have valid source 4749 // locations). Implicit InitListExpr's are created by the semantic analyzer. 4750 // FIXME: This is wrong; InitListExprs created by semantic analysis have 4751 // valid source locations too! 4752 bool isExplicit() const { 4753 return LBraceLoc.isValid() && RBraceLoc.isValid(); 4754 } 4755 4756 // Is this an initializer for an array of characters, initialized by a string 4757 // literal or an @encode? 4758 bool isStringLiteralInit() const; 4759 4760 /// Is this a transparent initializer list (that is, an InitListExpr that is 4761 /// purely syntactic, and whose semantics are that of the sole contained 4762 /// initializer)? 4763 bool isTransparent() const; 4764 4765 /// Is this the zero initializer {0} in a language which considers it 4766 /// idiomatic? 4767 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; 4768 4769 SourceLocation getLBraceLoc() const { return LBraceLoc; } 4770 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 4771 SourceLocation getRBraceLoc() const { return RBraceLoc; } 4772 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 4773 4774 bool isSemanticForm() const { return AltForm.getInt(); } 4775 InitListExpr *getSemanticForm() const { 4776 return isSemanticForm() ? nullptr : AltForm.getPointer(); 4777 } 4778 bool isSyntacticForm() const { 4779 return !AltForm.getInt() || !AltForm.getPointer(); 4780 } 4781 InitListExpr *getSyntacticForm() const { 4782 return isSemanticForm() ? AltForm.getPointer() : nullptr; 4783 } 4784 4785 void setSyntacticForm(InitListExpr *Init) { 4786 AltForm.setPointer(Init); 4787 AltForm.setInt(true); 4788 Init->AltForm.setPointer(this); 4789 Init->AltForm.setInt(false); 4790 } 4791 4792 bool hadArrayRangeDesignator() const { 4793 return InitListExprBits.HadArrayRangeDesignator != 0; 4794 } 4795 void sawArrayRangeDesignator(bool ARD = true) { 4796 InitListExprBits.HadArrayRangeDesignator = ARD; 4797 } 4798 4799 SourceLocation getBeginLoc() const LLVM_READONLY; 4800 SourceLocation getEndLoc() const LLVM_READONLY; 4801 4802 static bool classof(const Stmt *T) { 4803 return T->getStmtClass() == InitListExprClass; 4804 } 4805 4806 // Iterators 4807 child_range children() { 4808 const_child_range CCR = const_cast<const InitListExpr *>(this)->children(); 4809 return child_range(cast_away_const(CCR.begin()), 4810 cast_away_const(CCR.end())); 4811 } 4812 4813 const_child_range children() const { 4814 // FIXME: This does not include the array filler expression. 4815 if (InitExprs.empty()) 4816 return const_child_range(const_child_iterator(), const_child_iterator()); 4817 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 4818 } 4819 4820 typedef InitExprsTy::iterator iterator; 4821 typedef InitExprsTy::const_iterator const_iterator; 4822 typedef InitExprsTy::reverse_iterator reverse_iterator; 4823 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 4824 4825 iterator begin() { return InitExprs.begin(); } 4826 const_iterator begin() const { return InitExprs.begin(); } 4827 iterator end() { return InitExprs.end(); } 4828 const_iterator end() const { return InitExprs.end(); } 4829 reverse_iterator rbegin() { return InitExprs.rbegin(); } 4830 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 4831 reverse_iterator rend() { return InitExprs.rend(); } 4832 const_reverse_iterator rend() const { return InitExprs.rend(); } 4833 4834 friend class ASTStmtReader; 4835 friend class ASTStmtWriter; 4836}; 4837 4838/// Represents a C99 designated initializer expression. 4839/// 4840/// A designated initializer expression (C99 6.7.8) contains one or 4841/// more designators (which can be field designators, array 4842/// designators, or GNU array-range designators) followed by an 4843/// expression that initializes the field or element(s) that the 4844/// designators refer to. For example, given: 4845/// 4846/// @code 4847/// struct point { 4848/// double x; 4849/// double y; 4850/// }; 4851/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 4852/// @endcode 4853/// 4854/// The InitListExpr contains three DesignatedInitExprs, the first of 4855/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 4856/// designators, one array designator for @c [2] followed by one field 4857/// designator for @c .y. The initialization expression will be 1.0. 4858class DesignatedInitExpr final 4859 : public Expr, 4860 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> { 4861public: 4862 /// Forward declaration of the Designator class. 4863 class Designator; 4864 4865private: 4866 /// The location of the '=' or ':' prior to the actual initializer 4867 /// expression. 4868 SourceLocation EqualOrColonLoc; 4869 4870 /// Whether this designated initializer used the GNU deprecated 4871 /// syntax rather than the C99 '=' syntax. 4872 unsigned GNUSyntax : 1; 4873 4874 /// The number of designators in this initializer expression. 4875 unsigned NumDesignators : 15; 4876 4877 /// The number of subexpressions of this initializer expression, 4878 /// which contains both the initializer and any additional 4879 /// expressions used by array and array-range designators. 4880 unsigned NumSubExprs : 16; 4881 4882 /// The designators in this designated initialization 4883 /// expression. 4884 Designator *Designators; 4885 4886 DesignatedInitExpr(const ASTContext &C, QualType Ty, 4887 llvm::ArrayRef<Designator> Designators, 4888 SourceLocation EqualOrColonLoc, bool GNUSyntax, 4889 ArrayRef<Expr *> IndexExprs, Expr *Init); 4890 4891 explicit DesignatedInitExpr(unsigned NumSubExprs) 4892 : Expr(DesignatedInitExprClass, EmptyShell()), 4893 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } 4894 4895public: 4896 /// A field designator, e.g., ".x". 4897 struct FieldDesignator { 4898 /// Refers to the field that is being initialized. The low bit 4899 /// of this field determines whether this is actually a pointer 4900 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 4901 /// initially constructed, a field designator will store an 4902 /// IdentifierInfo*. After semantic analysis has resolved that 4903 /// name, the field designator will instead store a FieldDecl*. 4904 uintptr_t NameOrField; 4905 4906 /// The location of the '.' in the designated initializer. 4907 unsigned DotLoc; 4908 4909 /// The location of the field name in the designated initializer. 4910 unsigned FieldLoc; 4911 }; 4912 4913 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 4914 struct ArrayOrRangeDesignator { 4915 /// Location of the first index expression within the designated 4916 /// initializer expression's list of subexpressions. 4917 unsigned Index; 4918 /// The location of the '[' starting the array range designator. 4919 unsigned LBracketLoc; 4920 /// The location of the ellipsis separating the start and end 4921 /// indices. Only valid for GNU array-range designators. 4922 unsigned EllipsisLoc; 4923 /// The location of the ']' terminating the array range designator. 4924 unsigned RBracketLoc; 4925 }; 4926 4927 /// Represents a single C99 designator. 4928 /// 4929 /// @todo This class is infuriatingly similar to clang::Designator, 4930 /// but minor differences (storing indices vs. storing pointers) 4931 /// keep us from reusing it. Try harder, later, to rectify these 4932 /// differences. 4933 class Designator { 4934 /// The kind of designator this describes. 4935 enum { 4936 FieldDesignator, 4937 ArrayDesignator, 4938 ArrayRangeDesignator 4939 } Kind; 4940 4941 union { 4942 /// A field designator, e.g., ".x". 4943 struct FieldDesignator Field; 4944 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 4945 struct ArrayOrRangeDesignator ArrayOrRange; 4946 }; 4947 friend class DesignatedInitExpr; 4948 4949 public: 4950 Designator() {} 4951 4952 /// Initializes a field designator. 4953 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 4954 SourceLocation FieldLoc) 4955 : Kind(FieldDesignator) { 4956 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 4957 Field.DotLoc = DotLoc.getRawEncoding(); 4958 Field.FieldLoc = FieldLoc.getRawEncoding(); 4959 } 4960 4961 /// Initializes an array designator. 4962 Designator(unsigned Index, SourceLocation LBracketLoc, 4963 SourceLocation RBracketLoc) 4964 : Kind(ArrayDesignator) { 4965 ArrayOrRange.Index = Index; 4966 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4967 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 4968 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4969 } 4970 4971 /// Initializes a GNU array-range designator. 4972 Designator(unsigned Index, SourceLocation LBracketLoc, 4973 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 4974 : Kind(ArrayRangeDesignator) { 4975 ArrayOrRange.Index = Index; 4976 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4977 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 4978 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4979 } 4980 4981 bool isFieldDesignator() const { return Kind == FieldDesignator; } 4982 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 4983 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 4984 4985 IdentifierInfo *getFieldName() const; 4986 4987 FieldDecl *getField() const { 4988 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4989 if (Field.NameOrField & 0x01) 4990 return nullptr; 4991 else 4992 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 4993 } 4994 4995 void setField(FieldDecl *FD) { 4996 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4997 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 4998 } 4999 5000 SourceLocation getDotLoc() const { 5001 assert(Kind == FieldDesignator && "Only valid on a field designator"); 5002 return SourceLocation::getFromRawEncoding(Field.DotLoc); 5003 } 5004 5005 SourceLocation getFieldLoc() const { 5006 assert(Kind == FieldDesignator && "Only valid on a field designator"); 5007 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 5008 } 5009 5010 SourceLocation getLBracketLoc() const { 5011 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 5012 "Only valid on an array or array-range designator"); 5013 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 5014 } 5015 5016 SourceLocation getRBracketLoc() const { 5017 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 5018 "Only valid on an array or array-range designator"); 5019 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 5020 } 5021 5022 SourceLocation getEllipsisLoc() const { 5023 assert(Kind == ArrayRangeDesignator && 5024 "Only valid on an array-range designator"); 5025 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 5026 } 5027 5028 unsigned getFirstExprIndex() const { 5029 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 5030 "Only valid on an array or array-range designator"); 5031 return ArrayOrRange.Index; 5032 } 5033 5034 SourceLocation getBeginLoc() const LLVM_READONLY { 5035 if (Kind == FieldDesignator) 5036 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 5037 else 5038 return getLBracketLoc(); 5039 } 5040 SourceLocation getEndLoc() const LLVM_READONLY { 5041 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 5042 } 5043 SourceRange getSourceRange() const LLVM_READONLY { 5044 return SourceRange(getBeginLoc(), getEndLoc()); 5045 } 5046 }; 5047 5048 static DesignatedInitExpr *Create(const ASTContext &C, 5049 llvm::ArrayRef<Designator> Designators, 5050 ArrayRef<Expr*> IndexExprs, 5051 SourceLocation EqualOrColonLoc, 5052 bool GNUSyntax, Expr *Init); 5053 5054 static DesignatedInitExpr *CreateEmpty(const ASTContext &C, 5055 unsigned NumIndexExprs); 5056 5057 /// Returns the number of designators in this initializer. 5058 unsigned size() const { return NumDesignators; } 5059 5060 // Iterator access to the designators. 5061 llvm::MutableArrayRef<Designator> designators() { 5062 return {Designators, NumDesignators}; 5063 } 5064 5065 llvm::ArrayRef<Designator> designators() const { 5066 return {Designators, NumDesignators}; 5067 } 5068 5069 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } 5070 const Designator *getDesignator(unsigned Idx) const { 5071 return &designators()[Idx]; 5072 } 5073 5074 void setDesignators(const ASTContext &C, const Designator *Desigs, 5075 unsigned NumDesigs); 5076 5077 Expr *getArrayIndex(const Designator &D) const; 5078 Expr *getArrayRangeStart(const Designator &D) const; 5079 Expr *getArrayRangeEnd(const Designator &D) const; 5080 5081 /// Retrieve the location of the '=' that precedes the 5082 /// initializer value itself, if present. 5083 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 5084 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 5085 5086 /// Whether this designated initializer should result in direct-initialization 5087 /// of the designated subobject (eg, '{.foo{1, 2, 3}}'). 5088 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); } 5089 5090 /// Determines whether this designated initializer used the 5091 /// deprecated GNU syntax for designated initializers. 5092 bool usesGNUSyntax() const { return GNUSyntax; } 5093 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 5094 5095 /// Retrieve the initializer value. 5096 Expr *getInit() const { 5097 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 5098 } 5099 5100 void setInit(Expr *init) { 5101 *child_begin() = init; 5102 } 5103 5104 /// Retrieve the total number of subexpressions in this 5105 /// designated initializer expression, including the actual 5106 /// initialized value and any expressions that occur within array 5107 /// and array-range designators. 5108 unsigned getNumSubExprs() const { return NumSubExprs; } 5109 5110 Expr *getSubExpr(unsigned Idx) const { 5111 assert(Idx < NumSubExprs && "Subscript out of range"); 5112 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]); 5113 } 5114 5115 void setSubExpr(unsigned Idx, Expr *E) { 5116 assert(Idx < NumSubExprs && "Subscript out of range"); 5117 getTrailingObjects<Stmt *>()[Idx] = E; 5118 } 5119 5120 /// Replaces the designator at index @p Idx with the series 5121 /// of designators in [First, Last). 5122 void ExpandDesignator(const ASTContext &C, unsigned Idx, 5123 const Designator *First, const Designator *Last); 5124 5125 SourceRange getDesignatorsSourceRange() const; 5126 5127 SourceLocation getBeginLoc() const LLVM_READONLY; 5128 SourceLocation getEndLoc() const LLVM_READONLY; 5129 5130 static bool classof(const Stmt *T) { 5131 return T->getStmtClass() == DesignatedInitExprClass; 5132 } 5133 5134 // Iterators 5135 child_range children() { 5136 Stmt **begin = getTrailingObjects<Stmt *>(); 5137 return child_range(begin, begin + NumSubExprs); 5138 } 5139 const_child_range children() const { 5140 Stmt * const *begin = getTrailingObjects<Stmt *>(); 5141 return const_child_range(begin, begin + NumSubExprs); 5142 } 5143 5144 friend TrailingObjects; 5145}; 5146 5147/// Represents a place-holder for an object not to be initialized by 5148/// anything. 5149/// 5150/// This only makes sense when it appears as part of an updater of a 5151/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE 5152/// initializes a big object, and the NoInitExpr's mark the spots within the 5153/// big object not to be overwritten by the updater. 5154/// 5155/// \see DesignatedInitUpdateExpr 5156class NoInitExpr : public Expr { 5157public: 5158 explicit NoInitExpr(QualType ty) 5159 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary) { 5160 setDependence(computeDependence(this)); 5161 } 5162 5163 explicit NoInitExpr(EmptyShell Empty) 5164 : Expr(NoInitExprClass, Empty) { } 5165 5166 static bool classof(const Stmt *T) { 5167 return T->getStmtClass() == NoInitExprClass; 5168 } 5169 5170 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5171 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5172 5173 // Iterators 5174 child_range children() { 5175 return child_range(child_iterator(), child_iterator()); 5176 } 5177 const_child_range children() const { 5178 return const_child_range(const_child_iterator(), const_child_iterator()); 5179 } 5180}; 5181 5182// In cases like: 5183// struct Q { int a, b, c; }; 5184// Q *getQ(); 5185// void foo() { 5186// struct A { Q q; } a = { *getQ(), .q.b = 3 }; 5187// } 5188// 5189// We will have an InitListExpr for a, with type A, and then a 5190// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE 5191// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" 5192// 5193class DesignatedInitUpdateExpr : public Expr { 5194 // BaseAndUpdaterExprs[0] is the base expression; 5195 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. 5196 Stmt *BaseAndUpdaterExprs[2]; 5197 5198public: 5199 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, 5200 Expr *baseExprs, SourceLocation rBraceLoc); 5201 5202 explicit DesignatedInitUpdateExpr(EmptyShell Empty) 5203 : Expr(DesignatedInitUpdateExprClass, Empty) { } 5204 5205 SourceLocation getBeginLoc() const LLVM_READONLY; 5206 SourceLocation getEndLoc() const LLVM_READONLY; 5207 5208 static bool classof(const Stmt *T) { 5209 return T->getStmtClass() == DesignatedInitUpdateExprClass; 5210 } 5211 5212 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); } 5213 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } 5214 5215 InitListExpr *getUpdater() const { 5216 return cast<InitListExpr>(BaseAndUpdaterExprs[1]); 5217 } 5218 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } 5219 5220 // Iterators 5221 // children = the base and the updater 5222 child_range children() { 5223 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); 5224 } 5225 const_child_range children() const { 5226 return const_child_range(&BaseAndUpdaterExprs[0], 5227 &BaseAndUpdaterExprs[0] + 2); 5228 } 5229}; 5230 5231/// Represents a loop initializing the elements of an array. 5232/// 5233/// The need to initialize the elements of an array occurs in a number of 5234/// contexts: 5235/// 5236/// * in the implicit copy/move constructor for a class with an array member 5237/// * when a lambda-expression captures an array by value 5238/// * when a decomposition declaration decomposes an array 5239/// 5240/// There are two subexpressions: a common expression (the source array) 5241/// that is evaluated once up-front, and a per-element initializer that 5242/// runs once for each array element. 5243/// 5244/// Within the per-element initializer, the common expression may be referenced 5245/// via an OpaqueValueExpr, and the current index may be obtained via an 5246/// ArrayInitIndexExpr. 5247class ArrayInitLoopExpr : public Expr { 5248 Stmt *SubExprs[2]; 5249 5250 explicit ArrayInitLoopExpr(EmptyShell Empty) 5251 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} 5252 5253public: 5254 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) 5255 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary), 5256 SubExprs{CommonInit, ElementInit} { 5257 setDependence(computeDependence(this)); 5258 } 5259 5260 /// Get the common subexpression shared by all initializations (the source 5261 /// array). 5262 OpaqueValueExpr *getCommonExpr() const { 5263 return cast<OpaqueValueExpr>(SubExprs[0]); 5264 } 5265 5266 /// Get the initializer to use for each array element. 5267 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); } 5268 5269 llvm::APInt getArraySize() const { 5270 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe()) 5271 ->getSize(); 5272 } 5273 5274 static bool classof(const Stmt *S) { 5275 return S->getStmtClass() == ArrayInitLoopExprClass; 5276 } 5277 5278 SourceLocation getBeginLoc() const LLVM_READONLY { 5279 return getCommonExpr()->getBeginLoc(); 5280 } 5281 SourceLocation getEndLoc() const LLVM_READONLY { 5282 return getCommonExpr()->getEndLoc(); 5283 } 5284 5285 child_range children() { 5286 return child_range(SubExprs, SubExprs + 2); 5287 } 5288 const_child_range children() const { 5289 return const_child_range(SubExprs, SubExprs + 2); 5290 } 5291 5292 friend class ASTReader; 5293 friend class ASTStmtReader; 5294 friend class ASTStmtWriter; 5295}; 5296 5297/// Represents the index of the current element of an array being 5298/// initialized by an ArrayInitLoopExpr. This can only appear within the 5299/// subexpression of an ArrayInitLoopExpr. 5300class ArrayInitIndexExpr : public Expr { 5301 explicit ArrayInitIndexExpr(EmptyShell Empty) 5302 : Expr(ArrayInitIndexExprClass, Empty) {} 5303 5304public: 5305 explicit ArrayInitIndexExpr(QualType T) 5306 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary) { 5307 setDependence(ExprDependence::None); 5308 } 5309 5310 static bool classof(const Stmt *S) { 5311 return S->getStmtClass() == ArrayInitIndexExprClass; 5312 } 5313 5314 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5315 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5316 5317 child_range children() { 5318 return child_range(child_iterator(), child_iterator()); 5319 } 5320 const_child_range children() const { 5321 return const_child_range(const_child_iterator(), const_child_iterator()); 5322 } 5323 5324 friend class ASTReader; 5325 friend class ASTStmtReader; 5326}; 5327 5328/// Represents an implicitly-generated value initialization of 5329/// an object of a given type. 5330/// 5331/// Implicit value initializations occur within semantic initializer 5332/// list expressions (InitListExpr) as placeholders for subobject 5333/// initializations not explicitly specified by the user. 5334/// 5335/// \see InitListExpr 5336class ImplicitValueInitExpr : public Expr { 5337public: 5338 explicit ImplicitValueInitExpr(QualType ty) 5339 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary) { 5340 setDependence(computeDependence(this)); 5341 } 5342 5343 /// Construct an empty implicit value initialization. 5344 explicit ImplicitValueInitExpr(EmptyShell Empty) 5345 : Expr(ImplicitValueInitExprClass, Empty) { } 5346 5347 static bool classof(const Stmt *T) { 5348 return T->getStmtClass() == ImplicitValueInitExprClass; 5349 } 5350 5351 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5352 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5353 5354 // Iterators 5355 child_range children() { 5356 return child_range(child_iterator(), child_iterator()); 5357 } 5358 const_child_range children() const { 5359 return const_child_range(const_child_iterator(), const_child_iterator()); 5360 } 5361}; 5362 5363class ParenListExpr final 5364 : public Expr, 5365 private llvm::TrailingObjects<ParenListExpr, Stmt *> { 5366 friend class ASTStmtReader; 5367 friend TrailingObjects; 5368 5369 /// The location of the left and right parentheses. 5370 SourceLocation LParenLoc, RParenLoc; 5371 5372 /// Build a paren list. 5373 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, 5374 SourceLocation RParenLoc); 5375 5376 /// Build an empty paren list. 5377 ParenListExpr(EmptyShell Empty, unsigned NumExprs); 5378 5379public: 5380 /// Create a paren list. 5381 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc, 5382 ArrayRef<Expr *> Exprs, 5383 SourceLocation RParenLoc); 5384 5385 /// Create an empty paren list. 5386 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs); 5387 5388 /// Return the number of expressions in this paren list. 5389 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; } 5390 5391 Expr *getExpr(unsigned Init) { 5392 assert(Init < getNumExprs() && "Initializer access out of range!"); 5393 return getExprs()[Init]; 5394 } 5395 5396 const Expr *getExpr(unsigned Init) const { 5397 return const_cast<ParenListExpr *>(this)->getExpr(Init); 5398 } 5399 5400 Expr **getExprs() { 5401 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>()); 5402 } 5403 5404 ArrayRef<Expr *> exprs() { 5405 return llvm::makeArrayRef(getExprs(), getNumExprs()); 5406 } 5407 5408 SourceLocation getLParenLoc() const { return LParenLoc; } 5409 SourceLocation getRParenLoc() const { return RParenLoc; } 5410 SourceLocation getBeginLoc() const { return getLParenLoc(); } 5411 SourceLocation getEndLoc() const { return getRParenLoc(); } 5412 5413 static bool classof(const Stmt *T) { 5414 return T->getStmtClass() == ParenListExprClass; 5415 } 5416 5417 // Iterators 5418 child_range children() { 5419 return child_range(getTrailingObjects<Stmt *>(), 5420 getTrailingObjects<Stmt *>() + getNumExprs()); 5421 } 5422 const_child_range children() const { 5423 return const_child_range(getTrailingObjects<Stmt *>(), 5424 getTrailingObjects<Stmt *>() + getNumExprs()); 5425 } 5426}; 5427 5428/// Represents a C11 generic selection. 5429/// 5430/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling 5431/// expression, followed by one or more generic associations. Each generic 5432/// association specifies a type name and an expression, or "default" and an 5433/// expression (in which case it is known as a default generic association). 5434/// The type and value of the generic selection are identical to those of its 5435/// result expression, which is defined as the expression in the generic 5436/// association with a type name that is compatible with the type of the 5437/// controlling expression, or the expression in the default generic association 5438/// if no types are compatible. For example: 5439/// 5440/// @code 5441/// _Generic(X, double: 1, float: 2, default: 3) 5442/// @endcode 5443/// 5444/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 5445/// or 3 if "hello". 5446/// 5447/// As an extension, generic selections are allowed in C++, where the following 5448/// additional semantics apply: 5449/// 5450/// Any generic selection whose controlling expression is type-dependent or 5451/// which names a dependent type in its association list is result-dependent, 5452/// which means that the choice of result expression is dependent. 5453/// Result-dependent generic associations are both type- and value-dependent. 5454class GenericSelectionExpr final 5455 : public Expr, 5456 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *, 5457 TypeSourceInfo *> { 5458 friend class ASTStmtReader; 5459 friend class ASTStmtWriter; 5460 friend TrailingObjects; 5461 5462 /// The number of association expressions and the index of the result 5463 /// expression in the case where the generic selection expression is not 5464 /// result-dependent. The result index is equal to ResultDependentIndex 5465 /// if and only if the generic selection expression is result-dependent. 5466 unsigned NumAssocs, ResultIndex; 5467 enum : unsigned { 5468 ResultDependentIndex = std::numeric_limits<unsigned>::max(), 5469 ControllingIndex = 0, 5470 AssocExprStartIndex = 1 5471 }; 5472 5473 /// The location of the "default" and of the right parenthesis. 5474 SourceLocation DefaultLoc, RParenLoc; 5475 5476 // GenericSelectionExpr is followed by several trailing objects. 5477 // They are (in order): 5478 // 5479 // * A single Stmt * for the controlling expression. 5480 // * An array of getNumAssocs() Stmt * for the association expressions. 5481 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the 5482 // association expressions. 5483 unsigned numTrailingObjects(OverloadToken<Stmt *>) const { 5484 // Add one to account for the controlling expression; the remainder 5485 // are the associated expressions. 5486 return 1 + getNumAssocs(); 5487 } 5488 5489 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { 5490 return getNumAssocs(); 5491 } 5492 5493 template <bool Const> class AssociationIteratorTy; 5494 /// Bundle together an association expression and its TypeSourceInfo. 5495 /// The Const template parameter is for the const and non-const versions 5496 /// of AssociationTy. 5497 template <bool Const> class AssociationTy { 5498 friend class GenericSelectionExpr; 5499 template <bool OtherConst> friend class AssociationIteratorTy; 5500 using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>; 5501 using TSIPtrTy = 5502 std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>; 5503 ExprPtrTy E; 5504 TSIPtrTy TSI; 5505 bool Selected; 5506 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected) 5507 : E(E), TSI(TSI), Selected(Selected) {} 5508 5509 public: 5510 ExprPtrTy getAssociationExpr() const { return E; } 5511 TSIPtrTy getTypeSourceInfo() const { return TSI; } 5512 QualType getType() const { return TSI ? TSI->getType() : QualType(); } 5513 bool isSelected() const { return Selected; } 5514 AssociationTy *operator->() { return this; } 5515 const AssociationTy *operator->() const { return this; } 5516 }; // class AssociationTy 5517 5518 /// Iterator over const and non-const Association objects. The Association 5519 /// objects are created on the fly when the iterator is dereferenced. 5520 /// This abstract over how exactly the association expressions and the 5521 /// corresponding TypeSourceInfo * are stored. 5522 template <bool Const> 5523 class AssociationIteratorTy 5524 : public llvm::iterator_facade_base< 5525 AssociationIteratorTy<Const>, std::input_iterator_tag, 5526 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>, 5527 AssociationTy<Const>> { 5528 friend class GenericSelectionExpr; 5529 // FIXME: This iterator could conceptually be a random access iterator, and 5530 // it would be nice if we could strengthen the iterator category someday. 5531 // However this iterator does not satisfy two requirements of forward 5532 // iterators: 5533 // a) reference = T& or reference = const T& 5534 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only 5535 // if *It1 and *It2 are bound to the same objects. 5536 // An alternative design approach was discussed during review; 5537 // store an Association object inside the iterator, and return a reference 5538 // to it when dereferenced. This idea was discarded beacuse of nasty 5539 // lifetime issues: 5540 // AssociationIterator It = ...; 5541 // const Association &Assoc = *It++; // Oops, Assoc is dangling. 5542 using BaseTy = typename AssociationIteratorTy::iterator_facade_base; 5543 using StmtPtrPtrTy = 5544 std::conditional_t<Const, const Stmt *const *, Stmt **>; 5545 using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *, 5546 TypeSourceInfo **>; 5547 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped. 5548 TSIPtrPtrTy TSI; // Kept in sync with E. 5549 unsigned Offset = 0, SelectedOffset = 0; 5550 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset, 5551 unsigned SelectedOffset) 5552 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {} 5553 5554 public: 5555 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {} 5556 typename BaseTy::reference operator*() const { 5557 return AssociationTy<Const>(cast<Expr>(*E), *TSI, 5558 Offset == SelectedOffset); 5559 } 5560 typename BaseTy::pointer operator->() const { return **this; } 5561 using BaseTy::operator++; 5562 AssociationIteratorTy &operator++() { 5563 ++E; 5564 ++TSI; 5565 ++Offset; 5566 return *this; 5567 } 5568 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; } 5569 }; // class AssociationIterator 5570 5571 /// Build a non-result-dependent generic selection expression. 5572 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5573 Expr *ControllingExpr, 5574 ArrayRef<TypeSourceInfo *> AssocTypes, 5575 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5576 SourceLocation RParenLoc, 5577 bool ContainsUnexpandedParameterPack, 5578 unsigned ResultIndex); 5579 5580 /// Build a result-dependent generic selection expression. 5581 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5582 Expr *ControllingExpr, 5583 ArrayRef<TypeSourceInfo *> AssocTypes, 5584 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5585 SourceLocation RParenLoc, 5586 bool ContainsUnexpandedParameterPack); 5587 5588 /// Build an empty generic selection expression for deserialization. 5589 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs); 5590 5591public: 5592 /// Create a non-result-dependent generic selection expression. 5593 static GenericSelectionExpr * 5594 Create(const ASTContext &Context, SourceLocation GenericLoc, 5595 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5596 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5597 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, 5598 unsigned ResultIndex); 5599 5600 /// Create a result-dependent generic selection expression. 5601 static GenericSelectionExpr * 5602 Create(const ASTContext &Context, SourceLocation GenericLoc, 5603 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5604 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5605 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); 5606 5607 /// Create an empty generic selection expression for deserialization. 5608 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context, 5609 unsigned NumAssocs); 5610 5611 using Association = AssociationTy<false>; 5612 using ConstAssociation = AssociationTy<true>; 5613 using AssociationIterator = AssociationIteratorTy<false>; 5614 using ConstAssociationIterator = AssociationIteratorTy<true>; 5615 using association_range = llvm::iterator_range<AssociationIterator>; 5616 using const_association_range = 5617 llvm::iterator_range<ConstAssociationIterator>; 5618 5619 /// The number of association expressions. 5620 unsigned getNumAssocs() const { return NumAssocs; } 5621 5622 /// The zero-based index of the result expression's generic association in 5623 /// the generic selection's association list. Defined only if the 5624 /// generic selection is not result-dependent. 5625 unsigned getResultIndex() const { 5626 assert(!isResultDependent() && 5627 "Generic selection is result-dependent but getResultIndex called!"); 5628 return ResultIndex; 5629 } 5630 5631 /// Whether this generic selection is result-dependent. 5632 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; } 5633 5634 /// Return the controlling expression of this generic selection expression. 5635 Expr *getControllingExpr() { 5636 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); 5637 } 5638 const Expr *getControllingExpr() const { 5639 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); 5640 } 5641 5642 /// Return the result expression of this controlling expression. Defined if 5643 /// and only if the generic selection expression is not result-dependent. 5644 Expr *getResultExpr() { 5645 return cast<Expr>( 5646 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); 5647 } 5648 const Expr *getResultExpr() const { 5649 return cast<Expr>( 5650 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); 5651 } 5652 5653 ArrayRef<Expr *> getAssocExprs() const { 5654 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() + 5655 AssocExprStartIndex), 5656 NumAssocs}; 5657 } 5658 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const { 5659 return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs}; 5660 } 5661 5662 /// Return the Ith association expression with its TypeSourceInfo, 5663 /// bundled together in GenericSelectionExpr::(Const)Association. 5664 Association getAssociation(unsigned I) { 5665 assert(I < getNumAssocs() && 5666 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 5667 return Association( 5668 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), 5669 getTrailingObjects<TypeSourceInfo *>()[I], 5670 !isResultDependent() && (getResultIndex() == I)); 5671 } 5672 ConstAssociation getAssociation(unsigned I) const { 5673 assert(I < getNumAssocs() && 5674 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 5675 return ConstAssociation( 5676 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), 5677 getTrailingObjects<TypeSourceInfo *>()[I], 5678 !isResultDependent() && (getResultIndex() == I)); 5679 } 5680 5681 association_range associations() { 5682 AssociationIterator Begin(getTrailingObjects<Stmt *>() + 5683 AssocExprStartIndex, 5684 getTrailingObjects<TypeSourceInfo *>(), 5685 /*Offset=*/0, ResultIndex); 5686 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 5687 /*Offset=*/NumAssocs, ResultIndex); 5688 return llvm::make_range(Begin, End); 5689 } 5690 5691 const_association_range associations() const { 5692 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() + 5693 AssocExprStartIndex, 5694 getTrailingObjects<TypeSourceInfo *>(), 5695 /*Offset=*/0, ResultIndex); 5696 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 5697 /*Offset=*/NumAssocs, ResultIndex); 5698 return llvm::make_range(Begin, End); 5699 } 5700 5701 SourceLocation getGenericLoc() const { 5702 return GenericSelectionExprBits.GenericLoc; 5703 } 5704 SourceLocation getDefaultLoc() const { return DefaultLoc; } 5705 SourceLocation getRParenLoc() const { return RParenLoc; } 5706 SourceLocation getBeginLoc() const { return getGenericLoc(); } 5707 SourceLocation getEndLoc() const { return getRParenLoc(); } 5708 5709 static bool classof(const Stmt *T) { 5710 return T->getStmtClass() == GenericSelectionExprClass; 5711 } 5712 5713 child_range children() { 5714 return child_range(getTrailingObjects<Stmt *>(), 5715 getTrailingObjects<Stmt *>() + 5716 numTrailingObjects(OverloadToken<Stmt *>())); 5717 } 5718 const_child_range children() const { 5719 return const_child_range(getTrailingObjects<Stmt *>(), 5720 getTrailingObjects<Stmt *>() + 5721 numTrailingObjects(OverloadToken<Stmt *>())); 5722 } 5723}; 5724 5725//===----------------------------------------------------------------------===// 5726// Clang Extensions 5727//===----------------------------------------------------------------------===// 5728 5729/// ExtVectorElementExpr - This represents access to specific elements of a 5730/// vector, and may occur on the left hand side or right hand side. For example 5731/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 5732/// 5733/// Note that the base may have either vector or pointer to vector type, just 5734/// like a struct field reference. 5735/// 5736class ExtVectorElementExpr : public Expr { 5737 Stmt *Base; 5738 IdentifierInfo *Accessor; 5739 SourceLocation AccessorLoc; 5740public: 5741 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 5742 IdentifierInfo &accessor, SourceLocation loc) 5743 : Expr(ExtVectorElementExprClass, ty, VK, 5744 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent)), 5745 Base(base), Accessor(&accessor), AccessorLoc(loc) { 5746 setDependence(computeDependence(this)); 5747 } 5748 5749 /// Build an empty vector element expression. 5750 explicit ExtVectorElementExpr(EmptyShell Empty) 5751 : Expr(ExtVectorElementExprClass, Empty) { } 5752 5753 const Expr *getBase() const { return cast<Expr>(Base); } 5754 Expr *getBase() { return cast<Expr>(Base); } 5755 void setBase(Expr *E) { Base = E; } 5756 5757 IdentifierInfo &getAccessor() const { return *Accessor; } 5758 void setAccessor(IdentifierInfo *II) { Accessor = II; } 5759 5760 SourceLocation getAccessorLoc() const { return AccessorLoc; } 5761 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 5762 5763 /// getNumElements - Get the number of components being selected. 5764 unsigned getNumElements() const; 5765 5766 /// containsDuplicateElements - Return true if any element access is 5767 /// repeated. 5768 bool containsDuplicateElements() const; 5769 5770 /// getEncodedElementAccess - Encode the elements accessed into an llvm 5771 /// aggregate Constant of ConstantInt(s). 5772 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const; 5773 5774 SourceLocation getBeginLoc() const LLVM_READONLY { 5775 return getBase()->getBeginLoc(); 5776 } 5777 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; } 5778 5779 /// isArrow - Return true if the base expression is a pointer to vector, 5780 /// return false if the base expression is a vector. 5781 bool isArrow() const; 5782 5783 static bool classof(const Stmt *T) { 5784 return T->getStmtClass() == ExtVectorElementExprClass; 5785 } 5786 5787 // Iterators 5788 child_range children() { return child_range(&Base, &Base+1); } 5789 const_child_range children() const { 5790 return const_child_range(&Base, &Base + 1); 5791 } 5792}; 5793 5794/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 5795/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 5796class BlockExpr : public Expr { 5797protected: 5798 BlockDecl *TheBlock; 5799public: 5800 BlockExpr(BlockDecl *BD, QualType ty) 5801 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary), TheBlock(BD) { 5802 setDependence(computeDependence(this)); 5803 } 5804 5805 /// Build an empty block expression. 5806 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 5807 5808 const BlockDecl *getBlockDecl() const { return TheBlock; } 5809 BlockDecl *getBlockDecl() { return TheBlock; } 5810 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 5811 5812 // Convenience functions for probing the underlying BlockDecl. 5813 SourceLocation getCaretLocation() const; 5814 const Stmt *getBody() const; 5815 Stmt *getBody(); 5816 5817 SourceLocation getBeginLoc() const LLVM_READONLY { 5818 return getCaretLocation(); 5819 } 5820 SourceLocation getEndLoc() const LLVM_READONLY { 5821 return getBody()->getEndLoc(); 5822 } 5823 5824 /// getFunctionType - Return the underlying function type for this block. 5825 const FunctionProtoType *getFunctionType() const; 5826 5827 static bool classof(const Stmt *T) { 5828 return T->getStmtClass() == BlockExprClass; 5829 } 5830 5831 // Iterators 5832 child_range children() { 5833 return child_range(child_iterator(), child_iterator()); 5834 } 5835 const_child_range children() const { 5836 return const_child_range(const_child_iterator(), const_child_iterator()); 5837 } 5838}; 5839 5840/// Copy initialization expr of a __block variable and a boolean flag that 5841/// indicates whether the expression can throw. 5842struct BlockVarCopyInit { 5843 BlockVarCopyInit() = default; 5844 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow) 5845 : ExprAndFlag(CopyExpr, CanThrow) {} 5846 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) { 5847 ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow); 5848 } 5849 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); } 5850 bool canThrow() const { return ExprAndFlag.getInt(); } 5851 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag; 5852}; 5853 5854/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 5855/// This AST node provides support for reinterpreting a type to another 5856/// type of the same size. 5857class AsTypeExpr : public Expr { 5858private: 5859 Stmt *SrcExpr; 5860 SourceLocation BuiltinLoc, RParenLoc; 5861 5862 friend class ASTReader; 5863 friend class ASTStmtReader; 5864 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 5865 5866public: 5867 AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK, 5868 ExprObjectKind OK, SourceLocation BuiltinLoc, 5869 SourceLocation RParenLoc) 5870 : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr), 5871 BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) { 5872 setDependence(computeDependence(this)); 5873 } 5874 5875 /// getSrcExpr - Return the Expr to be converted. 5876 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 5877 5878 /// getBuiltinLoc - Return the location of the __builtin_astype token. 5879 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 5880 5881 /// getRParenLoc - Return the location of final right parenthesis. 5882 SourceLocation getRParenLoc() const { return RParenLoc; } 5883 5884 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 5885 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 5886 5887 static bool classof(const Stmt *T) { 5888 return T->getStmtClass() == AsTypeExprClass; 5889 } 5890 5891 // Iterators 5892 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 5893 const_child_range children() const { 5894 return const_child_range(&SrcExpr, &SrcExpr + 1); 5895 } 5896}; 5897 5898/// PseudoObjectExpr - An expression which accesses a pseudo-object 5899/// l-value. A pseudo-object is an abstract object, accesses to which 5900/// are translated to calls. The pseudo-object expression has a 5901/// syntactic form, which shows how the expression was actually 5902/// written in the source code, and a semantic form, which is a series 5903/// of expressions to be executed in order which detail how the 5904/// operation is actually evaluated. Optionally, one of the semantic 5905/// forms may also provide a result value for the expression. 5906/// 5907/// If any of the semantic-form expressions is an OpaqueValueExpr, 5908/// that OVE is required to have a source expression, and it is bound 5909/// to the result of that source expression. Such OVEs may appear 5910/// only in subsequent semantic-form expressions and as 5911/// sub-expressions of the syntactic form. 5912/// 5913/// PseudoObjectExpr should be used only when an operation can be 5914/// usefully described in terms of fairly simple rewrite rules on 5915/// objects and functions that are meant to be used by end-developers. 5916/// For example, under the Itanium ABI, dynamic casts are implemented 5917/// as a call to a runtime function called __dynamic_cast; using this 5918/// class to describe that would be inappropriate because that call is 5919/// not really part of the user-visible semantics, and instead the 5920/// cast is properly reflected in the AST and IR-generation has been 5921/// taught to generate the call as necessary. In contrast, an 5922/// Objective-C property access is semantically defined to be 5923/// equivalent to a particular message send, and this is very much 5924/// part of the user model. The name of this class encourages this 5925/// modelling design. 5926class PseudoObjectExpr final 5927 : public Expr, 5928 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> { 5929 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. 5930 // Always at least two, because the first sub-expression is the 5931 // syntactic form. 5932 5933 // PseudoObjectExprBits.ResultIndex - The index of the 5934 // sub-expression holding the result. 0 means the result is void, 5935 // which is unambiguous because it's the index of the syntactic 5936 // form. Note that this is therefore 1 higher than the value passed 5937 // in to Create, which is an index within the semantic forms. 5938 // Note also that ASTStmtWriter assumes this encoding. 5939 5940 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); } 5941 const Expr * const *getSubExprsBuffer() const { 5942 return getTrailingObjects<Expr *>(); 5943 } 5944 5945 PseudoObjectExpr(QualType type, ExprValueKind VK, 5946 Expr *syntactic, ArrayRef<Expr*> semantic, 5947 unsigned resultIndex); 5948 5949 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); 5950 5951 unsigned getNumSubExprs() const { 5952 return PseudoObjectExprBits.NumSubExprs; 5953 } 5954 5955public: 5956 /// NoResult - A value for the result index indicating that there is 5957 /// no semantic result. 5958 enum : unsigned { NoResult = ~0U }; 5959 5960 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, 5961 ArrayRef<Expr*> semantic, 5962 unsigned resultIndex); 5963 5964 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, 5965 unsigned numSemanticExprs); 5966 5967 /// Return the syntactic form of this expression, i.e. the 5968 /// expression it actually looks like. Likely to be expressed in 5969 /// terms of OpaqueValueExprs bound in the semantic form. 5970 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } 5971 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } 5972 5973 /// Return the index of the result-bearing expression into the semantics 5974 /// expressions, or PseudoObjectExpr::NoResult if there is none. 5975 unsigned getResultExprIndex() const { 5976 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; 5977 return PseudoObjectExprBits.ResultIndex - 1; 5978 } 5979 5980 /// Return the result-bearing expression, or null if there is none. 5981 Expr *getResultExpr() { 5982 if (PseudoObjectExprBits.ResultIndex == 0) 5983 return nullptr; 5984 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; 5985 } 5986 const Expr *getResultExpr() const { 5987 return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); 5988 } 5989 5990 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } 5991 5992 typedef Expr * const *semantics_iterator; 5993 typedef const Expr * const *const_semantics_iterator; 5994 semantics_iterator semantics_begin() { 5995 return getSubExprsBuffer() + 1; 5996 } 5997 const_semantics_iterator semantics_begin() const { 5998 return getSubExprsBuffer() + 1; 5999 } 6000 semantics_iterator semantics_end() { 6001 return getSubExprsBuffer() + getNumSubExprs(); 6002 } 6003 const_semantics_iterator semantics_end() const { 6004 return getSubExprsBuffer() + getNumSubExprs(); 6005 } 6006 6007 llvm::iterator_range<semantics_iterator> semantics() { 6008 return llvm::make_range(semantics_begin(), semantics_end()); 6009 } 6010 llvm::iterator_range<const_semantics_iterator> semantics() const { 6011 return llvm::make_range(semantics_begin(), semantics_end()); 6012 } 6013 6014 Expr *getSemanticExpr(unsigned index) { 6015 assert(index + 1 < getNumSubExprs()); 6016 return getSubExprsBuffer()[index + 1]; 6017 } 6018 const Expr *getSemanticExpr(unsigned index) const { 6019 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); 6020 } 6021 6022 SourceLocation getExprLoc() const LLVM_READONLY { 6023 return getSyntacticForm()->getExprLoc(); 6024 } 6025 6026 SourceLocation getBeginLoc() const LLVM_READONLY { 6027 return getSyntacticForm()->getBeginLoc(); 6028 } 6029 SourceLocation getEndLoc() const LLVM_READONLY { 6030 return getSyntacticForm()->getEndLoc(); 6031 } 6032 6033 child_range children() { 6034 const_child_range CCR = 6035 const_cast<const PseudoObjectExpr *>(this)->children(); 6036 return child_range(cast_away_const(CCR.begin()), 6037 cast_away_const(CCR.end())); 6038 } 6039 const_child_range children() const { 6040 Stmt *const *cs = const_cast<Stmt *const *>( 6041 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer())); 6042 return const_child_range(cs, cs + getNumSubExprs()); 6043 } 6044 6045 static bool classof(const Stmt *T) { 6046 return T->getStmtClass() == PseudoObjectExprClass; 6047 } 6048 6049 friend TrailingObjects; 6050 friend class ASTStmtReader; 6051}; 6052 6053/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 6054/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 6055/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, 6056/// and corresponding __opencl_atomic_* for OpenCL 2.0. 6057/// All of these instructions take one primary pointer, at least one memory 6058/// order. The instructions for which getScopeModel returns non-null value 6059/// take one synch scope. 6060class AtomicExpr : public Expr { 6061public: 6062 enum AtomicOp { 6063#define BUILTIN(ID, TYPE, ATTRS) 6064#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, 6065#include "clang/Basic/Builtins.def" 6066 // Avoid trailing comma 6067 BI_First = 0 6068 }; 6069 6070private: 6071 /// Location of sub-expressions. 6072 /// The location of Scope sub-expression is NumSubExprs - 1, which is 6073 /// not fixed, therefore is not defined in enum. 6074 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; 6075 Stmt *SubExprs[END_EXPR + 1]; 6076 unsigned NumSubExprs; 6077 SourceLocation BuiltinLoc, RParenLoc; 6078 AtomicOp Op; 6079 6080 friend class ASTStmtReader; 6081public: 6082 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, 6083 AtomicOp op, SourceLocation RP); 6084 6085 /// Determine the number of arguments the specified atomic builtin 6086 /// should have. 6087 static unsigned getNumSubExprs(AtomicOp Op); 6088 6089 /// Build an empty AtomicExpr. 6090 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 6091 6092 Expr *getPtr() const { 6093 return cast<Expr>(SubExprs[PTR]); 6094 } 6095 Expr *getOrder() const { 6096 return cast<Expr>(SubExprs[ORDER]); 6097 } 6098 Expr *getScope() const { 6099 assert(getScopeModel() && "No scope"); 6100 return cast<Expr>(SubExprs[NumSubExprs - 1]); 6101 } 6102 Expr *getVal1() const { 6103 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init) 6104 return cast<Expr>(SubExprs[ORDER]); 6105 assert(NumSubExprs > VAL1); 6106 return cast<Expr>(SubExprs[VAL1]); 6107 } 6108 Expr *getOrderFail() const { 6109 assert(NumSubExprs > ORDER_FAIL); 6110 return cast<Expr>(SubExprs[ORDER_FAIL]); 6111 } 6112 Expr *getVal2() const { 6113 if (Op == AO__atomic_exchange) 6114 return cast<Expr>(SubExprs[ORDER_FAIL]); 6115 assert(NumSubExprs > VAL2); 6116 return cast<Expr>(SubExprs[VAL2]); 6117 } 6118 Expr *getWeak() const { 6119 assert(NumSubExprs > WEAK); 6120 return cast<Expr>(SubExprs[WEAK]); 6121 } 6122 QualType getValueType() const; 6123 6124 AtomicOp getOp() const { return Op; } 6125 unsigned getNumSubExprs() const { return NumSubExprs; } 6126 6127 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 6128 const Expr * const *getSubExprs() const { 6129 return reinterpret_cast<Expr * const *>(SubExprs); 6130 } 6131 6132 bool isVolatile() const { 6133 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 6134 } 6135 6136 bool isCmpXChg() const { 6137 return getOp() == AO__c11_atomic_compare_exchange_strong || 6138 getOp() == AO__c11_atomic_compare_exchange_weak || 6139 getOp() == AO__opencl_atomic_compare_exchange_strong || 6140 getOp() == AO__opencl_atomic_compare_exchange_weak || 6141 getOp() == AO__atomic_compare_exchange || 6142 getOp() == AO__atomic_compare_exchange_n; 6143 } 6144 6145 bool isOpenCL() const { 6146 return getOp() >= AO__opencl_atomic_init && 6147 getOp() <= AO__opencl_atomic_fetch_max; 6148 } 6149 6150 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 6151 SourceLocation getRParenLoc() const { return RParenLoc; } 6152 6153 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 6154 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 6155 6156 static bool classof(const Stmt *T) { 6157 return T->getStmtClass() == AtomicExprClass; 6158 } 6159 6160 // Iterators 6161 child_range children() { 6162 return child_range(SubExprs, SubExprs+NumSubExprs); 6163 } 6164 const_child_range children() const { 6165 return const_child_range(SubExprs, SubExprs + NumSubExprs); 6166 } 6167 6168 /// Get atomic scope model for the atomic op code. 6169 /// \return empty atomic scope model if the atomic op code does not have 6170 /// scope operand. 6171 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) { 6172 auto Kind = 6173 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max) 6174 ? AtomicScopeModelKind::OpenCL 6175 : AtomicScopeModelKind::None; 6176 return AtomicScopeModel::create(Kind); 6177 } 6178 6179 /// Get atomic scope model. 6180 /// \return empty atomic scope model if this atomic expression does not have 6181 /// scope operand. 6182 std::unique_ptr<AtomicScopeModel> getScopeModel() const { 6183 return getScopeModel(getOp()); 6184 } 6185}; 6186 6187/// TypoExpr - Internal placeholder for expressions where typo correction 6188/// still needs to be performed and/or an error diagnostic emitted. 6189class TypoExpr : public Expr { 6190 // The location for the typo name. 6191 SourceLocation TypoLoc; 6192 6193public: 6194 TypoExpr(QualType T, SourceLocation TypoLoc) 6195 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) { 6196 assert(T->isDependentType() && "TypoExpr given a non-dependent type"); 6197 setDependence(ExprDependence::TypeValueInstantiation | 6198 ExprDependence::Error); 6199 } 6200 6201 child_range children() { 6202 return child_range(child_iterator(), child_iterator()); 6203 } 6204 const_child_range children() const { 6205 return const_child_range(const_child_iterator(), const_child_iterator()); 6206 } 6207 6208 SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; } 6209 SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; } 6210 6211 static bool classof(const Stmt *T) { 6212 return T->getStmtClass() == TypoExprClass; 6213 } 6214 6215}; 6216 6217/// Frontend produces RecoveryExprs on semantic errors that prevent creating 6218/// other well-formed expressions. E.g. when type-checking of a binary operator 6219/// fails, we cannot produce a BinaryOperator expression. Instead, we can choose 6220/// to produce a recovery expression storing left and right operands. 6221/// 6222/// RecoveryExpr does not have any semantic meaning in C++, it is only useful to 6223/// preserve expressions in AST that would otherwise be dropped. It captures 6224/// subexpressions of some expression that we could not construct and source 6225/// range covered by the expression. 6226/// 6227/// By default, RecoveryExpr uses dependence-bits to take advantage of existing 6228/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved 6229/// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In 6230/// addition to that, clang does not report most errors on dependent 6231/// expressions, so we get rid of bogus errors for free. However, note that 6232/// unlike other dependent expressions, RecoveryExpr can be produced in 6233/// non-template contexts. 6234/// 6235/// We will preserve the type in RecoveryExpr when the type is known, e.g. 6236/// preserving the return type for a broken non-overloaded function call, a 6237/// overloaded call where all candidates have the same return type. In this 6238/// case, the expression is not type-dependent (unless the known type is itself 6239/// dependent) 6240/// 6241/// One can also reliably suppress all bogus errors on expressions containing 6242/// recovery expressions by examining results of Expr::containsErrors(). 6243/// 6244/// FIXME: RecoveryExpr is currently generated by default in C++ mode only, as 6245/// dependence isn't handled properly on several C-only codepaths. 6246class RecoveryExpr final : public Expr, 6247 private llvm::TrailingObjects<RecoveryExpr, Expr *> { 6248public: 6249 static RecoveryExpr *Create(ASTContext &Ctx, QualType T, 6250 SourceLocation BeginLoc, SourceLocation EndLoc, 6251 ArrayRef<Expr *> SubExprs); 6252 static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs); 6253 6254 ArrayRef<Expr *> subExpressions() { 6255 auto *B = getTrailingObjects<Expr *>(); 6256 return llvm::makeArrayRef(B, B + NumExprs); 6257 } 6258 6259 ArrayRef<const Expr *> subExpressions() const { 6260 return const_cast<RecoveryExpr *>(this)->subExpressions(); 6261 } 6262 6263 child_range children() { 6264 Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); 6265 return child_range(B, B + NumExprs); 6266 } 6267 6268 SourceLocation getBeginLoc() const { return BeginLoc; } 6269 SourceLocation getEndLoc() const { return EndLoc; } 6270 6271 static bool classof(const Stmt *T) { 6272 return T->getStmtClass() == RecoveryExprClass; 6273 } 6274 6275private: 6276 RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, 6277 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs); 6278 RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs) 6279 : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {} 6280 6281 size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; } 6282 6283 SourceLocation BeginLoc, EndLoc; 6284 unsigned NumExprs; 6285 friend TrailingObjects; 6286 friend class ASTStmtReader; 6287 friend class ASTStmtWriter; 6288}; 6289 6290} // end namespace clang 6291 6292#endif // LLVM_CLANG_AST_EXPR_H 6293