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