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