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