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