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