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