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