Expr.h revision ec5bc81fd55bfcc26fc4bde6d5e33113d94c2209
1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the Expr interface and subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_AST_EXPR_H 15#define LLVM_CLANG_AST_EXPR_H 16 17#include "clang/AST/APValue.h" 18#include "clang/AST/Stmt.h" 19#include "clang/AST/Type.h" 20#include "clang/AST/DeclAccessPair.h" 21#include "clang/AST/OperationKinds.h" 22#include "clang/AST/ASTVector.h" 23#include "clang/AST/UsuallyTinyPtrVector.h" 24#include "clang/Basic/TypeTraits.h" 25#include "llvm/ADT/APSInt.h" 26#include "llvm/ADT/APFloat.h" 27#include "llvm/ADT/SmallVector.h" 28#include "llvm/ADT/StringRef.h" 29#include <cctype> 30 31namespace clang { 32 class ASTContext; 33 class APValue; 34 class Decl; 35 class IdentifierInfo; 36 class ParmVarDecl; 37 class NamedDecl; 38 class ValueDecl; 39 class BlockDecl; 40 class CXXBaseSpecifier; 41 class CXXOperatorCallExpr; 42 class CXXMemberCallExpr; 43 class ObjCPropertyRefExpr; 44 class TemplateArgumentLoc; 45 class TemplateArgumentListInfo; 46 class OpaqueValueExpr; 47 48/// \brief A simple array of base specifiers. 49typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 50 51/// Expr - This represents one expression. Note that Expr's are subclasses of 52/// Stmt. This allows an expression to be transparently used any place a Stmt 53/// is required. 54/// 55class Expr : public Stmt { 56 QualType TR; 57 58protected: 59 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, 60 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) 61 : Stmt(SC) 62 { 63 ExprBits.TypeDependent = TD; 64 ExprBits.ValueDependent = VD; 65 ExprBits.InstantiationDependent = ID; 66 ExprBits.ValueKind = VK; 67 ExprBits.ObjectKind = OK; 68 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 69 setType(T); 70 } 71 72 /// \brief Construct an empty expression. 73 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { } 74 75public: 76 QualType getType() const { return TR; } 77 void setType(QualType t) { 78 // In C++, the type of an expression is always adjusted so that it 79 // will not have reference type an expression will never have 80 // reference type (C++ [expr]p6). Use 81 // QualType::getNonReferenceType() to retrieve the non-reference 82 // type. Additionally, inspect Expr::isLvalue to determine whether 83 // an expression that is adjusted in this manner should be 84 // considered an lvalue. 85 assert((t.isNull() || !t->isReferenceType()) && 86 "Expressions can't have reference type"); 87 88 TR = t; 89 } 90 91 /// isValueDependent - Determines whether this expression is 92 /// value-dependent (C++ [temp.dep.constexpr]). For example, the 93 /// array bound of "Chars" in the following example is 94 /// value-dependent. 95 /// @code 96 /// template<int Size, char (&Chars)[Size]> struct meta_string; 97 /// @endcode 98 bool isValueDependent() const { return ExprBits.ValueDependent; } 99 100 /// \brief Set whether this expression is value-dependent or not. 101 void setValueDependent(bool VD) { 102 ExprBits.ValueDependent = VD; 103 if (VD) 104 ExprBits.InstantiationDependent = true; 105 } 106 107 /// isTypeDependent - Determines whether this expression is 108 /// type-dependent (C++ [temp.dep.expr]), which means that its type 109 /// could change from one template instantiation to the next. For 110 /// example, the expressions "x" and "x + y" are type-dependent in 111 /// the following code, but "y" is not type-dependent: 112 /// @code 113 /// template<typename T> 114 /// void add(T x, int y) { 115 /// x + y; 116 /// } 117 /// @endcode 118 bool isTypeDependent() const { return ExprBits.TypeDependent; } 119 120 /// \brief Set whether this expression is type-dependent or not. 121 void setTypeDependent(bool TD) { 122 ExprBits.TypeDependent = TD; 123 if (TD) 124 ExprBits.InstantiationDependent = true; 125 } 126 127 /// \brief Whether this expression is instantiation-dependent, meaning that 128 /// it depends in some way on a template parameter, even if neither its type 129 /// nor (constant) value can change due to the template instantiation. 130 /// 131 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 132 /// instantiation-dependent (since it involves a template parameter \c T), but 133 /// is neither type- nor value-dependent, since the type of the inner 134 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 135 /// \c sizeof is known. 136 /// 137 /// \code 138 /// template<typename T> 139 /// void f(T x, T y) { 140 /// sizeof(sizeof(T() + T()); 141 /// } 142 /// \endcode 143 /// 144 bool isInstantiationDependent() const { 145 return ExprBits.InstantiationDependent; 146 } 147 148 /// \brief Set whether this expression is instantiation-dependent or not. 149 void setInstantiationDependent(bool ID) { 150 ExprBits.InstantiationDependent = ID; 151 } 152 153 /// \brief Whether this expression contains an unexpanded parameter 154 /// pack (for C++0x variadic templates). 155 /// 156 /// Given the following function template: 157 /// 158 /// \code 159 /// template<typename F, typename ...Types> 160 /// void forward(const F &f, Types &&...args) { 161 /// f(static_cast<Types&&>(args)...); 162 /// } 163 /// \endcode 164 /// 165 /// The expressions \c args and \c static_cast<Types&&>(args) both 166 /// contain parameter packs. 167 bool containsUnexpandedParameterPack() const { 168 return ExprBits.ContainsUnexpandedParameterPack; 169 } 170 171 /// \brief Set the bit that describes whether this expression 172 /// contains an unexpanded parameter pack. 173 void setContainsUnexpandedParameterPack(bool PP = true) { 174 ExprBits.ContainsUnexpandedParameterPack = PP; 175 } 176 177 /// getExprLoc - Return the preferred location for the arrow when diagnosing 178 /// a problem with a generic expression. 179 SourceLocation getExprLoc() const; 180 181 /// isUnusedResultAWarning - Return true if this immediate expression should 182 /// be warned about if the result is unused. If so, fill in Loc and Ranges 183 /// with location to warn on and the source range[s] to report with the 184 /// warning. 185 bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 186 SourceRange &R2, ASTContext &Ctx) const; 187 188 /// isLValue - True if this expression is an "l-value" according to 189 /// the rules of the current language. C and C++ give somewhat 190 /// different rules for this concept, but in general, the result of 191 /// an l-value expression identifies a specific object whereas the 192 /// result of an r-value expression is a value detached from any 193 /// specific storage. 194 /// 195 /// C++0x divides the concept of "r-value" into pure r-values 196 /// ("pr-values") and so-called expiring values ("x-values"), which 197 /// identify specific objects that can be safely cannibalized for 198 /// their resources. This is an unfortunate abuse of terminology on 199 /// the part of the C++ committee. In Clang, when we say "r-value", 200 /// we generally mean a pr-value. 201 bool isLValue() const { return getValueKind() == VK_LValue; } 202 bool isRValue() const { return getValueKind() == VK_RValue; } 203 bool isXValue() const { return getValueKind() == VK_XValue; } 204 bool isGLValue() const { return getValueKind() != VK_RValue; } 205 206 enum LValueClassification { 207 LV_Valid, 208 LV_NotObjectType, 209 LV_IncompleteVoidType, 210 LV_DuplicateVectorComponents, 211 LV_InvalidExpression, 212 LV_InvalidMessageExpression, 213 LV_MemberFunction, 214 LV_SubObjCPropertySetting, 215 LV_ClassTemporary 216 }; 217 /// Reasons why an expression might not be an l-value. 218 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 219 220 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 221 /// does not have an incomplete type, does not have a const-qualified type, 222 /// and if it is a structure or union, does not have any member (including, 223 /// recursively, any member or element of all contained aggregates or unions) 224 /// with a const-qualified type. 225 /// 226 /// \param Loc [in] [out] - A source location which *may* be filled 227 /// in with the location of the expression making this a 228 /// non-modifiable lvalue, if specified. 229 enum isModifiableLvalueResult { 230 MLV_Valid, 231 MLV_NotObjectType, 232 MLV_IncompleteVoidType, 233 MLV_DuplicateVectorComponents, 234 MLV_InvalidExpression, 235 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 236 MLV_IncompleteType, 237 MLV_ConstQualified, 238 MLV_ArrayType, 239 MLV_NotBlockQualified, 240 MLV_ReadonlyProperty, 241 MLV_NoSetterProperty, 242 MLV_MemberFunction, 243 MLV_SubObjCPropertySetting, 244 MLV_InvalidMessageExpression, 245 MLV_ClassTemporary 246 }; 247 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, 248 SourceLocation *Loc = 0) const; 249 250 /// \brief The return type of classify(). Represents the C++0x expression 251 /// taxonomy. 252 class Classification { 253 public: 254 /// \brief The various classification results. Most of these mean prvalue. 255 enum Kinds { 256 CL_LValue, 257 CL_XValue, 258 CL_Function, // Functions cannot be lvalues in C. 259 CL_Void, // Void cannot be an lvalue in C. 260 CL_AddressableVoid, // Void expression whose address can be taken in C. 261 CL_DuplicateVectorComponents, // A vector shuffle with dupes. 262 CL_MemberFunction, // An expression referring to a member function 263 CL_SubObjCPropertySetting, 264 CL_ClassTemporary, // A prvalue of class type 265 CL_ObjCMessageRValue, // ObjC message is an rvalue 266 CL_PRValue // A prvalue for any other reason, of any other type 267 }; 268 /// \brief The results of modification testing. 269 enum ModifiableType { 270 CM_Untested, // testModifiable was false. 271 CM_Modifiable, 272 CM_RValue, // Not modifiable because it's an rvalue 273 CM_Function, // Not modifiable because it's a function; C++ only 274 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext 275 CM_NotBlockQualified, // Not captured in the closure 276 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter 277 CM_ConstQualified, 278 CM_ArrayType, 279 CM_IncompleteType 280 }; 281 282 private: 283 friend class Expr; 284 285 unsigned short Kind; 286 unsigned short Modifiable; 287 288 explicit Classification(Kinds k, ModifiableType m) 289 : Kind(k), Modifiable(m) 290 {} 291 292 public: 293 Classification() {} 294 295 Kinds getKind() const { return static_cast<Kinds>(Kind); } 296 ModifiableType getModifiable() const { 297 assert(Modifiable != CM_Untested && "Did not test for modifiability."); 298 return static_cast<ModifiableType>(Modifiable); 299 } 300 bool isLValue() const { return Kind == CL_LValue; } 301 bool isXValue() const { return Kind == CL_XValue; } 302 bool isGLValue() const { return Kind <= CL_XValue; } 303 bool isPRValue() const { return Kind >= CL_Function; } 304 bool isRValue() const { return Kind >= CL_XValue; } 305 bool isModifiable() const { return getModifiable() == CM_Modifiable; } 306 307 /// \brief Create a simple, modifiably lvalue 308 static Classification makeSimpleLValue() { 309 return Classification(CL_LValue, CM_Modifiable); 310 } 311 312 }; 313 /// \brief Classify - Classify this expression according to the C++0x 314 /// expression taxonomy. 315 /// 316 /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the 317 /// old lvalue vs rvalue. This function determines the type of expression this 318 /// is. There are three expression types: 319 /// - lvalues are classical lvalues as in C++03. 320 /// - prvalues are equivalent to rvalues in C++03. 321 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a 322 /// function returning an rvalue reference. 323 /// lvalues and xvalues are collectively referred to as glvalues, while 324 /// prvalues and xvalues together form rvalues. 325 Classification Classify(ASTContext &Ctx) const { 326 return ClassifyImpl(Ctx, 0); 327 } 328 329 /// \brief ClassifyModifiable - Classify this expression according to the 330 /// C++0x expression taxonomy, and see if it is valid on the left side 331 /// of an assignment. 332 /// 333 /// This function extends classify in that it also tests whether the 334 /// expression is modifiable (C99 6.3.2.1p1). 335 /// \param Loc A source location that might be filled with a relevant location 336 /// if the expression is not modifiable. 337 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ 338 return ClassifyImpl(Ctx, &Loc); 339 } 340 341 /// getValueKindForType - Given a formal return or parameter type, 342 /// give its value kind. 343 static ExprValueKind getValueKindForType(QualType T) { 344 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 345 return (isa<LValueReferenceType>(RT) 346 ? VK_LValue 347 : (RT->getPointeeType()->isFunctionType() 348 ? VK_LValue : VK_XValue)); 349 return VK_RValue; 350 } 351 352 /// getValueKind - The value kind that this expression produces. 353 ExprValueKind getValueKind() const { 354 return static_cast<ExprValueKind>(ExprBits.ValueKind); 355 } 356 357 /// getObjectKind - The object kind that this expression produces. 358 /// Object kinds are meaningful only for expressions that yield an 359 /// l-value or x-value. 360 ExprObjectKind getObjectKind() const { 361 return static_cast<ExprObjectKind>(ExprBits.ObjectKind); 362 } 363 364 bool isOrdinaryOrBitFieldObject() const { 365 ExprObjectKind OK = getObjectKind(); 366 return (OK == OK_Ordinary || OK == OK_BitField); 367 } 368 369 /// setValueKind - Set the value kind produced by this expression. 370 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } 371 372 /// setObjectKind - Set the object kind produced by this expression. 373 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } 374 375private: 376 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 377 378public: 379 380 /// \brief If this expression refers to a bit-field, retrieve the 381 /// declaration of that bit-field. 382 FieldDecl *getBitField(); 383 384 const FieldDecl *getBitField() const { 385 return const_cast<Expr*>(this)->getBitField(); 386 } 387 388 /// \brief If this expression is an l-value for an Objective C 389 /// property, find the underlying property reference expression. 390 const ObjCPropertyRefExpr *getObjCProperty() const; 391 392 /// \brief Returns whether this expression refers to a vector element. 393 bool refersToVectorElement() const; 394 395 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 396 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 397 /// but also int expressions which are produced by things like comparisons in 398 /// C. 399 bool isKnownToHaveBooleanValue() const; 400 401 /// isIntegerConstantExpr - Return true if this expression is a valid integer 402 /// constant expression, and, if so, return its value in Result. If not a 403 /// valid i-c-e, return false and fill in Loc (if specified) with the location 404 /// of the invalid expression. 405 bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 406 SourceLocation *Loc = 0, 407 bool isEvaluated = true) const; 408 bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const { 409 llvm::APSInt X; 410 return isIntegerConstantExpr(X, Ctx, Loc); 411 } 412 /// isConstantInitializer - Returns true if this expression is a constant 413 /// initializer, which can be emitted at compile-time. 414 bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const; 415 416 /// EvalResult is a struct with detailed info about an evaluated expression. 417 struct EvalResult { 418 /// Val - This is the value the expression can be folded to. 419 APValue Val; 420 421 /// HasSideEffects - Whether the evaluated expression has side effects. 422 /// For example, (f() && 0) can be folded, but it still has side effects. 423 bool HasSideEffects; 424 425 /// Diag - If the expression is unfoldable, then Diag contains a note 426 /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret 427 /// position for the error, and DiagExpr is the expression that caused 428 /// the error. 429 /// If the expression is foldable, but not an integer constant expression, 430 /// Diag contains a note diagnostic that describes why it isn't an integer 431 /// constant expression. If the expression *is* an integer constant 432 /// expression, then Diag will be zero. 433 unsigned Diag; 434 const Expr *DiagExpr; 435 SourceLocation DiagLoc; 436 437 EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {} 438 439 // isGlobalLValue - Return true if the evaluated lvalue expression 440 // is global. 441 bool isGlobalLValue() const; 442 // hasSideEffects - Return true if the evaluated expression has 443 // side effects. 444 bool hasSideEffects() const { 445 return HasSideEffects; 446 } 447 }; 448 449 /// Evaluate - Return true if this is a constant which we can fold using 450 /// any crazy technique (that has nothing to do with language standards) that 451 /// we want to. If this function returns true, it returns the folded constant 452 /// in Result. 453 bool Evaluate(EvalResult &Result, const ASTContext &Ctx) const; 454 455 /// EvaluateAsBooleanCondition - Return true if this is a constant 456 /// which we we can fold and convert to a boolean condition using 457 /// any crazy technique that we want to. 458 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const; 459 460 /// isEvaluatable - Call Evaluate to see if this expression can be constant 461 /// folded, but discard the result. 462 bool isEvaluatable(const ASTContext &Ctx) const; 463 464 /// HasSideEffects - This routine returns true for all those expressions 465 /// which must be evaluated each time and must not be optimized away 466 /// or evaluated at compile time. Example is a function call, volatile 467 /// variable read. 468 bool HasSideEffects(const ASTContext &Ctx) const; 469 470 /// EvaluateAsInt - Call Evaluate and return the folded integer. This 471 /// must be called on an expression that constant folds to an integer. 472 llvm::APSInt EvaluateAsInt(const ASTContext &Ctx) const; 473 474 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue 475 /// with link time known address. 476 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const; 477 478 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue. 479 bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) const; 480 481 /// \brief Enumeration used to describe the kind of Null pointer constant 482 /// returned from \c isNullPointerConstant(). 483 enum NullPointerConstantKind { 484 /// \brief Expression is not a Null pointer constant. 485 NPCK_NotNull = 0, 486 487 /// \brief Expression is a Null pointer constant built from a zero integer. 488 NPCK_ZeroInteger, 489 490 /// \brief Expression is a C++0X nullptr. 491 NPCK_CXX0X_nullptr, 492 493 /// \brief Expression is a GNU-style __null constant. 494 NPCK_GNUNull 495 }; 496 497 /// \brief Enumeration used to describe how \c isNullPointerConstant() 498 /// should cope with value-dependent expressions. 499 enum NullPointerConstantValueDependence { 500 /// \brief Specifies that the expression should never be value-dependent. 501 NPC_NeverValueDependent = 0, 502 503 /// \brief Specifies that a value-dependent expression of integral or 504 /// dependent type should be considered a null pointer constant. 505 NPC_ValueDependentIsNull, 506 507 /// \brief Specifies that a value-dependent expression should be considered 508 /// to never be a null pointer constant. 509 NPC_ValueDependentIsNotNull 510 }; 511 512 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 513 /// a Null pointer constant. The return value can further distinguish the 514 /// kind of NULL pointer constant that was detected. 515 NullPointerConstantKind isNullPointerConstant( 516 ASTContext &Ctx, 517 NullPointerConstantValueDependence NPC) const; 518 519 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 520 /// write barrier. 521 bool isOBJCGCCandidate(ASTContext &Ctx) const; 522 523 /// \brief Returns true if this expression is a bound member function. 524 bool isBoundMemberFunction(ASTContext &Ctx) const; 525 526 /// \brief Given an expression of bound-member type, find the type 527 /// of the member. Returns null if this is an *overloaded* bound 528 /// member expression. 529 static QualType findBoundMemberType(const Expr *expr); 530 531 /// \brief Result type of CanThrow(). 532 enum CanThrowResult { 533 CT_Cannot, 534 CT_Dependent, 535 CT_Can 536 }; 537 /// \brief Test if this expression, if evaluated, might throw, according to 538 /// the rules of C++ [expr.unary.noexcept]. 539 CanThrowResult CanThrow(ASTContext &C) const; 540 541 /// IgnoreImpCasts - Skip past any implicit casts which might 542 /// surround this expression. Only skips ImplicitCastExprs. 543 Expr *IgnoreImpCasts(); 544 545 /// IgnoreImplicit - Skip past any implicit AST nodes which might 546 /// surround this expression. 547 Expr *IgnoreImplicit() { return cast<Expr>(Stmt::IgnoreImplicit()); } 548 549 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return 550 /// its subexpression. If that subexpression is also a ParenExpr, 551 /// then this method recursively returns its subexpression, and so forth. 552 /// Otherwise, the method returns the current Expr. 553 Expr *IgnoreParens(); 554 555 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 556 /// or CastExprs, returning their operand. 557 Expr *IgnoreParenCasts(); 558 559 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off any 560 /// ParenExpr or ImplicitCastExprs, returning their operand. 561 Expr *IgnoreParenImpCasts(); 562 563 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a 564 /// call to a conversion operator, return the argument. 565 Expr *IgnoreConversionOperator(); 566 567 const Expr *IgnoreConversionOperator() const { 568 return const_cast<Expr*>(this)->IgnoreConversionOperator(); 569 } 570 571 const Expr *IgnoreParenImpCasts() const { 572 return const_cast<Expr*>(this)->IgnoreParenImpCasts(); 573 } 574 575 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and 576 /// CastExprs that represent lvalue casts, returning their operand. 577 Expr *IgnoreParenLValueCasts(); 578 579 const Expr *IgnoreParenLValueCasts() const { 580 return const_cast<Expr*>(this)->IgnoreParenLValueCasts(); 581 } 582 583 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 584 /// value (including ptr->int casts of the same size). Strip off any 585 /// ParenExpr or CastExprs, returning their operand. 586 Expr *IgnoreParenNoopCasts(ASTContext &Ctx); 587 588 /// \brief Determine whether this expression is a default function argument. 589 /// 590 /// Default arguments are implicitly generated in the abstract syntax tree 591 /// by semantic analysis for function calls, object constructions, etc. in 592 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 593 /// this routine also looks through any implicit casts to determine whether 594 /// the expression is a default argument. 595 bool isDefaultArgument() const; 596 597 /// \brief Determine whether the result of this expression is a 598 /// temporary object of the given class type. 599 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 600 601 /// \brief Whether this expression is an implicit reference to 'this' in C++. 602 bool isImplicitCXXThis() const; 603 604 const Expr *IgnoreImpCasts() const { 605 return const_cast<Expr*>(this)->IgnoreImpCasts(); 606 } 607 const Expr *IgnoreParens() const { 608 return const_cast<Expr*>(this)->IgnoreParens(); 609 } 610 const Expr *IgnoreParenCasts() const { 611 return const_cast<Expr*>(this)->IgnoreParenCasts(); 612 } 613 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const { 614 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx); 615 } 616 617 static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs); 618 static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs); 619 620 static bool classof(const Stmt *T) { 621 return T->getStmtClass() >= firstExprConstant && 622 T->getStmtClass() <= lastExprConstant; 623 } 624 static bool classof(const Expr *) { return true; } 625}; 626 627 628//===----------------------------------------------------------------------===// 629// Primary Expressions. 630//===----------------------------------------------------------------------===// 631 632/// OpaqueValueExpr - An expression referring to an opaque object of a 633/// fixed type and value class. These don't correspond to concrete 634/// syntax; instead they're used to express operations (usually copy 635/// operations) on values whose source is generally obvious from 636/// context. 637class OpaqueValueExpr : public Expr { 638 friend class ASTStmtReader; 639 Expr *SourceExpr; 640 SourceLocation Loc; 641 642public: 643 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 644 ExprObjectKind OK = OK_Ordinary) 645 : Expr(OpaqueValueExprClass, T, VK, OK, 646 T->isDependentType(), T->isDependentType(), 647 T->isInstantiationDependentType(), 648 false), 649 SourceExpr(0), Loc(Loc) { 650 } 651 652 /// Given an expression which invokes a copy constructor --- i.e. a 653 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 654 /// find the OpaqueValueExpr that's the source of the construction. 655 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 656 657 explicit OpaqueValueExpr(EmptyShell Empty) 658 : Expr(OpaqueValueExprClass, Empty) { } 659 660 /// \brief Retrieve the location of this expression. 661 SourceLocation getLocation() const { return Loc; } 662 663 SourceRange getSourceRange() const { 664 if (SourceExpr) return SourceExpr->getSourceRange(); 665 return Loc; 666 } 667 SourceLocation getExprLoc() const { 668 if (SourceExpr) return SourceExpr->getExprLoc(); 669 return Loc; 670 } 671 672 child_range children() { return child_range(); } 673 674 /// The source expression of an opaque value expression is the 675 /// expression which originally generated the value. This is 676 /// provided as a convenience for analyses that don't wish to 677 /// precisely model the execution behavior of the program. 678 /// 679 /// The source expression is typically set when building the 680 /// expression which binds the opaque value expression in the first 681 /// place. 682 Expr *getSourceExpr() const { return SourceExpr; } 683 void setSourceExpr(Expr *e) { SourceExpr = e; } 684 685 static bool classof(const Stmt *T) { 686 return T->getStmtClass() == OpaqueValueExprClass; 687 } 688 static bool classof(const OpaqueValueExpr *) { return true; } 689}; 690 691/// \brief Represents an explicit template argument list in C++, e.g., 692/// the "<int>" in "sort<int>". 693struct ExplicitTemplateArgumentList { 694 /// \brief The source location of the left angle bracket ('<'); 695 SourceLocation LAngleLoc; 696 697 /// \brief The source location of the right angle bracket ('>'); 698 SourceLocation RAngleLoc; 699 700 /// \brief The number of template arguments in TemplateArgs. 701 /// The actual template arguments (if any) are stored after the 702 /// ExplicitTemplateArgumentList structure. 703 unsigned NumTemplateArgs; 704 705 /// \brief Retrieve the template arguments 706 TemplateArgumentLoc *getTemplateArgs() { 707 return reinterpret_cast<TemplateArgumentLoc *> (this + 1); 708 } 709 710 /// \brief Retrieve the template arguments 711 const TemplateArgumentLoc *getTemplateArgs() const { 712 return reinterpret_cast<const TemplateArgumentLoc *> (this + 1); 713 } 714 715 void initializeFrom(const TemplateArgumentListInfo &List); 716 void initializeFrom(const TemplateArgumentListInfo &List, 717 bool &Dependent, bool &InstantiationDependent, 718 bool &ContainsUnexpandedParameterPack); 719 void copyInto(TemplateArgumentListInfo &List) const; 720 static std::size_t sizeFor(unsigned NumTemplateArgs); 721 static std::size_t sizeFor(const TemplateArgumentListInfo &List); 722}; 723 724/// \brief A reference to a declared variable, function, enum, etc. 725/// [C99 6.5.1p2] 726/// 727/// This encodes all the information about how a declaration is referenced 728/// within an expression. 729/// 730/// There are several optional constructs attached to DeclRefExprs only when 731/// they apply in order to conserve memory. These are laid out past the end of 732/// the object, and flags in the DeclRefExprBitfield track whether they exist: 733/// 734/// DeclRefExprBits.HasQualifier: 735/// Specifies when this declaration reference expression has a C++ 736/// nested-name-specifier. 737/// DeclRefExprBits.HasFoundDecl: 738/// Specifies when this declaration reference expression has a record of 739/// a NamedDecl (different from the referenced ValueDecl) which was found 740/// during name lookup and/or overload resolution. 741/// DeclRefExprBits.HasExplicitTemplateArgs: 742/// Specifies when this declaration reference expression has an explicit 743/// C++ template argument list. 744class DeclRefExpr : public Expr { 745 /// \brief The declaration that we are referencing. 746 ValueDecl *D; 747 748 /// \brief The location of the declaration name itself. 749 SourceLocation Loc; 750 751 /// \brief Provides source/type location info for the declaration name 752 /// embedded in D. 753 DeclarationNameLoc DNLoc; 754 755 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 756 NestedNameSpecifierLoc &getInternalQualifierLoc() { 757 assert(hasQualifier()); 758 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1); 759 } 760 761 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc. 762 const NestedNameSpecifierLoc &getInternalQualifierLoc() const { 763 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc(); 764 } 765 766 /// \brief Test whether there is a distinct FoundDecl attached to the end of 767 /// this DRE. 768 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 769 770 /// \brief Helper to retrieve the optional NamedDecl through which this 771 /// reference occured. 772 NamedDecl *&getInternalFoundDecl() { 773 assert(hasFoundDecl()); 774 if (hasQualifier()) 775 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1); 776 return *reinterpret_cast<NamedDecl **>(this + 1); 777 } 778 779 /// \brief Helper to retrieve the optional NamedDecl through which this 780 /// reference occured. 781 NamedDecl *getInternalFoundDecl() const { 782 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl(); 783 } 784 785 DeclRefExpr(NestedNameSpecifierLoc QualifierLoc, 786 ValueDecl *D, const DeclarationNameInfo &NameInfo, 787 NamedDecl *FoundD, 788 const TemplateArgumentListInfo *TemplateArgs, 789 QualType T, ExprValueKind VK); 790 791 /// \brief Construct an empty declaration reference expression. 792 explicit DeclRefExpr(EmptyShell Empty) 793 : Expr(DeclRefExprClass, Empty) { } 794 795 /// \brief Computes the type- and value-dependence flags for this 796 /// declaration reference expression. 797 void computeDependence(); 798 799public: 800 DeclRefExpr(ValueDecl *D, QualType T, ExprValueKind VK, SourceLocation L, 801 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) 802 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), 803 D(D), Loc(L), DNLoc(LocInfo) { 804 DeclRefExprBits.HasQualifier = 0; 805 DeclRefExprBits.HasExplicitTemplateArgs = 0; 806 DeclRefExprBits.HasFoundDecl = 0; 807 computeDependence(); 808 } 809 810 static DeclRefExpr *Create(ASTContext &Context, 811 NestedNameSpecifierLoc QualifierLoc, 812 ValueDecl *D, 813 SourceLocation NameLoc, 814 QualType T, ExprValueKind VK, 815 NamedDecl *FoundD = 0, 816 const TemplateArgumentListInfo *TemplateArgs = 0); 817 818 static DeclRefExpr *Create(ASTContext &Context, 819 NestedNameSpecifierLoc QualifierLoc, 820 ValueDecl *D, 821 const DeclarationNameInfo &NameInfo, 822 QualType T, ExprValueKind VK, 823 NamedDecl *FoundD = 0, 824 const TemplateArgumentListInfo *TemplateArgs = 0); 825 826 /// \brief Construct an empty declaration reference expression. 827 static DeclRefExpr *CreateEmpty(ASTContext &Context, 828 bool HasQualifier, 829 bool HasFoundDecl, 830 bool HasExplicitTemplateArgs, 831 unsigned NumTemplateArgs); 832 833 ValueDecl *getDecl() { return D; } 834 const ValueDecl *getDecl() const { return D; } 835 void setDecl(ValueDecl *NewD) { D = NewD; } 836 837 DeclarationNameInfo getNameInfo() const { 838 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc); 839 } 840 841 SourceLocation getLocation() const { return Loc; } 842 void setLocation(SourceLocation L) { Loc = L; } 843 SourceRange getSourceRange() const; 844 845 /// \brief Determine whether this declaration reference was preceded by a 846 /// C++ nested-name-specifier, e.g., \c N::foo. 847 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 848 849 /// \brief If the name was qualified, retrieves the nested-name-specifier 850 /// that precedes the name. Otherwise, returns NULL. 851 NestedNameSpecifier *getQualifier() const { 852 if (!hasQualifier()) 853 return 0; 854 855 return getInternalQualifierLoc().getNestedNameSpecifier(); 856 } 857 858 /// \brief If the name was qualified, retrieves the nested-name-specifier 859 /// that precedes the name, with source-location information. 860 NestedNameSpecifierLoc getQualifierLoc() const { 861 if (!hasQualifier()) 862 return NestedNameSpecifierLoc(); 863 864 return getInternalQualifierLoc(); 865 } 866 867 /// \brief Get the NamedDecl through which this reference occured. 868 /// 869 /// This Decl may be different from the ValueDecl actually referred to in the 870 /// presence of using declarations, etc. It always returns non-NULL, and may 871 /// simple return the ValueDecl when appropriate. 872 NamedDecl *getFoundDecl() { 873 return hasFoundDecl() ? getInternalFoundDecl() : D; 874 } 875 876 /// \brief Get the NamedDecl through which this reference occurred. 877 /// See non-const variant. 878 const NamedDecl *getFoundDecl() const { 879 return hasFoundDecl() ? getInternalFoundDecl() : D; 880 } 881 882 /// \brief Determines whether this declaration reference was followed by an 883 /// explict template argument list. 884 bool hasExplicitTemplateArgs() const { 885 return DeclRefExprBits.HasExplicitTemplateArgs; 886 } 887 888 /// \brief Retrieve the explicit template argument list that followed the 889 /// member template name. 890 ExplicitTemplateArgumentList &getExplicitTemplateArgs() { 891 assert(hasExplicitTemplateArgs()); 892 if (hasFoundDecl()) 893 return *reinterpret_cast<ExplicitTemplateArgumentList *>( 894 &getInternalFoundDecl() + 1); 895 896 if (hasQualifier()) 897 return *reinterpret_cast<ExplicitTemplateArgumentList *>( 898 &getInternalQualifierLoc() + 1); 899 900 return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1); 901 } 902 903 /// \brief Retrieve the explicit template argument list that followed the 904 /// member template name. 905 const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const { 906 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs(); 907 } 908 909 /// \brief Retrieves the optional explicit template arguments. 910 /// This points to the same data as getExplicitTemplateArgs(), but 911 /// returns null if there are no explicit template arguments. 912 const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const { 913 if (!hasExplicitTemplateArgs()) return 0; 914 return &getExplicitTemplateArgs(); 915 } 916 917 /// \brief Copies the template arguments (if present) into the given 918 /// structure. 919 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 920 if (hasExplicitTemplateArgs()) 921 getExplicitTemplateArgs().copyInto(List); 922 } 923 924 /// \brief Retrieve the location of the left angle bracket following the 925 /// member name ('<'), if any. 926 SourceLocation getLAngleLoc() const { 927 if (!hasExplicitTemplateArgs()) 928 return SourceLocation(); 929 930 return getExplicitTemplateArgs().LAngleLoc; 931 } 932 933 /// \brief Retrieve the template arguments provided as part of this 934 /// template-id. 935 const TemplateArgumentLoc *getTemplateArgs() const { 936 if (!hasExplicitTemplateArgs()) 937 return 0; 938 939 return getExplicitTemplateArgs().getTemplateArgs(); 940 } 941 942 /// \brief Retrieve the number of template arguments provided as part of this 943 /// template-id. 944 unsigned getNumTemplateArgs() const { 945 if (!hasExplicitTemplateArgs()) 946 return 0; 947 948 return getExplicitTemplateArgs().NumTemplateArgs; 949 } 950 951 /// \brief Retrieve the location of the right angle bracket following the 952 /// template arguments ('>'). 953 SourceLocation getRAngleLoc() const { 954 if (!hasExplicitTemplateArgs()) 955 return SourceLocation(); 956 957 return getExplicitTemplateArgs().RAngleLoc; 958 } 959 960 static bool classof(const Stmt *T) { 961 return T->getStmtClass() == DeclRefExprClass; 962 } 963 static bool classof(const DeclRefExpr *) { return true; } 964 965 // Iterators 966 child_range children() { return child_range(); } 967 968 friend class ASTStmtReader; 969 friend class ASTStmtWriter; 970}; 971 972/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__. 973class PredefinedExpr : public Expr { 974public: 975 enum IdentType { 976 Func, 977 Function, 978 PrettyFunction, 979 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the 980 /// 'virtual' keyword is omitted for virtual member functions. 981 PrettyFunctionNoVirtual 982 }; 983 984private: 985 SourceLocation Loc; 986 IdentType Type; 987public: 988 PredefinedExpr(SourceLocation l, QualType type, IdentType IT) 989 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary, 990 type->isDependentType(), type->isDependentType(), 991 type->isInstantiationDependentType(), 992 /*ContainsUnexpandedParameterPack=*/false), 993 Loc(l), Type(IT) {} 994 995 /// \brief Construct an empty predefined expression. 996 explicit PredefinedExpr(EmptyShell Empty) 997 : Expr(PredefinedExprClass, Empty) { } 998 999 IdentType getIdentType() const { return Type; } 1000 void setIdentType(IdentType IT) { Type = IT; } 1001 1002 SourceLocation getLocation() const { return Loc; } 1003 void setLocation(SourceLocation L) { Loc = L; } 1004 1005 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl); 1006 1007 SourceRange getSourceRange() const { return SourceRange(Loc); } 1008 1009 static bool classof(const Stmt *T) { 1010 return T->getStmtClass() == PredefinedExprClass; 1011 } 1012 static bool classof(const PredefinedExpr *) { return true; } 1013 1014 // Iterators 1015 child_range children() { return child_range(); } 1016}; 1017 1018/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without 1019/// leaking memory. 1020/// 1021/// For large floats/integers, APFloat/APInt will allocate memory from the heap 1022/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1023/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1024/// the APFloat/APInt values will never get freed. APNumericStorage uses 1025/// ASTContext's allocator for memory allocation. 1026class APNumericStorage { 1027 unsigned BitWidth; 1028 union { 1029 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1030 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1031 }; 1032 1033 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1034 1035 APNumericStorage(const APNumericStorage&); // do not implement 1036 APNumericStorage& operator=(const APNumericStorage&); // do not implement 1037 1038protected: 1039 APNumericStorage() : BitWidth(0), VAL(0) { } 1040 1041 llvm::APInt getIntValue() const { 1042 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1043 if (NumWords > 1) 1044 return llvm::APInt(BitWidth, NumWords, pVal); 1045 else 1046 return llvm::APInt(BitWidth, VAL); 1047 } 1048 void setIntValue(ASTContext &C, const llvm::APInt &Val); 1049}; 1050 1051class APIntStorage : public APNumericStorage { 1052public: 1053 llvm::APInt getValue() const { return getIntValue(); } 1054 void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); } 1055}; 1056 1057class APFloatStorage : public APNumericStorage { 1058public: 1059 llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); } 1060 void setValue(ASTContext &C, const llvm::APFloat &Val) { 1061 setIntValue(C, Val.bitcastToAPInt()); 1062 } 1063}; 1064 1065class IntegerLiteral : public Expr { 1066 APIntStorage Num; 1067 SourceLocation Loc; 1068 1069 /// \brief Construct an empty integer literal. 1070 explicit IntegerLiteral(EmptyShell Empty) 1071 : Expr(IntegerLiteralClass, Empty) { } 1072 1073public: 1074 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1075 // or UnsignedLongLongTy 1076 IntegerLiteral(ASTContext &C, const llvm::APInt &V, 1077 QualType type, SourceLocation l) 1078 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1079 false, false), 1080 Loc(l) { 1081 assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); 1082 assert(V.getBitWidth() == C.getIntWidth(type) && 1083 "Integer type is not the correct size for constant."); 1084 setValue(C, V); 1085 } 1086 1087 /// \brief Returns a new integer literal with value 'V' and type 'type'. 1088 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1089 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1090 /// \param V - the value that the returned integer literal contains. 1091 static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V, 1092 QualType type, SourceLocation l); 1093 /// \brief Returns a new empty integer literal. 1094 static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty); 1095 1096 llvm::APInt getValue() const { return Num.getValue(); } 1097 SourceRange getSourceRange() const { return SourceRange(Loc); } 1098 1099 /// \brief Retrieve the location of the literal. 1100 SourceLocation getLocation() const { return Loc; } 1101 1102 void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); } 1103 void setLocation(SourceLocation Location) { Loc = Location; } 1104 1105 static bool classof(const Stmt *T) { 1106 return T->getStmtClass() == IntegerLiteralClass; 1107 } 1108 static bool classof(const IntegerLiteral *) { return true; } 1109 1110 // Iterators 1111 child_range children() { return child_range(); } 1112}; 1113 1114class CharacterLiteral : public Expr { 1115public: 1116 enum CharacterKind { 1117 Ascii, 1118 Wide, 1119 UTF16, 1120 UTF32 1121 }; 1122 1123private: 1124 unsigned Value; 1125 SourceLocation Loc; 1126 unsigned Kind : 2; 1127public: 1128 // type should be IntTy 1129 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1130 SourceLocation l) 1131 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1132 false, false), 1133 Value(value), Loc(l), Kind(kind) { 1134 } 1135 1136 /// \brief Construct an empty character literal. 1137 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1138 1139 SourceLocation getLocation() const { return Loc; } 1140 CharacterKind getKind() const { return static_cast<CharacterKind>(Kind); } 1141 1142 SourceRange getSourceRange() const { return SourceRange(Loc); } 1143 1144 unsigned getValue() const { return Value; } 1145 1146 void setLocation(SourceLocation Location) { Loc = Location; } 1147 void setKind(CharacterKind kind) { Kind = kind; } 1148 void setValue(unsigned Val) { Value = Val; } 1149 1150 static bool classof(const Stmt *T) { 1151 return T->getStmtClass() == CharacterLiteralClass; 1152 } 1153 static bool classof(const CharacterLiteral *) { return true; } 1154 1155 // Iterators 1156 child_range children() { return child_range(); } 1157}; 1158 1159class FloatingLiteral : public Expr { 1160 APFloatStorage Num; 1161 bool IsExact : 1; 1162 SourceLocation Loc; 1163 1164 FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact, 1165 QualType Type, SourceLocation L) 1166 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false, 1167 false, false), 1168 IsExact(isexact), Loc(L) { 1169 setValue(C, V); 1170 } 1171 1172 /// \brief Construct an empty floating-point literal. 1173 explicit FloatingLiteral(EmptyShell Empty) 1174 : Expr(FloatingLiteralClass, Empty), IsExact(false) { } 1175 1176public: 1177 static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V, 1178 bool isexact, QualType Type, SourceLocation L); 1179 static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty); 1180 1181 llvm::APFloat getValue() const { return Num.getValue(); } 1182 void setValue(ASTContext &C, const llvm::APFloat &Val) { 1183 Num.setValue(C, Val); 1184 } 1185 1186 bool isExact() const { return IsExact; } 1187 void setExact(bool E) { IsExact = E; } 1188 1189 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1190 /// double. Note that this may cause loss of precision, but is useful for 1191 /// debugging dumps, etc. 1192 double getValueAsApproximateDouble() const; 1193 1194 SourceLocation getLocation() const { return Loc; } 1195 void setLocation(SourceLocation L) { Loc = L; } 1196 1197 SourceRange getSourceRange() const { return SourceRange(Loc); } 1198 1199 static bool classof(const Stmt *T) { 1200 return T->getStmtClass() == FloatingLiteralClass; 1201 } 1202 static bool classof(const FloatingLiteral *) { return true; } 1203 1204 // Iterators 1205 child_range children() { return child_range(); } 1206}; 1207 1208/// ImaginaryLiteral - We support imaginary integer and floating point literals, 1209/// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1210/// IntegerLiteral classes. Instances of this class always have a Complex type 1211/// whose element type matches the subexpression. 1212/// 1213class ImaginaryLiteral : public Expr { 1214 Stmt *Val; 1215public: 1216 ImaginaryLiteral(Expr *val, QualType Ty) 1217 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, 1218 false, false), 1219 Val(val) {} 1220 1221 /// \brief Build an empty imaginary literal. 1222 explicit ImaginaryLiteral(EmptyShell Empty) 1223 : Expr(ImaginaryLiteralClass, Empty) { } 1224 1225 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1226 Expr *getSubExpr() { return cast<Expr>(Val); } 1227 void setSubExpr(Expr *E) { Val = E; } 1228 1229 SourceRange getSourceRange() const { return Val->getSourceRange(); } 1230 static bool classof(const Stmt *T) { 1231 return T->getStmtClass() == ImaginaryLiteralClass; 1232 } 1233 static bool classof(const ImaginaryLiteral *) { return true; } 1234 1235 // Iterators 1236 child_range children() { return child_range(&Val, &Val+1); } 1237}; 1238 1239/// StringLiteral - This represents a string literal expression, e.g. "foo" 1240/// or L"bar" (wide strings). The actual string is returned by getStrData() 1241/// is NOT null-terminated, and the length of the string is determined by 1242/// calling getByteLength(). The C type for a string is always a 1243/// ConstantArrayType. In C++, the char type is const qualified, in C it is 1244/// not. 1245/// 1246/// Note that strings in C can be formed by concatenation of multiple string 1247/// literal pptokens in translation phase #6. This keeps track of the locations 1248/// of each of these pieces. 1249/// 1250/// Strings in C can also be truncated and extended by assigning into arrays, 1251/// e.g. with constructs like: 1252/// char X[2] = "foobar"; 1253/// In this case, getByteLength() will return 6, but the string literal will 1254/// have type "char[2]". 1255class StringLiteral : public Expr { 1256public: 1257 enum StringKind { 1258 Ascii, 1259 Wide, 1260 UTF8, 1261 UTF16, 1262 UTF32 1263 }; 1264 1265private: 1266 friend class ASTStmtReader; 1267 1268 const char *StrData; 1269 unsigned ByteLength; 1270 unsigned NumConcatenated; 1271 unsigned Kind : 3; 1272 bool IsPascal : 1; 1273 SourceLocation TokLocs[1]; 1274 1275 StringLiteral(QualType Ty) : 1276 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false, 1277 false) {} 1278 1279public: 1280 /// This is the "fully general" constructor that allows representation of 1281 /// strings formed from multiple concatenated tokens. 1282 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind, 1283 bool Pascal, QualType Ty, 1284 const SourceLocation *Loc, unsigned NumStrs); 1285 1286 /// Simple constructor for string literals made from one token. 1287 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind, 1288 bool Pascal, QualType Ty, 1289 SourceLocation Loc) { 1290 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1); 1291 } 1292 1293 /// \brief Construct an empty string literal. 1294 static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs); 1295 1296 StringRef getString() const { 1297 return StringRef(StrData, ByteLength); 1298 } 1299 1300 unsigned getByteLength() const { return ByteLength; } 1301 1302 /// \brief Sets the string data to the given string data. 1303 void setString(ASTContext &C, StringRef Str); 1304 1305 StringKind getKind() const { return static_cast<StringKind>(Kind); } 1306 bool isAscii() const { return Kind == Ascii; } 1307 bool isWide() const { return Kind == Wide; } 1308 bool isUTF8() const { return Kind == UTF8; } 1309 bool isUTF16() const { return Kind == UTF16; } 1310 bool isUTF32() const { return Kind == UTF32; } 1311 bool isPascal() const { return IsPascal; } 1312 1313 bool containsNonAsciiOrNull() const { 1314 StringRef Str = getString(); 1315 for (unsigned i = 0, e = Str.size(); i != e; ++i) 1316 if (!isascii(Str[i]) || !Str[i]) 1317 return true; 1318 return false; 1319 } 1320 /// getNumConcatenated - Get the number of string literal tokens that were 1321 /// concatenated in translation phase #6 to form this string literal. 1322 unsigned getNumConcatenated() const { return NumConcatenated; } 1323 1324 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1325 assert(TokNum < NumConcatenated && "Invalid tok number"); 1326 return TokLocs[TokNum]; 1327 } 1328 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1329 assert(TokNum < NumConcatenated && "Invalid tok number"); 1330 TokLocs[TokNum] = L; 1331 } 1332 1333 /// getLocationOfByte - Return a source location that points to the specified 1334 /// byte of this string literal. 1335 /// 1336 /// Strings are amazingly complex. They can be formed from multiple tokens 1337 /// and can have escape sequences in them in addition to the usual trigraph 1338 /// and escaped newline business. This routine handles this complexity. 1339 /// 1340 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1341 const LangOptions &Features, 1342 const TargetInfo &Target) const; 1343 1344 typedef const SourceLocation *tokloc_iterator; 1345 tokloc_iterator tokloc_begin() const { return TokLocs; } 1346 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; } 1347 1348 SourceRange getSourceRange() const { 1349 return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]); 1350 } 1351 static bool classof(const Stmt *T) { 1352 return T->getStmtClass() == StringLiteralClass; 1353 } 1354 static bool classof(const StringLiteral *) { return true; } 1355 1356 // Iterators 1357 child_range children() { return child_range(); } 1358}; 1359 1360/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 1361/// AST node is only formed if full location information is requested. 1362class ParenExpr : public Expr { 1363 SourceLocation L, R; 1364 Stmt *Val; 1365public: 1366 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 1367 : Expr(ParenExprClass, val->getType(), 1368 val->getValueKind(), val->getObjectKind(), 1369 val->isTypeDependent(), val->isValueDependent(), 1370 val->isInstantiationDependent(), 1371 val->containsUnexpandedParameterPack()), 1372 L(l), R(r), Val(val) {} 1373 1374 /// \brief Construct an empty parenthesized expression. 1375 explicit ParenExpr(EmptyShell Empty) 1376 : Expr(ParenExprClass, Empty) { } 1377 1378 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1379 Expr *getSubExpr() { return cast<Expr>(Val); } 1380 void setSubExpr(Expr *E) { Val = E; } 1381 1382 SourceRange getSourceRange() const { return SourceRange(L, R); } 1383 1384 /// \brief Get the location of the left parentheses '('. 1385 SourceLocation getLParen() const { return L; } 1386 void setLParen(SourceLocation Loc) { L = Loc; } 1387 1388 /// \brief Get the location of the right parentheses ')'. 1389 SourceLocation getRParen() const { return R; } 1390 void setRParen(SourceLocation Loc) { R = Loc; } 1391 1392 static bool classof(const Stmt *T) { 1393 return T->getStmtClass() == ParenExprClass; 1394 } 1395 static bool classof(const ParenExpr *) { return true; } 1396 1397 // Iterators 1398 child_range children() { return child_range(&Val, &Val+1); } 1399}; 1400 1401 1402/// UnaryOperator - This represents the unary-expression's (except sizeof and 1403/// alignof), the postinc/postdec operators from postfix-expression, and various 1404/// extensions. 1405/// 1406/// Notes on various nodes: 1407/// 1408/// Real/Imag - These return the real/imag part of a complex operand. If 1409/// applied to a non-complex value, the former returns its operand and the 1410/// later returns zero in the type of the operand. 1411/// 1412class UnaryOperator : public Expr { 1413public: 1414 typedef UnaryOperatorKind Opcode; 1415 1416private: 1417 unsigned Opc : 5; 1418 SourceLocation Loc; 1419 Stmt *Val; 1420public: 1421 1422 UnaryOperator(Expr *input, Opcode opc, QualType type, 1423 ExprValueKind VK, ExprObjectKind OK, SourceLocation l) 1424 : Expr(UnaryOperatorClass, type, VK, OK, 1425 input->isTypeDependent() || type->isDependentType(), 1426 input->isValueDependent(), 1427 (input->isInstantiationDependent() || 1428 type->isInstantiationDependentType()), 1429 input->containsUnexpandedParameterPack()), 1430 Opc(opc), Loc(l), Val(input) {} 1431 1432 /// \brief Build an empty unary operator. 1433 explicit UnaryOperator(EmptyShell Empty) 1434 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } 1435 1436 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 1437 void setOpcode(Opcode O) { Opc = O; } 1438 1439 Expr *getSubExpr() const { return cast<Expr>(Val); } 1440 void setSubExpr(Expr *E) { Val = E; } 1441 1442 /// getOperatorLoc - Return the location of the operator. 1443 SourceLocation getOperatorLoc() const { return Loc; } 1444 void setOperatorLoc(SourceLocation L) { Loc = L; } 1445 1446 /// isPostfix - Return true if this is a postfix operation, like x++. 1447 static bool isPostfix(Opcode Op) { 1448 return Op == UO_PostInc || Op == UO_PostDec; 1449 } 1450 1451 /// isPrefix - Return true if this is a prefix operation, like --x. 1452 static bool isPrefix(Opcode Op) { 1453 return Op == UO_PreInc || Op == UO_PreDec; 1454 } 1455 1456 bool isPrefix() const { return isPrefix(getOpcode()); } 1457 bool isPostfix() const { return isPostfix(getOpcode()); } 1458 bool isIncrementOp() const { 1459 return Opc == UO_PreInc || Opc == UO_PostInc; 1460 } 1461 bool isIncrementDecrementOp() const { 1462 return Opc <= UO_PreDec; 1463 } 1464 static bool isArithmeticOp(Opcode Op) { 1465 return Op >= UO_Plus && Op <= UO_LNot; 1466 } 1467 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 1468 1469 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1470 /// corresponds to, e.g. "sizeof" or "[pre]++" 1471 static const char *getOpcodeStr(Opcode Op); 1472 1473 /// \brief Retrieve the unary opcode that corresponds to the given 1474 /// overloaded operator. 1475 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 1476 1477 /// \brief Retrieve the overloaded operator kind that corresponds to 1478 /// the given unary opcode. 1479 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 1480 1481 SourceRange getSourceRange() const { 1482 if (isPostfix()) 1483 return SourceRange(Val->getLocStart(), Loc); 1484 else 1485 return SourceRange(Loc, Val->getLocEnd()); 1486 } 1487 SourceLocation getExprLoc() const { return Loc; } 1488 1489 static bool classof(const Stmt *T) { 1490 return T->getStmtClass() == UnaryOperatorClass; 1491 } 1492 static bool classof(const UnaryOperator *) { return true; } 1493 1494 // Iterators 1495 child_range children() { return child_range(&Val, &Val+1); } 1496}; 1497 1498/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 1499/// offsetof(record-type, member-designator). For example, given: 1500/// @code 1501/// struct S { 1502/// float f; 1503/// double d; 1504/// }; 1505/// struct T { 1506/// int i; 1507/// struct S s[10]; 1508/// }; 1509/// @endcode 1510/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 1511 1512class OffsetOfExpr : public Expr { 1513public: 1514 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 1515 class OffsetOfNode { 1516 public: 1517 /// \brief The kind of offsetof node we have. 1518 enum Kind { 1519 /// \brief An index into an array. 1520 Array = 0x00, 1521 /// \brief A field. 1522 Field = 0x01, 1523 /// \brief A field in a dependent type, known only by its name. 1524 Identifier = 0x02, 1525 /// \brief An implicit indirection through a C++ base class, when the 1526 /// field found is in a base class. 1527 Base = 0x03 1528 }; 1529 1530 private: 1531 enum { MaskBits = 2, Mask = 0x03 }; 1532 1533 /// \brief The source range that covers this part of the designator. 1534 SourceRange Range; 1535 1536 /// \brief The data describing the designator, which comes in three 1537 /// different forms, depending on the lower two bits. 1538 /// - An unsigned index into the array of Expr*'s stored after this node 1539 /// in memory, for [constant-expression] designators. 1540 /// - A FieldDecl*, for references to a known field. 1541 /// - An IdentifierInfo*, for references to a field with a given name 1542 /// when the class type is dependent. 1543 /// - A CXXBaseSpecifier*, for references that look at a field in a 1544 /// base class. 1545 uintptr_t Data; 1546 1547 public: 1548 /// \brief Create an offsetof node that refers to an array element. 1549 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 1550 SourceLocation RBracketLoc) 1551 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { } 1552 1553 /// \brief Create an offsetof node that refers to a field. 1554 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, 1555 SourceLocation NameLoc) 1556 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1557 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { } 1558 1559 /// \brief Create an offsetof node that refers to an identifier. 1560 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 1561 SourceLocation NameLoc) 1562 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc), 1563 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { } 1564 1565 /// \brief Create an offsetof node that refers into a C++ base class. 1566 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 1567 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 1568 1569 /// \brief Determine what kind of offsetof node this is. 1570 Kind getKind() const { 1571 return static_cast<Kind>(Data & Mask); 1572 } 1573 1574 /// \brief For an array element node, returns the index into the array 1575 /// of expressions. 1576 unsigned getArrayExprIndex() const { 1577 assert(getKind() == Array); 1578 return Data >> 2; 1579 } 1580 1581 /// \brief For a field offsetof node, returns the field. 1582 FieldDecl *getField() const { 1583 assert(getKind() == Field); 1584 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 1585 } 1586 1587 /// \brief For a field or identifier offsetof node, returns the name of 1588 /// the field. 1589 IdentifierInfo *getFieldName() const; 1590 1591 /// \brief For a base class node, returns the base specifier. 1592 CXXBaseSpecifier *getBase() const { 1593 assert(getKind() == Base); 1594 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 1595 } 1596 1597 /// \brief Retrieve the source range that covers this offsetof node. 1598 /// 1599 /// For an array element node, the source range contains the locations of 1600 /// the square brackets. For a field or identifier node, the source range 1601 /// contains the location of the period (if there is one) and the 1602 /// identifier. 1603 SourceRange getSourceRange() const { return Range; } 1604 }; 1605 1606private: 1607 1608 SourceLocation OperatorLoc, RParenLoc; 1609 // Base type; 1610 TypeSourceInfo *TSInfo; 1611 // Number of sub-components (i.e. instances of OffsetOfNode). 1612 unsigned NumComps; 1613 // Number of sub-expressions (i.e. array subscript expressions). 1614 unsigned NumExprs; 1615 1616 OffsetOfExpr(ASTContext &C, QualType type, 1617 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1618 OffsetOfNode* compsPtr, unsigned numComps, 1619 Expr** exprsPtr, unsigned numExprs, 1620 SourceLocation RParenLoc); 1621 1622 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 1623 : Expr(OffsetOfExprClass, EmptyShell()), 1624 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {} 1625 1626public: 1627 1628 static OffsetOfExpr *Create(ASTContext &C, QualType type, 1629 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 1630 OffsetOfNode* compsPtr, unsigned numComps, 1631 Expr** exprsPtr, unsigned numExprs, 1632 SourceLocation RParenLoc); 1633 1634 static OffsetOfExpr *CreateEmpty(ASTContext &C, 1635 unsigned NumComps, unsigned NumExprs); 1636 1637 /// getOperatorLoc - Return the location of the operator. 1638 SourceLocation getOperatorLoc() const { return OperatorLoc; } 1639 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 1640 1641 /// \brief Return the location of the right parentheses. 1642 SourceLocation getRParenLoc() const { return RParenLoc; } 1643 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 1644 1645 TypeSourceInfo *getTypeSourceInfo() const { 1646 return TSInfo; 1647 } 1648 void setTypeSourceInfo(TypeSourceInfo *tsi) { 1649 TSInfo = tsi; 1650 } 1651 1652 const OffsetOfNode &getComponent(unsigned Idx) const { 1653 assert(Idx < NumComps && "Subscript out of range"); 1654 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx]; 1655 } 1656 1657 void setComponent(unsigned Idx, OffsetOfNode ON) { 1658 assert(Idx < NumComps && "Subscript out of range"); 1659 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON; 1660 } 1661 1662 unsigned getNumComponents() const { 1663 return NumComps; 1664 } 1665 1666 Expr* getIndexExpr(unsigned Idx) { 1667 assert(Idx < NumExprs && "Subscript out of range"); 1668 return reinterpret_cast<Expr **>( 1669 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx]; 1670 } 1671 const Expr *getIndexExpr(unsigned Idx) const { 1672 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx); 1673 } 1674 1675 void setIndexExpr(unsigned Idx, Expr* E) { 1676 assert(Idx < NumComps && "Subscript out of range"); 1677 reinterpret_cast<Expr **>( 1678 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E; 1679 } 1680 1681 unsigned getNumExpressions() const { 1682 return NumExprs; 1683 } 1684 1685 SourceRange getSourceRange() const { 1686 return SourceRange(OperatorLoc, RParenLoc); 1687 } 1688 1689 static bool classof(const Stmt *T) { 1690 return T->getStmtClass() == OffsetOfExprClass; 1691 } 1692 1693 static bool classof(const OffsetOfExpr *) { return true; } 1694 1695 // Iterators 1696 child_range children() { 1697 Stmt **begin = 1698 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1) 1699 + NumComps); 1700 return child_range(begin, begin + NumExprs); 1701 } 1702}; 1703 1704/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 1705/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 1706/// vec_step (OpenCL 1.1 6.11.12). 1707class UnaryExprOrTypeTraitExpr : public Expr { 1708 unsigned Kind : 2; 1709 bool isType : 1; // true if operand is a type, false if an expression 1710 union { 1711 TypeSourceInfo *Ty; 1712 Stmt *Ex; 1713 } Argument; 1714 SourceLocation OpLoc, RParenLoc; 1715 1716public: 1717 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 1718 QualType resultType, SourceLocation op, 1719 SourceLocation rp) : 1720 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1721 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1722 // Value-dependent if the argument is type-dependent. 1723 TInfo->getType()->isDependentType(), 1724 TInfo->getType()->isInstantiationDependentType(), 1725 TInfo->getType()->containsUnexpandedParameterPack()), 1726 Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) { 1727 Argument.Ty = TInfo; 1728 } 1729 1730 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 1731 QualType resultType, SourceLocation op, 1732 SourceLocation rp) : 1733 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 1734 false, // Never type-dependent (C++ [temp.dep.expr]p3). 1735 // Value-dependent if the argument is type-dependent. 1736 E->isTypeDependent(), 1737 E->isInstantiationDependent(), 1738 E->containsUnexpandedParameterPack()), 1739 Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) { 1740 Argument.Ex = E; 1741 } 1742 1743 /// \brief Construct an empty sizeof/alignof expression. 1744 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 1745 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 1746 1747 UnaryExprOrTypeTrait getKind() const { 1748 return static_cast<UnaryExprOrTypeTrait>(Kind); 1749 } 1750 void setKind(UnaryExprOrTypeTrait K) { Kind = K; } 1751 1752 bool isArgumentType() const { return isType; } 1753 QualType getArgumentType() const { 1754 return getArgumentTypeInfo()->getType(); 1755 } 1756 TypeSourceInfo *getArgumentTypeInfo() const { 1757 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 1758 return Argument.Ty; 1759 } 1760 Expr *getArgumentExpr() { 1761 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 1762 return static_cast<Expr*>(Argument.Ex); 1763 } 1764 const Expr *getArgumentExpr() const { 1765 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 1766 } 1767 1768 void setArgument(Expr *E) { Argument.Ex = E; isType = false; } 1769 void setArgument(TypeSourceInfo *TInfo) { 1770 Argument.Ty = TInfo; 1771 isType = true; 1772 } 1773 1774 /// Gets the argument type, or the type of the argument expression, whichever 1775 /// is appropriate. 1776 QualType getTypeOfArgument() const { 1777 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 1778 } 1779 1780 SourceLocation getOperatorLoc() const { return OpLoc; } 1781 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 1782 1783 SourceLocation getRParenLoc() const { return RParenLoc; } 1784 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 1785 1786 SourceRange getSourceRange() const { 1787 return SourceRange(OpLoc, RParenLoc); 1788 } 1789 1790 static bool classof(const Stmt *T) { 1791 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 1792 } 1793 static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; } 1794 1795 // Iterators 1796 child_range children(); 1797}; 1798 1799//===----------------------------------------------------------------------===// 1800// Postfix Operators. 1801//===----------------------------------------------------------------------===// 1802 1803/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 1804class ArraySubscriptExpr : public Expr { 1805 enum { LHS, RHS, END_EXPR=2 }; 1806 Stmt* SubExprs[END_EXPR]; 1807 SourceLocation RBracketLoc; 1808public: 1809 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 1810 ExprValueKind VK, ExprObjectKind OK, 1811 SourceLocation rbracketloc) 1812 : Expr(ArraySubscriptExprClass, t, VK, OK, 1813 lhs->isTypeDependent() || rhs->isTypeDependent(), 1814 lhs->isValueDependent() || rhs->isValueDependent(), 1815 (lhs->isInstantiationDependent() || 1816 rhs->isInstantiationDependent()), 1817 (lhs->containsUnexpandedParameterPack() || 1818 rhs->containsUnexpandedParameterPack())), 1819 RBracketLoc(rbracketloc) { 1820 SubExprs[LHS] = lhs; 1821 SubExprs[RHS] = rhs; 1822 } 1823 1824 /// \brief Create an empty array subscript expression. 1825 explicit ArraySubscriptExpr(EmptyShell Shell) 1826 : Expr(ArraySubscriptExprClass, Shell) { } 1827 1828 /// An array access can be written A[4] or 4[A] (both are equivalent). 1829 /// - getBase() and getIdx() always present the normalized view: A[4]. 1830 /// In this case getBase() returns "A" and getIdx() returns "4". 1831 /// - getLHS() and getRHS() present the syntactic view. e.g. for 1832 /// 4[A] getLHS() returns "4". 1833 /// Note: Because vector element access is also written A[4] we must 1834 /// predicate the format conversion in getBase and getIdx only on the 1835 /// the type of the RHS, as it is possible for the LHS to be a vector of 1836 /// integer type 1837 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 1838 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 1839 void setLHS(Expr *E) { SubExprs[LHS] = E; } 1840 1841 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 1842 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 1843 void setRHS(Expr *E) { SubExprs[RHS] = E; } 1844 1845 Expr *getBase() { 1846 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 1847 } 1848 1849 const Expr *getBase() const { 1850 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); 1851 } 1852 1853 Expr *getIdx() { 1854 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 1855 } 1856 1857 const Expr *getIdx() const { 1858 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); 1859 } 1860 1861 SourceRange getSourceRange() const { 1862 return SourceRange(getLHS()->getLocStart(), RBracketLoc); 1863 } 1864 1865 SourceLocation getRBracketLoc() const { return RBracketLoc; } 1866 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } 1867 1868 SourceLocation getExprLoc() const { return getBase()->getExprLoc(); } 1869 1870 static bool classof(const Stmt *T) { 1871 return T->getStmtClass() == ArraySubscriptExprClass; 1872 } 1873 static bool classof(const ArraySubscriptExpr *) { return true; } 1874 1875 // Iterators 1876 child_range children() { 1877 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 1878 } 1879}; 1880 1881 1882/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 1883/// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 1884/// while its subclasses may represent alternative syntax that (semantically) 1885/// results in a function call. For example, CXXOperatorCallExpr is 1886/// a subclass for overloaded operator calls that use operator syntax, e.g., 1887/// "str1 + str2" to resolve to a function call. 1888class CallExpr : public Expr { 1889 enum { FN=0, PREARGS_START=1 }; 1890 Stmt **SubExprs; 1891 unsigned NumArgs; 1892 SourceLocation RParenLoc; 1893 1894protected: 1895 // These versions of the constructor are for derived classes. 1896 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 1897 Expr **args, unsigned numargs, QualType t, ExprValueKind VK, 1898 SourceLocation rparenloc); 1899 CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty); 1900 1901 Stmt *getPreArg(unsigned i) { 1902 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1903 return SubExprs[PREARGS_START+i]; 1904 } 1905 const Stmt *getPreArg(unsigned i) const { 1906 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1907 return SubExprs[PREARGS_START+i]; 1908 } 1909 void setPreArg(unsigned i, Stmt *PreArg) { 1910 assert(i < getNumPreArgs() && "Prearg access out of range!"); 1911 SubExprs[PREARGS_START+i] = PreArg; 1912 } 1913 1914 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 1915 1916public: 1917 CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, 1918 ExprValueKind VK, SourceLocation rparenloc); 1919 1920 /// \brief Build an empty call expression. 1921 CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty); 1922 1923 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); } 1924 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); } 1925 void setCallee(Expr *F) { SubExprs[FN] = F; } 1926 1927 Decl *getCalleeDecl(); 1928 const Decl *getCalleeDecl() const { 1929 return const_cast<CallExpr*>(this)->getCalleeDecl(); 1930 } 1931 1932 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. 1933 FunctionDecl *getDirectCallee(); 1934 const FunctionDecl *getDirectCallee() const { 1935 return const_cast<CallExpr*>(this)->getDirectCallee(); 1936 } 1937 1938 /// getNumArgs - Return the number of actual arguments to this call. 1939 /// 1940 unsigned getNumArgs() const { return NumArgs; } 1941 1942 /// \brief Retrieve the call arguments. 1943 Expr **getArgs() { 1944 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START); 1945 } 1946 1947 /// getArg - Return the specified argument. 1948 Expr *getArg(unsigned Arg) { 1949 assert(Arg < NumArgs && "Arg access out of range!"); 1950 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 1951 } 1952 const Expr *getArg(unsigned Arg) const { 1953 assert(Arg < NumArgs && "Arg access out of range!"); 1954 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]); 1955 } 1956 1957 /// setArg - Set the specified argument. 1958 void setArg(unsigned Arg, Expr *ArgExpr) { 1959 assert(Arg < NumArgs && "Arg access out of range!"); 1960 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; 1961 } 1962 1963 /// setNumArgs - This changes the number of arguments present in this call. 1964 /// Any orphaned expressions are deleted by this, and any new operands are set 1965 /// to null. 1966 void setNumArgs(ASTContext& C, unsigned NumArgs); 1967 1968 typedef ExprIterator arg_iterator; 1969 typedef ConstExprIterator const_arg_iterator; 1970 1971 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } 1972 arg_iterator arg_end() { 1973 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 1974 } 1975 const_arg_iterator arg_begin() const { 1976 return SubExprs+PREARGS_START+getNumPreArgs(); 1977 } 1978 const_arg_iterator arg_end() const { 1979 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); 1980 } 1981 1982 /// getNumCommas - Return the number of commas that must have been present in 1983 /// this function call. 1984 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } 1985 1986 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 1987 /// not, return 0. 1988 unsigned isBuiltinCall(const ASTContext &Context) const; 1989 1990 /// getCallReturnType - Get the return type of the call expr. This is not 1991 /// always the type of the expr itself, if the return type is a reference 1992 /// type. 1993 QualType getCallReturnType() const; 1994 1995 SourceLocation getRParenLoc() const { return RParenLoc; } 1996 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 1997 1998 SourceRange getSourceRange() const; 1999 2000 static bool classof(const Stmt *T) { 2001 return T->getStmtClass() >= firstCallExprConstant && 2002 T->getStmtClass() <= lastCallExprConstant; 2003 } 2004 static bool classof(const CallExpr *) { return true; } 2005 2006 // Iterators 2007 child_range children() { 2008 return child_range(&SubExprs[0], 2009 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); 2010 } 2011}; 2012 2013/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2014/// 2015class MemberExpr : public Expr { 2016 /// Extra data stored in some member expressions. 2017 struct MemberNameQualifier { 2018 /// \brief The nested-name-specifier that qualifies the name, including 2019 /// source-location information. 2020 NestedNameSpecifierLoc QualifierLoc; 2021 2022 /// \brief The DeclAccessPair through which the MemberDecl was found due to 2023 /// name qualifiers. 2024 DeclAccessPair FoundDecl; 2025 }; 2026 2027 /// Base - the expression for the base pointer or structure references. In 2028 /// X.F, this is "X". 2029 Stmt *Base; 2030 2031 /// MemberDecl - This is the decl being referenced by the field/member name. 2032 /// In X.F, this is the decl referenced by F. 2033 ValueDecl *MemberDecl; 2034 2035 /// MemberLoc - This is the location of the member name. 2036 SourceLocation MemberLoc; 2037 2038 /// MemberDNLoc - Provides source/type location info for the 2039 /// declaration name embedded in MemberDecl. 2040 DeclarationNameLoc MemberDNLoc; 2041 2042 /// IsArrow - True if this is "X->F", false if this is "X.F". 2043 bool IsArrow : 1; 2044 2045 /// \brief True if this member expression used a nested-name-specifier to 2046 /// refer to the member, e.g., "x->Base::f", or found its member via a using 2047 /// declaration. When true, a MemberNameQualifier 2048 /// structure is allocated immediately after the MemberExpr. 2049 bool HasQualifierOrFoundDecl : 1; 2050 2051 /// \brief True if this member expression specified a template argument list 2052 /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList 2053 /// structure (and its TemplateArguments) are allocated immediately after 2054 /// the MemberExpr or, if the member expression also has a qualifier, after 2055 /// the MemberNameQualifier structure. 2056 bool HasExplicitTemplateArgumentList : 1; 2057 2058 /// \brief Retrieve the qualifier that preceded the member name, if any. 2059 MemberNameQualifier *getMemberQualifier() { 2060 assert(HasQualifierOrFoundDecl); 2061 return reinterpret_cast<MemberNameQualifier *> (this + 1); 2062 } 2063 2064 /// \brief Retrieve the qualifier that preceded the member name, if any. 2065 const MemberNameQualifier *getMemberQualifier() const { 2066 return const_cast<MemberExpr *>(this)->getMemberQualifier(); 2067 } 2068 2069public: 2070 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2071 const DeclarationNameInfo &NameInfo, QualType ty, 2072 ExprValueKind VK, ExprObjectKind OK) 2073 : Expr(MemberExprClass, ty, VK, OK, 2074 base->isTypeDependent(), 2075 base->isValueDependent(), 2076 base->isInstantiationDependent(), 2077 base->containsUnexpandedParameterPack()), 2078 Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()), 2079 MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow), 2080 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) { 2081 assert(memberdecl->getDeclName() == NameInfo.getName()); 2082 } 2083 2084 // NOTE: this constructor should be used only when it is known that 2085 // the member name can not provide additional syntactic info 2086 // (i.e., source locations for C++ operator names or type source info 2087 // for constructors, destructors and conversion oeprators). 2088 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, 2089 SourceLocation l, QualType ty, 2090 ExprValueKind VK, ExprObjectKind OK) 2091 : Expr(MemberExprClass, ty, VK, OK, 2092 base->isTypeDependent(), base->isValueDependent(), 2093 base->isInstantiationDependent(), 2094 base->containsUnexpandedParameterPack()), 2095 Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(), 2096 IsArrow(isarrow), 2097 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {} 2098 2099 static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, 2100 NestedNameSpecifierLoc QualifierLoc, 2101 ValueDecl *memberdecl, DeclAccessPair founddecl, 2102 DeclarationNameInfo MemberNameInfo, 2103 const TemplateArgumentListInfo *targs, 2104 QualType ty, ExprValueKind VK, ExprObjectKind OK); 2105 2106 void setBase(Expr *E) { Base = E; } 2107 Expr *getBase() const { return cast<Expr>(Base); } 2108 2109 /// \brief Retrieve the member declaration to which this expression refers. 2110 /// 2111 /// The returned declaration will either be a FieldDecl or (in C++) 2112 /// a CXXMethodDecl. 2113 ValueDecl *getMemberDecl() const { return MemberDecl; } 2114 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2115 2116 /// \brief Retrieves the declaration found by lookup. 2117 DeclAccessPair getFoundDecl() const { 2118 if (!HasQualifierOrFoundDecl) 2119 return DeclAccessPair::make(getMemberDecl(), 2120 getMemberDecl()->getAccess()); 2121 return getMemberQualifier()->FoundDecl; 2122 } 2123 2124 /// \brief Determines whether this member expression actually had 2125 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2126 /// x->Base::foo. 2127 bool hasQualifier() const { return getQualifier() != 0; } 2128 2129 /// \brief If the member name was qualified, retrieves the 2130 /// nested-name-specifier that precedes the member name. Otherwise, returns 2131 /// NULL. 2132 NestedNameSpecifier *getQualifier() const { 2133 if (!HasQualifierOrFoundDecl) 2134 return 0; 2135 2136 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier(); 2137 } 2138 2139 /// \brief If the member name was qualified, retrieves the 2140 /// nested-name-specifier that precedes the member name, with source-location 2141 /// information. 2142 NestedNameSpecifierLoc getQualifierLoc() const { 2143 if (!hasQualifier()) 2144 return NestedNameSpecifierLoc(); 2145 2146 return getMemberQualifier()->QualifierLoc; 2147 } 2148 2149 /// \brief Determines whether this member expression actually had a C++ 2150 /// template argument list explicitly specified, e.g., x.f<int>. 2151 bool hasExplicitTemplateArgs() const { 2152 return HasExplicitTemplateArgumentList; 2153 } 2154 2155 /// \brief Copies the template arguments (if present) into the given 2156 /// structure. 2157 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2158 if (hasExplicitTemplateArgs()) 2159 getExplicitTemplateArgs().copyInto(List); 2160 } 2161 2162 /// \brief Retrieve the explicit template argument list that 2163 /// follow the member template name. This must only be called on an 2164 /// expression with explicit template arguments. 2165 ExplicitTemplateArgumentList &getExplicitTemplateArgs() { 2166 assert(HasExplicitTemplateArgumentList); 2167 if (!HasQualifierOrFoundDecl) 2168 return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1); 2169 2170 return *reinterpret_cast<ExplicitTemplateArgumentList *>( 2171 getMemberQualifier() + 1); 2172 } 2173 2174 /// \brief Retrieve the explicit template argument list that 2175 /// followed the member template name. This must only be called on 2176 /// an expression with explicit template arguments. 2177 const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const { 2178 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs(); 2179 } 2180 2181 /// \brief Retrieves the optional explicit template arguments. 2182 /// This points to the same data as getExplicitTemplateArgs(), but 2183 /// returns null if there are no explicit template arguments. 2184 const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const { 2185 if (!hasExplicitTemplateArgs()) return 0; 2186 return &getExplicitTemplateArgs(); 2187 } 2188 2189 /// \brief Retrieve the location of the left angle bracket following the 2190 /// member name ('<'), if any. 2191 SourceLocation getLAngleLoc() const { 2192 if (!HasExplicitTemplateArgumentList) 2193 return SourceLocation(); 2194 2195 return getExplicitTemplateArgs().LAngleLoc; 2196 } 2197 2198 /// \brief Retrieve the template arguments provided as part of this 2199 /// template-id. 2200 const TemplateArgumentLoc *getTemplateArgs() const { 2201 if (!HasExplicitTemplateArgumentList) 2202 return 0; 2203 2204 return getExplicitTemplateArgs().getTemplateArgs(); 2205 } 2206 2207 /// \brief Retrieve the number of template arguments provided as part of this 2208 /// template-id. 2209 unsigned getNumTemplateArgs() const { 2210 if (!HasExplicitTemplateArgumentList) 2211 return 0; 2212 2213 return getExplicitTemplateArgs().NumTemplateArgs; 2214 } 2215 2216 /// \brief Retrieve the location of the right angle bracket following the 2217 /// template arguments ('>'). 2218 SourceLocation getRAngleLoc() const { 2219 if (!HasExplicitTemplateArgumentList) 2220 return SourceLocation(); 2221 2222 return getExplicitTemplateArgs().RAngleLoc; 2223 } 2224 2225 /// \brief Retrieve the member declaration name info. 2226 DeclarationNameInfo getMemberNameInfo() const { 2227 return DeclarationNameInfo(MemberDecl->getDeclName(), 2228 MemberLoc, MemberDNLoc); 2229 } 2230 2231 bool isArrow() const { return IsArrow; } 2232 void setArrow(bool A) { IsArrow = A; } 2233 2234 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2235 /// location of 'F'. 2236 SourceLocation getMemberLoc() const { return MemberLoc; } 2237 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 2238 2239 SourceRange getSourceRange() const; 2240 2241 SourceLocation getExprLoc() const { return MemberLoc; } 2242 2243 /// \brief Determine whether the base of this explicit is implicit. 2244 bool isImplicitAccess() const { 2245 return getBase() && getBase()->isImplicitCXXThis(); 2246 } 2247 2248 static bool classof(const Stmt *T) { 2249 return T->getStmtClass() == MemberExprClass; 2250 } 2251 static bool classof(const MemberExpr *) { return true; } 2252 2253 // Iterators 2254 child_range children() { return child_range(&Base, &Base+1); } 2255 2256 friend class ASTReader; 2257 friend class ASTStmtWriter; 2258}; 2259 2260/// CompoundLiteralExpr - [C99 6.5.2.5] 2261/// 2262class CompoundLiteralExpr : public Expr { 2263 /// LParenLoc - If non-null, this is the location of the left paren in a 2264 /// compound literal like "(int){4}". This can be null if this is a 2265 /// synthesized compound expression. 2266 SourceLocation LParenLoc; 2267 2268 /// The type as written. This can be an incomplete array type, in 2269 /// which case the actual expression type will be different. 2270 TypeSourceInfo *TInfo; 2271 Stmt *Init; 2272 bool FileScope; 2273public: 2274 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 2275 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 2276 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 2277 tinfo->getType()->isDependentType(), 2278 init->isValueDependent(), 2279 (init->isInstantiationDependent() || 2280 tinfo->getType()->isInstantiationDependentType()), 2281 init->containsUnexpandedParameterPack()), 2282 LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {} 2283 2284 /// \brief Construct an empty compound literal. 2285 explicit CompoundLiteralExpr(EmptyShell Empty) 2286 : Expr(CompoundLiteralExprClass, Empty) { } 2287 2288 const Expr *getInitializer() const { return cast<Expr>(Init); } 2289 Expr *getInitializer() { return cast<Expr>(Init); } 2290 void setInitializer(Expr *E) { Init = E; } 2291 2292 bool isFileScope() const { return FileScope; } 2293 void setFileScope(bool FS) { FileScope = FS; } 2294 2295 SourceLocation getLParenLoc() const { return LParenLoc; } 2296 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 2297 2298 TypeSourceInfo *getTypeSourceInfo() const { return TInfo; } 2299 void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; } 2300 2301 SourceRange getSourceRange() const { 2302 // FIXME: Init should never be null. 2303 if (!Init) 2304 return SourceRange(); 2305 if (LParenLoc.isInvalid()) 2306 return Init->getSourceRange(); 2307 return SourceRange(LParenLoc, Init->getLocEnd()); 2308 } 2309 2310 static bool classof(const Stmt *T) { 2311 return T->getStmtClass() == CompoundLiteralExprClass; 2312 } 2313 static bool classof(const CompoundLiteralExpr *) { return true; } 2314 2315 // Iterators 2316 child_range children() { return child_range(&Init, &Init+1); } 2317}; 2318 2319/// CastExpr - Base class for type casts, including both implicit 2320/// casts (ImplicitCastExpr) and explicit casts that have some 2321/// representation in the source code (ExplicitCastExpr's derived 2322/// classes). 2323class CastExpr : public Expr { 2324public: 2325 typedef clang::CastKind CastKind; 2326 2327private: 2328 Stmt *Op; 2329 2330 void CheckCastConsistency() const { 2331#ifndef NDEBUG 2332 switch (getCastKind()) { 2333 case CK_DerivedToBase: 2334 case CK_UncheckedDerivedToBase: 2335 case CK_DerivedToBaseMemberPointer: 2336 case CK_BaseToDerived: 2337 case CK_BaseToDerivedMemberPointer: 2338 assert(!path_empty() && "Cast kind should have a base path!"); 2339 break; 2340 2341 // These should not have an inheritance path. 2342 case CK_BitCast: 2343 case CK_Dynamic: 2344 case CK_ToUnion: 2345 case CK_ArrayToPointerDecay: 2346 case CK_FunctionToPointerDecay: 2347 case CK_NullToMemberPointer: 2348 case CK_NullToPointer: 2349 case CK_ConstructorConversion: 2350 case CK_IntegralToPointer: 2351 case CK_PointerToIntegral: 2352 case CK_ToVoid: 2353 case CK_VectorSplat: 2354 case CK_IntegralCast: 2355 case CK_IntegralToFloating: 2356 case CK_FloatingToIntegral: 2357 case CK_FloatingCast: 2358 case CK_AnyPointerToObjCPointerCast: 2359 case CK_AnyPointerToBlockPointerCast: 2360 case CK_ObjCObjectLValueCast: 2361 case CK_FloatingRealToComplex: 2362 case CK_FloatingComplexToReal: 2363 case CK_FloatingComplexCast: 2364 case CK_FloatingComplexToIntegralComplex: 2365 case CK_IntegralRealToComplex: 2366 case CK_IntegralComplexToReal: 2367 case CK_IntegralComplexCast: 2368 case CK_IntegralComplexToFloatingComplex: 2369 case CK_ObjCProduceObject: 2370 case CK_ObjCConsumeObject: 2371 case CK_ObjCReclaimReturnedObject: 2372 assert(!getType()->isBooleanType() && "unheralded conversion to bool"); 2373 // fallthrough to check for null base path 2374 2375 case CK_Dependent: 2376 case CK_LValueToRValue: 2377 case CK_GetObjCProperty: 2378 case CK_NoOp: 2379 case CK_PointerToBoolean: 2380 case CK_IntegralToBoolean: 2381 case CK_FloatingToBoolean: 2382 case CK_MemberPointerToBoolean: 2383 case CK_FloatingComplexToBoolean: 2384 case CK_IntegralComplexToBoolean: 2385 case CK_LValueBitCast: // -> bool& 2386 case CK_UserDefinedConversion: // operator bool() 2387 assert(path_empty() && "Cast kind should not have a base path!"); 2388 break; 2389 } 2390#endif 2391 } 2392 2393 const CXXBaseSpecifier * const *path_buffer() const { 2394 return const_cast<CastExpr*>(this)->path_buffer(); 2395 } 2396 CXXBaseSpecifier **path_buffer(); 2397 2398 void setBasePathSize(unsigned basePathSize) { 2399 CastExprBits.BasePathSize = basePathSize; 2400 assert(CastExprBits.BasePathSize == basePathSize && 2401 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); 2402 } 2403 2404protected: 2405 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, 2406 const CastKind kind, Expr *op, unsigned BasePathSize) : 2407 Expr(SC, ty, VK, OK_Ordinary, 2408 // Cast expressions are type-dependent if the type is 2409 // dependent (C++ [temp.dep.expr]p3). 2410 ty->isDependentType(), 2411 // Cast expressions are value-dependent if the type is 2412 // dependent or if the subexpression is value-dependent. 2413 ty->isDependentType() || (op && op->isValueDependent()), 2414 (ty->isInstantiationDependentType() || 2415 (op && op->isInstantiationDependent())), 2416 (ty->containsUnexpandedParameterPack() || 2417 op->containsUnexpandedParameterPack())), 2418 Op(op) { 2419 assert(kind != CK_Invalid && "creating cast with invalid cast kind"); 2420 CastExprBits.Kind = kind; 2421 setBasePathSize(BasePathSize); 2422 CheckCastConsistency(); 2423 } 2424 2425 /// \brief Construct an empty cast. 2426 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 2427 : Expr(SC, Empty) { 2428 setBasePathSize(BasePathSize); 2429 } 2430 2431public: 2432 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 2433 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 2434 const char *getCastKindName() const; 2435 2436 Expr *getSubExpr() { return cast<Expr>(Op); } 2437 const Expr *getSubExpr() const { return cast<Expr>(Op); } 2438 void setSubExpr(Expr *E) { Op = E; } 2439 2440 /// \brief Retrieve the cast subexpression as it was written in the source 2441 /// code, looking through any implicit casts or other intermediate nodes 2442 /// introduced by semantic analysis. 2443 Expr *getSubExprAsWritten(); 2444 const Expr *getSubExprAsWritten() const { 2445 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 2446 } 2447 2448 typedef CXXBaseSpecifier **path_iterator; 2449 typedef const CXXBaseSpecifier * const *path_const_iterator; 2450 bool path_empty() const { return CastExprBits.BasePathSize == 0; } 2451 unsigned path_size() const { return CastExprBits.BasePathSize; } 2452 path_iterator path_begin() { return path_buffer(); } 2453 path_iterator path_end() { return path_buffer() + path_size(); } 2454 path_const_iterator path_begin() const { return path_buffer(); } 2455 path_const_iterator path_end() const { return path_buffer() + path_size(); } 2456 2457 void setCastPath(const CXXCastPath &Path); 2458 2459 static bool classof(const Stmt *T) { 2460 return T->getStmtClass() >= firstCastExprConstant && 2461 T->getStmtClass() <= lastCastExprConstant; 2462 } 2463 static bool classof(const CastExpr *) { return true; } 2464 2465 // Iterators 2466 child_range children() { return child_range(&Op, &Op+1); } 2467}; 2468 2469/// ImplicitCastExpr - Allows us to explicitly represent implicit type 2470/// conversions, which have no direct representation in the original 2471/// source code. For example: converting T[]->T*, void f()->void 2472/// (*f)(), float->double, short->int, etc. 2473/// 2474/// In C, implicit casts always produce rvalues. However, in C++, an 2475/// implicit cast whose result is being bound to a reference will be 2476/// an lvalue or xvalue. For example: 2477/// 2478/// @code 2479/// class Base { }; 2480/// class Derived : public Base { }; 2481/// Derived &&ref(); 2482/// void f(Derived d) { 2483/// Base& b = d; // initializer is an ImplicitCastExpr 2484/// // to an lvalue of type Base 2485/// Base&& r = ref(); // initializer is an ImplicitCastExpr 2486/// // to an xvalue of type Base 2487/// } 2488/// @endcode 2489class ImplicitCastExpr : public CastExpr { 2490private: 2491 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 2492 unsigned BasePathLength, ExprValueKind VK) 2493 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { 2494 } 2495 2496 /// \brief Construct an empty implicit cast. 2497 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 2498 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 2499 2500public: 2501 enum OnStack_t { OnStack }; 2502 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 2503 ExprValueKind VK) 2504 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 2505 } 2506 2507 static ImplicitCastExpr *Create(ASTContext &Context, QualType T, 2508 CastKind Kind, Expr *Operand, 2509 const CXXCastPath *BasePath, 2510 ExprValueKind Cat); 2511 2512 static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2513 2514 SourceRange getSourceRange() const { 2515 return getSubExpr()->getSourceRange(); 2516 } 2517 2518 static bool classof(const Stmt *T) { 2519 return T->getStmtClass() == ImplicitCastExprClass; 2520 } 2521 static bool classof(const ImplicitCastExpr *) { return true; } 2522}; 2523 2524inline Expr *Expr::IgnoreImpCasts() { 2525 Expr *e = this; 2526 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 2527 e = ice->getSubExpr(); 2528 return e; 2529} 2530 2531/// ExplicitCastExpr - An explicit cast written in the source 2532/// code. 2533/// 2534/// This class is effectively an abstract class, because it provides 2535/// the basic representation of an explicitly-written cast without 2536/// specifying which kind of cast (C cast, functional cast, static 2537/// cast, etc.) was written; specific derived classes represent the 2538/// particular style of cast and its location information. 2539/// 2540/// Unlike implicit casts, explicit cast nodes have two different 2541/// types: the type that was written into the source code, and the 2542/// actual type of the expression as determined by semantic 2543/// analysis. These types may differ slightly. For example, in C++ one 2544/// can cast to a reference type, which indicates that the resulting 2545/// expression will be an lvalue or xvalue. The reference type, however, 2546/// will not be used as the type of the expression. 2547class ExplicitCastExpr : public CastExpr { 2548 /// TInfo - Source type info for the (written) type 2549 /// this expression is casting to. 2550 TypeSourceInfo *TInfo; 2551 2552protected: 2553 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 2554 CastKind kind, Expr *op, unsigned PathSize, 2555 TypeSourceInfo *writtenTy) 2556 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 2557 2558 /// \brief Construct an empty explicit cast. 2559 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 2560 : CastExpr(SC, Shell, PathSize) { } 2561 2562public: 2563 /// getTypeInfoAsWritten - Returns the type source info for the type 2564 /// that this expression is casting to. 2565 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 2566 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 2567 2568 /// getTypeAsWritten - Returns the type that this expression is 2569 /// casting to, as written in the source code. 2570 QualType getTypeAsWritten() const { return TInfo->getType(); } 2571 2572 static bool classof(const Stmt *T) { 2573 return T->getStmtClass() >= firstExplicitCastExprConstant && 2574 T->getStmtClass() <= lastExplicitCastExprConstant; 2575 } 2576 static bool classof(const ExplicitCastExpr *) { return true; } 2577}; 2578 2579/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 2580/// cast in C++ (C++ [expr.cast]), which uses the syntax 2581/// (Type)expr. For example: @c (int)f. 2582class CStyleCastExpr : public ExplicitCastExpr { 2583 SourceLocation LPLoc; // the location of the left paren 2584 SourceLocation RPLoc; // the location of the right paren 2585 2586 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 2587 unsigned PathSize, TypeSourceInfo *writtenTy, 2588 SourceLocation l, SourceLocation r) 2589 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 2590 writtenTy), LPLoc(l), RPLoc(r) {} 2591 2592 /// \brief Construct an empty C-style explicit cast. 2593 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 2594 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 2595 2596public: 2597 static CStyleCastExpr *Create(ASTContext &Context, QualType T, 2598 ExprValueKind VK, CastKind K, 2599 Expr *Op, const CXXCastPath *BasePath, 2600 TypeSourceInfo *WrittenTy, SourceLocation L, 2601 SourceLocation R); 2602 2603 static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); 2604 2605 SourceLocation getLParenLoc() const { return LPLoc; } 2606 void setLParenLoc(SourceLocation L) { LPLoc = L; } 2607 2608 SourceLocation getRParenLoc() const { return RPLoc; } 2609 void setRParenLoc(SourceLocation L) { RPLoc = L; } 2610 2611 SourceRange getSourceRange() const { 2612 return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd()); 2613 } 2614 static bool classof(const Stmt *T) { 2615 return T->getStmtClass() == CStyleCastExprClass; 2616 } 2617 static bool classof(const CStyleCastExpr *) { return true; } 2618}; 2619 2620/// \brief A builtin binary operation expression such as "x + y" or "x <= y". 2621/// 2622/// This expression node kind describes a builtin binary operation, 2623/// such as "x + y" for integer values "x" and "y". The operands will 2624/// already have been converted to appropriate types (e.g., by 2625/// performing promotions or conversions). 2626/// 2627/// In C++, where operators may be overloaded, a different kind of 2628/// expression node (CXXOperatorCallExpr) is used to express the 2629/// invocation of an overloaded operator with operator syntax. Within 2630/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 2631/// used to store an expression "x + y" depends on the subexpressions 2632/// for x and y. If neither x or y is type-dependent, and the "+" 2633/// operator resolves to a built-in operation, BinaryOperator will be 2634/// used to express the computation (x and y may still be 2635/// value-dependent). If either x or y is type-dependent, or if the 2636/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 2637/// be used to express the computation. 2638class BinaryOperator : public Expr { 2639public: 2640 typedef BinaryOperatorKind Opcode; 2641 2642private: 2643 unsigned Opc : 6; 2644 SourceLocation OpLoc; 2645 2646 enum { LHS, RHS, END_EXPR }; 2647 Stmt* SubExprs[END_EXPR]; 2648public: 2649 2650 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2651 ExprValueKind VK, ExprObjectKind OK, 2652 SourceLocation opLoc) 2653 : Expr(BinaryOperatorClass, ResTy, VK, OK, 2654 lhs->isTypeDependent() || rhs->isTypeDependent(), 2655 lhs->isValueDependent() || rhs->isValueDependent(), 2656 (lhs->isInstantiationDependent() || 2657 rhs->isInstantiationDependent()), 2658 (lhs->containsUnexpandedParameterPack() || 2659 rhs->containsUnexpandedParameterPack())), 2660 Opc(opc), OpLoc(opLoc) { 2661 SubExprs[LHS] = lhs; 2662 SubExprs[RHS] = rhs; 2663 assert(!isCompoundAssignmentOp() && 2664 "Use ArithAssignBinaryOperator for compound assignments"); 2665 } 2666 2667 /// \brief Construct an empty binary operator. 2668 explicit BinaryOperator(EmptyShell Empty) 2669 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } 2670 2671 SourceLocation getOperatorLoc() const { return OpLoc; } 2672 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2673 2674 Opcode getOpcode() const { return static_cast<Opcode>(Opc); } 2675 void setOpcode(Opcode O) { Opc = O; } 2676 2677 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2678 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2679 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2680 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2681 2682 SourceRange getSourceRange() const { 2683 return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd()); 2684 } 2685 2686 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2687 /// corresponds to, e.g. "<<=". 2688 static const char *getOpcodeStr(Opcode Op); 2689 2690 const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 2691 2692 /// \brief Retrieve the binary opcode that corresponds to the given 2693 /// overloaded operator. 2694 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 2695 2696 /// \brief Retrieve the overloaded operator kind that corresponds to 2697 /// the given binary opcode. 2698 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2699 2700 /// predicates to categorize the respective opcodes. 2701 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } 2702 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } 2703 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 2704 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 2705 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 2706 bool isShiftOp() const { return isShiftOp(getOpcode()); } 2707 2708 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 2709 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 2710 2711 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 2712 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 2713 2714 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 2715 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 2716 2717 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } 2718 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 2719 2720 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 2721 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 2722 2723 static bool isAssignmentOp(Opcode Opc) { 2724 return Opc >= BO_Assign && Opc <= BO_OrAssign; 2725 } 2726 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 2727 2728 static bool isCompoundAssignmentOp(Opcode Opc) { 2729 return Opc > BO_Assign && Opc <= BO_OrAssign; 2730 } 2731 bool isCompoundAssignmentOp() const { 2732 return isCompoundAssignmentOp(getOpcode()); 2733 } 2734 2735 static bool isShiftAssignOp(Opcode Opc) { 2736 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 2737 } 2738 bool isShiftAssignOp() const { 2739 return isShiftAssignOp(getOpcode()); 2740 } 2741 2742 static bool classof(const Stmt *S) { 2743 return S->getStmtClass() >= firstBinaryOperatorConstant && 2744 S->getStmtClass() <= lastBinaryOperatorConstant; 2745 } 2746 static bool classof(const BinaryOperator *) { return true; } 2747 2748 // Iterators 2749 child_range children() { 2750 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2751 } 2752 2753protected: 2754 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 2755 ExprValueKind VK, ExprObjectKind OK, 2756 SourceLocation opLoc, bool dead) 2757 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 2758 lhs->isTypeDependent() || rhs->isTypeDependent(), 2759 lhs->isValueDependent() || rhs->isValueDependent(), 2760 (lhs->isInstantiationDependent() || 2761 rhs->isInstantiationDependent()), 2762 (lhs->containsUnexpandedParameterPack() || 2763 rhs->containsUnexpandedParameterPack())), 2764 Opc(opc), OpLoc(opLoc) { 2765 SubExprs[LHS] = lhs; 2766 SubExprs[RHS] = rhs; 2767 } 2768 2769 BinaryOperator(StmtClass SC, EmptyShell Empty) 2770 : Expr(SC, Empty), Opc(BO_MulAssign) { } 2771}; 2772 2773/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 2774/// track of the type the operation is performed in. Due to the semantics of 2775/// these operators, the operands are promoted, the arithmetic performed, an 2776/// implicit conversion back to the result type done, then the assignment takes 2777/// place. This captures the intermediate type which the computation is done 2778/// in. 2779class CompoundAssignOperator : public BinaryOperator { 2780 QualType ComputationLHSType; 2781 QualType ComputationResultType; 2782public: 2783 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 2784 ExprValueKind VK, ExprObjectKind OK, 2785 QualType CompLHSType, QualType CompResultType, 2786 SourceLocation OpLoc) 2787 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true), 2788 ComputationLHSType(CompLHSType), 2789 ComputationResultType(CompResultType) { 2790 assert(isCompoundAssignmentOp() && 2791 "Only should be used for compound assignments"); 2792 } 2793 2794 /// \brief Build an empty compound assignment operator expression. 2795 explicit CompoundAssignOperator(EmptyShell Empty) 2796 : BinaryOperator(CompoundAssignOperatorClass, Empty) { } 2797 2798 // The two computation types are the type the LHS is converted 2799 // to for the computation and the type of the result; the two are 2800 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 2801 QualType getComputationLHSType() const { return ComputationLHSType; } 2802 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 2803 2804 QualType getComputationResultType() const { return ComputationResultType; } 2805 void setComputationResultType(QualType T) { ComputationResultType = T; } 2806 2807 static bool classof(const CompoundAssignOperator *) { return true; } 2808 static bool classof(const Stmt *S) { 2809 return S->getStmtClass() == CompoundAssignOperatorClass; 2810 } 2811}; 2812 2813/// AbstractConditionalOperator - An abstract base class for 2814/// ConditionalOperator and BinaryConditionalOperator. 2815class AbstractConditionalOperator : public Expr { 2816 SourceLocation QuestionLoc, ColonLoc; 2817 friend class ASTStmtReader; 2818 2819protected: 2820 AbstractConditionalOperator(StmtClass SC, QualType T, 2821 ExprValueKind VK, ExprObjectKind OK, 2822 bool TD, bool VD, bool ID, 2823 bool ContainsUnexpandedParameterPack, 2824 SourceLocation qloc, 2825 SourceLocation cloc) 2826 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), 2827 QuestionLoc(qloc), ColonLoc(cloc) {} 2828 2829 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 2830 : Expr(SC, Empty) { } 2831 2832public: 2833 // getCond - Return the expression representing the condition for 2834 // the ?: operator. 2835 Expr *getCond() const; 2836 2837 // getTrueExpr - Return the subexpression representing the value of 2838 // the expression if the condition evaluates to true. 2839 Expr *getTrueExpr() const; 2840 2841 // getFalseExpr - Return the subexpression representing the value of 2842 // the expression if the condition evaluates to false. This is 2843 // the same as getRHS. 2844 Expr *getFalseExpr() const; 2845 2846 SourceLocation getQuestionLoc() const { return QuestionLoc; } 2847 SourceLocation getColonLoc() const { return ColonLoc; } 2848 2849 static bool classof(const Stmt *T) { 2850 return T->getStmtClass() == ConditionalOperatorClass || 2851 T->getStmtClass() == BinaryConditionalOperatorClass; 2852 } 2853 static bool classof(const AbstractConditionalOperator *) { return true; } 2854}; 2855 2856/// ConditionalOperator - The ?: ternary operator. The GNU "missing 2857/// middle" extension is a BinaryConditionalOperator. 2858class ConditionalOperator : public AbstractConditionalOperator { 2859 enum { COND, LHS, RHS, END_EXPR }; 2860 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 2861 2862 friend class ASTStmtReader; 2863public: 2864 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 2865 SourceLocation CLoc, Expr *rhs, 2866 QualType t, ExprValueKind VK, ExprObjectKind OK) 2867 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, 2868 // FIXME: the type of the conditional operator doesn't 2869 // depend on the type of the conditional, but the standard 2870 // seems to imply that it could. File a bug! 2871 (lhs->isTypeDependent() || rhs->isTypeDependent()), 2872 (cond->isValueDependent() || lhs->isValueDependent() || 2873 rhs->isValueDependent()), 2874 (cond->isInstantiationDependent() || 2875 lhs->isInstantiationDependent() || 2876 rhs->isInstantiationDependent()), 2877 (cond->containsUnexpandedParameterPack() || 2878 lhs->containsUnexpandedParameterPack() || 2879 rhs->containsUnexpandedParameterPack()), 2880 QLoc, CLoc) { 2881 SubExprs[COND] = cond; 2882 SubExprs[LHS] = lhs; 2883 SubExprs[RHS] = rhs; 2884 } 2885 2886 /// \brief Build an empty conditional operator. 2887 explicit ConditionalOperator(EmptyShell Empty) 2888 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 2889 2890 // getCond - Return the expression representing the condition for 2891 // the ?: operator. 2892 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 2893 2894 // getTrueExpr - Return the subexpression representing the value of 2895 // the expression if the condition evaluates to true. 2896 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 2897 2898 // getFalseExpr - Return the subexpression representing the value of 2899 // the expression if the condition evaluates to false. This is 2900 // the same as getRHS. 2901 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 2902 2903 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2904 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2905 2906 SourceRange getSourceRange() const { 2907 return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd()); 2908 } 2909 static bool classof(const Stmt *T) { 2910 return T->getStmtClass() == ConditionalOperatorClass; 2911 } 2912 static bool classof(const ConditionalOperator *) { return true; } 2913 2914 // Iterators 2915 child_range children() { 2916 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2917 } 2918}; 2919 2920/// BinaryConditionalOperator - The GNU extension to the conditional 2921/// operator which allows the middle operand to be omitted. 2922/// 2923/// This is a different expression kind on the assumption that almost 2924/// every client ends up needing to know that these are different. 2925class BinaryConditionalOperator : public AbstractConditionalOperator { 2926 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 2927 2928 /// - the common condition/left-hand-side expression, which will be 2929 /// evaluated as the opaque value 2930 /// - the condition, expressed in terms of the opaque value 2931 /// - the left-hand-side, expressed in terms of the opaque value 2932 /// - the right-hand-side 2933 Stmt *SubExprs[NUM_SUBEXPRS]; 2934 OpaqueValueExpr *OpaqueValue; 2935 2936 friend class ASTStmtReader; 2937public: 2938 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 2939 Expr *cond, Expr *lhs, Expr *rhs, 2940 SourceLocation qloc, SourceLocation cloc, 2941 QualType t, ExprValueKind VK, ExprObjectKind OK) 2942 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 2943 (common->isTypeDependent() || rhs->isTypeDependent()), 2944 (common->isValueDependent() || rhs->isValueDependent()), 2945 (common->isInstantiationDependent() || 2946 rhs->isInstantiationDependent()), 2947 (common->containsUnexpandedParameterPack() || 2948 rhs->containsUnexpandedParameterPack()), 2949 qloc, cloc), 2950 OpaqueValue(opaqueValue) { 2951 SubExprs[COMMON] = common; 2952 SubExprs[COND] = cond; 2953 SubExprs[LHS] = lhs; 2954 SubExprs[RHS] = rhs; 2955 2956 OpaqueValue->setSourceExpr(common); 2957 } 2958 2959 /// \brief Build an empty conditional operator. 2960 explicit BinaryConditionalOperator(EmptyShell Empty) 2961 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 2962 2963 /// \brief getCommon - Return the common expression, written to the 2964 /// left of the condition. The opaque value will be bound to the 2965 /// result of this expression. 2966 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 2967 2968 /// \brief getOpaqueValue - Return the opaque value placeholder. 2969 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 2970 2971 /// \brief getCond - Return the condition expression; this is defined 2972 /// in terms of the opaque value. 2973 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 2974 2975 /// \brief getTrueExpr - Return the subexpression which will be 2976 /// evaluated if the condition evaluates to true; this is defined 2977 /// in terms of the opaque value. 2978 Expr *getTrueExpr() const { 2979 return cast<Expr>(SubExprs[LHS]); 2980 } 2981 2982 /// \brief getFalseExpr - Return the subexpression which will be 2983 /// evaluated if the condnition evaluates to false; this is 2984 /// defined in terms of the opaque value. 2985 Expr *getFalseExpr() const { 2986 return cast<Expr>(SubExprs[RHS]); 2987 } 2988 2989 SourceRange getSourceRange() const { 2990 return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd()); 2991 } 2992 static bool classof(const Stmt *T) { 2993 return T->getStmtClass() == BinaryConditionalOperatorClass; 2994 } 2995 static bool classof(const BinaryConditionalOperator *) { return true; } 2996 2997 // Iterators 2998 child_range children() { 2999 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 3000 } 3001}; 3002 3003inline Expr *AbstractConditionalOperator::getCond() const { 3004 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3005 return co->getCond(); 3006 return cast<BinaryConditionalOperator>(this)->getCond(); 3007} 3008 3009inline Expr *AbstractConditionalOperator::getTrueExpr() const { 3010 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3011 return co->getTrueExpr(); 3012 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 3013} 3014 3015inline Expr *AbstractConditionalOperator::getFalseExpr() const { 3016 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3017 return co->getFalseExpr(); 3018 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 3019} 3020 3021/// AddrLabelExpr - The GNU address of label extension, representing &&label. 3022class AddrLabelExpr : public Expr { 3023 SourceLocation AmpAmpLoc, LabelLoc; 3024 LabelDecl *Label; 3025public: 3026 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 3027 QualType t) 3028 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, 3029 false), 3030 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 3031 3032 /// \brief Build an empty address of a label expression. 3033 explicit AddrLabelExpr(EmptyShell Empty) 3034 : Expr(AddrLabelExprClass, Empty) { } 3035 3036 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 3037 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 3038 SourceLocation getLabelLoc() const { return LabelLoc; } 3039 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 3040 3041 SourceRange getSourceRange() const { 3042 return SourceRange(AmpAmpLoc, LabelLoc); 3043 } 3044 3045 LabelDecl *getLabel() const { return Label; } 3046 void setLabel(LabelDecl *L) { Label = L; } 3047 3048 static bool classof(const Stmt *T) { 3049 return T->getStmtClass() == AddrLabelExprClass; 3050 } 3051 static bool classof(const AddrLabelExpr *) { return true; } 3052 3053 // Iterators 3054 child_range children() { return child_range(); } 3055}; 3056 3057/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 3058/// The StmtExpr contains a single CompoundStmt node, which it evaluates and 3059/// takes the value of the last subexpression. 3060/// 3061/// A StmtExpr is always an r-value; values "returned" out of a 3062/// StmtExpr will be copied. 3063class StmtExpr : public Expr { 3064 Stmt *SubStmt; 3065 SourceLocation LParenLoc, RParenLoc; 3066public: 3067 // FIXME: Does type-dependence need to be computed differently? 3068 // FIXME: Do we need to compute instantiation instantiation-dependence for 3069 // statements? (ugh!) 3070 StmtExpr(CompoundStmt *substmt, QualType T, 3071 SourceLocation lp, SourceLocation rp) : 3072 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, 3073 T->isDependentType(), false, false, false), 3074 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 3075 3076 /// \brief Build an empty statement expression. 3077 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 3078 3079 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 3080 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 3081 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 3082 3083 SourceRange getSourceRange() const { 3084 return SourceRange(LParenLoc, RParenLoc); 3085 } 3086 3087 SourceLocation getLParenLoc() const { return LParenLoc; } 3088 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3089 SourceLocation getRParenLoc() const { return RParenLoc; } 3090 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3091 3092 static bool classof(const Stmt *T) { 3093 return T->getStmtClass() == StmtExprClass; 3094 } 3095 static bool classof(const StmtExpr *) { return true; } 3096 3097 // Iterators 3098 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 3099}; 3100 3101 3102/// ShuffleVectorExpr - clang-specific builtin-in function 3103/// __builtin_shufflevector. 3104/// This AST node represents a operator that does a constant 3105/// shuffle, similar to LLVM's shufflevector instruction. It takes 3106/// two vectors and a variable number of constant indices, 3107/// and returns the appropriately shuffled vector. 3108class ShuffleVectorExpr : public Expr { 3109 SourceLocation BuiltinLoc, RParenLoc; 3110 3111 // SubExprs - the list of values passed to the __builtin_shufflevector 3112 // function. The first two are vectors, and the rest are constant 3113 // indices. The number of values in this list is always 3114 // 2+the number of indices in the vector type. 3115 Stmt **SubExprs; 3116 unsigned NumExprs; 3117 3118public: 3119 ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr, 3120 QualType Type, SourceLocation BLoc, 3121 SourceLocation RP); 3122 3123 /// \brief Build an empty vector-shuffle expression. 3124 explicit ShuffleVectorExpr(EmptyShell Empty) 3125 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { } 3126 3127 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3128 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3129 3130 SourceLocation getRParenLoc() const { return RParenLoc; } 3131 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3132 3133 SourceRange getSourceRange() const { 3134 return SourceRange(BuiltinLoc, RParenLoc); 3135 } 3136 static bool classof(const Stmt *T) { 3137 return T->getStmtClass() == ShuffleVectorExprClass; 3138 } 3139 static bool classof(const ShuffleVectorExpr *) { return true; } 3140 3141 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 3142 /// constant expression, the actual arguments passed in, and the function 3143 /// pointers. 3144 unsigned getNumSubExprs() const { return NumExprs; } 3145 3146 /// \brief Retrieve the array of expressions. 3147 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 3148 3149 /// getExpr - Return the Expr at the specified index. 3150 Expr *getExpr(unsigned Index) { 3151 assert((Index < NumExprs) && "Arg access out of range!"); 3152 return cast<Expr>(SubExprs[Index]); 3153 } 3154 const Expr *getExpr(unsigned Index) const { 3155 assert((Index < NumExprs) && "Arg access out of range!"); 3156 return cast<Expr>(SubExprs[Index]); 3157 } 3158 3159 void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs); 3160 3161 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) { 3162 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 3163 return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue(); 3164 } 3165 3166 // Iterators 3167 child_range children() { 3168 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 3169 } 3170}; 3171 3172/// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 3173/// This AST node is similar to the conditional operator (?:) in C, with 3174/// the following exceptions: 3175/// - the test expression must be a integer constant expression. 3176/// - the expression returned acts like the chosen subexpression in every 3177/// visible way: the type is the same as that of the chosen subexpression, 3178/// and all predicates (whether it's an l-value, whether it's an integer 3179/// constant expression, etc.) return the same result as for the chosen 3180/// sub-expression. 3181class ChooseExpr : public Expr { 3182 enum { COND, LHS, RHS, END_EXPR }; 3183 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3184 SourceLocation BuiltinLoc, RParenLoc; 3185public: 3186 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, 3187 QualType t, ExprValueKind VK, ExprObjectKind OK, 3188 SourceLocation RP, bool TypeDependent, bool ValueDependent) 3189 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, 3190 (cond->isInstantiationDependent() || 3191 lhs->isInstantiationDependent() || 3192 rhs->isInstantiationDependent()), 3193 (cond->containsUnexpandedParameterPack() || 3194 lhs->containsUnexpandedParameterPack() || 3195 rhs->containsUnexpandedParameterPack())), 3196 BuiltinLoc(BLoc), RParenLoc(RP) { 3197 SubExprs[COND] = cond; 3198 SubExprs[LHS] = lhs; 3199 SubExprs[RHS] = rhs; 3200 } 3201 3202 /// \brief Build an empty __builtin_choose_expr. 3203 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 3204 3205 /// isConditionTrue - Return whether the condition is true (i.e. not 3206 /// equal to zero). 3207 bool isConditionTrue(const ASTContext &C) const; 3208 3209 /// getChosenSubExpr - Return the subexpression chosen according to the 3210 /// condition. 3211 Expr *getChosenSubExpr(const ASTContext &C) const { 3212 return isConditionTrue(C) ? getLHS() : getRHS(); 3213 } 3214 3215 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3216 void setCond(Expr *E) { SubExprs[COND] = E; } 3217 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3218 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3219 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3220 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3221 3222 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3223 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3224 3225 SourceLocation getRParenLoc() const { return RParenLoc; } 3226 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3227 3228 SourceRange getSourceRange() const { 3229 return SourceRange(BuiltinLoc, RParenLoc); 3230 } 3231 static bool classof(const Stmt *T) { 3232 return T->getStmtClass() == ChooseExprClass; 3233 } 3234 static bool classof(const ChooseExpr *) { return true; } 3235 3236 // Iterators 3237 child_range children() { 3238 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3239 } 3240}; 3241 3242/// GNUNullExpr - Implements the GNU __null extension, which is a name 3243/// for a null pointer constant that has integral type (e.g., int or 3244/// long) and is the same size and alignment as a pointer. The __null 3245/// extension is typically only used by system headers, which define 3246/// NULL as __null in C++ rather than using 0 (which is an integer 3247/// that may not match the size of a pointer). 3248class GNUNullExpr : public Expr { 3249 /// TokenLoc - The location of the __null keyword. 3250 SourceLocation TokenLoc; 3251 3252public: 3253 GNUNullExpr(QualType Ty, SourceLocation Loc) 3254 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, 3255 false), 3256 TokenLoc(Loc) { } 3257 3258 /// \brief Build an empty GNU __null expression. 3259 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 3260 3261 /// getTokenLocation - The location of the __null token. 3262 SourceLocation getTokenLocation() const { return TokenLoc; } 3263 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 3264 3265 SourceRange getSourceRange() const { 3266 return SourceRange(TokenLoc); 3267 } 3268 static bool classof(const Stmt *T) { 3269 return T->getStmtClass() == GNUNullExprClass; 3270 } 3271 static bool classof(const GNUNullExpr *) { return true; } 3272 3273 // Iterators 3274 child_range children() { return child_range(); } 3275}; 3276 3277/// VAArgExpr, used for the builtin function __builtin_va_arg. 3278class VAArgExpr : public Expr { 3279 Stmt *Val; 3280 TypeSourceInfo *TInfo; 3281 SourceLocation BuiltinLoc, RParenLoc; 3282public: 3283 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo, 3284 SourceLocation RPLoc, QualType t) 3285 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, 3286 t->isDependentType(), false, 3287 (TInfo->getType()->isInstantiationDependentType() || 3288 e->isInstantiationDependent()), 3289 (TInfo->getType()->containsUnexpandedParameterPack() || 3290 e->containsUnexpandedParameterPack())), 3291 Val(e), TInfo(TInfo), 3292 BuiltinLoc(BLoc), 3293 RParenLoc(RPLoc) { } 3294 3295 /// \brief Create an empty __builtin_va_arg expression. 3296 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { } 3297 3298 const Expr *getSubExpr() const { return cast<Expr>(Val); } 3299 Expr *getSubExpr() { return cast<Expr>(Val); } 3300 void setSubExpr(Expr *E) { Val = E; } 3301 3302 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; } 3303 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; } 3304 3305 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3306 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3307 3308 SourceLocation getRParenLoc() const { return RParenLoc; } 3309 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3310 3311 SourceRange getSourceRange() const { 3312 return SourceRange(BuiltinLoc, RParenLoc); 3313 } 3314 static bool classof(const Stmt *T) { 3315 return T->getStmtClass() == VAArgExprClass; 3316 } 3317 static bool classof(const VAArgExpr *) { return true; } 3318 3319 // Iterators 3320 child_range children() { return child_range(&Val, &Val+1); } 3321}; 3322 3323/// @brief Describes an C or C++ initializer list. 3324/// 3325/// InitListExpr describes an initializer list, which can be used to 3326/// initialize objects of different types, including 3327/// struct/class/union types, arrays, and vectors. For example: 3328/// 3329/// @code 3330/// struct foo x = { 1, { 2, 3 } }; 3331/// @endcode 3332/// 3333/// Prior to semantic analysis, an initializer list will represent the 3334/// initializer list as written by the user, but will have the 3335/// placeholder type "void". This initializer list is called the 3336/// syntactic form of the initializer, and may contain C99 designated 3337/// initializers (represented as DesignatedInitExprs), initializations 3338/// of subobject members without explicit braces, and so on. Clients 3339/// interested in the original syntax of the initializer list should 3340/// use the syntactic form of the initializer list. 3341/// 3342/// After semantic analysis, the initializer list will represent the 3343/// semantic form of the initializer, where the initializations of all 3344/// subobjects are made explicit with nested InitListExpr nodes and 3345/// C99 designators have been eliminated by placing the designated 3346/// initializations into the subobject they initialize. Additionally, 3347/// any "holes" in the initialization, where no initializer has been 3348/// specified for a particular subobject, will be replaced with 3349/// implicitly-generated ImplicitValueInitExpr expressions that 3350/// value-initialize the subobjects. Note, however, that the 3351/// initializer lists may still have fewer initializers than there are 3352/// elements to initialize within the object. 3353/// 3354/// Given the semantic form of the initializer list, one can retrieve 3355/// the original syntactic form of that initializer list (if it 3356/// exists) using getSyntacticForm(). Since many initializer lists 3357/// have the same syntactic and semantic forms, getSyntacticForm() may 3358/// return NULL, indicating that the current initializer list also 3359/// serves as its syntactic form. 3360class InitListExpr : public Expr { 3361 // FIXME: Eliminate this vector in favor of ASTContext allocation 3362 typedef ASTVector<Stmt *> InitExprsTy; 3363 InitExprsTy InitExprs; 3364 SourceLocation LBraceLoc, RBraceLoc; 3365 3366 /// Contains the initializer list that describes the syntactic form 3367 /// written in the source code. 3368 InitListExpr *SyntacticForm; 3369 3370 /// \brief Either: 3371 /// If this initializer list initializes an array with more elements than 3372 /// there are initializers in the list, specifies an expression to be used 3373 /// for value initialization of the rest of the elements. 3374 /// Or 3375 /// If this initializer list initializes a union, specifies which 3376 /// field within the union will be initialized. 3377 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 3378 3379 /// Whether this initializer list originally had a GNU array-range 3380 /// designator in it. This is a temporary marker used by CodeGen. 3381 bool HadArrayRangeDesignator; 3382 3383public: 3384 InitListExpr(ASTContext &C, SourceLocation lbraceloc, 3385 Expr **initexprs, unsigned numinits, 3386 SourceLocation rbraceloc); 3387 3388 /// \brief Build an empty initializer list. 3389 explicit InitListExpr(ASTContext &C, EmptyShell Empty) 3390 : Expr(InitListExprClass, Empty), InitExprs(C) { } 3391 3392 unsigned getNumInits() const { return InitExprs.size(); } 3393 3394 /// \brief Retrieve the set of initializers. 3395 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 3396 3397 const Expr *getInit(unsigned Init) const { 3398 assert(Init < getNumInits() && "Initializer access out of range!"); 3399 return cast_or_null<Expr>(InitExprs[Init]); 3400 } 3401 3402 Expr *getInit(unsigned Init) { 3403 assert(Init < getNumInits() && "Initializer access out of range!"); 3404 return cast_or_null<Expr>(InitExprs[Init]); 3405 } 3406 3407 void setInit(unsigned Init, Expr *expr) { 3408 assert(Init < getNumInits() && "Initializer access out of range!"); 3409 InitExprs[Init] = expr; 3410 } 3411 3412 /// \brief Reserve space for some number of initializers. 3413 void reserveInits(ASTContext &C, unsigned NumInits); 3414 3415 /// @brief Specify the number of initializers 3416 /// 3417 /// If there are more than @p NumInits initializers, the remaining 3418 /// initializers will be destroyed. If there are fewer than @p 3419 /// NumInits initializers, NULL expressions will be added for the 3420 /// unknown initializers. 3421 void resizeInits(ASTContext &Context, unsigned NumInits); 3422 3423 /// @brief Updates the initializer at index @p Init with the new 3424 /// expression @p expr, and returns the old expression at that 3425 /// location. 3426 /// 3427 /// When @p Init is out of range for this initializer list, the 3428 /// initializer list will be extended with NULL expressions to 3429 /// accommodate the new entry. 3430 Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr); 3431 3432 /// \brief If this initializer list initializes an array with more elements 3433 /// than there are initializers in the list, specifies an expression to be 3434 /// used for value initialization of the rest of the elements. 3435 Expr *getArrayFiller() { 3436 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 3437 } 3438 const Expr *getArrayFiller() const { 3439 return const_cast<InitListExpr *>(this)->getArrayFiller(); 3440 } 3441 void setArrayFiller(Expr *filler); 3442 3443 /// \brief If this initializes a union, specifies which field in the 3444 /// union to initialize. 3445 /// 3446 /// Typically, this field is the first named field within the 3447 /// union. However, a designated initializer can specify the 3448 /// initialization of a different field within the union. 3449 FieldDecl *getInitializedFieldInUnion() { 3450 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 3451 } 3452 const FieldDecl *getInitializedFieldInUnion() const { 3453 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 3454 } 3455 void setInitializedFieldInUnion(FieldDecl *FD) { 3456 ArrayFillerOrUnionFieldInit = FD; 3457 } 3458 3459 // Explicit InitListExpr's originate from source code (and have valid source 3460 // locations). Implicit InitListExpr's are created by the semantic analyzer. 3461 bool isExplicit() { 3462 return LBraceLoc.isValid() && RBraceLoc.isValid(); 3463 } 3464 3465 SourceLocation getLBraceLoc() const { return LBraceLoc; } 3466 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 3467 SourceLocation getRBraceLoc() const { return RBraceLoc; } 3468 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 3469 3470 /// @brief Retrieve the initializer list that describes the 3471 /// syntactic form of the initializer. 3472 /// 3473 /// 3474 InitListExpr *getSyntacticForm() const { return SyntacticForm; } 3475 void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; } 3476 3477 bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; } 3478 void sawArrayRangeDesignator(bool ARD = true) { 3479 HadArrayRangeDesignator = ARD; 3480 } 3481 3482 SourceRange getSourceRange() const; 3483 3484 static bool classof(const Stmt *T) { 3485 return T->getStmtClass() == InitListExprClass; 3486 } 3487 static bool classof(const InitListExpr *) { return true; } 3488 3489 // Iterators 3490 child_range children() { 3491 if (InitExprs.empty()) return child_range(); 3492 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 3493 } 3494 3495 typedef InitExprsTy::iterator iterator; 3496 typedef InitExprsTy::const_iterator const_iterator; 3497 typedef InitExprsTy::reverse_iterator reverse_iterator; 3498 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 3499 3500 iterator begin() { return InitExprs.begin(); } 3501 const_iterator begin() const { return InitExprs.begin(); } 3502 iterator end() { return InitExprs.end(); } 3503 const_iterator end() const { return InitExprs.end(); } 3504 reverse_iterator rbegin() { return InitExprs.rbegin(); } 3505 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 3506 reverse_iterator rend() { return InitExprs.rend(); } 3507 const_reverse_iterator rend() const { return InitExprs.rend(); } 3508 3509 friend class ASTStmtReader; 3510 friend class ASTStmtWriter; 3511}; 3512 3513/// @brief Represents a C99 designated initializer expression. 3514/// 3515/// A designated initializer expression (C99 6.7.8) contains one or 3516/// more designators (which can be field designators, array 3517/// designators, or GNU array-range designators) followed by an 3518/// expression that initializes the field or element(s) that the 3519/// designators refer to. For example, given: 3520/// 3521/// @code 3522/// struct point { 3523/// double x; 3524/// double y; 3525/// }; 3526/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 3527/// @endcode 3528/// 3529/// The InitListExpr contains three DesignatedInitExprs, the first of 3530/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 3531/// designators, one array designator for @c [2] followed by one field 3532/// designator for @c .y. The initalization expression will be 1.0. 3533class DesignatedInitExpr : public Expr { 3534public: 3535 /// \brief Forward declaration of the Designator class. 3536 class Designator; 3537 3538private: 3539 /// The location of the '=' or ':' prior to the actual initializer 3540 /// expression. 3541 SourceLocation EqualOrColonLoc; 3542 3543 /// Whether this designated initializer used the GNU deprecated 3544 /// syntax rather than the C99 '=' syntax. 3545 bool GNUSyntax : 1; 3546 3547 /// The number of designators in this initializer expression. 3548 unsigned NumDesignators : 15; 3549 3550 /// \brief The designators in this designated initialization 3551 /// expression. 3552 Designator *Designators; 3553 3554 /// The number of subexpressions of this initializer expression, 3555 /// which contains both the initializer and any additional 3556 /// expressions used by array and array-range designators. 3557 unsigned NumSubExprs : 16; 3558 3559 3560 DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators, 3561 const Designator *Designators, 3562 SourceLocation EqualOrColonLoc, bool GNUSyntax, 3563 Expr **IndexExprs, unsigned NumIndexExprs, 3564 Expr *Init); 3565 3566 explicit DesignatedInitExpr(unsigned NumSubExprs) 3567 : Expr(DesignatedInitExprClass, EmptyShell()), 3568 NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { } 3569 3570public: 3571 /// A field designator, e.g., ".x". 3572 struct FieldDesignator { 3573 /// Refers to the field that is being initialized. The low bit 3574 /// of this field determines whether this is actually a pointer 3575 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 3576 /// initially constructed, a field designator will store an 3577 /// IdentifierInfo*. After semantic analysis has resolved that 3578 /// name, the field designator will instead store a FieldDecl*. 3579 uintptr_t NameOrField; 3580 3581 /// The location of the '.' in the designated initializer. 3582 unsigned DotLoc; 3583 3584 /// The location of the field name in the designated initializer. 3585 unsigned FieldLoc; 3586 }; 3587 3588 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3589 struct ArrayOrRangeDesignator { 3590 /// Location of the first index expression within the designated 3591 /// initializer expression's list of subexpressions. 3592 unsigned Index; 3593 /// The location of the '[' starting the array range designator. 3594 unsigned LBracketLoc; 3595 /// The location of the ellipsis separating the start and end 3596 /// indices. Only valid for GNU array-range designators. 3597 unsigned EllipsisLoc; 3598 /// The location of the ']' terminating the array range designator. 3599 unsigned RBracketLoc; 3600 }; 3601 3602 /// @brief Represents a single C99 designator. 3603 /// 3604 /// @todo This class is infuriatingly similar to clang::Designator, 3605 /// but minor differences (storing indices vs. storing pointers) 3606 /// keep us from reusing it. Try harder, later, to rectify these 3607 /// differences. 3608 class Designator { 3609 /// @brief The kind of designator this describes. 3610 enum { 3611 FieldDesignator, 3612 ArrayDesignator, 3613 ArrayRangeDesignator 3614 } Kind; 3615 3616 union { 3617 /// A field designator, e.g., ".x". 3618 struct FieldDesignator Field; 3619 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 3620 struct ArrayOrRangeDesignator ArrayOrRange; 3621 }; 3622 friend class DesignatedInitExpr; 3623 3624 public: 3625 Designator() {} 3626 3627 /// @brief Initializes a field designator. 3628 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 3629 SourceLocation FieldLoc) 3630 : Kind(FieldDesignator) { 3631 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 3632 Field.DotLoc = DotLoc.getRawEncoding(); 3633 Field.FieldLoc = FieldLoc.getRawEncoding(); 3634 } 3635 3636 /// @brief Initializes an array designator. 3637 Designator(unsigned Index, SourceLocation LBracketLoc, 3638 SourceLocation RBracketLoc) 3639 : Kind(ArrayDesignator) { 3640 ArrayOrRange.Index = Index; 3641 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3642 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 3643 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3644 } 3645 3646 /// @brief Initializes a GNU array-range designator. 3647 Designator(unsigned Index, SourceLocation LBracketLoc, 3648 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 3649 : Kind(ArrayRangeDesignator) { 3650 ArrayOrRange.Index = Index; 3651 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 3652 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 3653 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 3654 } 3655 3656 bool isFieldDesignator() const { return Kind == FieldDesignator; } 3657 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 3658 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 3659 3660 IdentifierInfo *getFieldName() const; 3661 3662 FieldDecl *getField() const { 3663 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3664 if (Field.NameOrField & 0x01) 3665 return 0; 3666 else 3667 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 3668 } 3669 3670 void setField(FieldDecl *FD) { 3671 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3672 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 3673 } 3674 3675 SourceLocation getDotLoc() const { 3676 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3677 return SourceLocation::getFromRawEncoding(Field.DotLoc); 3678 } 3679 3680 SourceLocation getFieldLoc() const { 3681 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3682 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 3683 } 3684 3685 SourceLocation getLBracketLoc() const { 3686 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3687 "Only valid on an array or array-range designator"); 3688 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 3689 } 3690 3691 SourceLocation getRBracketLoc() const { 3692 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3693 "Only valid on an array or array-range designator"); 3694 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 3695 } 3696 3697 SourceLocation getEllipsisLoc() const { 3698 assert(Kind == ArrayRangeDesignator && 3699 "Only valid on an array-range designator"); 3700 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 3701 } 3702 3703 unsigned getFirstExprIndex() const { 3704 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 3705 "Only valid on an array or array-range designator"); 3706 return ArrayOrRange.Index; 3707 } 3708 3709 SourceLocation getStartLocation() const { 3710 if (Kind == FieldDesignator) 3711 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 3712 else 3713 return getLBracketLoc(); 3714 } 3715 SourceLocation getEndLocation() const { 3716 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 3717 } 3718 SourceRange getSourceRange() const { 3719 return SourceRange(getStartLocation(), getEndLocation()); 3720 } 3721 }; 3722 3723 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators, 3724 unsigned NumDesignators, 3725 Expr **IndexExprs, unsigned NumIndexExprs, 3726 SourceLocation EqualOrColonLoc, 3727 bool GNUSyntax, Expr *Init); 3728 3729 static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs); 3730 3731 /// @brief Returns the number of designators in this initializer. 3732 unsigned size() const { return NumDesignators; } 3733 3734 // Iterator access to the designators. 3735 typedef Designator *designators_iterator; 3736 designators_iterator designators_begin() { return Designators; } 3737 designators_iterator designators_end() { 3738 return Designators + NumDesignators; 3739 } 3740 3741 typedef const Designator *const_designators_iterator; 3742 const_designators_iterator designators_begin() const { return Designators; } 3743 const_designators_iterator designators_end() const { 3744 return Designators + NumDesignators; 3745 } 3746 3747 typedef std::reverse_iterator<designators_iterator> 3748 reverse_designators_iterator; 3749 reverse_designators_iterator designators_rbegin() { 3750 return reverse_designators_iterator(designators_end()); 3751 } 3752 reverse_designators_iterator designators_rend() { 3753 return reverse_designators_iterator(designators_begin()); 3754 } 3755 3756 typedef std::reverse_iterator<const_designators_iterator> 3757 const_reverse_designators_iterator; 3758 const_reverse_designators_iterator designators_rbegin() const { 3759 return const_reverse_designators_iterator(designators_end()); 3760 } 3761 const_reverse_designators_iterator designators_rend() const { 3762 return const_reverse_designators_iterator(designators_begin()); 3763 } 3764 3765 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; } 3766 3767 void setDesignators(ASTContext &C, const Designator *Desigs, 3768 unsigned NumDesigs); 3769 3770 Expr *getArrayIndex(const Designator& D); 3771 Expr *getArrayRangeStart(const Designator& D); 3772 Expr *getArrayRangeEnd(const Designator& D); 3773 3774 /// @brief Retrieve the location of the '=' that precedes the 3775 /// initializer value itself, if present. 3776 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 3777 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 3778 3779 /// @brief Determines whether this designated initializer used the 3780 /// deprecated GNU syntax for designated initializers. 3781 bool usesGNUSyntax() const { return GNUSyntax; } 3782 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 3783 3784 /// @brief Retrieve the initializer value. 3785 Expr *getInit() const { 3786 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 3787 } 3788 3789 void setInit(Expr *init) { 3790 *child_begin() = init; 3791 } 3792 3793 /// \brief Retrieve the total number of subexpressions in this 3794 /// designated initializer expression, including the actual 3795 /// initialized value and any expressions that occur within array 3796 /// and array-range designators. 3797 unsigned getNumSubExprs() const { return NumSubExprs; } 3798 3799 Expr *getSubExpr(unsigned Idx) { 3800 assert(Idx < NumSubExprs && "Subscript out of range"); 3801 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3802 Ptr += sizeof(DesignatedInitExpr); 3803 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx]; 3804 } 3805 3806 void setSubExpr(unsigned Idx, Expr *E) { 3807 assert(Idx < NumSubExprs && "Subscript out of range"); 3808 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3809 Ptr += sizeof(DesignatedInitExpr); 3810 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E; 3811 } 3812 3813 /// \brief Replaces the designator at index @p Idx with the series 3814 /// of designators in [First, Last). 3815 void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First, 3816 const Designator *Last); 3817 3818 SourceRange getDesignatorsSourceRange() const; 3819 3820 SourceRange getSourceRange() const; 3821 3822 static bool classof(const Stmt *T) { 3823 return T->getStmtClass() == DesignatedInitExprClass; 3824 } 3825 static bool classof(const DesignatedInitExpr *) { return true; } 3826 3827 // Iterators 3828 child_range children() { 3829 Stmt **begin = reinterpret_cast<Stmt**>(this + 1); 3830 return child_range(begin, begin + NumSubExprs); 3831 } 3832}; 3833 3834/// \brief Represents an implicitly-generated value initialization of 3835/// an object of a given type. 3836/// 3837/// Implicit value initializations occur within semantic initializer 3838/// list expressions (InitListExpr) as placeholders for subobject 3839/// initializations not explicitly specified by the user. 3840/// 3841/// \see InitListExpr 3842class ImplicitValueInitExpr : public Expr { 3843public: 3844 explicit ImplicitValueInitExpr(QualType ty) 3845 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, 3846 false, false, ty->isInstantiationDependentType(), false) { } 3847 3848 /// \brief Construct an empty implicit value initialization. 3849 explicit ImplicitValueInitExpr(EmptyShell Empty) 3850 : Expr(ImplicitValueInitExprClass, Empty) { } 3851 3852 static bool classof(const Stmt *T) { 3853 return T->getStmtClass() == ImplicitValueInitExprClass; 3854 } 3855 static bool classof(const ImplicitValueInitExpr *) { return true; } 3856 3857 SourceRange getSourceRange() const { 3858 return SourceRange(); 3859 } 3860 3861 // Iterators 3862 child_range children() { return child_range(); } 3863}; 3864 3865 3866class ParenListExpr : public Expr { 3867 Stmt **Exprs; 3868 unsigned NumExprs; 3869 SourceLocation LParenLoc, RParenLoc; 3870 3871public: 3872 ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, 3873 unsigned numexprs, SourceLocation rparenloc, QualType T); 3874 3875 /// \brief Build an empty paren list. 3876 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } 3877 3878 unsigned getNumExprs() const { return NumExprs; } 3879 3880 const Expr* getExpr(unsigned Init) const { 3881 assert(Init < getNumExprs() && "Initializer access out of range!"); 3882 return cast_or_null<Expr>(Exprs[Init]); 3883 } 3884 3885 Expr* getExpr(unsigned Init) { 3886 assert(Init < getNumExprs() && "Initializer access out of range!"); 3887 return cast_or_null<Expr>(Exprs[Init]); 3888 } 3889 3890 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); } 3891 3892 SourceLocation getLParenLoc() const { return LParenLoc; } 3893 SourceLocation getRParenLoc() const { return RParenLoc; } 3894 3895 SourceRange getSourceRange() const { 3896 return SourceRange(LParenLoc, RParenLoc); 3897 } 3898 static bool classof(const Stmt *T) { 3899 return T->getStmtClass() == ParenListExprClass; 3900 } 3901 static bool classof(const ParenListExpr *) { return true; } 3902 3903 // Iterators 3904 child_range children() { 3905 return child_range(&Exprs[0], &Exprs[0]+NumExprs); 3906 } 3907 3908 friend class ASTStmtReader; 3909 friend class ASTStmtWriter; 3910}; 3911 3912 3913/// \brief Represents a C1X generic selection. 3914/// 3915/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling 3916/// expression, followed by one or more generic associations. Each generic 3917/// association specifies a type name and an expression, or "default" and an 3918/// expression (in which case it is known as a default generic association). 3919/// The type and value of the generic selection are identical to those of its 3920/// result expression, which is defined as the expression in the generic 3921/// association with a type name that is compatible with the type of the 3922/// controlling expression, or the expression in the default generic association 3923/// if no types are compatible. For example: 3924/// 3925/// @code 3926/// _Generic(X, double: 1, float: 2, default: 3) 3927/// @endcode 3928/// 3929/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 3930/// or 3 if "hello". 3931/// 3932/// As an extension, generic selections are allowed in C++, where the following 3933/// additional semantics apply: 3934/// 3935/// Any generic selection whose controlling expression is type-dependent or 3936/// which names a dependent type in its association list is result-dependent, 3937/// which means that the choice of result expression is dependent. 3938/// Result-dependent generic associations are both type- and value-dependent. 3939class GenericSelectionExpr : public Expr { 3940 enum { CONTROLLING, END_EXPR }; 3941 TypeSourceInfo **AssocTypes; 3942 Stmt **SubExprs; 3943 unsigned NumAssocs, ResultIndex; 3944 SourceLocation GenericLoc, DefaultLoc, RParenLoc; 3945 3946public: 3947 GenericSelectionExpr(ASTContext &Context, 3948 SourceLocation GenericLoc, Expr *ControllingExpr, 3949 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3950 unsigned NumAssocs, SourceLocation DefaultLoc, 3951 SourceLocation RParenLoc, 3952 bool ContainsUnexpandedParameterPack, 3953 unsigned ResultIndex); 3954 3955 /// This constructor is used in the result-dependent case. 3956 GenericSelectionExpr(ASTContext &Context, 3957 SourceLocation GenericLoc, Expr *ControllingExpr, 3958 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3959 unsigned NumAssocs, SourceLocation DefaultLoc, 3960 SourceLocation RParenLoc, 3961 bool ContainsUnexpandedParameterPack); 3962 3963 explicit GenericSelectionExpr(EmptyShell Empty) 3964 : Expr(GenericSelectionExprClass, Empty) { } 3965 3966 unsigned getNumAssocs() const { return NumAssocs; } 3967 3968 SourceLocation getGenericLoc() const { return GenericLoc; } 3969 SourceLocation getDefaultLoc() const { return DefaultLoc; } 3970 SourceLocation getRParenLoc() const { return RParenLoc; } 3971 3972 const Expr *getAssocExpr(unsigned i) const { 3973 return cast<Expr>(SubExprs[END_EXPR+i]); 3974 } 3975 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); } 3976 3977 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const { 3978 return AssocTypes[i]; 3979 } 3980 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; } 3981 3982 QualType getAssocType(unsigned i) const { 3983 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i)) 3984 return TS->getType(); 3985 else 3986 return QualType(); 3987 } 3988 3989 const Expr *getControllingExpr() const { 3990 return cast<Expr>(SubExprs[CONTROLLING]); 3991 } 3992 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); } 3993 3994 /// Whether this generic selection is result-dependent. 3995 bool isResultDependent() const { return ResultIndex == -1U; } 3996 3997 /// The zero-based index of the result expression's generic association in 3998 /// the generic selection's association list. Defined only if the 3999 /// generic selection is not result-dependent. 4000 unsigned getResultIndex() const { 4001 assert(!isResultDependent() && "Generic selection is result-dependent"); 4002 return ResultIndex; 4003 } 4004 4005 /// The generic selection's result expression. Defined only if the 4006 /// generic selection is not result-dependent. 4007 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); } 4008 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); } 4009 4010 SourceRange getSourceRange() const { 4011 return SourceRange(GenericLoc, RParenLoc); 4012 } 4013 static bool classof(const Stmt *T) { 4014 return T->getStmtClass() == GenericSelectionExprClass; 4015 } 4016 static bool classof(const GenericSelectionExpr *) { return true; } 4017 4018 child_range children() { 4019 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs); 4020 } 4021 4022 friend class ASTStmtReader; 4023}; 4024 4025//===----------------------------------------------------------------------===// 4026// Clang Extensions 4027//===----------------------------------------------------------------------===// 4028 4029 4030/// ExtVectorElementExpr - This represents access to specific elements of a 4031/// vector, and may occur on the left hand side or right hand side. For example 4032/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 4033/// 4034/// Note that the base may have either vector or pointer to vector type, just 4035/// like a struct field reference. 4036/// 4037class ExtVectorElementExpr : public Expr { 4038 Stmt *Base; 4039 IdentifierInfo *Accessor; 4040 SourceLocation AccessorLoc; 4041public: 4042 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 4043 IdentifierInfo &accessor, SourceLocation loc) 4044 : Expr(ExtVectorElementExprClass, ty, VK, 4045 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), 4046 base->isTypeDependent(), base->isValueDependent(), 4047 base->isInstantiationDependent(), 4048 base->containsUnexpandedParameterPack()), 4049 Base(base), Accessor(&accessor), AccessorLoc(loc) {} 4050 4051 /// \brief Build an empty vector element expression. 4052 explicit ExtVectorElementExpr(EmptyShell Empty) 4053 : Expr(ExtVectorElementExprClass, Empty) { } 4054 4055 const Expr *getBase() const { return cast<Expr>(Base); } 4056 Expr *getBase() { return cast<Expr>(Base); } 4057 void setBase(Expr *E) { Base = E; } 4058 4059 IdentifierInfo &getAccessor() const { return *Accessor; } 4060 void setAccessor(IdentifierInfo *II) { Accessor = II; } 4061 4062 SourceLocation getAccessorLoc() const { return AccessorLoc; } 4063 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 4064 4065 /// getNumElements - Get the number of components being selected. 4066 unsigned getNumElements() const; 4067 4068 /// containsDuplicateElements - Return true if any element access is 4069 /// repeated. 4070 bool containsDuplicateElements() const; 4071 4072 /// getEncodedElementAccess - Encode the elements accessed into an llvm 4073 /// aggregate Constant of ConstantInt(s). 4074 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const; 4075 4076 SourceRange getSourceRange() const { 4077 return SourceRange(getBase()->getLocStart(), AccessorLoc); 4078 } 4079 4080 /// isArrow - Return true if the base expression is a pointer to vector, 4081 /// return false if the base expression is a vector. 4082 bool isArrow() const; 4083 4084 static bool classof(const Stmt *T) { 4085 return T->getStmtClass() == ExtVectorElementExprClass; 4086 } 4087 static bool classof(const ExtVectorElementExpr *) { return true; } 4088 4089 // Iterators 4090 child_range children() { return child_range(&Base, &Base+1); } 4091}; 4092 4093 4094/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 4095/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 4096class BlockExpr : public Expr { 4097protected: 4098 BlockDecl *TheBlock; 4099public: 4100 BlockExpr(BlockDecl *BD, QualType ty) 4101 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, 4102 ty->isDependentType(), false, 4103 // FIXME: Check for instantiate-dependence in the statement? 4104 ty->isInstantiationDependentType(), 4105 false), 4106 TheBlock(BD) {} 4107 4108 /// \brief Build an empty block expression. 4109 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 4110 4111 const BlockDecl *getBlockDecl() const { return TheBlock; } 4112 BlockDecl *getBlockDecl() { return TheBlock; } 4113 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 4114 4115 // Convenience functions for probing the underlying BlockDecl. 4116 SourceLocation getCaretLocation() const; 4117 const Stmt *getBody() const; 4118 Stmt *getBody(); 4119 4120 SourceRange getSourceRange() const { 4121 return SourceRange(getCaretLocation(), getBody()->getLocEnd()); 4122 } 4123 4124 /// getFunctionType - Return the underlying function type for this block. 4125 const FunctionType *getFunctionType() const; 4126 4127 static bool classof(const Stmt *T) { 4128 return T->getStmtClass() == BlockExprClass; 4129 } 4130 static bool classof(const BlockExpr *) { return true; } 4131 4132 // Iterators 4133 child_range children() { return child_range(); } 4134}; 4135 4136/// BlockDeclRefExpr - A reference to a local variable declared in an 4137/// enclosing scope. 4138class BlockDeclRefExpr : public Expr { 4139 VarDecl *D; 4140 SourceLocation Loc; 4141 bool IsByRef : 1; 4142 bool ConstQualAdded : 1; 4143public: 4144 BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK, 4145 SourceLocation l, bool ByRef, bool constAdded = false); 4146 4147 // \brief Build an empty reference to a declared variable in a 4148 // block. 4149 explicit BlockDeclRefExpr(EmptyShell Empty) 4150 : Expr(BlockDeclRefExprClass, Empty) { } 4151 4152 VarDecl *getDecl() { return D; } 4153 const VarDecl *getDecl() const { return D; } 4154 void setDecl(VarDecl *VD) { D = VD; } 4155 4156 SourceLocation getLocation() const { return Loc; } 4157 void setLocation(SourceLocation L) { Loc = L; } 4158 4159 SourceRange getSourceRange() const { return SourceRange(Loc); } 4160 4161 bool isByRef() const { return IsByRef; } 4162 void setByRef(bool BR) { IsByRef = BR; } 4163 4164 bool isConstQualAdded() const { return ConstQualAdded; } 4165 void setConstQualAdded(bool C) { ConstQualAdded = C; } 4166 4167 static bool classof(const Stmt *T) { 4168 return T->getStmtClass() == BlockDeclRefExprClass; 4169 } 4170 static bool classof(const BlockDeclRefExpr *) { return true; } 4171 4172 // Iterators 4173 child_range children() { return child_range(); } 4174}; 4175 4176/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 4177/// This AST node provides support for reinterpreting a type to another 4178/// type of the same size. 4179class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr? 4180private: 4181 Stmt *SrcExpr; 4182 SourceLocation BuiltinLoc, RParenLoc; 4183 4184 friend class ASTReader; 4185 friend class ASTStmtReader; 4186 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 4187 4188public: 4189 AsTypeExpr(Expr* SrcExpr, QualType DstType, 4190 ExprValueKind VK, ExprObjectKind OK, 4191 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4192 : Expr(AsTypeExprClass, DstType, VK, OK, 4193 DstType->isDependentType(), 4194 DstType->isDependentType() || SrcExpr->isValueDependent(), 4195 (DstType->isInstantiationDependentType() || 4196 SrcExpr->isInstantiationDependent()), 4197 (DstType->containsUnexpandedParameterPack() || 4198 SrcExpr->containsUnexpandedParameterPack())), 4199 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 4200 4201 /// getSrcExpr - Return the Expr to be converted. 4202 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4203 4204 /// getBuiltinLoc - Return the location of the __builtin_astype token. 4205 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4206 4207 /// getRParenLoc - Return the location of final right parenthesis. 4208 SourceLocation getRParenLoc() const { return RParenLoc; } 4209 4210 SourceRange getSourceRange() const { 4211 return SourceRange(BuiltinLoc, RParenLoc); 4212 } 4213 4214 static bool classof(const Stmt *T) { 4215 return T->getStmtClass() == AsTypeExprClass; 4216 } 4217 static bool classof(const AsTypeExpr *) { return true; } 4218 4219 // Iterators 4220 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4221}; 4222} // end namespace clang 4223 4224#endif 4225