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