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