1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the Expr interface and subclasses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_AST_EXPR_H 14 #define LLVM_CLANG_AST_EXPR_H 15 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTVector.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclAccessPair.h" 20 #include "clang/AST/OperationKinds.h" 21 #include "clang/AST/Stmt.h" 22 #include "clang/AST/TemplateBase.h" 23 #include "clang/AST/Type.h" 24 #include "clang/Basic/CharInfo.h" 25 #include "clang/Basic/FixedPoint.h" 26 #include "clang/Basic/LangOptions.h" 27 #include "clang/Basic/SyncScope.h" 28 #include "clang/Basic/TypeTraits.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APSInt.h" 31 #include "llvm/ADT/iterator.h" 32 #include "llvm/ADT/iterator_range.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/Support/AtomicOrdering.h" 36 #include "llvm/Support/Compiler.h" 37 #include "llvm/Support/TrailingObjects.h" 38 39 namespace clang { 40 class APValue; 41 class ASTContext; 42 class BlockDecl; 43 class CXXBaseSpecifier; 44 class CXXMemberCallExpr; 45 class CXXOperatorCallExpr; 46 class CastExpr; 47 class Decl; 48 class IdentifierInfo; 49 class MaterializeTemporaryExpr; 50 class NamedDecl; 51 class ObjCPropertyRefExpr; 52 class OpaqueValueExpr; 53 class ParmVarDecl; 54 class StringLiteral; 55 class TargetInfo; 56 class ValueDecl; 57 58 /// A simple array of base specifiers. 59 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 60 61 /// An adjustment to be made to the temporary created when emitting a 62 /// reference binding, which accesses a particular subobject of that temporary. 63 struct SubobjectAdjustment { 64 enum { 65 DerivedToBaseAdjustment, 66 FieldAdjustment, 67 MemberPointerAdjustment 68 } Kind; 69 70 struct DTB { 71 const CastExpr *BasePath; 72 const CXXRecordDecl *DerivedClass; 73 }; 74 75 struct P { 76 const MemberPointerType *MPT; 77 Expr *RHS; 78 }; 79 80 union { 81 struct DTB DerivedToBase; 82 FieldDecl *Field; 83 struct P Ptr; 84 }; 85 86 SubobjectAdjustment(const CastExpr *BasePath, 87 const CXXRecordDecl *DerivedClass) 88 : Kind(DerivedToBaseAdjustment) { 89 DerivedToBase.BasePath = BasePath; 90 DerivedToBase.DerivedClass = DerivedClass; 91 } 92 93 SubobjectAdjustment(FieldDecl *Field) 94 : Kind(FieldAdjustment) { 95 this->Field = Field; 96 } 97 98 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) 99 : Kind(MemberPointerAdjustment) { 100 this->Ptr.MPT = MPT; 101 this->Ptr.RHS = RHS; 102 } 103 }; 104 105 /// This represents one expression. Note that Expr's are subclasses of Stmt. 106 /// This allows an expression to be transparently used any place a Stmt is 107 /// required. 108 class Expr : public ValueStmt { 109 QualType TR; 110 111 public: 112 Expr() = delete; 113 Expr(const Expr&) = delete; 114 Expr(Expr &&) = delete; 115 Expr &operator=(const Expr&) = delete; 116 Expr &operator=(Expr&&) = delete; 117 118 protected: 119 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, 120 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) 121 : ValueStmt(SC) 122 { 123 ExprBits.TypeDependent = TD; 124 ExprBits.ValueDependent = VD; 125 ExprBits.InstantiationDependent = ID; 126 ExprBits.ValueKind = VK; 127 ExprBits.ObjectKind = OK; 128 assert(ExprBits.ObjectKind == OK && "truncated kind"); 129 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 130 setType(T); 131 } 132 133 /// Construct an empty expression. 134 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { } 135 136 public: 137 QualType getType() const { return TR; } 138 void setType(QualType t) { 139 // In C++, the type of an expression is always adjusted so that it 140 // will not have reference type (C++ [expr]p6). Use 141 // QualType::getNonReferenceType() to retrieve the non-reference 142 // type. Additionally, inspect Expr::isLvalue to determine whether 143 // an expression that is adjusted in this manner should be 144 // considered an lvalue. 145 assert((t.isNull() || !t->isReferenceType()) && 146 "Expressions can't have reference type"); 147 148 TR = t; 149 } 150 151 /// isValueDependent - Determines whether this expression is 152 /// value-dependent (C++ [temp.dep.constexpr]). For example, the 153 /// array bound of "Chars" in the following example is 154 /// value-dependent. 155 /// @code 156 /// template<int Size, char (&Chars)[Size]> struct meta_string; 157 /// @endcode 158 bool isValueDependent() const { return ExprBits.ValueDependent; } 159 160 /// Set whether this expression is value-dependent or not. 161 void setValueDependent(bool VD) { 162 ExprBits.ValueDependent = VD; 163 } 164 165 /// isTypeDependent - Determines whether this expression is 166 /// type-dependent (C++ [temp.dep.expr]), which means that its type 167 /// could change from one template instantiation to the next. For 168 /// example, the expressions "x" and "x + y" are type-dependent in 169 /// the following code, but "y" is not type-dependent: 170 /// @code 171 /// template<typename T> 172 /// void add(T x, int y) { 173 /// x + y; 174 /// } 175 /// @endcode 176 bool isTypeDependent() const { return ExprBits.TypeDependent; } 177 178 /// Set whether this expression is type-dependent or not. 179 void setTypeDependent(bool TD) { 180 ExprBits.TypeDependent = TD; 181 } 182 183 /// Whether this expression is instantiation-dependent, meaning that 184 /// it depends in some way on a template parameter, even if neither its type 185 /// nor (constant) value can change due to the template instantiation. 186 /// 187 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is 188 /// instantiation-dependent (since it involves a template parameter \c T), but 189 /// is neither type- nor value-dependent, since the type of the inner 190 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer 191 /// \c sizeof is known. 192 /// 193 /// \code 194 /// template<typename T> 195 /// void f(T x, T y) { 196 /// sizeof(sizeof(T() + T()); 197 /// } 198 /// \endcode 199 /// 200 bool isInstantiationDependent() const { 201 return ExprBits.InstantiationDependent; 202 } 203 204 /// Set whether this expression is instantiation-dependent or not. 205 void setInstantiationDependent(bool ID) { 206 ExprBits.InstantiationDependent = ID; 207 } 208 209 /// Whether this expression contains an unexpanded parameter 210 /// pack (for C++11 variadic templates). 211 /// 212 /// Given the following function template: 213 /// 214 /// \code 215 /// template<typename F, typename ...Types> 216 /// void forward(const F &f, Types &&...args) { 217 /// f(static_cast<Types&&>(args)...); 218 /// } 219 /// \endcode 220 /// 221 /// The expressions \c args and \c static_cast<Types&&>(args) both 222 /// contain parameter packs. 223 bool containsUnexpandedParameterPack() const { 224 return ExprBits.ContainsUnexpandedParameterPack; 225 } 226 227 /// Set the bit that describes whether this expression 228 /// contains an unexpanded parameter pack. 229 void setContainsUnexpandedParameterPack(bool PP = true) { 230 ExprBits.ContainsUnexpandedParameterPack = PP; 231 } 232 233 /// getExprLoc - Return the preferred location for the arrow when diagnosing 234 /// a problem with a generic expression. 235 SourceLocation getExprLoc() const LLVM_READONLY; 236 237 /// isUnusedResultAWarning - Return true if this immediate expression should 238 /// be warned about if the result is unused. If so, fill in expr, location, 239 /// and ranges with expr to warn on and source locations/ranges appropriate 240 /// for a warning. 241 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, 242 SourceRange &R1, SourceRange &R2, 243 ASTContext &Ctx) const; 244 245 /// isLValue - True if this expression is an "l-value" according to 246 /// the rules of the current language. C and C++ give somewhat 247 /// different rules for this concept, but in general, the result of 248 /// an l-value expression identifies a specific object whereas the 249 /// result of an r-value expression is a value detached from any 250 /// specific storage. 251 /// 252 /// C++11 divides the concept of "r-value" into pure r-values 253 /// ("pr-values") and so-called expiring values ("x-values"), which 254 /// identify specific objects that can be safely cannibalized for 255 /// their resources. This is an unfortunate abuse of terminology on 256 /// the part of the C++ committee. In Clang, when we say "r-value", 257 /// we generally mean a pr-value. 258 bool isLValue() const { return getValueKind() == VK_LValue; } 259 bool isRValue() const { return getValueKind() == VK_RValue; } 260 bool isXValue() const { return getValueKind() == VK_XValue; } 261 bool isGLValue() const { return getValueKind() != VK_RValue; } 262 263 enum LValueClassification { 264 LV_Valid, 265 LV_NotObjectType, 266 LV_IncompleteVoidType, 267 LV_DuplicateVectorComponents, 268 LV_InvalidExpression, 269 LV_InvalidMessageExpression, 270 LV_MemberFunction, 271 LV_SubObjCPropertySetting, 272 LV_ClassTemporary, 273 LV_ArrayTemporary 274 }; 275 /// Reasons why an expression might not be an l-value. 276 LValueClassification ClassifyLValue(ASTContext &Ctx) const; 277 278 enum isModifiableLvalueResult { 279 MLV_Valid, 280 MLV_NotObjectType, 281 MLV_IncompleteVoidType, 282 MLV_DuplicateVectorComponents, 283 MLV_InvalidExpression, 284 MLV_LValueCast, // Specialized form of MLV_InvalidExpression. 285 MLV_IncompleteType, 286 MLV_ConstQualified, 287 MLV_ConstQualifiedField, 288 MLV_ConstAddrSpace, 289 MLV_ArrayType, 290 MLV_NoSetterProperty, 291 MLV_MemberFunction, 292 MLV_SubObjCPropertySetting, 293 MLV_InvalidMessageExpression, 294 MLV_ClassTemporary, 295 MLV_ArrayTemporary 296 }; 297 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, 298 /// does not have an incomplete type, does not have a const-qualified type, 299 /// and if it is a structure or union, does not have any member (including, 300 /// recursively, any member or element of all contained aggregates or unions) 301 /// with a const-qualified type. 302 /// 303 /// \param Loc [in,out] - A source location which *may* be filled 304 /// in with the location of the expression making this a 305 /// non-modifiable lvalue, if specified. 306 isModifiableLvalueResult 307 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; 308 309 /// The return type of classify(). Represents the C++11 expression 310 /// taxonomy. 311 class Classification { 312 public: 313 /// The various classification results. Most of these mean prvalue. 314 enum Kinds { 315 CL_LValue, 316 CL_XValue, 317 CL_Function, // Functions cannot be lvalues in C. 318 CL_Void, // Void cannot be an lvalue in C. 319 CL_AddressableVoid, // Void expression whose address can be taken in C. 320 CL_DuplicateVectorComponents, // A vector shuffle with dupes. 321 CL_MemberFunction, // An expression referring to a member function 322 CL_SubObjCPropertySetting, 323 CL_ClassTemporary, // A temporary of class type, or subobject thereof. 324 CL_ArrayTemporary, // A temporary of array type. 325 CL_ObjCMessageRValue, // ObjC message is an rvalue 326 CL_PRValue // A prvalue for any other reason, of any other type 327 }; 328 /// The results of modification testing. 329 enum ModifiableType { 330 CM_Untested, // testModifiable was false. 331 CM_Modifiable, 332 CM_RValue, // Not modifiable because it's an rvalue 333 CM_Function, // Not modifiable because it's a function; C++ only 334 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext 335 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter 336 CM_ConstQualified, 337 CM_ConstQualifiedField, 338 CM_ConstAddrSpace, 339 CM_ArrayType, 340 CM_IncompleteType 341 }; 342 343 private: 344 friend class Expr; 345 346 unsigned short Kind; 347 unsigned short Modifiable; 348 349 explicit Classification(Kinds k, ModifiableType m) 350 : Kind(k), Modifiable(m) 351 {} 352 353 public: 354 Classification() {} 355 356 Kinds getKind() const { return static_cast<Kinds>(Kind); } 357 ModifiableType getModifiable() const { 358 assert(Modifiable != CM_Untested && "Did not test for modifiability."); 359 return static_cast<ModifiableType>(Modifiable); 360 } 361 bool isLValue() const { return Kind == CL_LValue; } 362 bool isXValue() const { return Kind == CL_XValue; } 363 bool isGLValue() const { return Kind <= CL_XValue; } 364 bool isPRValue() const { return Kind >= CL_Function; } 365 bool isRValue() const { return Kind >= CL_XValue; } 366 bool isModifiable() const { return getModifiable() == CM_Modifiable; } 367 368 /// Create a simple, modifiably lvalue 369 static Classification makeSimpleLValue() { 370 return Classification(CL_LValue, CM_Modifiable); 371 } 372 373 }; 374 /// Classify - Classify this expression according to the C++11 375 /// expression taxonomy. 376 /// 377 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the 378 /// old lvalue vs rvalue. This function determines the type of expression this 379 /// is. There are three expression types: 380 /// - lvalues are classical lvalues as in C++03. 381 /// - prvalues are equivalent to rvalues in C++03. 382 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a 383 /// function returning an rvalue reference. 384 /// lvalues and xvalues are collectively referred to as glvalues, while 385 /// prvalues and xvalues together form rvalues. 386 Classification Classify(ASTContext &Ctx) const { 387 return ClassifyImpl(Ctx, nullptr); 388 } 389 390 /// ClassifyModifiable - Classify this expression according to the 391 /// C++11 expression taxonomy, and see if it is valid on the left side 392 /// of an assignment. 393 /// 394 /// This function extends classify in that it also tests whether the 395 /// expression is modifiable (C99 6.3.2.1p1). 396 /// \param Loc A source location that might be filled with a relevant location 397 /// if the expression is not modifiable. 398 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ 399 return ClassifyImpl(Ctx, &Loc); 400 } 401 402 /// getValueKindForType - Given a formal return or parameter type, 403 /// give its value kind. 404 static ExprValueKind getValueKindForType(QualType T) { 405 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 406 return (isa<LValueReferenceType>(RT) 407 ? VK_LValue 408 : (RT->getPointeeType()->isFunctionType() 409 ? VK_LValue : VK_XValue)); 410 return VK_RValue; 411 } 412 413 /// getValueKind - The value kind that this expression produces. 414 ExprValueKind getValueKind() const { 415 return static_cast<ExprValueKind>(ExprBits.ValueKind); 416 } 417 418 /// getObjectKind - The object kind that this expression produces. 419 /// Object kinds are meaningful only for expressions that yield an 420 /// l-value or x-value. 421 ExprObjectKind getObjectKind() const { 422 return static_cast<ExprObjectKind>(ExprBits.ObjectKind); 423 } 424 425 bool isOrdinaryOrBitFieldObject() const { 426 ExprObjectKind OK = getObjectKind(); 427 return (OK == OK_Ordinary || OK == OK_BitField); 428 } 429 430 /// setValueKind - Set the value kind produced by this expression. 431 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } 432 433 /// setObjectKind - Set the object kind produced by this expression. 434 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } 435 436 private: 437 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; 438 439 public: 440 441 /// Returns true if this expression is a gl-value that 442 /// potentially refers to a bit-field. 443 /// 444 /// In C++, whether a gl-value refers to a bitfield is essentially 445 /// an aspect of the value-kind type system. 446 bool refersToBitField() const { return getObjectKind() == OK_BitField; } 447 448 /// If this expression refers to a bit-field, retrieve the 449 /// declaration of that bit-field. 450 /// 451 /// Note that this returns a non-null pointer in subtly different 452 /// places than refersToBitField returns true. In particular, this can 453 /// return a non-null pointer even for r-values loaded from 454 /// bit-fields, but it will return null for a conditional bit-field. 455 FieldDecl *getSourceBitField(); 456 457 const FieldDecl *getSourceBitField() const { 458 return const_cast<Expr*>(this)->getSourceBitField(); 459 } 460 461 Decl *getReferencedDeclOfCallee(); 462 const Decl *getReferencedDeclOfCallee() const { 463 return const_cast<Expr*>(this)->getReferencedDeclOfCallee(); 464 } 465 466 /// If this expression is an l-value for an Objective C 467 /// property, find the underlying property reference expression. 468 const ObjCPropertyRefExpr *getObjCProperty() const; 469 470 /// Check if this expression is the ObjC 'self' implicit parameter. 471 bool isObjCSelfExpr() const; 472 473 /// Returns whether this expression refers to a vector element. 474 bool refersToVectorElement() const; 475 476 /// Returns whether this expression refers to a global register 477 /// variable. 478 bool refersToGlobalRegisterVar() const; 479 480 /// Returns whether this expression has a placeholder type. 481 bool hasPlaceholderType() const { 482 return getType()->isPlaceholderType(); 483 } 484 485 /// Returns whether this expression has a specific placeholder type. 486 bool hasPlaceholderType(BuiltinType::Kind K) const { 487 assert(BuiltinType::isPlaceholderTypeKind(K)); 488 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) 489 return BT->getKind() == K; 490 return false; 491 } 492 493 /// isKnownToHaveBooleanValue - Return true if this is an integer expression 494 /// that is known to return 0 or 1. This happens for _Bool/bool expressions 495 /// but also int expressions which are produced by things like comparisons in 496 /// C. 497 bool isKnownToHaveBooleanValue() const; 498 499 /// isIntegerConstantExpr - Return true if this expression is a valid integer 500 /// constant expression, and, if so, return its value in Result. If not a 501 /// valid i-c-e, return false and fill in Loc (if specified) with the location 502 /// of the invalid expression. 503 /// 504 /// Note: This does not perform the implicit conversions required by C++11 505 /// [expr.const]p5. 506 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, 507 SourceLocation *Loc = nullptr, 508 bool isEvaluated = true) const; 509 bool isIntegerConstantExpr(const ASTContext &Ctx, 510 SourceLocation *Loc = nullptr) const; 511 512 /// isCXX98IntegralConstantExpr - Return true if this expression is an 513 /// integral constant expression in C++98. Can only be used in C++. 514 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; 515 516 /// isCXX11ConstantExpr - Return true if this expression is a constant 517 /// expression in C++11. Can only be used in C++. 518 /// 519 /// Note: This does not perform the implicit conversions required by C++11 520 /// [expr.const]p5. 521 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, 522 SourceLocation *Loc = nullptr) const; 523 524 /// isPotentialConstantExpr - Return true if this function's definition 525 /// might be usable in a constant expression in C++11, if it were marked 526 /// constexpr. Return false if the function can never produce a constant 527 /// expression, along with diagnostics describing why not. 528 static bool isPotentialConstantExpr(const FunctionDecl *FD, 529 SmallVectorImpl< 530 PartialDiagnosticAt> &Diags); 531 532 /// isPotentialConstantExprUnevaluted - Return true if this expression might 533 /// be usable in a constant expression in C++11 in an unevaluated context, if 534 /// it were in function FD marked constexpr. Return false if the function can 535 /// never produce a constant expression, along with diagnostics describing 536 /// why not. 537 static bool isPotentialConstantExprUnevaluated(Expr *E, 538 const FunctionDecl *FD, 539 SmallVectorImpl< 540 PartialDiagnosticAt> &Diags); 541 542 /// isConstantInitializer - Returns true if this expression can be emitted to 543 /// IR as a constant, and thus can be used as a constant initializer in C. 544 /// If this expression is not constant and Culprit is non-null, 545 /// it is used to store the address of first non constant expr. 546 bool isConstantInitializer(ASTContext &Ctx, bool ForRef, 547 const Expr **Culprit = nullptr) const; 548 549 /// EvalStatus is a struct with detailed info about an evaluation in progress. 550 struct EvalStatus { 551 /// Whether the evaluated expression has side effects. 552 /// For example, (f() && 0) can be folded, but it still has side effects. 553 bool HasSideEffects; 554 555 /// Whether the evaluation hit undefined behavior. 556 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. 557 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. 558 bool HasUndefinedBehavior; 559 560 /// Diag - If this is non-null, it will be filled in with a stack of notes 561 /// indicating why evaluation failed (or why it failed to produce a constant 562 /// expression). 563 /// If the expression is unfoldable, the notes will indicate why it's not 564 /// foldable. If the expression is foldable, but not a constant expression, 565 /// the notes will describes why it isn't a constant expression. If the 566 /// expression *is* a constant expression, no notes will be produced. 567 SmallVectorImpl<PartialDiagnosticAt> *Diag; 568 569 EvalStatus() 570 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {} 571 572 // hasSideEffects - Return true if the evaluated expression has 573 // side effects. 574 bool hasSideEffects() const { 575 return HasSideEffects; 576 } 577 }; 578 579 /// EvalResult is a struct with detailed info about an evaluated expression. 580 struct EvalResult : EvalStatus { 581 /// Val - This is the value the expression can be folded to. 582 APValue Val; 583 584 // isGlobalLValue - Return true if the evaluated lvalue expression 585 // is global. 586 bool isGlobalLValue() const; 587 }; 588 589 /// EvaluateAsRValue - Return true if this is a constant which we can fold to 590 /// an rvalue using any crazy technique (that has nothing to do with language 591 /// standards) that we want to, even if the expression has side-effects. If 592 /// this function returns true, it returns the folded constant in Result. If 593 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be 594 /// applied. 595 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 596 bool InConstantContext = false) const; 597 598 /// EvaluateAsBooleanCondition - Return true if this is a constant 599 /// which we can fold and convert to a boolean condition using 600 /// any crazy technique that we want to, even if the expression has 601 /// side-effects. 602 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 603 bool InConstantContext = false) const; 604 605 enum SideEffectsKind { 606 SE_NoSideEffects, ///< Strictly evaluate the expression. 607 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not 608 ///< arbitrary unmodeled side effects. 609 SE_AllowSideEffects ///< Allow any unmodeled side effect. 610 }; 611 612 /// EvaluateAsInt - Return true if this is a constant which we can fold and 613 /// convert to an integer, using any crazy technique that we want to. 614 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 615 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 616 bool InConstantContext = false) const; 617 618 /// EvaluateAsFloat - Return true if this is a constant which we can fold and 619 /// convert to a floating point value, using any crazy technique that we 620 /// want to. 621 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, 622 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 623 bool InConstantContext = false) const; 624 625 /// EvaluateAsFloat - Return true if this is a constant which we can fold and 626 /// convert to a fixed point value. 627 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 628 SideEffectsKind AllowSideEffects = SE_NoSideEffects, 629 bool InConstantContext = false) const; 630 631 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 632 /// constant folded without side-effects, but discard the result. 633 bool isEvaluatable(const ASTContext &Ctx, 634 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; 635 636 /// HasSideEffects - This routine returns true for all those expressions 637 /// which have any effect other than producing a value. Example is a function 638 /// call, volatile variable read, or throwing an exception. If 639 /// IncludePossibleEffects is false, this call treats certain expressions with 640 /// potential side effects (such as function call-like expressions, 641 /// instantiation-dependent expressions, or invocations from a macro) as not 642 /// having side effects. 643 bool HasSideEffects(const ASTContext &Ctx, 644 bool IncludePossibleEffects = true) const; 645 646 /// Determine whether this expression involves a call to any function 647 /// that is not trivial. 648 bool hasNonTrivialCall(const ASTContext &Ctx) const; 649 650 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded 651 /// integer. This must be called on an expression that constant folds to an 652 /// integer. 653 llvm::APSInt EvaluateKnownConstInt( 654 const ASTContext &Ctx, 655 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 656 657 llvm::APSInt EvaluateKnownConstIntCheckOverflow( 658 const ASTContext &Ctx, 659 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; 660 661 void EvaluateForOverflow(const ASTContext &Ctx) const; 662 663 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an 664 /// lvalue with link time known address, with no side-effects. 665 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 666 bool InConstantContext = false) const; 667 668 /// EvaluateAsInitializer - Evaluate an expression as if it were the 669 /// initializer of the given declaration. Returns true if the initializer 670 /// can be folded to a constant, and produces any relevant notes. In C++11, 671 /// notes will be produced if the expression is not a constant expression. 672 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, 673 const VarDecl *VD, 674 SmallVectorImpl<PartialDiagnosticAt> &Notes) const; 675 676 /// EvaluateWithSubstitution - Evaluate an expression as if from the context 677 /// of a call to the given function with the given arguments, inside an 678 /// unevaluated context. Returns true if the expression could be folded to a 679 /// constant. 680 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 681 const FunctionDecl *Callee, 682 ArrayRef<const Expr*> Args, 683 const Expr *This = nullptr) const; 684 685 /// Indicates how the constant expression will be used. 686 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling }; 687 688 /// Evaluate an expression that is required to be a constant expression. 689 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 690 const ASTContext &Ctx) const; 691 692 /// If the current Expr is a pointer, this will try to statically 693 /// determine the number of bytes available where the pointer is pointing. 694 /// Returns true if all of the above holds and we were able to figure out the 695 /// size, false otherwise. 696 /// 697 /// \param Type - How to evaluate the size of the Expr, as defined by the 698 /// "type" parameter of __builtin_object_size 699 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 700 unsigned Type) const; 701 702 /// Enumeration used to describe the kind of Null pointer constant 703 /// returned from \c isNullPointerConstant(). 704 enum NullPointerConstantKind { 705 /// Expression is not a Null pointer constant. 706 NPCK_NotNull = 0, 707 708 /// Expression is a Null pointer constant built from a zero integer 709 /// expression that is not a simple, possibly parenthesized, zero literal. 710 /// C++ Core Issue 903 will classify these expressions as "not pointers" 711 /// once it is adopted. 712 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 713 NPCK_ZeroExpression, 714 715 /// Expression is a Null pointer constant built from a literal zero. 716 NPCK_ZeroLiteral, 717 718 /// Expression is a C++11 nullptr. 719 NPCK_CXX11_nullptr, 720 721 /// Expression is a GNU-style __null constant. 722 NPCK_GNUNull 723 }; 724 725 /// Enumeration used to describe how \c isNullPointerConstant() 726 /// should cope with value-dependent expressions. 727 enum NullPointerConstantValueDependence { 728 /// Specifies that the expression should never be value-dependent. 729 NPC_NeverValueDependent = 0, 730 731 /// Specifies that a value-dependent expression of integral or 732 /// dependent type should be considered a null pointer constant. 733 NPC_ValueDependentIsNull, 734 735 /// Specifies that a value-dependent expression should be considered 736 /// to never be a null pointer constant. 737 NPC_ValueDependentIsNotNull 738 }; 739 740 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to 741 /// a Null pointer constant. The return value can further distinguish the 742 /// kind of NULL pointer constant that was detected. 743 NullPointerConstantKind isNullPointerConstant( 744 ASTContext &Ctx, 745 NullPointerConstantValueDependence NPC) const; 746 747 /// isOBJCGCCandidate - Return true if this expression may be used in a read/ 748 /// write barrier. 749 bool isOBJCGCCandidate(ASTContext &Ctx) const; 750 751 /// Returns true if this expression is a bound member function. 752 bool isBoundMemberFunction(ASTContext &Ctx) const; 753 754 /// Given an expression of bound-member type, find the type 755 /// of the member. Returns null if this is an *overloaded* bound 756 /// member expression. 757 static QualType findBoundMemberType(const Expr *expr); 758 759 /// Skip past any implicit casts which might surround this expression until 760 /// reaching a fixed point. Skips: 761 /// * ImplicitCastExpr 762 /// * FullExpr 763 Expr *IgnoreImpCasts() LLVM_READONLY; 764 const Expr *IgnoreImpCasts() const { 765 return const_cast<Expr *>(this)->IgnoreImpCasts(); 766 } 767 768 /// Skip past any casts which might surround this expression until reaching 769 /// a fixed point. Skips: 770 /// * CastExpr 771 /// * FullExpr 772 /// * MaterializeTemporaryExpr 773 /// * SubstNonTypeTemplateParmExpr 774 Expr *IgnoreCasts() LLVM_READONLY; 775 const Expr *IgnoreCasts() const { 776 return const_cast<Expr *>(this)->IgnoreCasts(); 777 } 778 779 /// Skip past any implicit AST nodes which might surround this expression 780 /// until reaching a fixed point. Skips: 781 /// * What IgnoreImpCasts() skips 782 /// * MaterializeTemporaryExpr 783 /// * CXXBindTemporaryExpr 784 Expr *IgnoreImplicit() LLVM_READONLY; 785 const Expr *IgnoreImplicit() const { 786 return const_cast<Expr *>(this)->IgnoreImplicit(); 787 } 788 789 /// Skip past any parentheses which might surround this expression until 790 /// reaching a fixed point. Skips: 791 /// * ParenExpr 792 /// * UnaryOperator if `UO_Extension` 793 /// * GenericSelectionExpr if `!isResultDependent()` 794 /// * ChooseExpr if `!isConditionDependent()` 795 /// * ConstantExpr 796 Expr *IgnoreParens() LLVM_READONLY; 797 const Expr *IgnoreParens() const { 798 return const_cast<Expr *>(this)->IgnoreParens(); 799 } 800 801 /// Skip past any parentheses and implicit casts which might surround this 802 /// expression until reaching a fixed point. 803 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to 804 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However 805 /// this is currently not the case. Instead IgnoreParenImpCasts() skips: 806 /// * What IgnoreParens() skips 807 /// * What IgnoreImpCasts() skips 808 /// * MaterializeTemporaryExpr 809 /// * SubstNonTypeTemplateParmExpr 810 Expr *IgnoreParenImpCasts() LLVM_READONLY; 811 const Expr *IgnoreParenImpCasts() const { 812 return const_cast<Expr *>(this)->IgnoreParenImpCasts(); 813 } 814 815 /// Skip past any parentheses and casts which might surround this expression 816 /// until reaching a fixed point. Skips: 817 /// * What IgnoreParens() skips 818 /// * What IgnoreCasts() skips 819 Expr *IgnoreParenCasts() LLVM_READONLY; 820 const Expr *IgnoreParenCasts() const { 821 return const_cast<Expr *>(this)->IgnoreParenCasts(); 822 } 823 824 /// Skip conversion operators. If this Expr is a call to a conversion 825 /// operator, return the argument. 826 Expr *IgnoreConversionOperator() LLVM_READONLY; 827 const Expr *IgnoreConversionOperator() const { 828 return const_cast<Expr *>(this)->IgnoreConversionOperator(); 829 } 830 831 /// Skip past any parentheses and lvalue casts which might surround this 832 /// expression until reaching a fixed point. Skips: 833 /// * What IgnoreParens() skips 834 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue 835 /// casts are skipped 836 /// FIXME: This is intended purely as a temporary workaround for code 837 /// that hasn't yet been rewritten to do the right thing about those 838 /// casts, and may disappear along with the last internal use. 839 Expr *IgnoreParenLValueCasts() LLVM_READONLY; 840 const Expr *IgnoreParenLValueCasts() const { 841 return const_cast<Expr *>(this)->IgnoreParenLValueCasts(); 842 } 843 844 /// Skip past any parenthese and casts which do not change the value 845 /// (including ptr->int casts of the same size) until reaching a fixed point. 846 /// Skips: 847 /// * What IgnoreParens() skips 848 /// * CastExpr which do not change the value 849 /// * SubstNonTypeTemplateParmExpr 850 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY; 851 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const { 852 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx); 853 } 854 855 /// Skip past any parentheses and derived-to-base casts until reaching a 856 /// fixed point. Skips: 857 /// * What IgnoreParens() skips 858 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase, 859 /// CK_UncheckedDerivedToBase and CK_NoOp) 860 Expr *ignoreParenBaseCasts() LLVM_READONLY; 861 const Expr *ignoreParenBaseCasts() const { 862 return const_cast<Expr *>(this)->ignoreParenBaseCasts(); 863 } 864 865 /// Determine whether this expression is a default function argument. 866 /// 867 /// Default arguments are implicitly generated in the abstract syntax tree 868 /// by semantic analysis for function calls, object constructions, etc. in 869 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; 870 /// this routine also looks through any implicit casts to determine whether 871 /// the expression is a default argument. 872 bool isDefaultArgument() const; 873 874 /// Determine whether the result of this expression is a 875 /// temporary object of the given class type. 876 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; 877 878 /// Whether this expression is an implicit reference to 'this' in C++. 879 bool isImplicitCXXThis() const; 880 881 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); 882 883 /// For an expression of class type or pointer to class type, 884 /// return the most derived class decl the expression is known to refer to. 885 /// 886 /// If this expression is a cast, this method looks through it to find the 887 /// most derived decl that can be inferred from the expression. 888 /// This is valid because derived-to-base conversions have undefined 889 /// behavior if the object isn't dynamically of the derived type. 890 const CXXRecordDecl *getBestDynamicClassType() const; 891 892 /// Get the inner expression that determines the best dynamic class. 893 /// If this is a prvalue, we guarantee that it is of the most-derived type 894 /// for the object itself. 895 const Expr *getBestDynamicClassTypeExpr() const; 896 897 /// Walk outwards from an expression we want to bind a reference to and 898 /// find the expression whose lifetime needs to be extended. Record 899 /// the LHSs of comma expressions and adjustments needed along the path. 900 const Expr *skipRValueSubobjectAdjustments( 901 SmallVectorImpl<const Expr *> &CommaLHS, 902 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; 903 const Expr *skipRValueSubobjectAdjustments() const { 904 SmallVector<const Expr *, 8> CommaLHSs; 905 SmallVector<SubobjectAdjustment, 8> Adjustments; 906 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 907 } 908 909 /// Checks that the two Expr's will refer to the same value as a comparison 910 /// operand. The caller must ensure that the values referenced by the Expr's 911 /// are not modified between E1 and E2 or the result my be invalid. 912 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2); 913 914 static bool classof(const Stmt *T) { 915 return T->getStmtClass() >= firstExprConstant && 916 T->getStmtClass() <= lastExprConstant; 917 } 918 }; 919 920 //===----------------------------------------------------------------------===// 921 // Wrapper Expressions. 922 //===----------------------------------------------------------------------===// 923 924 /// FullExpr - Represents a "full-expression" node. 925 class FullExpr : public Expr { 926 protected: 927 Stmt *SubExpr; 928 929 FullExpr(StmtClass SC, Expr *subexpr) 930 : Expr(SC, subexpr->getType(), 931 subexpr->getValueKind(), subexpr->getObjectKind(), 932 subexpr->isTypeDependent(), subexpr->isValueDependent(), 933 subexpr->isInstantiationDependent(), 934 subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {} 935 FullExpr(StmtClass SC, EmptyShell Empty) 936 : Expr(SC, Empty) {} 937 public: 938 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } 939 Expr *getSubExpr() { return cast<Expr>(SubExpr); } 940 941 /// As with any mutator of the AST, be very careful when modifying an 942 /// existing AST to preserve its invariants. 943 void setSubExpr(Expr *E) { SubExpr = E; } 944 945 static bool classof(const Stmt *T) { 946 return T->getStmtClass() >= firstFullExprConstant && 947 T->getStmtClass() <= lastFullExprConstant; 948 } 949 }; 950 951 /// ConstantExpr - An expression that occurs in a constant context and 952 /// optionally the result of evaluating the expression. 953 class ConstantExpr final 954 : public FullExpr, 955 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> { 956 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value, 957 "this class assumes llvm::APInt::WordType is uint64_t for " 958 "trail-allocated storage"); 959 960 public: 961 /// Describes the kind of result that can be trail-allocated. 962 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue }; 963 964 private: 965 size_t numTrailingObjects(OverloadToken<APValue>) const { 966 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue; 967 } 968 size_t numTrailingObjects(OverloadToken<uint64_t>) const { 969 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64; 970 } 971 972 void DefaultInit(ResultStorageKind StorageKind); 973 uint64_t &Int64Result() { 974 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && 975 "invalid accessor"); 976 return *getTrailingObjects<uint64_t>(); 977 } 978 const uint64_t &Int64Result() const { 979 return const_cast<ConstantExpr *>(this)->Int64Result(); 980 } 981 APValue &APValueResult() { 982 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && 983 "invalid accessor"); 984 return *getTrailingObjects<APValue>(); 985 } 986 const APValue &APValueResult() const { 987 return const_cast<ConstantExpr *>(this)->APValueResult(); 988 } 989 990 ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind); 991 ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty); 992 993 public: 994 friend TrailingObjects; 995 friend class ASTStmtReader; 996 friend class ASTStmtWriter; 997 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 998 const APValue &Result); 999 static ConstantExpr *Create(const ASTContext &Context, Expr *E, 1000 ResultStorageKind Storage = RSK_None); 1001 static ConstantExpr *CreateEmpty(const ASTContext &Context, 1002 ResultStorageKind StorageKind, 1003 EmptyShell Empty); 1004 1005 static ResultStorageKind getStorageKind(const APValue &Value); 1006 static ResultStorageKind getStorageKind(const Type *T, 1007 const ASTContext &Context); 1008 1009 SourceLocation getBeginLoc() const LLVM_READONLY { 1010 return SubExpr->getBeginLoc(); 1011 } 1012 SourceLocation getEndLoc() const LLVM_READONLY { 1013 return SubExpr->getEndLoc(); 1014 } 1015 1016 static bool classof(const Stmt *T) { 1017 return T->getStmtClass() == ConstantExprClass; 1018 } 1019 1020 void SetResult(APValue Value, const ASTContext &Context) { 1021 MoveIntoResult(Value, Context); 1022 } 1023 void MoveIntoResult(APValue &Value, const ASTContext &Context); 1024 1025 APValue::ValueKind getResultAPValueKind() const { 1026 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind); 1027 } 1028 ResultStorageKind getResultStorageKind() const { 1029 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind); 1030 } 1031 APValue getAPValueResult() const; 1032 const APValue &getResultAsAPValue() const { return APValueResult(); } 1033 llvm::APSInt getResultAsAPSInt() const; 1034 // Iterators 1035 child_range children() { return child_range(&SubExpr, &SubExpr+1); } 1036 const_child_range children() const { 1037 return const_child_range(&SubExpr, &SubExpr + 1); 1038 } 1039 }; 1040 1041 //===----------------------------------------------------------------------===// 1042 // Primary Expressions. 1043 //===----------------------------------------------------------------------===// 1044 1045 /// OpaqueValueExpr - An expression referring to an opaque object of a 1046 /// fixed type and value class. These don't correspond to concrete 1047 /// syntax; instead they're used to express operations (usually copy 1048 /// operations) on values whose source is generally obvious from 1049 /// context. 1050 class OpaqueValueExpr : public Expr { 1051 friend class ASTStmtReader; 1052 Expr *SourceExpr; 1053 1054 public: 1055 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, 1056 ExprObjectKind OK = OK_Ordinary, 1057 Expr *SourceExpr = nullptr) 1058 : Expr(OpaqueValueExprClass, T, VK, OK, 1059 T->isDependentType() || 1060 (SourceExpr && SourceExpr->isTypeDependent()), 1061 T->isDependentType() || 1062 (SourceExpr && SourceExpr->isValueDependent()), 1063 T->isInstantiationDependentType() || 1064 (SourceExpr && SourceExpr->isInstantiationDependent()), 1065 false), 1066 SourceExpr(SourceExpr) { 1067 setIsUnique(false); 1068 OpaqueValueExprBits.Loc = Loc; 1069 } 1070 1071 /// Given an expression which invokes a copy constructor --- i.e. a 1072 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- 1073 /// find the OpaqueValueExpr that's the source of the construction. 1074 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); 1075 1076 explicit OpaqueValueExpr(EmptyShell Empty) 1077 : Expr(OpaqueValueExprClass, Empty) {} 1078 1079 /// Retrieve the location of this expression. 1080 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; } 1081 1082 SourceLocation getBeginLoc() const LLVM_READONLY { 1083 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation(); 1084 } 1085 SourceLocation getEndLoc() const LLVM_READONLY { 1086 return SourceExpr ? SourceExpr->getEndLoc() : getLocation(); 1087 } 1088 SourceLocation getExprLoc() const LLVM_READONLY { 1089 return SourceExpr ? SourceExpr->getExprLoc() : getLocation(); 1090 } 1091 1092 child_range children() { 1093 return child_range(child_iterator(), child_iterator()); 1094 } 1095 1096 const_child_range children() const { 1097 return const_child_range(const_child_iterator(), const_child_iterator()); 1098 } 1099 1100 /// The source expression of an opaque value expression is the 1101 /// expression which originally generated the value. This is 1102 /// provided as a convenience for analyses that don't wish to 1103 /// precisely model the execution behavior of the program. 1104 /// 1105 /// The source expression is typically set when building the 1106 /// expression which binds the opaque value expression in the first 1107 /// place. 1108 Expr *getSourceExpr() const { return SourceExpr; } 1109 1110 void setIsUnique(bool V) { 1111 assert((!V || SourceExpr) && 1112 "unique OVEs are expected to have source expressions"); 1113 OpaqueValueExprBits.IsUnique = V; 1114 } 1115 1116 bool isUnique() const { return OpaqueValueExprBits.IsUnique; } 1117 1118 static bool classof(const Stmt *T) { 1119 return T->getStmtClass() == OpaqueValueExprClass; 1120 } 1121 }; 1122 1123 /// A reference to a declared variable, function, enum, etc. 1124 /// [C99 6.5.1p2] 1125 /// 1126 /// This encodes all the information about how a declaration is referenced 1127 /// within an expression. 1128 /// 1129 /// There are several optional constructs attached to DeclRefExprs only when 1130 /// they apply in order to conserve memory. These are laid out past the end of 1131 /// the object, and flags in the DeclRefExprBitfield track whether they exist: 1132 /// 1133 /// DeclRefExprBits.HasQualifier: 1134 /// Specifies when this declaration reference expression has a C++ 1135 /// nested-name-specifier. 1136 /// DeclRefExprBits.HasFoundDecl: 1137 /// Specifies when this declaration reference expression has a record of 1138 /// a NamedDecl (different from the referenced ValueDecl) which was found 1139 /// during name lookup and/or overload resolution. 1140 /// DeclRefExprBits.HasTemplateKWAndArgsInfo: 1141 /// Specifies when this declaration reference expression has an explicit 1142 /// C++ template keyword and/or template argument list. 1143 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture 1144 /// Specifies when this declaration reference expression (validly) 1145 /// refers to an enclosed local or a captured variable. 1146 class DeclRefExpr final 1147 : public Expr, 1148 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc, 1149 NamedDecl *, ASTTemplateKWAndArgsInfo, 1150 TemplateArgumentLoc> { 1151 friend class ASTStmtReader; 1152 friend class ASTStmtWriter; 1153 friend TrailingObjects; 1154 1155 /// The declaration that we are referencing. 1156 ValueDecl *D; 1157 1158 /// Provides source/type location info for the declaration name 1159 /// embedded in D. 1160 DeclarationNameLoc DNLoc; 1161 1162 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const { 1163 return hasQualifier(); 1164 } 1165 1166 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const { 1167 return hasFoundDecl(); 1168 } 1169 1170 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 1171 return hasTemplateKWAndArgsInfo(); 1172 } 1173 1174 /// Test whether there is a distinct FoundDecl attached to the end of 1175 /// this DRE. 1176 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } 1177 1178 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, 1179 SourceLocation TemplateKWLoc, ValueDecl *D, 1180 bool RefersToEnlosingVariableOrCapture, 1181 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, 1182 const TemplateArgumentListInfo *TemplateArgs, QualType T, 1183 ExprValueKind VK, NonOdrUseReason NOUR); 1184 1185 /// Construct an empty declaration reference expression. 1186 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {} 1187 1188 /// Computes the type- and value-dependence flags for this 1189 /// declaration reference expression. 1190 void computeDependence(const ASTContext &Ctx); 1191 1192 public: 1193 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, 1194 bool RefersToEnclosingVariableOrCapture, QualType T, 1195 ExprValueKind VK, SourceLocation L, 1196 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(), 1197 NonOdrUseReason NOUR = NOUR_None); 1198 1199 static DeclRefExpr * 1200 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1201 SourceLocation TemplateKWLoc, ValueDecl *D, 1202 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, 1203 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, 1204 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1205 NonOdrUseReason NOUR = NOUR_None); 1206 1207 static DeclRefExpr * 1208 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, 1209 SourceLocation TemplateKWLoc, ValueDecl *D, 1210 bool RefersToEnclosingVariableOrCapture, 1211 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, 1212 NamedDecl *FoundD = nullptr, 1213 const TemplateArgumentListInfo *TemplateArgs = nullptr, 1214 NonOdrUseReason NOUR = NOUR_None); 1215 1216 /// Construct an empty declaration reference expression. 1217 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 1218 bool HasFoundDecl, 1219 bool HasTemplateKWAndArgsInfo, 1220 unsigned NumTemplateArgs); 1221 1222 ValueDecl *getDecl() { return D; } 1223 const ValueDecl *getDecl() const { return D; } 1224 void setDecl(ValueDecl *NewD) { D = NewD; } 1225 1226 DeclarationNameInfo getNameInfo() const { 1227 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc); 1228 } 1229 1230 SourceLocation getLocation() const { return DeclRefExprBits.Loc; } 1231 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; } 1232 SourceLocation getBeginLoc() const LLVM_READONLY; 1233 SourceLocation getEndLoc() const LLVM_READONLY; 1234 1235 /// Determine whether this declaration reference was preceded by a 1236 /// C++ nested-name-specifier, e.g., \c N::foo. 1237 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } 1238 1239 /// If the name was qualified, retrieves the nested-name-specifier 1240 /// that precedes the name, with source-location information. 1241 NestedNameSpecifierLoc getQualifierLoc() const { 1242 if (!hasQualifier()) 1243 return NestedNameSpecifierLoc(); 1244 return *getTrailingObjects<NestedNameSpecifierLoc>(); 1245 } 1246 1247 /// If the name was qualified, retrieves the nested-name-specifier 1248 /// that precedes the name. Otherwise, returns NULL. 1249 NestedNameSpecifier *getQualifier() const { 1250 return getQualifierLoc().getNestedNameSpecifier(); 1251 } 1252 1253 /// Get the NamedDecl through which this reference occurred. 1254 /// 1255 /// This Decl may be different from the ValueDecl actually referred to in the 1256 /// presence of using declarations, etc. It always returns non-NULL, and may 1257 /// simple return the ValueDecl when appropriate. 1258 1259 NamedDecl *getFoundDecl() { 1260 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1261 } 1262 1263 /// Get the NamedDecl through which this reference occurred. 1264 /// See non-const variant. 1265 const NamedDecl *getFoundDecl() const { 1266 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; 1267 } 1268 1269 bool hasTemplateKWAndArgsInfo() const { 1270 return DeclRefExprBits.HasTemplateKWAndArgsInfo; 1271 } 1272 1273 /// Retrieve the location of the template keyword preceding 1274 /// this name, if any. 1275 SourceLocation getTemplateKeywordLoc() const { 1276 if (!hasTemplateKWAndArgsInfo()) 1277 return SourceLocation(); 1278 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 1279 } 1280 1281 /// Retrieve the location of the left angle bracket starting the 1282 /// explicit template argument list following the name, if any. 1283 SourceLocation getLAngleLoc() const { 1284 if (!hasTemplateKWAndArgsInfo()) 1285 return SourceLocation(); 1286 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 1287 } 1288 1289 /// Retrieve the location of the right angle bracket ending the 1290 /// explicit template argument list following the name, if any. 1291 SourceLocation getRAngleLoc() const { 1292 if (!hasTemplateKWAndArgsInfo()) 1293 return SourceLocation(); 1294 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 1295 } 1296 1297 /// Determines whether the name in this declaration reference 1298 /// was preceded by the template keyword. 1299 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 1300 1301 /// Determines whether this declaration reference was followed by an 1302 /// explicit template argument list. 1303 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 1304 1305 /// Copies the template arguments (if present) into the given 1306 /// structure. 1307 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 1308 if (hasExplicitTemplateArgs()) 1309 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 1310 getTrailingObjects<TemplateArgumentLoc>(), List); 1311 } 1312 1313 /// Retrieve the template arguments provided as part of this 1314 /// template-id. 1315 const TemplateArgumentLoc *getTemplateArgs() const { 1316 if (!hasExplicitTemplateArgs()) 1317 return nullptr; 1318 return getTrailingObjects<TemplateArgumentLoc>(); 1319 } 1320 1321 /// Retrieve the number of template arguments provided as part of this 1322 /// template-id. 1323 unsigned getNumTemplateArgs() const { 1324 if (!hasExplicitTemplateArgs()) 1325 return 0; 1326 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 1327 } 1328 1329 ArrayRef<TemplateArgumentLoc> template_arguments() const { 1330 return {getTemplateArgs(), getNumTemplateArgs()}; 1331 } 1332 1333 /// Returns true if this expression refers to a function that 1334 /// was resolved from an overloaded set having size greater than 1. 1335 bool hadMultipleCandidates() const { 1336 return DeclRefExprBits.HadMultipleCandidates; 1337 } 1338 /// Sets the flag telling whether this expression refers to 1339 /// a function that was resolved from an overloaded set having size 1340 /// greater than 1. 1341 void setHadMultipleCandidates(bool V = true) { 1342 DeclRefExprBits.HadMultipleCandidates = V; 1343 } 1344 1345 /// Is this expression a non-odr-use reference, and if so, why? 1346 NonOdrUseReason isNonOdrUse() const { 1347 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason); 1348 } 1349 1350 /// Does this DeclRefExpr refer to an enclosing local or a captured 1351 /// variable? 1352 bool refersToEnclosingVariableOrCapture() const { 1353 return DeclRefExprBits.RefersToEnclosingVariableOrCapture; 1354 } 1355 1356 static bool classof(const Stmt *T) { 1357 return T->getStmtClass() == DeclRefExprClass; 1358 } 1359 1360 // Iterators 1361 child_range children() { 1362 return child_range(child_iterator(), child_iterator()); 1363 } 1364 1365 const_child_range children() const { 1366 return const_child_range(const_child_iterator(), const_child_iterator()); 1367 } 1368 }; 1369 1370 /// Used by IntegerLiteral/FloatingLiteral to store the numeric without 1371 /// leaking memory. 1372 /// 1373 /// For large floats/integers, APFloat/APInt will allocate memory from the heap 1374 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator 1375 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with 1376 /// the APFloat/APInt values will never get freed. APNumericStorage uses 1377 /// ASTContext's allocator for memory allocation. 1378 class APNumericStorage { 1379 union { 1380 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 1381 uint64_t *pVal; ///< Used to store the >64 bits integer value. 1382 }; 1383 unsigned BitWidth; 1384 1385 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } 1386 1387 APNumericStorage(const APNumericStorage &) = delete; 1388 void operator=(const APNumericStorage &) = delete; 1389 1390 protected: 1391 APNumericStorage() : VAL(0), BitWidth(0) { } 1392 1393 llvm::APInt getIntValue() const { 1394 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 1395 if (NumWords > 1) 1396 return llvm::APInt(BitWidth, NumWords, pVal); 1397 else 1398 return llvm::APInt(BitWidth, VAL); 1399 } 1400 void setIntValue(const ASTContext &C, const llvm::APInt &Val); 1401 }; 1402 1403 class APIntStorage : private APNumericStorage { 1404 public: 1405 llvm::APInt getValue() const { return getIntValue(); } 1406 void setValue(const ASTContext &C, const llvm::APInt &Val) { 1407 setIntValue(C, Val); 1408 } 1409 }; 1410 1411 class APFloatStorage : private APNumericStorage { 1412 public: 1413 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { 1414 return llvm::APFloat(Semantics, getIntValue()); 1415 } 1416 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1417 setIntValue(C, Val.bitcastToAPInt()); 1418 } 1419 }; 1420 1421 class IntegerLiteral : public Expr, public APIntStorage { 1422 SourceLocation Loc; 1423 1424 /// Construct an empty integer literal. 1425 explicit IntegerLiteral(EmptyShell Empty) 1426 : Expr(IntegerLiteralClass, Empty) { } 1427 1428 public: 1429 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, 1430 // or UnsignedLongLongTy 1431 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1432 SourceLocation l); 1433 1434 /// Returns a new integer literal with value 'V' and type 'type'. 1435 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, 1436 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V 1437 /// \param V - the value that the returned integer literal contains. 1438 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, 1439 QualType type, SourceLocation l); 1440 /// Returns a new empty integer literal. 1441 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); 1442 1443 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1444 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1445 1446 /// Retrieve the location of the literal. 1447 SourceLocation getLocation() const { return Loc; } 1448 1449 void setLocation(SourceLocation Location) { Loc = Location; } 1450 1451 static bool classof(const Stmt *T) { 1452 return T->getStmtClass() == IntegerLiteralClass; 1453 } 1454 1455 // Iterators 1456 child_range children() { 1457 return child_range(child_iterator(), child_iterator()); 1458 } 1459 const_child_range children() const { 1460 return const_child_range(const_child_iterator(), const_child_iterator()); 1461 } 1462 }; 1463 1464 class FixedPointLiteral : public Expr, public APIntStorage { 1465 SourceLocation Loc; 1466 unsigned Scale; 1467 1468 /// \brief Construct an empty integer literal. 1469 explicit FixedPointLiteral(EmptyShell Empty) 1470 : Expr(FixedPointLiteralClass, Empty) {} 1471 1472 public: 1473 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, 1474 SourceLocation l, unsigned Scale); 1475 1476 // Store the int as is without any bit shifting. 1477 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C, 1478 const llvm::APInt &V, 1479 QualType type, SourceLocation l, 1480 unsigned Scale); 1481 1482 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1483 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1484 1485 /// \brief Retrieve the location of the literal. 1486 SourceLocation getLocation() const { return Loc; } 1487 1488 void setLocation(SourceLocation Location) { Loc = Location; } 1489 1490 static bool classof(const Stmt *T) { 1491 return T->getStmtClass() == FixedPointLiteralClass; 1492 } 1493 1494 std::string getValueAsString(unsigned Radix) const; 1495 1496 // Iterators 1497 child_range children() { 1498 return child_range(child_iterator(), child_iterator()); 1499 } 1500 const_child_range children() const { 1501 return const_child_range(const_child_iterator(), const_child_iterator()); 1502 } 1503 }; 1504 1505 class CharacterLiteral : public Expr { 1506 public: 1507 enum CharacterKind { 1508 Ascii, 1509 Wide, 1510 UTF8, 1511 UTF16, 1512 UTF32 1513 }; 1514 1515 private: 1516 unsigned Value; 1517 SourceLocation Loc; 1518 public: 1519 // type should be IntTy 1520 CharacterLiteral(unsigned value, CharacterKind kind, QualType type, 1521 SourceLocation l) 1522 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, 1523 false, false), 1524 Value(value), Loc(l) { 1525 CharacterLiteralBits.Kind = kind; 1526 } 1527 1528 /// Construct an empty character literal. 1529 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } 1530 1531 SourceLocation getLocation() const { return Loc; } 1532 CharacterKind getKind() const { 1533 return static_cast<CharacterKind>(CharacterLiteralBits.Kind); 1534 } 1535 1536 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1537 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1538 1539 unsigned getValue() const { return Value; } 1540 1541 void setLocation(SourceLocation Location) { Loc = Location; } 1542 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } 1543 void setValue(unsigned Val) { Value = Val; } 1544 1545 static bool classof(const Stmt *T) { 1546 return T->getStmtClass() == CharacterLiteralClass; 1547 } 1548 1549 // Iterators 1550 child_range children() { 1551 return child_range(child_iterator(), child_iterator()); 1552 } 1553 const_child_range children() const { 1554 return const_child_range(const_child_iterator(), const_child_iterator()); 1555 } 1556 }; 1557 1558 class FloatingLiteral : public Expr, private APFloatStorage { 1559 SourceLocation Loc; 1560 1561 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, 1562 QualType Type, SourceLocation L); 1563 1564 /// Construct an empty floating-point literal. 1565 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); 1566 1567 public: 1568 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, 1569 bool isexact, QualType Type, SourceLocation L); 1570 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); 1571 1572 llvm::APFloat getValue() const { 1573 return APFloatStorage::getValue(getSemantics()); 1574 } 1575 void setValue(const ASTContext &C, const llvm::APFloat &Val) { 1576 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); 1577 APFloatStorage::setValue(C, Val); 1578 } 1579 1580 /// Get a raw enumeration value representing the floating-point semantics of 1581 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1582 llvm::APFloatBase::Semantics getRawSemantics() const { 1583 return static_cast<llvm::APFloatBase::Semantics>( 1584 FloatingLiteralBits.Semantics); 1585 } 1586 1587 /// Set the raw enumeration value representing the floating-point semantics of 1588 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. 1589 void setRawSemantics(llvm::APFloatBase::Semantics Sem) { 1590 FloatingLiteralBits.Semantics = Sem; 1591 } 1592 1593 /// Return the APFloat semantics this literal uses. 1594 const llvm::fltSemantics &getSemantics() const { 1595 return llvm::APFloatBase::EnumToSemantics( 1596 static_cast<llvm::APFloatBase::Semantics>( 1597 FloatingLiteralBits.Semantics)); 1598 } 1599 1600 /// Set the APFloat semantics this literal uses. 1601 void setSemantics(const llvm::fltSemantics &Sem) { 1602 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem); 1603 } 1604 1605 bool isExact() const { return FloatingLiteralBits.IsExact; } 1606 void setExact(bool E) { FloatingLiteralBits.IsExact = E; } 1607 1608 /// getValueAsApproximateDouble - This returns the value as an inaccurate 1609 /// double. Note that this may cause loss of precision, but is useful for 1610 /// debugging dumps, etc. 1611 double getValueAsApproximateDouble() const; 1612 1613 SourceLocation getLocation() const { return Loc; } 1614 void setLocation(SourceLocation L) { Loc = L; } 1615 1616 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; } 1617 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; } 1618 1619 static bool classof(const Stmt *T) { 1620 return T->getStmtClass() == FloatingLiteralClass; 1621 } 1622 1623 // Iterators 1624 child_range children() { 1625 return child_range(child_iterator(), child_iterator()); 1626 } 1627 const_child_range children() const { 1628 return const_child_range(const_child_iterator(), const_child_iterator()); 1629 } 1630 }; 1631 1632 /// ImaginaryLiteral - We support imaginary integer and floating point literals, 1633 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and 1634 /// IntegerLiteral classes. Instances of this class always have a Complex type 1635 /// whose element type matches the subexpression. 1636 /// 1637 class ImaginaryLiteral : public Expr { 1638 Stmt *Val; 1639 public: 1640 ImaginaryLiteral(Expr *val, QualType Ty) 1641 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, 1642 false, false), 1643 Val(val) {} 1644 1645 /// Build an empty imaginary literal. 1646 explicit ImaginaryLiteral(EmptyShell Empty) 1647 : Expr(ImaginaryLiteralClass, Empty) { } 1648 1649 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1650 Expr *getSubExpr() { return cast<Expr>(Val); } 1651 void setSubExpr(Expr *E) { Val = E; } 1652 1653 SourceLocation getBeginLoc() const LLVM_READONLY { 1654 return Val->getBeginLoc(); 1655 } 1656 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); } 1657 1658 static bool classof(const Stmt *T) { 1659 return T->getStmtClass() == ImaginaryLiteralClass; 1660 } 1661 1662 // Iterators 1663 child_range children() { return child_range(&Val, &Val+1); } 1664 const_child_range children() const { 1665 return const_child_range(&Val, &Val + 1); 1666 } 1667 }; 1668 1669 /// StringLiteral - This represents a string literal expression, e.g. "foo" 1670 /// or L"bar" (wide strings). The actual string data can be obtained with 1671 /// getBytes() and is NOT null-terminated. The length of the string data is 1672 /// determined by calling getByteLength(). 1673 /// 1674 /// The C type for a string is always a ConstantArrayType. In C++, the char 1675 /// type is const qualified, in C it is not. 1676 /// 1677 /// Note that strings in C can be formed by concatenation of multiple string 1678 /// literal pptokens in translation phase #6. This keeps track of the locations 1679 /// of each of these pieces. 1680 /// 1681 /// Strings in C can also be truncated and extended by assigning into arrays, 1682 /// e.g. with constructs like: 1683 /// char X[2] = "foobar"; 1684 /// In this case, getByteLength() will return 6, but the string literal will 1685 /// have type "char[2]". 1686 class StringLiteral final 1687 : public Expr, 1688 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation, 1689 char> { 1690 friend class ASTStmtReader; 1691 friend TrailingObjects; 1692 1693 /// StringLiteral is followed by several trailing objects. They are in order: 1694 /// 1695 /// * A single unsigned storing the length in characters of this string. The 1696 /// length in bytes is this length times the width of a single character. 1697 /// Always present and stored as a trailing objects because storing it in 1698 /// StringLiteral would increase the size of StringLiteral by sizeof(void *) 1699 /// due to alignment requirements. If you add some data to StringLiteral, 1700 /// consider moving it inside StringLiteral. 1701 /// 1702 /// * An array of getNumConcatenated() SourceLocation, one for each of the 1703 /// token this string is made of. 1704 /// 1705 /// * An array of getByteLength() char used to store the string data. 1706 1707 public: 1708 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 }; 1709 1710 private: 1711 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; } 1712 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { 1713 return getNumConcatenated(); 1714 } 1715 1716 unsigned numTrailingObjects(OverloadToken<char>) const { 1717 return getByteLength(); 1718 } 1719 1720 char *getStrDataAsChar() { return getTrailingObjects<char>(); } 1721 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); } 1722 1723 const uint16_t *getStrDataAsUInt16() const { 1724 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>()); 1725 } 1726 1727 const uint32_t *getStrDataAsUInt32() const { 1728 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>()); 1729 } 1730 1731 /// Build a string literal. 1732 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind, 1733 bool Pascal, QualType Ty, const SourceLocation *Loc, 1734 unsigned NumConcatenated); 1735 1736 /// Build an empty string literal. 1737 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length, 1738 unsigned CharByteWidth); 1739 1740 /// Map a target and string kind to the appropriate character width. 1741 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK); 1742 1743 /// Set one of the string literal token. 1744 void setStrTokenLoc(unsigned TokNum, SourceLocation L) { 1745 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1746 getTrailingObjects<SourceLocation>()[TokNum] = L; 1747 } 1748 1749 public: 1750 /// This is the "fully general" constructor that allows representation of 1751 /// strings formed from multiple concatenated tokens. 1752 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1753 StringKind Kind, bool Pascal, QualType Ty, 1754 const SourceLocation *Loc, 1755 unsigned NumConcatenated); 1756 1757 /// Simple constructor for string literals made from one token. 1758 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, 1759 StringKind Kind, bool Pascal, QualType Ty, 1760 SourceLocation Loc) { 1761 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1); 1762 } 1763 1764 /// Construct an empty string literal. 1765 static StringLiteral *CreateEmpty(const ASTContext &Ctx, 1766 unsigned NumConcatenated, unsigned Length, 1767 unsigned CharByteWidth); 1768 1769 StringRef getString() const { 1770 assert(getCharByteWidth() == 1 && 1771 "This function is used in places that assume strings use char"); 1772 return StringRef(getStrDataAsChar(), getByteLength()); 1773 } 1774 1775 /// Allow access to clients that need the byte representation, such as 1776 /// ASTWriterStmt::VisitStringLiteral(). 1777 StringRef getBytes() const { 1778 // FIXME: StringRef may not be the right type to use as a result for this. 1779 return StringRef(getStrDataAsChar(), getByteLength()); 1780 } 1781 1782 void outputString(raw_ostream &OS) const; 1783 1784 uint32_t getCodeUnit(size_t i) const { 1785 assert(i < getLength() && "out of bounds access"); 1786 switch (getCharByteWidth()) { 1787 case 1: 1788 return static_cast<unsigned char>(getStrDataAsChar()[i]); 1789 case 2: 1790 return getStrDataAsUInt16()[i]; 1791 case 4: 1792 return getStrDataAsUInt32()[i]; 1793 } 1794 llvm_unreachable("Unsupported character width!"); 1795 } 1796 1797 unsigned getByteLength() const { return getCharByteWidth() * getLength(); } 1798 unsigned getLength() const { return *getTrailingObjects<unsigned>(); } 1799 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; } 1800 1801 StringKind getKind() const { 1802 return static_cast<StringKind>(StringLiteralBits.Kind); 1803 } 1804 1805 bool isAscii() const { return getKind() == Ascii; } 1806 bool isWide() const { return getKind() == Wide; } 1807 bool isUTF8() const { return getKind() == UTF8; } 1808 bool isUTF16() const { return getKind() == UTF16; } 1809 bool isUTF32() const { return getKind() == UTF32; } 1810 bool isPascal() const { return StringLiteralBits.IsPascal; } 1811 1812 bool containsNonAscii() const { 1813 for (auto c : getString()) 1814 if (!isASCII(c)) 1815 return true; 1816 return false; 1817 } 1818 1819 bool containsNonAsciiOrNull() const { 1820 for (auto c : getString()) 1821 if (!isASCII(c) || !c) 1822 return true; 1823 return false; 1824 } 1825 1826 /// getNumConcatenated - Get the number of string literal tokens that were 1827 /// concatenated in translation phase #6 to form this string literal. 1828 unsigned getNumConcatenated() const { 1829 return StringLiteralBits.NumConcatenated; 1830 } 1831 1832 /// Get one of the string literal token. 1833 SourceLocation getStrTokenLoc(unsigned TokNum) const { 1834 assert(TokNum < getNumConcatenated() && "Invalid tok number"); 1835 return getTrailingObjects<SourceLocation>()[TokNum]; 1836 } 1837 1838 /// getLocationOfByte - Return a source location that points to the specified 1839 /// byte of this string literal. 1840 /// 1841 /// Strings are amazingly complex. They can be formed from multiple tokens 1842 /// and can have escape sequences in them in addition to the usual trigraph 1843 /// and escaped newline business. This routine handles this complexity. 1844 /// 1845 SourceLocation 1846 getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 1847 const LangOptions &Features, const TargetInfo &Target, 1848 unsigned *StartToken = nullptr, 1849 unsigned *StartTokenByteOffset = nullptr) const; 1850 1851 typedef const SourceLocation *tokloc_iterator; 1852 1853 tokloc_iterator tokloc_begin() const { 1854 return getTrailingObjects<SourceLocation>(); 1855 } 1856 1857 tokloc_iterator tokloc_end() const { 1858 return getTrailingObjects<SourceLocation>() + getNumConcatenated(); 1859 } 1860 1861 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); } 1862 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); } 1863 1864 static bool classof(const Stmt *T) { 1865 return T->getStmtClass() == StringLiteralClass; 1866 } 1867 1868 // Iterators 1869 child_range children() { 1870 return child_range(child_iterator(), child_iterator()); 1871 } 1872 const_child_range children() const { 1873 return const_child_range(const_child_iterator(), const_child_iterator()); 1874 } 1875 }; 1876 1877 /// [C99 6.4.2.2] - A predefined identifier such as __func__. 1878 class PredefinedExpr final 1879 : public Expr, 1880 private llvm::TrailingObjects<PredefinedExpr, Stmt *> { 1881 friend class ASTStmtReader; 1882 friend TrailingObjects; 1883 1884 // PredefinedExpr is optionally followed by a single trailing 1885 // "Stmt *" for the predefined identifier. It is present if and only if 1886 // hasFunctionName() is true and is always a "StringLiteral *". 1887 1888 public: 1889 enum IdentKind { 1890 Func, 1891 Function, 1892 LFunction, // Same as Function, but as wide string. 1893 FuncDName, 1894 FuncSig, 1895 LFuncSig, // Same as FuncSig, but as as wide string 1896 PrettyFunction, 1897 /// The same as PrettyFunction, except that the 1898 /// 'virtual' keyword is omitted for virtual member functions. 1899 PrettyFunctionNoVirtual 1900 }; 1901 1902 private: 1903 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, 1904 StringLiteral *SL); 1905 1906 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName); 1907 1908 /// True if this PredefinedExpr has storage for a function name. 1909 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; } 1910 1911 void setFunctionName(StringLiteral *SL) { 1912 assert(hasFunctionName() && 1913 "This PredefinedExpr has no storage for a function name!"); 1914 *getTrailingObjects<Stmt *>() = SL; 1915 } 1916 1917 public: 1918 /// Create a PredefinedExpr. 1919 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, 1920 QualType FNTy, IdentKind IK, StringLiteral *SL); 1921 1922 /// Create an empty PredefinedExpr. 1923 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx, 1924 bool HasFunctionName); 1925 1926 IdentKind getIdentKind() const { 1927 return static_cast<IdentKind>(PredefinedExprBits.Kind); 1928 } 1929 1930 SourceLocation getLocation() const { return PredefinedExprBits.Loc; } 1931 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; } 1932 1933 StringLiteral *getFunctionName() { 1934 return hasFunctionName() 1935 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 1936 : nullptr; 1937 } 1938 1939 const StringLiteral *getFunctionName() const { 1940 return hasFunctionName() 1941 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) 1942 : nullptr; 1943 } 1944 1945 static StringRef getIdentKindName(IdentKind IK); 1946 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl); 1947 1948 SourceLocation getBeginLoc() const { return getLocation(); } 1949 SourceLocation getEndLoc() const { return getLocation(); } 1950 1951 static bool classof(const Stmt *T) { 1952 return T->getStmtClass() == PredefinedExprClass; 1953 } 1954 1955 // Iterators 1956 child_range children() { 1957 return child_range(getTrailingObjects<Stmt *>(), 1958 getTrailingObjects<Stmt *>() + hasFunctionName()); 1959 } 1960 1961 const_child_range children() const { 1962 return const_child_range(getTrailingObjects<Stmt *>(), 1963 getTrailingObjects<Stmt *>() + hasFunctionName()); 1964 } 1965 }; 1966 1967 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This 1968 /// AST node is only formed if full location information is requested. 1969 class ParenExpr : public Expr { 1970 SourceLocation L, R; 1971 Stmt *Val; 1972 public: 1973 ParenExpr(SourceLocation l, SourceLocation r, Expr *val) 1974 : Expr(ParenExprClass, val->getType(), 1975 val->getValueKind(), val->getObjectKind(), 1976 val->isTypeDependent(), val->isValueDependent(), 1977 val->isInstantiationDependent(), 1978 val->containsUnexpandedParameterPack()), 1979 L(l), R(r), Val(val) {} 1980 1981 /// Construct an empty parenthesized expression. 1982 explicit ParenExpr(EmptyShell Empty) 1983 : Expr(ParenExprClass, Empty) { } 1984 1985 const Expr *getSubExpr() const { return cast<Expr>(Val); } 1986 Expr *getSubExpr() { return cast<Expr>(Val); } 1987 void setSubExpr(Expr *E) { Val = E; } 1988 1989 SourceLocation getBeginLoc() const LLVM_READONLY { return L; } 1990 SourceLocation getEndLoc() const LLVM_READONLY { return R; } 1991 1992 /// Get the location of the left parentheses '('. 1993 SourceLocation getLParen() const { return L; } 1994 void setLParen(SourceLocation Loc) { L = Loc; } 1995 1996 /// Get the location of the right parentheses ')'. 1997 SourceLocation getRParen() const { return R; } 1998 void setRParen(SourceLocation Loc) { R = Loc; } 1999 2000 static bool classof(const Stmt *T) { 2001 return T->getStmtClass() == ParenExprClass; 2002 } 2003 2004 // Iterators 2005 child_range children() { return child_range(&Val, &Val+1); } 2006 const_child_range children() const { 2007 return const_child_range(&Val, &Val + 1); 2008 } 2009 }; 2010 2011 /// UnaryOperator - This represents the unary-expression's (except sizeof and 2012 /// alignof), the postinc/postdec operators from postfix-expression, and various 2013 /// extensions. 2014 /// 2015 /// Notes on various nodes: 2016 /// 2017 /// Real/Imag - These return the real/imag part of a complex operand. If 2018 /// applied to a non-complex value, the former returns its operand and the 2019 /// later returns zero in the type of the operand. 2020 /// 2021 class UnaryOperator : public Expr { 2022 Stmt *Val; 2023 2024 public: 2025 typedef UnaryOperatorKind Opcode; 2026 2027 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK, 2028 ExprObjectKind OK, SourceLocation l, bool CanOverflow) 2029 : Expr(UnaryOperatorClass, type, VK, OK, 2030 input->isTypeDependent() || type->isDependentType(), 2031 input->isValueDependent(), 2032 (input->isInstantiationDependent() || 2033 type->isInstantiationDependentType()), 2034 input->containsUnexpandedParameterPack()), 2035 Val(input) { 2036 UnaryOperatorBits.Opc = opc; 2037 UnaryOperatorBits.CanOverflow = CanOverflow; 2038 UnaryOperatorBits.Loc = l; 2039 } 2040 2041 /// Build an empty unary operator. 2042 explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) { 2043 UnaryOperatorBits.Opc = UO_AddrOf; 2044 } 2045 2046 Opcode getOpcode() const { 2047 return static_cast<Opcode>(UnaryOperatorBits.Opc); 2048 } 2049 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; } 2050 2051 Expr *getSubExpr() const { return cast<Expr>(Val); } 2052 void setSubExpr(Expr *E) { Val = E; } 2053 2054 /// getOperatorLoc - Return the location of the operator. 2055 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; } 2056 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; } 2057 2058 /// Returns true if the unary operator can cause an overflow. For instance, 2059 /// signed int i = INT_MAX; i++; 2060 /// signed char c = CHAR_MAX; c++; 2061 /// Due to integer promotions, c++ is promoted to an int before the postfix 2062 /// increment, and the result is an int that cannot overflow. However, i++ 2063 /// can overflow. 2064 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; } 2065 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; } 2066 2067 /// isPostfix - Return true if this is a postfix operation, like x++. 2068 static bool isPostfix(Opcode Op) { 2069 return Op == UO_PostInc || Op == UO_PostDec; 2070 } 2071 2072 /// isPrefix - Return true if this is a prefix operation, like --x. 2073 static bool isPrefix(Opcode Op) { 2074 return Op == UO_PreInc || Op == UO_PreDec; 2075 } 2076 2077 bool isPrefix() const { return isPrefix(getOpcode()); } 2078 bool isPostfix() const { return isPostfix(getOpcode()); } 2079 2080 static bool isIncrementOp(Opcode Op) { 2081 return Op == UO_PreInc || Op == UO_PostInc; 2082 } 2083 bool isIncrementOp() const { 2084 return isIncrementOp(getOpcode()); 2085 } 2086 2087 static bool isDecrementOp(Opcode Op) { 2088 return Op == UO_PreDec || Op == UO_PostDec; 2089 } 2090 bool isDecrementOp() const { 2091 return isDecrementOp(getOpcode()); 2092 } 2093 2094 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } 2095 bool isIncrementDecrementOp() const { 2096 return isIncrementDecrementOp(getOpcode()); 2097 } 2098 2099 static bool isArithmeticOp(Opcode Op) { 2100 return Op >= UO_Plus && Op <= UO_LNot; 2101 } 2102 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } 2103 2104 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 2105 /// corresponds to, e.g. "sizeof" or "[pre]++" 2106 static StringRef getOpcodeStr(Opcode Op); 2107 2108 /// Retrieve the unary opcode that corresponds to the given 2109 /// overloaded operator. 2110 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); 2111 2112 /// Retrieve the overloaded operator kind that corresponds to 2113 /// the given unary opcode. 2114 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 2115 2116 SourceLocation getBeginLoc() const LLVM_READONLY { 2117 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc(); 2118 } 2119 SourceLocation getEndLoc() const LLVM_READONLY { 2120 return isPostfix() ? getOperatorLoc() : Val->getEndLoc(); 2121 } 2122 SourceLocation getExprLoc() const { return getOperatorLoc(); } 2123 2124 static bool classof(const Stmt *T) { 2125 return T->getStmtClass() == UnaryOperatorClass; 2126 } 2127 2128 // Iterators 2129 child_range children() { return child_range(&Val, &Val+1); } 2130 const_child_range children() const { 2131 return const_child_range(&Val, &Val + 1); 2132 } 2133 }; 2134 2135 /// Helper class for OffsetOfExpr. 2136 2137 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 2138 class OffsetOfNode { 2139 public: 2140 /// The kind of offsetof node we have. 2141 enum Kind { 2142 /// An index into an array. 2143 Array = 0x00, 2144 /// A field. 2145 Field = 0x01, 2146 /// A field in a dependent type, known only by its name. 2147 Identifier = 0x02, 2148 /// An implicit indirection through a C++ base class, when the 2149 /// field found is in a base class. 2150 Base = 0x03 2151 }; 2152 2153 private: 2154 enum { MaskBits = 2, Mask = 0x03 }; 2155 2156 /// The source range that covers this part of the designator. 2157 SourceRange Range; 2158 2159 /// The data describing the designator, which comes in three 2160 /// different forms, depending on the lower two bits. 2161 /// - An unsigned index into the array of Expr*'s stored after this node 2162 /// in memory, for [constant-expression] designators. 2163 /// - A FieldDecl*, for references to a known field. 2164 /// - An IdentifierInfo*, for references to a field with a given name 2165 /// when the class type is dependent. 2166 /// - A CXXBaseSpecifier*, for references that look at a field in a 2167 /// base class. 2168 uintptr_t Data; 2169 2170 public: 2171 /// Create an offsetof node that refers to an array element. 2172 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, 2173 SourceLocation RBracketLoc) 2174 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} 2175 2176 /// Create an offsetof node that refers to a field. 2177 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) 2178 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2179 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {} 2180 2181 /// Create an offsetof node that refers to an identifier. 2182 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, 2183 SourceLocation NameLoc) 2184 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), 2185 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {} 2186 2187 /// Create an offsetof node that refers into a C++ base class. 2188 explicit OffsetOfNode(const CXXBaseSpecifier *Base) 2189 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} 2190 2191 /// Determine what kind of offsetof node this is. 2192 Kind getKind() const { return static_cast<Kind>(Data & Mask); } 2193 2194 /// For an array element node, returns the index into the array 2195 /// of expressions. 2196 unsigned getArrayExprIndex() const { 2197 assert(getKind() == Array); 2198 return Data >> 2; 2199 } 2200 2201 /// For a field offsetof node, returns the field. 2202 FieldDecl *getField() const { 2203 assert(getKind() == Field); 2204 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); 2205 } 2206 2207 /// For a field or identifier offsetof node, returns the name of 2208 /// the field. 2209 IdentifierInfo *getFieldName() const; 2210 2211 /// For a base class node, returns the base specifier. 2212 CXXBaseSpecifier *getBase() const { 2213 assert(getKind() == Base); 2214 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); 2215 } 2216 2217 /// Retrieve the source range that covers this offsetof node. 2218 /// 2219 /// For an array element node, the source range contains the locations of 2220 /// the square brackets. For a field or identifier node, the source range 2221 /// contains the location of the period (if there is one) and the 2222 /// identifier. 2223 SourceRange getSourceRange() const LLVM_READONLY { return Range; } 2224 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); } 2225 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); } 2226 }; 2227 2228 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form 2229 /// offsetof(record-type, member-designator). For example, given: 2230 /// @code 2231 /// struct S { 2232 /// float f; 2233 /// double d; 2234 /// }; 2235 /// struct T { 2236 /// int i; 2237 /// struct S s[10]; 2238 /// }; 2239 /// @endcode 2240 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). 2241 2242 class OffsetOfExpr final 2243 : public Expr, 2244 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> { 2245 SourceLocation OperatorLoc, RParenLoc; 2246 // Base type; 2247 TypeSourceInfo *TSInfo; 2248 // Number of sub-components (i.e. instances of OffsetOfNode). 2249 unsigned NumComps; 2250 // Number of sub-expressions (i.e. array subscript expressions). 2251 unsigned NumExprs; 2252 2253 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const { 2254 return NumComps; 2255 } 2256 2257 OffsetOfExpr(const ASTContext &C, QualType type, 2258 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2259 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, 2260 SourceLocation RParenLoc); 2261 2262 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) 2263 : Expr(OffsetOfExprClass, EmptyShell()), 2264 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} 2265 2266 public: 2267 2268 static OffsetOfExpr *Create(const ASTContext &C, QualType type, 2269 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 2270 ArrayRef<OffsetOfNode> comps, 2271 ArrayRef<Expr*> exprs, SourceLocation RParenLoc); 2272 2273 static OffsetOfExpr *CreateEmpty(const ASTContext &C, 2274 unsigned NumComps, unsigned NumExprs); 2275 2276 /// getOperatorLoc - Return the location of the operator. 2277 SourceLocation getOperatorLoc() const { return OperatorLoc; } 2278 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } 2279 2280 /// Return the location of the right parentheses. 2281 SourceLocation getRParenLoc() const { return RParenLoc; } 2282 void setRParenLoc(SourceLocation R) { RParenLoc = R; } 2283 2284 TypeSourceInfo *getTypeSourceInfo() const { 2285 return TSInfo; 2286 } 2287 void setTypeSourceInfo(TypeSourceInfo *tsi) { 2288 TSInfo = tsi; 2289 } 2290 2291 const OffsetOfNode &getComponent(unsigned Idx) const { 2292 assert(Idx < NumComps && "Subscript out of range"); 2293 return getTrailingObjects<OffsetOfNode>()[Idx]; 2294 } 2295 2296 void setComponent(unsigned Idx, OffsetOfNode ON) { 2297 assert(Idx < NumComps && "Subscript out of range"); 2298 getTrailingObjects<OffsetOfNode>()[Idx] = ON; 2299 } 2300 2301 unsigned getNumComponents() const { 2302 return NumComps; 2303 } 2304 2305 Expr* getIndexExpr(unsigned Idx) { 2306 assert(Idx < NumExprs && "Subscript out of range"); 2307 return getTrailingObjects<Expr *>()[Idx]; 2308 } 2309 2310 const Expr *getIndexExpr(unsigned Idx) const { 2311 assert(Idx < NumExprs && "Subscript out of range"); 2312 return getTrailingObjects<Expr *>()[Idx]; 2313 } 2314 2315 void setIndexExpr(unsigned Idx, Expr* E) { 2316 assert(Idx < NumComps && "Subscript out of range"); 2317 getTrailingObjects<Expr *>()[Idx] = E; 2318 } 2319 2320 unsigned getNumExpressions() const { 2321 return NumExprs; 2322 } 2323 2324 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; } 2325 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2326 2327 static bool classof(const Stmt *T) { 2328 return T->getStmtClass() == OffsetOfExprClass; 2329 } 2330 2331 // Iterators 2332 child_range children() { 2333 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); 2334 return child_range(begin, begin + NumExprs); 2335 } 2336 const_child_range children() const { 2337 Stmt *const *begin = 2338 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); 2339 return const_child_range(begin, begin + NumExprs); 2340 } 2341 friend TrailingObjects; 2342 }; 2343 2344 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) 2345 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and 2346 /// vec_step (OpenCL 1.1 6.11.12). 2347 class UnaryExprOrTypeTraitExpr : public Expr { 2348 union { 2349 TypeSourceInfo *Ty; 2350 Stmt *Ex; 2351 } Argument; 2352 SourceLocation OpLoc, RParenLoc; 2353 2354 public: 2355 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, 2356 QualType resultType, SourceLocation op, 2357 SourceLocation rp) : 2358 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, 2359 false, // Never type-dependent (C++ [temp.dep.expr]p3). 2360 // Value-dependent if the argument is type-dependent. 2361 TInfo->getType()->isDependentType(), 2362 TInfo->getType()->isInstantiationDependentType(), 2363 TInfo->getType()->containsUnexpandedParameterPack()), 2364 OpLoc(op), RParenLoc(rp) { 2365 UnaryExprOrTypeTraitExprBits.Kind = ExprKind; 2366 UnaryExprOrTypeTraitExprBits.IsType = true; 2367 Argument.Ty = TInfo; 2368 } 2369 2370 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, 2371 QualType resultType, SourceLocation op, 2372 SourceLocation rp); 2373 2374 /// Construct an empty sizeof/alignof expression. 2375 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) 2376 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } 2377 2378 UnaryExprOrTypeTrait getKind() const { 2379 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); 2380 } 2381 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} 2382 2383 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } 2384 QualType getArgumentType() const { 2385 return getArgumentTypeInfo()->getType(); 2386 } 2387 TypeSourceInfo *getArgumentTypeInfo() const { 2388 assert(isArgumentType() && "calling getArgumentType() when arg is expr"); 2389 return Argument.Ty; 2390 } 2391 Expr *getArgumentExpr() { 2392 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); 2393 return static_cast<Expr*>(Argument.Ex); 2394 } 2395 const Expr *getArgumentExpr() const { 2396 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); 2397 } 2398 2399 void setArgument(Expr *E) { 2400 Argument.Ex = E; 2401 UnaryExprOrTypeTraitExprBits.IsType = false; 2402 } 2403 void setArgument(TypeSourceInfo *TInfo) { 2404 Argument.Ty = TInfo; 2405 UnaryExprOrTypeTraitExprBits.IsType = true; 2406 } 2407 2408 /// Gets the argument type, or the type of the argument expression, whichever 2409 /// is appropriate. 2410 QualType getTypeOfArgument() const { 2411 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); 2412 } 2413 2414 SourceLocation getOperatorLoc() const { return OpLoc; } 2415 void setOperatorLoc(SourceLocation L) { OpLoc = L; } 2416 2417 SourceLocation getRParenLoc() const { return RParenLoc; } 2418 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2419 2420 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; } 2421 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 2422 2423 static bool classof(const Stmt *T) { 2424 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; 2425 } 2426 2427 // Iterators 2428 child_range children(); 2429 const_child_range children() const; 2430 }; 2431 2432 //===----------------------------------------------------------------------===// 2433 // Postfix Operators. 2434 //===----------------------------------------------------------------------===// 2435 2436 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. 2437 class ArraySubscriptExpr : public Expr { 2438 enum { LHS, RHS, END_EXPR }; 2439 Stmt *SubExprs[END_EXPR]; 2440 2441 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); } 2442 2443 public: 2444 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, 2445 ExprValueKind VK, ExprObjectKind OK, 2446 SourceLocation rbracketloc) 2447 : Expr(ArraySubscriptExprClass, t, VK, OK, 2448 lhs->isTypeDependent() || rhs->isTypeDependent(), 2449 lhs->isValueDependent() || rhs->isValueDependent(), 2450 (lhs->isInstantiationDependent() || 2451 rhs->isInstantiationDependent()), 2452 (lhs->containsUnexpandedParameterPack() || 2453 rhs->containsUnexpandedParameterPack())) { 2454 SubExprs[LHS] = lhs; 2455 SubExprs[RHS] = rhs; 2456 ArraySubscriptExprBits.RBracketLoc = rbracketloc; 2457 } 2458 2459 /// Create an empty array subscript expression. 2460 explicit ArraySubscriptExpr(EmptyShell Shell) 2461 : Expr(ArraySubscriptExprClass, Shell) { } 2462 2463 /// An array access can be written A[4] or 4[A] (both are equivalent). 2464 /// - getBase() and getIdx() always present the normalized view: A[4]. 2465 /// In this case getBase() returns "A" and getIdx() returns "4". 2466 /// - getLHS() and getRHS() present the syntactic view. e.g. for 2467 /// 4[A] getLHS() returns "4". 2468 /// Note: Because vector element access is also written A[4] we must 2469 /// predicate the format conversion in getBase and getIdx only on the 2470 /// the type of the RHS, as it is possible for the LHS to be a vector of 2471 /// integer type 2472 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } 2473 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 2474 void setLHS(Expr *E) { SubExprs[LHS] = E; } 2475 2476 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } 2477 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 2478 void setRHS(Expr *E) { SubExprs[RHS] = E; } 2479 2480 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); } 2481 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); } 2482 2483 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); } 2484 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); } 2485 2486 SourceLocation getBeginLoc() const LLVM_READONLY { 2487 return getLHS()->getBeginLoc(); 2488 } 2489 SourceLocation getEndLoc() const { return getRBracketLoc(); } 2490 2491 SourceLocation getRBracketLoc() const { 2492 return ArraySubscriptExprBits.RBracketLoc; 2493 } 2494 void setRBracketLoc(SourceLocation L) { 2495 ArraySubscriptExprBits.RBracketLoc = L; 2496 } 2497 2498 SourceLocation getExprLoc() const LLVM_READONLY { 2499 return getBase()->getExprLoc(); 2500 } 2501 2502 static bool classof(const Stmt *T) { 2503 return T->getStmtClass() == ArraySubscriptExprClass; 2504 } 2505 2506 // Iterators 2507 child_range children() { 2508 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 2509 } 2510 const_child_range children() const { 2511 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 2512 } 2513 }; 2514 2515 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). 2516 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", 2517 /// while its subclasses may represent alternative syntax that (semantically) 2518 /// results in a function call. For example, CXXOperatorCallExpr is 2519 /// a subclass for overloaded operator calls that use operator syntax, e.g., 2520 /// "str1 + str2" to resolve to a function call. 2521 class CallExpr : public Expr { 2522 enum { FN = 0, PREARGS_START = 1 }; 2523 2524 /// The number of arguments in the call expression. 2525 unsigned NumArgs; 2526 2527 /// The location of the right parenthese. This has a different meaning for 2528 /// the derived classes of CallExpr. 2529 SourceLocation RParenLoc; 2530 2531 void updateDependenciesFromArg(Expr *Arg); 2532 2533 // CallExpr store some data in trailing objects. However since CallExpr 2534 // is used a base of other expression classes we cannot use 2535 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic 2536 // and casts. 2537 // 2538 // The trailing objects are in order: 2539 // 2540 // * A single "Stmt *" for the callee expression. 2541 // 2542 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions. 2543 // 2544 // * An array of getNumArgs() "Stmt *" for the argument expressions. 2545 // 2546 // Note that we store the offset in bytes from the this pointer to the start 2547 // of the trailing objects. It would be perfectly possible to compute it 2548 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of 2549 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to 2550 // compute this once and then load the offset from the bit-fields of Stmt, 2551 // instead of re-computing the offset each time the trailing objects are 2552 // accessed. 2553 2554 /// Return a pointer to the start of the trailing array of "Stmt *". 2555 Stmt **getTrailingStmts() { 2556 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) + 2557 CallExprBits.OffsetToTrailingObjects); 2558 } 2559 Stmt *const *getTrailingStmts() const { 2560 return const_cast<CallExpr *>(this)->getTrailingStmts(); 2561 } 2562 2563 /// Map a statement class to the appropriate offset in bytes from the 2564 /// this pointer to the trailing objects. 2565 static unsigned offsetToTrailingObjects(StmtClass SC); 2566 2567 public: 2568 enum class ADLCallKind : bool { NotADL, UsesADL }; 2569 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL; 2570 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL; 2571 2572 protected: 2573 /// Build a call expression, assuming that appropriate storage has been 2574 /// allocated for the trailing objects. 2575 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, 2576 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2577 SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL); 2578 2579 /// Build an empty call expression, for deserialization. 2580 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, 2581 EmptyShell Empty); 2582 2583 /// Return the size in bytes needed for the trailing objects. 2584 /// Used by the derived classes to allocate the right amount of storage. 2585 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) { 2586 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *); 2587 } 2588 2589 Stmt *getPreArg(unsigned I) { 2590 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2591 return getTrailingStmts()[PREARGS_START + I]; 2592 } 2593 const Stmt *getPreArg(unsigned I) const { 2594 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2595 return getTrailingStmts()[PREARGS_START + I]; 2596 } 2597 void setPreArg(unsigned I, Stmt *PreArg) { 2598 assert(I < getNumPreArgs() && "Prearg access out of range!"); 2599 getTrailingStmts()[PREARGS_START + I] = PreArg; 2600 } 2601 2602 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } 2603 2604 public: 2605 /// Create a call expression. Fn is the callee expression, Args is the 2606 /// argument array, Ty is the type of the call expression (which is *not* 2607 /// the return type in general), VK is the value kind of the call expression 2608 /// (lvalue, rvalue, ...), and RParenLoc is the location of the right 2609 /// parenthese in the call expression. MinNumArgs specifies the minimum 2610 /// number of arguments. The actual number of arguments will be the greater 2611 /// of Args.size() and MinNumArgs. This is used in a few places to allocate 2612 /// enough storage for the default arguments. UsesADL specifies whether the 2613 /// callee was found through argument-dependent lookup. 2614 /// 2615 /// Note that you can use CreateTemporary if you need a temporary call 2616 /// expression on the stack. 2617 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn, 2618 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, 2619 SourceLocation RParenLoc, unsigned MinNumArgs = 0, 2620 ADLCallKind UsesADL = NotADL); 2621 2622 /// Create a temporary call expression with no arguments in the memory 2623 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr) 2624 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr): 2625 /// 2626 /// \code{.cpp} 2627 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 2628 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc); 2629 /// \endcode 2630 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty, 2631 ExprValueKind VK, SourceLocation RParenLoc, 2632 ADLCallKind UsesADL = NotADL); 2633 2634 /// Create an empty call expression, for deserialization. 2635 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, 2636 EmptyShell Empty); 2637 2638 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); } 2639 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); } 2640 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; } 2641 2642 ADLCallKind getADLCallKind() const { 2643 return static_cast<ADLCallKind>(CallExprBits.UsesADL); 2644 } 2645 void setADLCallKind(ADLCallKind V = UsesADL) { 2646 CallExprBits.UsesADL = static_cast<bool>(V); 2647 } 2648 bool usesADL() const { return getADLCallKind() == UsesADL; } 2649 2650 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } 2651 const Decl *getCalleeDecl() const { 2652 return getCallee()->getReferencedDeclOfCallee(); 2653 } 2654 2655 /// If the callee is a FunctionDecl, return it. Otherwise return null. 2656 FunctionDecl *getDirectCallee() { 2657 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 2658 } 2659 const FunctionDecl *getDirectCallee() const { 2660 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 2661 } 2662 2663 /// getNumArgs - Return the number of actual arguments to this call. 2664 unsigned getNumArgs() const { return NumArgs; } 2665 2666 /// Retrieve the call arguments. 2667 Expr **getArgs() { 2668 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START + 2669 getNumPreArgs()); 2670 } 2671 const Expr *const *getArgs() const { 2672 return reinterpret_cast<const Expr *const *>( 2673 getTrailingStmts() + PREARGS_START + getNumPreArgs()); 2674 } 2675 2676 /// getArg - Return the specified argument. 2677 Expr *getArg(unsigned Arg) { 2678 assert(Arg < getNumArgs() && "Arg access out of range!"); 2679 return getArgs()[Arg]; 2680 } 2681 const Expr *getArg(unsigned Arg) const { 2682 assert(Arg < getNumArgs() && "Arg access out of range!"); 2683 return getArgs()[Arg]; 2684 } 2685 2686 /// setArg - Set the specified argument. 2687 void setArg(unsigned Arg, Expr *ArgExpr) { 2688 assert(Arg < getNumArgs() && "Arg access out of range!"); 2689 getArgs()[Arg] = ArgExpr; 2690 } 2691 2692 /// Reduce the number of arguments in this call expression. This is used for 2693 /// example during error recovery to drop extra arguments. There is no way 2694 /// to perform the opposite because: 1.) We don't track how much storage 2695 /// we have for the argument array 2.) This would potentially require growing 2696 /// the argument array, something we cannot support since the arguments are 2697 /// stored in a trailing array. 2698 void shrinkNumArgs(unsigned NewNumArgs) { 2699 assert((NewNumArgs <= getNumArgs()) && 2700 "shrinkNumArgs cannot increase the number of arguments!"); 2701 NumArgs = NewNumArgs; 2702 } 2703 2704 /// Bluntly set a new number of arguments without doing any checks whatsoever. 2705 /// Only used during construction of a CallExpr in a few places in Sema. 2706 /// FIXME: Find a way to remove it. 2707 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; } 2708 2709 typedef ExprIterator arg_iterator; 2710 typedef ConstExprIterator const_arg_iterator; 2711 typedef llvm::iterator_range<arg_iterator> arg_range; 2712 typedef llvm::iterator_range<const_arg_iterator> const_arg_range; 2713 2714 arg_range arguments() { return arg_range(arg_begin(), arg_end()); } 2715 const_arg_range arguments() const { 2716 return const_arg_range(arg_begin(), arg_end()); 2717 } 2718 2719 arg_iterator arg_begin() { 2720 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 2721 } 2722 arg_iterator arg_end() { return arg_begin() + getNumArgs(); } 2723 2724 const_arg_iterator arg_begin() const { 2725 return getTrailingStmts() + PREARGS_START + getNumPreArgs(); 2726 } 2727 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); } 2728 2729 /// This method provides fast access to all the subexpressions of 2730 /// a CallExpr without going through the slower virtual child_iterator 2731 /// interface. This provides efficient reverse iteration of the 2732 /// subexpressions. This is currently used for CFG construction. 2733 ArrayRef<Stmt *> getRawSubExprs() { 2734 return llvm::makeArrayRef(getTrailingStmts(), 2735 PREARGS_START + getNumPreArgs() + getNumArgs()); 2736 } 2737 2738 /// getNumCommas - Return the number of commas that must have been present in 2739 /// this function call. 2740 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; } 2741 2742 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID 2743 /// of the callee. If not, return 0. 2744 unsigned getBuiltinCallee() const; 2745 2746 /// Returns \c true if this is a call to a builtin which does not 2747 /// evaluate side-effects within its arguments. 2748 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; 2749 2750 /// getCallReturnType - Get the return type of the call expr. This is not 2751 /// always the type of the expr itself, if the return type is a reference 2752 /// type. 2753 QualType getCallReturnType(const ASTContext &Ctx) const; 2754 2755 /// Returns the WarnUnusedResultAttr that is either declared on the called 2756 /// function, or its return type declaration. 2757 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const; 2758 2759 /// Returns true if this call expression should warn on unused results. 2760 bool hasUnusedResultAttr(const ASTContext &Ctx) const { 2761 return getUnusedResultAttr(Ctx) != nullptr; 2762 } 2763 2764 SourceLocation getRParenLoc() const { return RParenLoc; } 2765 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2766 2767 SourceLocation getBeginLoc() const LLVM_READONLY; 2768 SourceLocation getEndLoc() const LLVM_READONLY; 2769 2770 /// Return true if this is a call to __assume() or __builtin_assume() with 2771 /// a non-value-dependent constant parameter evaluating as false. 2772 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const; 2773 2774 bool isCallToStdMove() const { 2775 const FunctionDecl *FD = getDirectCallee(); 2776 return getNumArgs() == 1 && FD && FD->isInStdNamespace() && 2777 FD->getIdentifier() && FD->getIdentifier()->isStr("move"); 2778 } 2779 2780 static bool classof(const Stmt *T) { 2781 return T->getStmtClass() >= firstCallExprConstant && 2782 T->getStmtClass() <= lastCallExprConstant; 2783 } 2784 2785 // Iterators 2786 child_range children() { 2787 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START + 2788 getNumPreArgs() + getNumArgs()); 2789 } 2790 2791 const_child_range children() const { 2792 return const_child_range(getTrailingStmts(), 2793 getTrailingStmts() + PREARGS_START + 2794 getNumPreArgs() + getNumArgs()); 2795 } 2796 }; 2797 2798 /// Extra data stored in some MemberExpr objects. 2799 struct MemberExprNameQualifier { 2800 /// The nested-name-specifier that qualifies the name, including 2801 /// source-location information. 2802 NestedNameSpecifierLoc QualifierLoc; 2803 2804 /// The DeclAccessPair through which the MemberDecl was found due to 2805 /// name qualifiers. 2806 DeclAccessPair FoundDecl; 2807 }; 2808 2809 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. 2810 /// 2811 class MemberExpr final 2812 : public Expr, 2813 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier, 2814 ASTTemplateKWAndArgsInfo, 2815 TemplateArgumentLoc> { 2816 friend class ASTReader; 2817 friend class ASTStmtReader; 2818 friend class ASTStmtWriter; 2819 friend TrailingObjects; 2820 2821 /// Base - the expression for the base pointer or structure references. In 2822 /// X.F, this is "X". 2823 Stmt *Base; 2824 2825 /// MemberDecl - This is the decl being referenced by the field/member name. 2826 /// In X.F, this is the decl referenced by F. 2827 ValueDecl *MemberDecl; 2828 2829 /// MemberDNLoc - Provides source/type location info for the 2830 /// declaration name embedded in MemberDecl. 2831 DeclarationNameLoc MemberDNLoc; 2832 2833 /// MemberLoc - This is the location of the member name. 2834 SourceLocation MemberLoc; 2835 2836 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const { 2837 return hasQualifierOrFoundDecl(); 2838 } 2839 2840 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { 2841 return hasTemplateKWAndArgsInfo(); 2842 } 2843 2844 bool hasQualifierOrFoundDecl() const { 2845 return MemberExprBits.HasQualifierOrFoundDecl; 2846 } 2847 2848 bool hasTemplateKWAndArgsInfo() const { 2849 return MemberExprBits.HasTemplateKWAndArgsInfo; 2850 } 2851 2852 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, 2853 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo, 2854 QualType T, ExprValueKind VK, ExprObjectKind OK, 2855 NonOdrUseReason NOUR); 2856 MemberExpr(EmptyShell Empty) 2857 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {} 2858 2859 public: 2860 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow, 2861 SourceLocation OperatorLoc, 2862 NestedNameSpecifierLoc QualifierLoc, 2863 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, 2864 DeclAccessPair FoundDecl, 2865 DeclarationNameInfo MemberNameInfo, 2866 const TemplateArgumentListInfo *TemplateArgs, 2867 QualType T, ExprValueKind VK, ExprObjectKind OK, 2868 NonOdrUseReason NOUR); 2869 2870 /// Create an implicit MemberExpr, with no location, qualifier, template 2871 /// arguments, and so on. Suitable only for non-static member access. 2872 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base, 2873 bool IsArrow, ValueDecl *MemberDecl, 2874 QualType T, ExprValueKind VK, 2875 ExprObjectKind OK) { 2876 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(), 2877 SourceLocation(), MemberDecl, 2878 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()), 2879 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None); 2880 } 2881 2882 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, 2883 bool HasFoundDecl, 2884 bool HasTemplateKWAndArgsInfo, 2885 unsigned NumTemplateArgs); 2886 2887 void setBase(Expr *E) { Base = E; } 2888 Expr *getBase() const { return cast<Expr>(Base); } 2889 2890 /// Retrieve the member declaration to which this expression refers. 2891 /// 2892 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for 2893 /// static data members), a CXXMethodDecl, or an EnumConstantDecl. 2894 ValueDecl *getMemberDecl() const { return MemberDecl; } 2895 void setMemberDecl(ValueDecl *D) { MemberDecl = D; } 2896 2897 /// Retrieves the declaration found by lookup. 2898 DeclAccessPair getFoundDecl() const { 2899 if (!hasQualifierOrFoundDecl()) 2900 return DeclAccessPair::make(getMemberDecl(), 2901 getMemberDecl()->getAccess()); 2902 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl; 2903 } 2904 2905 /// Determines whether this member expression actually had 2906 /// a C++ nested-name-specifier prior to the name of the member, e.g., 2907 /// x->Base::foo. 2908 bool hasQualifier() const { return getQualifier() != nullptr; } 2909 2910 /// If the member name was qualified, retrieves the 2911 /// nested-name-specifier that precedes the member name, with source-location 2912 /// information. 2913 NestedNameSpecifierLoc getQualifierLoc() const { 2914 if (!hasQualifierOrFoundDecl()) 2915 return NestedNameSpecifierLoc(); 2916 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc; 2917 } 2918 2919 /// If the member name was qualified, retrieves the 2920 /// nested-name-specifier that precedes the member name. Otherwise, returns 2921 /// NULL. 2922 NestedNameSpecifier *getQualifier() const { 2923 return getQualifierLoc().getNestedNameSpecifier(); 2924 } 2925 2926 /// Retrieve the location of the template keyword preceding 2927 /// the member name, if any. 2928 SourceLocation getTemplateKeywordLoc() const { 2929 if (!hasTemplateKWAndArgsInfo()) 2930 return SourceLocation(); 2931 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; 2932 } 2933 2934 /// Retrieve the location of the left angle bracket starting the 2935 /// explicit template argument list following the member name, if any. 2936 SourceLocation getLAngleLoc() const { 2937 if (!hasTemplateKWAndArgsInfo()) 2938 return SourceLocation(); 2939 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; 2940 } 2941 2942 /// Retrieve the location of the right angle bracket ending the 2943 /// explicit template argument list following the member name, if any. 2944 SourceLocation getRAngleLoc() const { 2945 if (!hasTemplateKWAndArgsInfo()) 2946 return SourceLocation(); 2947 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; 2948 } 2949 2950 /// Determines whether the member name was preceded by the template keyword. 2951 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 2952 2953 /// Determines whether the member name was followed by an 2954 /// explicit template argument list. 2955 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } 2956 2957 /// Copies the template arguments (if present) into the given 2958 /// structure. 2959 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { 2960 if (hasExplicitTemplateArgs()) 2961 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( 2962 getTrailingObjects<TemplateArgumentLoc>(), List); 2963 } 2964 2965 /// Retrieve the template arguments provided as part of this 2966 /// template-id. 2967 const TemplateArgumentLoc *getTemplateArgs() const { 2968 if (!hasExplicitTemplateArgs()) 2969 return nullptr; 2970 2971 return getTrailingObjects<TemplateArgumentLoc>(); 2972 } 2973 2974 /// Retrieve the number of template arguments provided as part of this 2975 /// template-id. 2976 unsigned getNumTemplateArgs() const { 2977 if (!hasExplicitTemplateArgs()) 2978 return 0; 2979 2980 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; 2981 } 2982 2983 ArrayRef<TemplateArgumentLoc> template_arguments() const { 2984 return {getTemplateArgs(), getNumTemplateArgs()}; 2985 } 2986 2987 /// Retrieve the member declaration name info. 2988 DeclarationNameInfo getMemberNameInfo() const { 2989 return DeclarationNameInfo(MemberDecl->getDeclName(), 2990 MemberLoc, MemberDNLoc); 2991 } 2992 2993 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; } 2994 2995 bool isArrow() const { return MemberExprBits.IsArrow; } 2996 void setArrow(bool A) { MemberExprBits.IsArrow = A; } 2997 2998 /// getMemberLoc - Return the location of the "member", in X->F, it is the 2999 /// location of 'F'. 3000 SourceLocation getMemberLoc() const { return MemberLoc; } 3001 void setMemberLoc(SourceLocation L) { MemberLoc = L; } 3002 3003 SourceLocation getBeginLoc() const LLVM_READONLY; 3004 SourceLocation getEndLoc() const LLVM_READONLY; 3005 3006 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } 3007 3008 /// Determine whether the base of this explicit is implicit. 3009 bool isImplicitAccess() const { 3010 return getBase() && getBase()->isImplicitCXXThis(); 3011 } 3012 3013 /// Returns true if this member expression refers to a method that 3014 /// was resolved from an overloaded set having size greater than 1. 3015 bool hadMultipleCandidates() const { 3016 return MemberExprBits.HadMultipleCandidates; 3017 } 3018 /// Sets the flag telling whether this expression refers to 3019 /// a method that was resolved from an overloaded set having size 3020 /// greater than 1. 3021 void setHadMultipleCandidates(bool V = true) { 3022 MemberExprBits.HadMultipleCandidates = V; 3023 } 3024 3025 /// Returns true if virtual dispatch is performed. 3026 /// If the member access is fully qualified, (i.e. X::f()), virtual 3027 /// dispatching is not performed. In -fapple-kext mode qualified 3028 /// calls to virtual method will still go through the vtable. 3029 bool performsVirtualDispatch(const LangOptions &LO) const { 3030 return LO.AppleKext || !hasQualifier(); 3031 } 3032 3033 /// Is this expression a non-odr-use reference, and if so, why? 3034 /// This is only meaningful if the named member is a static member. 3035 NonOdrUseReason isNonOdrUse() const { 3036 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason); 3037 } 3038 3039 static bool classof(const Stmt *T) { 3040 return T->getStmtClass() == MemberExprClass; 3041 } 3042 3043 // Iterators 3044 child_range children() { return child_range(&Base, &Base+1); } 3045 const_child_range children() const { 3046 return const_child_range(&Base, &Base + 1); 3047 } 3048 }; 3049 3050 /// CompoundLiteralExpr - [C99 6.5.2.5] 3051 /// 3052 class CompoundLiteralExpr : public Expr { 3053 /// LParenLoc - If non-null, this is the location of the left paren in a 3054 /// compound literal like "(int){4}". This can be null if this is a 3055 /// synthesized compound expression. 3056 SourceLocation LParenLoc; 3057 3058 /// The type as written. This can be an incomplete array type, in 3059 /// which case the actual expression type will be different. 3060 /// The int part of the pair stores whether this expr is file scope. 3061 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; 3062 Stmt *Init; 3063 public: 3064 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, 3065 QualType T, ExprValueKind VK, Expr *init, bool fileScope) 3066 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, 3067 tinfo->getType()->isDependentType(), 3068 init->isValueDependent(), 3069 (init->isInstantiationDependent() || 3070 tinfo->getType()->isInstantiationDependentType()), 3071 init->containsUnexpandedParameterPack()), 3072 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} 3073 3074 /// Construct an empty compound literal. 3075 explicit CompoundLiteralExpr(EmptyShell Empty) 3076 : Expr(CompoundLiteralExprClass, Empty) { } 3077 3078 const Expr *getInitializer() const { return cast<Expr>(Init); } 3079 Expr *getInitializer() { return cast<Expr>(Init); } 3080 void setInitializer(Expr *E) { Init = E; } 3081 3082 bool isFileScope() const { return TInfoAndScope.getInt(); } 3083 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } 3084 3085 SourceLocation getLParenLoc() const { return LParenLoc; } 3086 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3087 3088 TypeSourceInfo *getTypeSourceInfo() const { 3089 return TInfoAndScope.getPointer(); 3090 } 3091 void setTypeSourceInfo(TypeSourceInfo *tinfo) { 3092 TInfoAndScope.setPointer(tinfo); 3093 } 3094 3095 SourceLocation getBeginLoc() const LLVM_READONLY { 3096 // FIXME: Init should never be null. 3097 if (!Init) 3098 return SourceLocation(); 3099 if (LParenLoc.isInvalid()) 3100 return Init->getBeginLoc(); 3101 return LParenLoc; 3102 } 3103 SourceLocation getEndLoc() const LLVM_READONLY { 3104 // FIXME: Init should never be null. 3105 if (!Init) 3106 return SourceLocation(); 3107 return Init->getEndLoc(); 3108 } 3109 3110 static bool classof(const Stmt *T) { 3111 return T->getStmtClass() == CompoundLiteralExprClass; 3112 } 3113 3114 // Iterators 3115 child_range children() { return child_range(&Init, &Init+1); } 3116 const_child_range children() const { 3117 return const_child_range(&Init, &Init + 1); 3118 } 3119 }; 3120 3121 /// CastExpr - Base class for type casts, including both implicit 3122 /// casts (ImplicitCastExpr) and explicit casts that have some 3123 /// representation in the source code (ExplicitCastExpr's derived 3124 /// classes). 3125 class CastExpr : public Expr { 3126 Stmt *Op; 3127 3128 bool CastConsistency() const; 3129 3130 const CXXBaseSpecifier * const *path_buffer() const { 3131 return const_cast<CastExpr*>(this)->path_buffer(); 3132 } 3133 CXXBaseSpecifier **path_buffer(); 3134 3135 protected: 3136 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, 3137 Expr *op, unsigned BasePathSize) 3138 : Expr(SC, ty, VK, OK_Ordinary, 3139 // Cast expressions are type-dependent if the type is 3140 // dependent (C++ [temp.dep.expr]p3). 3141 ty->isDependentType(), 3142 // Cast expressions are value-dependent if the type is 3143 // dependent or if the subexpression is value-dependent. 3144 ty->isDependentType() || (op && op->isValueDependent()), 3145 (ty->isInstantiationDependentType() || 3146 (op && op->isInstantiationDependent())), 3147 // An implicit cast expression doesn't (lexically) contain an 3148 // unexpanded pack, even if its target type does. 3149 ((SC != ImplicitCastExprClass && 3150 ty->containsUnexpandedParameterPack()) || 3151 (op && op->containsUnexpandedParameterPack()))), 3152 Op(op) { 3153 CastExprBits.Kind = kind; 3154 CastExprBits.PartOfExplicitCast = false; 3155 CastExprBits.BasePathSize = BasePathSize; 3156 assert((CastExprBits.BasePathSize == BasePathSize) && 3157 "BasePathSize overflow!"); 3158 assert(CastConsistency()); 3159 } 3160 3161 /// Construct an empty cast. 3162 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) 3163 : Expr(SC, Empty) { 3164 CastExprBits.PartOfExplicitCast = false; 3165 CastExprBits.BasePathSize = BasePathSize; 3166 assert((CastExprBits.BasePathSize == BasePathSize) && 3167 "BasePathSize overflow!"); 3168 } 3169 3170 public: 3171 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } 3172 void setCastKind(CastKind K) { CastExprBits.Kind = K; } 3173 3174 static const char *getCastKindName(CastKind CK); 3175 const char *getCastKindName() const { return getCastKindName(getCastKind()); } 3176 3177 Expr *getSubExpr() { return cast<Expr>(Op); } 3178 const Expr *getSubExpr() const { return cast<Expr>(Op); } 3179 void setSubExpr(Expr *E) { Op = E; } 3180 3181 /// Retrieve the cast subexpression as it was written in the source 3182 /// code, looking through any implicit casts or other intermediate nodes 3183 /// introduced by semantic analysis. 3184 Expr *getSubExprAsWritten(); 3185 const Expr *getSubExprAsWritten() const { 3186 return const_cast<CastExpr *>(this)->getSubExprAsWritten(); 3187 } 3188 3189 /// If this cast applies a user-defined conversion, retrieve the conversion 3190 /// function that it invokes. 3191 NamedDecl *getConversionFunction() const; 3192 3193 typedef CXXBaseSpecifier **path_iterator; 3194 typedef const CXXBaseSpecifier *const *path_const_iterator; 3195 bool path_empty() const { return path_size() == 0; } 3196 unsigned path_size() const { return CastExprBits.BasePathSize; } 3197 path_iterator path_begin() { return path_buffer(); } 3198 path_iterator path_end() { return path_buffer() + path_size(); } 3199 path_const_iterator path_begin() const { return path_buffer(); } 3200 path_const_iterator path_end() const { return path_buffer() + path_size(); } 3201 3202 llvm::iterator_range<path_iterator> path() { 3203 return llvm::make_range(path_begin(), path_end()); 3204 } 3205 llvm::iterator_range<path_const_iterator> path() const { 3206 return llvm::make_range(path_begin(), path_end()); 3207 } 3208 3209 const FieldDecl *getTargetUnionField() const { 3210 assert(getCastKind() == CK_ToUnion); 3211 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType()); 3212 } 3213 3214 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType, 3215 QualType opType); 3216 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD, 3217 QualType opType); 3218 3219 static bool classof(const Stmt *T) { 3220 return T->getStmtClass() >= firstCastExprConstant && 3221 T->getStmtClass() <= lastCastExprConstant; 3222 } 3223 3224 // Iterators 3225 child_range children() { return child_range(&Op, &Op+1); } 3226 const_child_range children() const { return const_child_range(&Op, &Op + 1); } 3227 }; 3228 3229 /// ImplicitCastExpr - Allows us to explicitly represent implicit type 3230 /// conversions, which have no direct representation in the original 3231 /// source code. For example: converting T[]->T*, void f()->void 3232 /// (*f)(), float->double, short->int, etc. 3233 /// 3234 /// In C, implicit casts always produce rvalues. However, in C++, an 3235 /// implicit cast whose result is being bound to a reference will be 3236 /// an lvalue or xvalue. For example: 3237 /// 3238 /// @code 3239 /// class Base { }; 3240 /// class Derived : public Base { }; 3241 /// Derived &&ref(); 3242 /// void f(Derived d) { 3243 /// Base& b = d; // initializer is an ImplicitCastExpr 3244 /// // to an lvalue of type Base 3245 /// Base&& r = ref(); // initializer is an ImplicitCastExpr 3246 /// // to an xvalue of type Base 3247 /// } 3248 /// @endcode 3249 class ImplicitCastExpr final 3250 : public CastExpr, 3251 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> { 3252 3253 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, 3254 unsigned BasePathLength, ExprValueKind VK) 3255 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { } 3256 3257 /// Construct an empty implicit cast. 3258 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) 3259 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } 3260 3261 public: 3262 enum OnStack_t { OnStack }; 3263 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, 3264 ExprValueKind VK) 3265 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { 3266 } 3267 3268 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; } 3269 void setIsPartOfExplicitCast(bool PartOfExplicitCast) { 3270 CastExprBits.PartOfExplicitCast = PartOfExplicitCast; 3271 } 3272 3273 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, 3274 CastKind Kind, Expr *Operand, 3275 const CXXCastPath *BasePath, 3276 ExprValueKind Cat); 3277 3278 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, 3279 unsigned PathSize); 3280 3281 SourceLocation getBeginLoc() const LLVM_READONLY { 3282 return getSubExpr()->getBeginLoc(); 3283 } 3284 SourceLocation getEndLoc() const LLVM_READONLY { 3285 return getSubExpr()->getEndLoc(); 3286 } 3287 3288 static bool classof(const Stmt *T) { 3289 return T->getStmtClass() == ImplicitCastExprClass; 3290 } 3291 3292 friend TrailingObjects; 3293 friend class CastExpr; 3294 }; 3295 3296 /// ExplicitCastExpr - An explicit cast written in the source 3297 /// code. 3298 /// 3299 /// This class is effectively an abstract class, because it provides 3300 /// the basic representation of an explicitly-written cast without 3301 /// specifying which kind of cast (C cast, functional cast, static 3302 /// cast, etc.) was written; specific derived classes represent the 3303 /// particular style of cast and its location information. 3304 /// 3305 /// Unlike implicit casts, explicit cast nodes have two different 3306 /// types: the type that was written into the source code, and the 3307 /// actual type of the expression as determined by semantic 3308 /// analysis. These types may differ slightly. For example, in C++ one 3309 /// can cast to a reference type, which indicates that the resulting 3310 /// expression will be an lvalue or xvalue. The reference type, however, 3311 /// will not be used as the type of the expression. 3312 class ExplicitCastExpr : public CastExpr { 3313 /// TInfo - Source type info for the (written) type 3314 /// this expression is casting to. 3315 TypeSourceInfo *TInfo; 3316 3317 protected: 3318 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, 3319 CastKind kind, Expr *op, unsigned PathSize, 3320 TypeSourceInfo *writtenTy) 3321 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} 3322 3323 /// Construct an empty explicit cast. 3324 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) 3325 : CastExpr(SC, Shell, PathSize) { } 3326 3327 public: 3328 /// getTypeInfoAsWritten - Returns the type source info for the type 3329 /// that this expression is casting to. 3330 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } 3331 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } 3332 3333 /// getTypeAsWritten - Returns the type that this expression is 3334 /// casting to, as written in the source code. 3335 QualType getTypeAsWritten() const { return TInfo->getType(); } 3336 3337 static bool classof(const Stmt *T) { 3338 return T->getStmtClass() >= firstExplicitCastExprConstant && 3339 T->getStmtClass() <= lastExplicitCastExprConstant; 3340 } 3341 }; 3342 3343 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style 3344 /// cast in C++ (C++ [expr.cast]), which uses the syntax 3345 /// (Type)expr. For example: @c (int)f. 3346 class CStyleCastExpr final 3347 : public ExplicitCastExpr, 3348 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> { 3349 SourceLocation LPLoc; // the location of the left paren 3350 SourceLocation RPLoc; // the location of the right paren 3351 3352 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, 3353 unsigned PathSize, TypeSourceInfo *writtenTy, 3354 SourceLocation l, SourceLocation r) 3355 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, 3356 writtenTy), LPLoc(l), RPLoc(r) {} 3357 3358 /// Construct an empty C-style explicit cast. 3359 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) 3360 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } 3361 3362 public: 3363 static CStyleCastExpr *Create(const ASTContext &Context, QualType T, 3364 ExprValueKind VK, CastKind K, 3365 Expr *Op, const CXXCastPath *BasePath, 3366 TypeSourceInfo *WrittenTy, SourceLocation L, 3367 SourceLocation R); 3368 3369 static CStyleCastExpr *CreateEmpty(const ASTContext &Context, 3370 unsigned PathSize); 3371 3372 SourceLocation getLParenLoc() const { return LPLoc; } 3373 void setLParenLoc(SourceLocation L) { LPLoc = L; } 3374 3375 SourceLocation getRParenLoc() const { return RPLoc; } 3376 void setRParenLoc(SourceLocation L) { RPLoc = L; } 3377 3378 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; } 3379 SourceLocation getEndLoc() const LLVM_READONLY { 3380 return getSubExpr()->getEndLoc(); 3381 } 3382 3383 static bool classof(const Stmt *T) { 3384 return T->getStmtClass() == CStyleCastExprClass; 3385 } 3386 3387 friend TrailingObjects; 3388 friend class CastExpr; 3389 }; 3390 3391 /// A builtin binary operation expression such as "x + y" or "x <= y". 3392 /// 3393 /// This expression node kind describes a builtin binary operation, 3394 /// such as "x + y" for integer values "x" and "y". The operands will 3395 /// already have been converted to appropriate types (e.g., by 3396 /// performing promotions or conversions). 3397 /// 3398 /// In C++, where operators may be overloaded, a different kind of 3399 /// expression node (CXXOperatorCallExpr) is used to express the 3400 /// invocation of an overloaded operator with operator syntax. Within 3401 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is 3402 /// used to store an expression "x + y" depends on the subexpressions 3403 /// for x and y. If neither x or y is type-dependent, and the "+" 3404 /// operator resolves to a built-in operation, BinaryOperator will be 3405 /// used to express the computation (x and y may still be 3406 /// value-dependent). If either x or y is type-dependent, or if the 3407 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will 3408 /// be used to express the computation. 3409 class BinaryOperator : public Expr { 3410 enum { LHS, RHS, END_EXPR }; 3411 Stmt *SubExprs[END_EXPR]; 3412 3413 public: 3414 typedef BinaryOperatorKind Opcode; 3415 3416 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3417 ExprValueKind VK, ExprObjectKind OK, 3418 SourceLocation opLoc, FPOptions FPFeatures) 3419 : Expr(BinaryOperatorClass, ResTy, VK, OK, 3420 lhs->isTypeDependent() || rhs->isTypeDependent(), 3421 lhs->isValueDependent() || rhs->isValueDependent(), 3422 (lhs->isInstantiationDependent() || 3423 rhs->isInstantiationDependent()), 3424 (lhs->containsUnexpandedParameterPack() || 3425 rhs->containsUnexpandedParameterPack())) { 3426 BinaryOperatorBits.Opc = opc; 3427 BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); 3428 BinaryOperatorBits.OpLoc = opLoc; 3429 SubExprs[LHS] = lhs; 3430 SubExprs[RHS] = rhs; 3431 assert(!isCompoundAssignmentOp() && 3432 "Use CompoundAssignOperator for compound assignments"); 3433 } 3434 3435 /// Construct an empty binary operator. 3436 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) { 3437 BinaryOperatorBits.Opc = BO_Comma; 3438 } 3439 3440 SourceLocation getExprLoc() const { return getOperatorLoc(); } 3441 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; } 3442 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; } 3443 3444 Opcode getOpcode() const { 3445 return static_cast<Opcode>(BinaryOperatorBits.Opc); 3446 } 3447 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; } 3448 3449 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3450 void setLHS(Expr *E) { SubExprs[LHS] = E; } 3451 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3452 void setRHS(Expr *E) { SubExprs[RHS] = E; } 3453 3454 SourceLocation getBeginLoc() const LLVM_READONLY { 3455 return getLHS()->getBeginLoc(); 3456 } 3457 SourceLocation getEndLoc() const LLVM_READONLY { 3458 return getRHS()->getEndLoc(); 3459 } 3460 3461 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 3462 /// corresponds to, e.g. "<<=". 3463 static StringRef getOpcodeStr(Opcode Op); 3464 3465 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } 3466 3467 /// Retrieve the binary opcode that corresponds to the given 3468 /// overloaded operator. 3469 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); 3470 3471 /// Retrieve the overloaded operator kind that corresponds to 3472 /// the given binary opcode. 3473 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); 3474 3475 /// predicates to categorize the respective opcodes. 3476 static bool isPtrMemOp(Opcode Opc) { 3477 return Opc == BO_PtrMemD || Opc == BO_PtrMemI; 3478 } 3479 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); } 3480 3481 static bool isMultiplicativeOp(Opcode Opc) { 3482 return Opc >= BO_Mul && Opc <= BO_Rem; 3483 } 3484 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } 3485 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } 3486 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } 3487 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } 3488 bool isShiftOp() const { return isShiftOp(getOpcode()); } 3489 3490 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } 3491 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } 3492 3493 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } 3494 bool isRelationalOp() const { return isRelationalOp(getOpcode()); } 3495 3496 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } 3497 bool isEqualityOp() const { return isEqualityOp(getOpcode()); } 3498 3499 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; } 3500 bool isComparisonOp() const { return isComparisonOp(getOpcode()); } 3501 3502 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; } 3503 bool isCommaOp() const { return isCommaOp(getOpcode()); } 3504 3505 static Opcode negateComparisonOp(Opcode Opc) { 3506 switch (Opc) { 3507 default: 3508 llvm_unreachable("Not a comparison operator."); 3509 case BO_LT: return BO_GE; 3510 case BO_GT: return BO_LE; 3511 case BO_LE: return BO_GT; 3512 case BO_GE: return BO_LT; 3513 case BO_EQ: return BO_NE; 3514 case BO_NE: return BO_EQ; 3515 } 3516 } 3517 3518 static Opcode reverseComparisonOp(Opcode Opc) { 3519 switch (Opc) { 3520 default: 3521 llvm_unreachable("Not a comparison operator."); 3522 case BO_LT: return BO_GT; 3523 case BO_GT: return BO_LT; 3524 case BO_LE: return BO_GE; 3525 case BO_GE: return BO_LE; 3526 case BO_EQ: 3527 case BO_NE: 3528 return Opc; 3529 } 3530 } 3531 3532 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } 3533 bool isLogicalOp() const { return isLogicalOp(getOpcode()); } 3534 3535 static bool isAssignmentOp(Opcode Opc) { 3536 return Opc >= BO_Assign && Opc <= BO_OrAssign; 3537 } 3538 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } 3539 3540 static bool isCompoundAssignmentOp(Opcode Opc) { 3541 return Opc > BO_Assign && Opc <= BO_OrAssign; 3542 } 3543 bool isCompoundAssignmentOp() const { 3544 return isCompoundAssignmentOp(getOpcode()); 3545 } 3546 static Opcode getOpForCompoundAssignment(Opcode Opc) { 3547 assert(isCompoundAssignmentOp(Opc)); 3548 if (Opc >= BO_AndAssign) 3549 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); 3550 else 3551 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); 3552 } 3553 3554 static bool isShiftAssignOp(Opcode Opc) { 3555 return Opc == BO_ShlAssign || Opc == BO_ShrAssign; 3556 } 3557 bool isShiftAssignOp() const { 3558 return isShiftAssignOp(getOpcode()); 3559 } 3560 3561 // Return true if a binary operator using the specified opcode and operands 3562 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized 3563 // integer to a pointer. 3564 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, 3565 Expr *LHS, Expr *RHS); 3566 3567 static bool classof(const Stmt *S) { 3568 return S->getStmtClass() >= firstBinaryOperatorConstant && 3569 S->getStmtClass() <= lastBinaryOperatorConstant; 3570 } 3571 3572 // Iterators 3573 child_range children() { 3574 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3575 } 3576 const_child_range children() const { 3577 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 3578 } 3579 3580 // Set the FP contractability status of this operator. Only meaningful for 3581 // operations on floating point types. 3582 void setFPFeatures(FPOptions F) { 3583 BinaryOperatorBits.FPFeatures = F.getInt(); 3584 } 3585 3586 FPOptions getFPFeatures() const { 3587 return FPOptions(BinaryOperatorBits.FPFeatures); 3588 } 3589 3590 // Get the FP contractability status of this operator. Only meaningful for 3591 // operations on floating point types. 3592 bool isFPContractableWithinStatement() const { 3593 return getFPFeatures().allowFPContractWithinStatement(); 3594 } 3595 3596 // Get the FENV_ACCESS status of this operator. Only meaningful for 3597 // operations on floating point types. 3598 bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); } 3599 3600 protected: 3601 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, 3602 ExprValueKind VK, ExprObjectKind OK, 3603 SourceLocation opLoc, FPOptions FPFeatures, bool dead2) 3604 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, 3605 lhs->isTypeDependent() || rhs->isTypeDependent(), 3606 lhs->isValueDependent() || rhs->isValueDependent(), 3607 (lhs->isInstantiationDependent() || 3608 rhs->isInstantiationDependent()), 3609 (lhs->containsUnexpandedParameterPack() || 3610 rhs->containsUnexpandedParameterPack())) { 3611 BinaryOperatorBits.Opc = opc; 3612 BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); 3613 BinaryOperatorBits.OpLoc = opLoc; 3614 SubExprs[LHS] = lhs; 3615 SubExprs[RHS] = rhs; 3616 } 3617 3618 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { 3619 BinaryOperatorBits.Opc = BO_MulAssign; 3620 } 3621 }; 3622 3623 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep 3624 /// track of the type the operation is performed in. Due to the semantics of 3625 /// these operators, the operands are promoted, the arithmetic performed, an 3626 /// implicit conversion back to the result type done, then the assignment takes 3627 /// place. This captures the intermediate type which the computation is done 3628 /// in. 3629 class CompoundAssignOperator : public BinaryOperator { 3630 QualType ComputationLHSType; 3631 QualType ComputationResultType; 3632 public: 3633 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, 3634 ExprValueKind VK, ExprObjectKind OK, 3635 QualType CompLHSType, QualType CompResultType, 3636 SourceLocation OpLoc, FPOptions FPFeatures) 3637 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, 3638 true), 3639 ComputationLHSType(CompLHSType), 3640 ComputationResultType(CompResultType) { 3641 assert(isCompoundAssignmentOp() && 3642 "Only should be used for compound assignments"); 3643 } 3644 3645 /// Build an empty compound assignment operator expression. 3646 explicit CompoundAssignOperator(EmptyShell Empty) 3647 : BinaryOperator(CompoundAssignOperatorClass, Empty) { } 3648 3649 // The two computation types are the type the LHS is converted 3650 // to for the computation and the type of the result; the two are 3651 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). 3652 QualType getComputationLHSType() const { return ComputationLHSType; } 3653 void setComputationLHSType(QualType T) { ComputationLHSType = T; } 3654 3655 QualType getComputationResultType() const { return ComputationResultType; } 3656 void setComputationResultType(QualType T) { ComputationResultType = T; } 3657 3658 static bool classof(const Stmt *S) { 3659 return S->getStmtClass() == CompoundAssignOperatorClass; 3660 } 3661 }; 3662 3663 /// AbstractConditionalOperator - An abstract base class for 3664 /// ConditionalOperator and BinaryConditionalOperator. 3665 class AbstractConditionalOperator : public Expr { 3666 SourceLocation QuestionLoc, ColonLoc; 3667 friend class ASTStmtReader; 3668 3669 protected: 3670 AbstractConditionalOperator(StmtClass SC, QualType T, 3671 ExprValueKind VK, ExprObjectKind OK, 3672 bool TD, bool VD, bool ID, 3673 bool ContainsUnexpandedParameterPack, 3674 SourceLocation qloc, 3675 SourceLocation cloc) 3676 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), 3677 QuestionLoc(qloc), ColonLoc(cloc) {} 3678 3679 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) 3680 : Expr(SC, Empty) { } 3681 3682 public: 3683 // getCond - Return the expression representing the condition for 3684 // the ?: operator. 3685 Expr *getCond() const; 3686 3687 // getTrueExpr - Return the subexpression representing the value of 3688 // the expression if the condition evaluates to true. 3689 Expr *getTrueExpr() const; 3690 3691 // getFalseExpr - Return the subexpression representing the value of 3692 // the expression if the condition evaluates to false. This is 3693 // the same as getRHS. 3694 Expr *getFalseExpr() const; 3695 3696 SourceLocation getQuestionLoc() const { return QuestionLoc; } 3697 SourceLocation getColonLoc() const { return ColonLoc; } 3698 3699 static bool classof(const Stmt *T) { 3700 return T->getStmtClass() == ConditionalOperatorClass || 3701 T->getStmtClass() == BinaryConditionalOperatorClass; 3702 } 3703 }; 3704 3705 /// ConditionalOperator - The ?: ternary operator. The GNU "missing 3706 /// middle" extension is a BinaryConditionalOperator. 3707 class ConditionalOperator : public AbstractConditionalOperator { 3708 enum { COND, LHS, RHS, END_EXPR }; 3709 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 3710 3711 friend class ASTStmtReader; 3712 public: 3713 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, 3714 SourceLocation CLoc, Expr *rhs, 3715 QualType t, ExprValueKind VK, ExprObjectKind OK) 3716 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, 3717 // FIXME: the type of the conditional operator doesn't 3718 // depend on the type of the conditional, but the standard 3719 // seems to imply that it could. File a bug! 3720 (lhs->isTypeDependent() || rhs->isTypeDependent()), 3721 (cond->isValueDependent() || lhs->isValueDependent() || 3722 rhs->isValueDependent()), 3723 (cond->isInstantiationDependent() || 3724 lhs->isInstantiationDependent() || 3725 rhs->isInstantiationDependent()), 3726 (cond->containsUnexpandedParameterPack() || 3727 lhs->containsUnexpandedParameterPack() || 3728 rhs->containsUnexpandedParameterPack()), 3729 QLoc, CLoc) { 3730 SubExprs[COND] = cond; 3731 SubExprs[LHS] = lhs; 3732 SubExprs[RHS] = rhs; 3733 } 3734 3735 /// Build an empty conditional operator. 3736 explicit ConditionalOperator(EmptyShell Empty) 3737 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } 3738 3739 // getCond - Return the expression representing the condition for 3740 // the ?: operator. 3741 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3742 3743 // getTrueExpr - Return the subexpression representing the value of 3744 // the expression if the condition evaluates to true. 3745 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } 3746 3747 // getFalseExpr - Return the subexpression representing the value of 3748 // the expression if the condition evaluates to false. This is 3749 // the same as getRHS. 3750 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } 3751 3752 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 3753 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 3754 3755 SourceLocation getBeginLoc() const LLVM_READONLY { 3756 return getCond()->getBeginLoc(); 3757 } 3758 SourceLocation getEndLoc() const LLVM_READONLY { 3759 return getRHS()->getEndLoc(); 3760 } 3761 3762 static bool classof(const Stmt *T) { 3763 return T->getStmtClass() == ConditionalOperatorClass; 3764 } 3765 3766 // Iterators 3767 child_range children() { 3768 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 3769 } 3770 const_child_range children() const { 3771 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 3772 } 3773 }; 3774 3775 /// BinaryConditionalOperator - The GNU extension to the conditional 3776 /// operator which allows the middle operand to be omitted. 3777 /// 3778 /// This is a different expression kind on the assumption that almost 3779 /// every client ends up needing to know that these are different. 3780 class BinaryConditionalOperator : public AbstractConditionalOperator { 3781 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; 3782 3783 /// - the common condition/left-hand-side expression, which will be 3784 /// evaluated as the opaque value 3785 /// - the condition, expressed in terms of the opaque value 3786 /// - the left-hand-side, expressed in terms of the opaque value 3787 /// - the right-hand-side 3788 Stmt *SubExprs[NUM_SUBEXPRS]; 3789 OpaqueValueExpr *OpaqueValue; 3790 3791 friend class ASTStmtReader; 3792 public: 3793 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, 3794 Expr *cond, Expr *lhs, Expr *rhs, 3795 SourceLocation qloc, SourceLocation cloc, 3796 QualType t, ExprValueKind VK, ExprObjectKind OK) 3797 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, 3798 (common->isTypeDependent() || rhs->isTypeDependent()), 3799 (common->isValueDependent() || rhs->isValueDependent()), 3800 (common->isInstantiationDependent() || 3801 rhs->isInstantiationDependent()), 3802 (common->containsUnexpandedParameterPack() || 3803 rhs->containsUnexpandedParameterPack()), 3804 qloc, cloc), 3805 OpaqueValue(opaqueValue) { 3806 SubExprs[COMMON] = common; 3807 SubExprs[COND] = cond; 3808 SubExprs[LHS] = lhs; 3809 SubExprs[RHS] = rhs; 3810 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); 3811 } 3812 3813 /// Build an empty conditional operator. 3814 explicit BinaryConditionalOperator(EmptyShell Empty) 3815 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } 3816 3817 /// getCommon - Return the common expression, written to the 3818 /// left of the condition. The opaque value will be bound to the 3819 /// result of this expression. 3820 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } 3821 3822 /// getOpaqueValue - Return the opaque value placeholder. 3823 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } 3824 3825 /// getCond - Return the condition expression; this is defined 3826 /// in terms of the opaque value. 3827 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 3828 3829 /// getTrueExpr - Return the subexpression which will be 3830 /// evaluated if the condition evaluates to true; this is defined 3831 /// in terms of the opaque value. 3832 Expr *getTrueExpr() const { 3833 return cast<Expr>(SubExprs[LHS]); 3834 } 3835 3836 /// getFalseExpr - Return the subexpression which will be 3837 /// evaluated if the condnition evaluates to false; this is 3838 /// defined in terms of the opaque value. 3839 Expr *getFalseExpr() const { 3840 return cast<Expr>(SubExprs[RHS]); 3841 } 3842 3843 SourceLocation getBeginLoc() const LLVM_READONLY { 3844 return getCommon()->getBeginLoc(); 3845 } 3846 SourceLocation getEndLoc() const LLVM_READONLY { 3847 return getFalseExpr()->getEndLoc(); 3848 } 3849 3850 static bool classof(const Stmt *T) { 3851 return T->getStmtClass() == BinaryConditionalOperatorClass; 3852 } 3853 3854 // Iterators 3855 child_range children() { 3856 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 3857 } 3858 const_child_range children() const { 3859 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); 3860 } 3861 }; 3862 3863 inline Expr *AbstractConditionalOperator::getCond() const { 3864 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3865 return co->getCond(); 3866 return cast<BinaryConditionalOperator>(this)->getCond(); 3867 } 3868 3869 inline Expr *AbstractConditionalOperator::getTrueExpr() const { 3870 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3871 return co->getTrueExpr(); 3872 return cast<BinaryConditionalOperator>(this)->getTrueExpr(); 3873 } 3874 3875 inline Expr *AbstractConditionalOperator::getFalseExpr() const { 3876 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) 3877 return co->getFalseExpr(); 3878 return cast<BinaryConditionalOperator>(this)->getFalseExpr(); 3879 } 3880 3881 /// AddrLabelExpr - The GNU address of label extension, representing &&label. 3882 class AddrLabelExpr : public Expr { 3883 SourceLocation AmpAmpLoc, LabelLoc; 3884 LabelDecl *Label; 3885 public: 3886 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, 3887 QualType t) 3888 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, 3889 false), 3890 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} 3891 3892 /// Build an empty address of a label expression. 3893 explicit AddrLabelExpr(EmptyShell Empty) 3894 : Expr(AddrLabelExprClass, Empty) { } 3895 3896 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } 3897 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } 3898 SourceLocation getLabelLoc() const { return LabelLoc; } 3899 void setLabelLoc(SourceLocation L) { LabelLoc = L; } 3900 3901 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; } 3902 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; } 3903 3904 LabelDecl *getLabel() const { return Label; } 3905 void setLabel(LabelDecl *L) { Label = L; } 3906 3907 static bool classof(const Stmt *T) { 3908 return T->getStmtClass() == AddrLabelExprClass; 3909 } 3910 3911 // Iterators 3912 child_range children() { 3913 return child_range(child_iterator(), child_iterator()); 3914 } 3915 const_child_range children() const { 3916 return const_child_range(const_child_iterator(), const_child_iterator()); 3917 } 3918 }; 3919 3920 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). 3921 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and 3922 /// takes the value of the last subexpression. 3923 /// 3924 /// A StmtExpr is always an r-value; values "returned" out of a 3925 /// StmtExpr will be copied. 3926 class StmtExpr : public Expr { 3927 Stmt *SubStmt; 3928 SourceLocation LParenLoc, RParenLoc; 3929 public: 3930 // FIXME: Does type-dependence need to be computed differently? 3931 // FIXME: Do we need to compute instantiation instantiation-dependence for 3932 // statements? (ugh!) 3933 StmtExpr(CompoundStmt *substmt, QualType T, 3934 SourceLocation lp, SourceLocation rp) : 3935 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, 3936 T->isDependentType(), false, false, false), 3937 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } 3938 3939 /// Build an empty statement expression. 3940 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } 3941 3942 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } 3943 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } 3944 void setSubStmt(CompoundStmt *S) { SubStmt = S; } 3945 3946 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; } 3947 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 3948 3949 SourceLocation getLParenLoc() const { return LParenLoc; } 3950 void setLParenLoc(SourceLocation L) { LParenLoc = L; } 3951 SourceLocation getRParenLoc() const { return RParenLoc; } 3952 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3953 3954 static bool classof(const Stmt *T) { 3955 return T->getStmtClass() == StmtExprClass; 3956 } 3957 3958 // Iterators 3959 child_range children() { return child_range(&SubStmt, &SubStmt+1); } 3960 const_child_range children() const { 3961 return const_child_range(&SubStmt, &SubStmt + 1); 3962 } 3963 }; 3964 3965 /// ShuffleVectorExpr - clang-specific builtin-in function 3966 /// __builtin_shufflevector. 3967 /// This AST node represents a operator that does a constant 3968 /// shuffle, similar to LLVM's shufflevector instruction. It takes 3969 /// two vectors and a variable number of constant indices, 3970 /// and returns the appropriately shuffled vector. 3971 class ShuffleVectorExpr : public Expr { 3972 SourceLocation BuiltinLoc, RParenLoc; 3973 3974 // SubExprs - the list of values passed to the __builtin_shufflevector 3975 // function. The first two are vectors, and the rest are constant 3976 // indices. The number of values in this list is always 3977 // 2+the number of indices in the vector type. 3978 Stmt **SubExprs; 3979 unsigned NumExprs; 3980 3981 public: 3982 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, 3983 SourceLocation BLoc, SourceLocation RP); 3984 3985 /// Build an empty vector-shuffle expression. 3986 explicit ShuffleVectorExpr(EmptyShell Empty) 3987 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } 3988 3989 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 3990 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 3991 3992 SourceLocation getRParenLoc() const { return RParenLoc; } 3993 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3994 3995 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 3996 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 3997 3998 static bool classof(const Stmt *T) { 3999 return T->getStmtClass() == ShuffleVectorExprClass; 4000 } 4001 4002 /// getNumSubExprs - Return the size of the SubExprs array. This includes the 4003 /// constant expression, the actual arguments passed in, and the function 4004 /// pointers. 4005 unsigned getNumSubExprs() const { return NumExprs; } 4006 4007 /// Retrieve the array of expressions. 4008 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 4009 4010 /// getExpr - Return the Expr at the specified index. 4011 Expr *getExpr(unsigned Index) { 4012 assert((Index < NumExprs) && "Arg access out of range!"); 4013 return cast<Expr>(SubExprs[Index]); 4014 } 4015 const Expr *getExpr(unsigned Index) const { 4016 assert((Index < NumExprs) && "Arg access out of range!"); 4017 return cast<Expr>(SubExprs[Index]); 4018 } 4019 4020 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); 4021 4022 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { 4023 assert((N < NumExprs - 2) && "Shuffle idx out of range!"); 4024 return getExpr(N+2)->EvaluateKnownConstInt(Ctx); 4025 } 4026 4027 // Iterators 4028 child_range children() { 4029 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); 4030 } 4031 const_child_range children() const { 4032 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); 4033 } 4034 }; 4035 4036 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector 4037 /// This AST node provides support for converting a vector type to another 4038 /// vector type of the same arity. 4039 class ConvertVectorExpr : public Expr { 4040 private: 4041 Stmt *SrcExpr; 4042 TypeSourceInfo *TInfo; 4043 SourceLocation BuiltinLoc, RParenLoc; 4044 4045 friend class ASTReader; 4046 friend class ASTStmtReader; 4047 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} 4048 4049 public: 4050 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType, 4051 ExprValueKind VK, ExprObjectKind OK, 4052 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 4053 : Expr(ConvertVectorExprClass, DstType, VK, OK, 4054 DstType->isDependentType(), 4055 DstType->isDependentType() || SrcExpr->isValueDependent(), 4056 (DstType->isInstantiationDependentType() || 4057 SrcExpr->isInstantiationDependent()), 4058 (DstType->containsUnexpandedParameterPack() || 4059 SrcExpr->containsUnexpandedParameterPack())), 4060 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 4061 4062 /// getSrcExpr - Return the Expr to be converted. 4063 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 4064 4065 /// getTypeSourceInfo - Return the destination type. 4066 TypeSourceInfo *getTypeSourceInfo() const { 4067 return TInfo; 4068 } 4069 void setTypeSourceInfo(TypeSourceInfo *ti) { 4070 TInfo = ti; 4071 } 4072 4073 /// getBuiltinLoc - Return the location of the __builtin_convertvector token. 4074 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4075 4076 /// getRParenLoc - Return the location of final right parenthesis. 4077 SourceLocation getRParenLoc() const { return RParenLoc; } 4078 4079 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4080 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4081 4082 static bool classof(const Stmt *T) { 4083 return T->getStmtClass() == ConvertVectorExprClass; 4084 } 4085 4086 // Iterators 4087 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 4088 const_child_range children() const { 4089 return const_child_range(&SrcExpr, &SrcExpr + 1); 4090 } 4091 }; 4092 4093 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. 4094 /// This AST node is similar to the conditional operator (?:) in C, with 4095 /// the following exceptions: 4096 /// - the test expression must be a integer constant expression. 4097 /// - the expression returned acts like the chosen subexpression in every 4098 /// visible way: the type is the same as that of the chosen subexpression, 4099 /// and all predicates (whether it's an l-value, whether it's an integer 4100 /// constant expression, etc.) return the same result as for the chosen 4101 /// sub-expression. 4102 class ChooseExpr : public Expr { 4103 enum { COND, LHS, RHS, END_EXPR }; 4104 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. 4105 SourceLocation BuiltinLoc, RParenLoc; 4106 bool CondIsTrue; 4107 public: 4108 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, 4109 QualType t, ExprValueKind VK, ExprObjectKind OK, 4110 SourceLocation RP, bool condIsTrue, 4111 bool TypeDependent, bool ValueDependent) 4112 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, 4113 (cond->isInstantiationDependent() || 4114 lhs->isInstantiationDependent() || 4115 rhs->isInstantiationDependent()), 4116 (cond->containsUnexpandedParameterPack() || 4117 lhs->containsUnexpandedParameterPack() || 4118 rhs->containsUnexpandedParameterPack())), 4119 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) { 4120 SubExprs[COND] = cond; 4121 SubExprs[LHS] = lhs; 4122 SubExprs[RHS] = rhs; 4123 } 4124 4125 /// Build an empty __builtin_choose_expr. 4126 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } 4127 4128 /// isConditionTrue - Return whether the condition is true (i.e. not 4129 /// equal to zero). 4130 bool isConditionTrue() const { 4131 assert(!isConditionDependent() && 4132 "Dependent condition isn't true or false"); 4133 return CondIsTrue; 4134 } 4135 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } 4136 4137 bool isConditionDependent() const { 4138 return getCond()->isTypeDependent() || getCond()->isValueDependent(); 4139 } 4140 4141 /// getChosenSubExpr - Return the subexpression chosen according to the 4142 /// condition. 4143 Expr *getChosenSubExpr() const { 4144 return isConditionTrue() ? getLHS() : getRHS(); 4145 } 4146 4147 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } 4148 void setCond(Expr *E) { SubExprs[COND] = E; } 4149 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } 4150 void setLHS(Expr *E) { SubExprs[LHS] = E; } 4151 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } 4152 void setRHS(Expr *E) { SubExprs[RHS] = E; } 4153 4154 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4155 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4156 4157 SourceLocation getRParenLoc() const { return RParenLoc; } 4158 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4159 4160 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4161 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4162 4163 static bool classof(const Stmt *T) { 4164 return T->getStmtClass() == ChooseExprClass; 4165 } 4166 4167 // Iterators 4168 child_range children() { 4169 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); 4170 } 4171 const_child_range children() const { 4172 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); 4173 } 4174 }; 4175 4176 /// GNUNullExpr - Implements the GNU __null extension, which is a name 4177 /// for a null pointer constant that has integral type (e.g., int or 4178 /// long) and is the same size and alignment as a pointer. The __null 4179 /// extension is typically only used by system headers, which define 4180 /// NULL as __null in C++ rather than using 0 (which is an integer 4181 /// that may not match the size of a pointer). 4182 class GNUNullExpr : public Expr { 4183 /// TokenLoc - The location of the __null keyword. 4184 SourceLocation TokenLoc; 4185 4186 public: 4187 GNUNullExpr(QualType Ty, SourceLocation Loc) 4188 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, 4189 false), 4190 TokenLoc(Loc) { } 4191 4192 /// Build an empty GNU __null expression. 4193 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } 4194 4195 /// getTokenLocation - The location of the __null token. 4196 SourceLocation getTokenLocation() const { return TokenLoc; } 4197 void setTokenLocation(SourceLocation L) { TokenLoc = L; } 4198 4199 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; } 4200 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; } 4201 4202 static bool classof(const Stmt *T) { 4203 return T->getStmtClass() == GNUNullExprClass; 4204 } 4205 4206 // Iterators 4207 child_range children() { 4208 return child_range(child_iterator(), child_iterator()); 4209 } 4210 const_child_range children() const { 4211 return const_child_range(const_child_iterator(), const_child_iterator()); 4212 } 4213 }; 4214 4215 /// Represents a call to the builtin function \c __builtin_va_arg. 4216 class VAArgExpr : public Expr { 4217 Stmt *Val; 4218 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo; 4219 SourceLocation BuiltinLoc, RParenLoc; 4220 public: 4221 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, 4222 SourceLocation RPLoc, QualType t, bool IsMS) 4223 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(), 4224 false, (TInfo->getType()->isInstantiationDependentType() || 4225 e->isInstantiationDependent()), 4226 (TInfo->getType()->containsUnexpandedParameterPack() || 4227 e->containsUnexpandedParameterPack())), 4228 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {} 4229 4230 /// Create an empty __builtin_va_arg expression. 4231 explicit VAArgExpr(EmptyShell Empty) 4232 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} 4233 4234 const Expr *getSubExpr() const { return cast<Expr>(Val); } 4235 Expr *getSubExpr() { return cast<Expr>(Val); } 4236 void setSubExpr(Expr *E) { Val = E; } 4237 4238 /// Returns whether this is really a Win64 ABI va_arg expression. 4239 bool isMicrosoftABI() const { return TInfo.getInt(); } 4240 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } 4241 4242 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } 4243 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } 4244 4245 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 4246 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } 4247 4248 SourceLocation getRParenLoc() const { return RParenLoc; } 4249 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 4250 4251 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 4252 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 4253 4254 static bool classof(const Stmt *T) { 4255 return T->getStmtClass() == VAArgExprClass; 4256 } 4257 4258 // Iterators 4259 child_range children() { return child_range(&Val, &Val+1); } 4260 const_child_range children() const { 4261 return const_child_range(&Val, &Val + 1); 4262 } 4263 }; 4264 4265 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), 4266 /// __builtin_FUNCTION(), or __builtin_FILE(). 4267 class SourceLocExpr final : public Expr { 4268 SourceLocation BuiltinLoc, RParenLoc; 4269 DeclContext *ParentContext; 4270 4271 public: 4272 enum IdentKind { Function, File, Line, Column }; 4273 4274 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, 4275 SourceLocation RParenLoc, DeclContext *Context); 4276 4277 /// Build an empty call expression. 4278 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {} 4279 4280 /// Return the result of evaluating this SourceLocExpr in the specified 4281 /// (and possibly null) default argument or initialization context. 4282 APValue EvaluateInContext(const ASTContext &Ctx, 4283 const Expr *DefaultExpr) const; 4284 4285 /// Return a string representing the name of the specific builtin function. 4286 StringRef getBuiltinStr() const; 4287 4288 IdentKind getIdentKind() const { 4289 return static_cast<IdentKind>(SourceLocExprBits.Kind); 4290 } 4291 4292 bool isStringType() const { 4293 switch (getIdentKind()) { 4294 case File: 4295 case Function: 4296 return true; 4297 case Line: 4298 case Column: 4299 return false; 4300 } 4301 llvm_unreachable("unknown source location expression kind"); 4302 } 4303 bool isIntType() const LLVM_READONLY { return !isStringType(); } 4304 4305 /// If the SourceLocExpr has been resolved return the subexpression 4306 /// representing the resolved value. Otherwise return null. 4307 const DeclContext *getParentContext() const { return ParentContext; } 4308 DeclContext *getParentContext() { return ParentContext; } 4309 4310 SourceLocation getLocation() const { return BuiltinLoc; } 4311 SourceLocation getBeginLoc() const { return BuiltinLoc; } 4312 SourceLocation getEndLoc() const { return RParenLoc; } 4313 4314 child_range children() { 4315 return child_range(child_iterator(), child_iterator()); 4316 } 4317 4318 const_child_range children() const { 4319 return const_child_range(child_iterator(), child_iterator()); 4320 } 4321 4322 static bool classof(const Stmt *T) { 4323 return T->getStmtClass() == SourceLocExprClass; 4324 } 4325 4326 private: 4327 friend class ASTStmtReader; 4328 }; 4329 4330 /// Describes an C or C++ initializer list. 4331 /// 4332 /// InitListExpr describes an initializer list, which can be used to 4333 /// initialize objects of different types, including 4334 /// struct/class/union types, arrays, and vectors. For example: 4335 /// 4336 /// @code 4337 /// struct foo x = { 1, { 2, 3 } }; 4338 /// @endcode 4339 /// 4340 /// Prior to semantic analysis, an initializer list will represent the 4341 /// initializer list as written by the user, but will have the 4342 /// placeholder type "void". This initializer list is called the 4343 /// syntactic form of the initializer, and may contain C99 designated 4344 /// initializers (represented as DesignatedInitExprs), initializations 4345 /// of subobject members without explicit braces, and so on. Clients 4346 /// interested in the original syntax of the initializer list should 4347 /// use the syntactic form of the initializer list. 4348 /// 4349 /// After semantic analysis, the initializer list will represent the 4350 /// semantic form of the initializer, where the initializations of all 4351 /// subobjects are made explicit with nested InitListExpr nodes and 4352 /// C99 designators have been eliminated by placing the designated 4353 /// initializations into the subobject they initialize. Additionally, 4354 /// any "holes" in the initialization, where no initializer has been 4355 /// specified for a particular subobject, will be replaced with 4356 /// implicitly-generated ImplicitValueInitExpr expressions that 4357 /// value-initialize the subobjects. Note, however, that the 4358 /// initializer lists may still have fewer initializers than there are 4359 /// elements to initialize within the object. 4360 /// 4361 /// After semantic analysis has completed, given an initializer list, 4362 /// method isSemanticForm() returns true if and only if this is the 4363 /// semantic form of the initializer list (note: the same AST node 4364 /// may at the same time be the syntactic form). 4365 /// Given the semantic form of the initializer list, one can retrieve 4366 /// the syntactic form of that initializer list (when different) 4367 /// using method getSyntacticForm(); the method returns null if applied 4368 /// to a initializer list which is already in syntactic form. 4369 /// Similarly, given the syntactic form (i.e., an initializer list such 4370 /// that isSemanticForm() returns false), one can retrieve the semantic 4371 /// form using method getSemanticForm(). 4372 /// Since many initializer lists have the same syntactic and semantic forms, 4373 /// getSyntacticForm() may return NULL, indicating that the current 4374 /// semantic initializer list also serves as its syntactic form. 4375 class InitListExpr : public Expr { 4376 // FIXME: Eliminate this vector in favor of ASTContext allocation 4377 typedef ASTVector<Stmt *> InitExprsTy; 4378 InitExprsTy InitExprs; 4379 SourceLocation LBraceLoc, RBraceLoc; 4380 4381 /// The alternative form of the initializer list (if it exists). 4382 /// The int part of the pair stores whether this initializer list is 4383 /// in semantic form. If not null, the pointer points to: 4384 /// - the syntactic form, if this is in semantic form; 4385 /// - the semantic form, if this is in syntactic form. 4386 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; 4387 4388 /// Either: 4389 /// If this initializer list initializes an array with more elements than 4390 /// there are initializers in the list, specifies an expression to be used 4391 /// for value initialization of the rest of the elements. 4392 /// Or 4393 /// If this initializer list initializes a union, specifies which 4394 /// field within the union will be initialized. 4395 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; 4396 4397 public: 4398 InitListExpr(const ASTContext &C, SourceLocation lbraceloc, 4399 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); 4400 4401 /// Build an empty initializer list. 4402 explicit InitListExpr(EmptyShell Empty) 4403 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } 4404 4405 unsigned getNumInits() const { return InitExprs.size(); } 4406 4407 /// Retrieve the set of initializers. 4408 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } 4409 4410 /// Retrieve the set of initializers. 4411 Expr * const *getInits() const { 4412 return reinterpret_cast<Expr * const *>(InitExprs.data()); 4413 } 4414 4415 ArrayRef<Expr *> inits() { 4416 return llvm::makeArrayRef(getInits(), getNumInits()); 4417 } 4418 4419 ArrayRef<Expr *> inits() const { 4420 return llvm::makeArrayRef(getInits(), getNumInits()); 4421 } 4422 4423 const Expr *getInit(unsigned Init) const { 4424 assert(Init < getNumInits() && "Initializer access out of range!"); 4425 return cast_or_null<Expr>(InitExprs[Init]); 4426 } 4427 4428 Expr *getInit(unsigned Init) { 4429 assert(Init < getNumInits() && "Initializer access out of range!"); 4430 return cast_or_null<Expr>(InitExprs[Init]); 4431 } 4432 4433 void setInit(unsigned Init, Expr *expr) { 4434 assert(Init < getNumInits() && "Initializer access out of range!"); 4435 InitExprs[Init] = expr; 4436 4437 if (expr) { 4438 ExprBits.TypeDependent |= expr->isTypeDependent(); 4439 ExprBits.ValueDependent |= expr->isValueDependent(); 4440 ExprBits.InstantiationDependent |= expr->isInstantiationDependent(); 4441 ExprBits.ContainsUnexpandedParameterPack |= 4442 expr->containsUnexpandedParameterPack(); 4443 } 4444 } 4445 4446 /// Reserve space for some number of initializers. 4447 void reserveInits(const ASTContext &C, unsigned NumInits); 4448 4449 /// Specify the number of initializers 4450 /// 4451 /// If there are more than @p NumInits initializers, the remaining 4452 /// initializers will be destroyed. If there are fewer than @p 4453 /// NumInits initializers, NULL expressions will be added for the 4454 /// unknown initializers. 4455 void resizeInits(const ASTContext &Context, unsigned NumInits); 4456 4457 /// Updates the initializer at index @p Init with the new 4458 /// expression @p expr, and returns the old expression at that 4459 /// location. 4460 /// 4461 /// When @p Init is out of range for this initializer list, the 4462 /// initializer list will be extended with NULL expressions to 4463 /// accommodate the new entry. 4464 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); 4465 4466 /// If this initializer list initializes an array with more elements 4467 /// than there are initializers in the list, specifies an expression to be 4468 /// used for value initialization of the rest of the elements. 4469 Expr *getArrayFiller() { 4470 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); 4471 } 4472 const Expr *getArrayFiller() const { 4473 return const_cast<InitListExpr *>(this)->getArrayFiller(); 4474 } 4475 void setArrayFiller(Expr *filler); 4476 4477 /// Return true if this is an array initializer and its array "filler" 4478 /// has been set. 4479 bool hasArrayFiller() const { return getArrayFiller(); } 4480 4481 /// If this initializes a union, specifies which field in the 4482 /// union to initialize. 4483 /// 4484 /// Typically, this field is the first named field within the 4485 /// union. However, a designated initializer can specify the 4486 /// initialization of a different field within the union. 4487 FieldDecl *getInitializedFieldInUnion() { 4488 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); 4489 } 4490 const FieldDecl *getInitializedFieldInUnion() const { 4491 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); 4492 } 4493 void setInitializedFieldInUnion(FieldDecl *FD) { 4494 assert((FD == nullptr 4495 || getInitializedFieldInUnion() == nullptr 4496 || getInitializedFieldInUnion() == FD) 4497 && "Only one field of a union may be initialized at a time!"); 4498 ArrayFillerOrUnionFieldInit = FD; 4499 } 4500 4501 // Explicit InitListExpr's originate from source code (and have valid source 4502 // locations). Implicit InitListExpr's are created by the semantic analyzer. 4503 // FIXME: This is wrong; InitListExprs created by semantic analysis have 4504 // valid source locations too! 4505 bool isExplicit() const { 4506 return LBraceLoc.isValid() && RBraceLoc.isValid(); 4507 } 4508 4509 // Is this an initializer for an array of characters, initialized by a string 4510 // literal or an @encode? 4511 bool isStringLiteralInit() const; 4512 4513 /// Is this a transparent initializer list (that is, an InitListExpr that is 4514 /// purely syntactic, and whose semantics are that of the sole contained 4515 /// initializer)? 4516 bool isTransparent() const; 4517 4518 /// Is this the zero initializer {0} in a language which considers it 4519 /// idiomatic? 4520 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; 4521 4522 SourceLocation getLBraceLoc() const { return LBraceLoc; } 4523 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } 4524 SourceLocation getRBraceLoc() const { return RBraceLoc; } 4525 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } 4526 4527 bool isSemanticForm() const { return AltForm.getInt(); } 4528 InitListExpr *getSemanticForm() const { 4529 return isSemanticForm() ? nullptr : AltForm.getPointer(); 4530 } 4531 bool isSyntacticForm() const { 4532 return !AltForm.getInt() || !AltForm.getPointer(); 4533 } 4534 InitListExpr *getSyntacticForm() const { 4535 return isSemanticForm() ? AltForm.getPointer() : nullptr; 4536 } 4537 4538 void setSyntacticForm(InitListExpr *Init) { 4539 AltForm.setPointer(Init); 4540 AltForm.setInt(true); 4541 Init->AltForm.setPointer(this); 4542 Init->AltForm.setInt(false); 4543 } 4544 4545 bool hadArrayRangeDesignator() const { 4546 return InitListExprBits.HadArrayRangeDesignator != 0; 4547 } 4548 void sawArrayRangeDesignator(bool ARD = true) { 4549 InitListExprBits.HadArrayRangeDesignator = ARD; 4550 } 4551 4552 SourceLocation getBeginLoc() const LLVM_READONLY; 4553 SourceLocation getEndLoc() const LLVM_READONLY; 4554 4555 static bool classof(const Stmt *T) { 4556 return T->getStmtClass() == InitListExprClass; 4557 } 4558 4559 // Iterators 4560 child_range children() { 4561 const_child_range CCR = const_cast<const InitListExpr *>(this)->children(); 4562 return child_range(cast_away_const(CCR.begin()), 4563 cast_away_const(CCR.end())); 4564 } 4565 4566 const_child_range children() const { 4567 // FIXME: This does not include the array filler expression. 4568 if (InitExprs.empty()) 4569 return const_child_range(const_child_iterator(), const_child_iterator()); 4570 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); 4571 } 4572 4573 typedef InitExprsTy::iterator iterator; 4574 typedef InitExprsTy::const_iterator const_iterator; 4575 typedef InitExprsTy::reverse_iterator reverse_iterator; 4576 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; 4577 4578 iterator begin() { return InitExprs.begin(); } 4579 const_iterator begin() const { return InitExprs.begin(); } 4580 iterator end() { return InitExprs.end(); } 4581 const_iterator end() const { return InitExprs.end(); } 4582 reverse_iterator rbegin() { return InitExprs.rbegin(); } 4583 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } 4584 reverse_iterator rend() { return InitExprs.rend(); } 4585 const_reverse_iterator rend() const { return InitExprs.rend(); } 4586 4587 friend class ASTStmtReader; 4588 friend class ASTStmtWriter; 4589 }; 4590 4591 /// Represents a C99 designated initializer expression. 4592 /// 4593 /// A designated initializer expression (C99 6.7.8) contains one or 4594 /// more designators (which can be field designators, array 4595 /// designators, or GNU array-range designators) followed by an 4596 /// expression that initializes the field or element(s) that the 4597 /// designators refer to. For example, given: 4598 /// 4599 /// @code 4600 /// struct point { 4601 /// double x; 4602 /// double y; 4603 /// }; 4604 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 4605 /// @endcode 4606 /// 4607 /// The InitListExpr contains three DesignatedInitExprs, the first of 4608 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two 4609 /// designators, one array designator for @c [2] followed by one field 4610 /// designator for @c .y. The initialization expression will be 1.0. 4611 class DesignatedInitExpr final 4612 : public Expr, 4613 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> { 4614 public: 4615 /// Forward declaration of the Designator class. 4616 class Designator; 4617 4618 private: 4619 /// The location of the '=' or ':' prior to the actual initializer 4620 /// expression. 4621 SourceLocation EqualOrColonLoc; 4622 4623 /// Whether this designated initializer used the GNU deprecated 4624 /// syntax rather than the C99 '=' syntax. 4625 unsigned GNUSyntax : 1; 4626 4627 /// The number of designators in this initializer expression. 4628 unsigned NumDesignators : 15; 4629 4630 /// The number of subexpressions of this initializer expression, 4631 /// which contains both the initializer and any additional 4632 /// expressions used by array and array-range designators. 4633 unsigned NumSubExprs : 16; 4634 4635 /// The designators in this designated initialization 4636 /// expression. 4637 Designator *Designators; 4638 4639 DesignatedInitExpr(const ASTContext &C, QualType Ty, 4640 llvm::ArrayRef<Designator> Designators, 4641 SourceLocation EqualOrColonLoc, bool GNUSyntax, 4642 ArrayRef<Expr *> IndexExprs, Expr *Init); 4643 4644 explicit DesignatedInitExpr(unsigned NumSubExprs) 4645 : Expr(DesignatedInitExprClass, EmptyShell()), 4646 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } 4647 4648 public: 4649 /// A field designator, e.g., ".x". 4650 struct FieldDesignator { 4651 /// Refers to the field that is being initialized. The low bit 4652 /// of this field determines whether this is actually a pointer 4653 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When 4654 /// initially constructed, a field designator will store an 4655 /// IdentifierInfo*. After semantic analysis has resolved that 4656 /// name, the field designator will instead store a FieldDecl*. 4657 uintptr_t NameOrField; 4658 4659 /// The location of the '.' in the designated initializer. 4660 unsigned DotLoc; 4661 4662 /// The location of the field name in the designated initializer. 4663 unsigned FieldLoc; 4664 }; 4665 4666 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 4667 struct ArrayOrRangeDesignator { 4668 /// Location of the first index expression within the designated 4669 /// initializer expression's list of subexpressions. 4670 unsigned Index; 4671 /// The location of the '[' starting the array range designator. 4672 unsigned LBracketLoc; 4673 /// The location of the ellipsis separating the start and end 4674 /// indices. Only valid for GNU array-range designators. 4675 unsigned EllipsisLoc; 4676 /// The location of the ']' terminating the array range designator. 4677 unsigned RBracketLoc; 4678 }; 4679 4680 /// Represents a single C99 designator. 4681 /// 4682 /// @todo This class is infuriatingly similar to clang::Designator, 4683 /// but minor differences (storing indices vs. storing pointers) 4684 /// keep us from reusing it. Try harder, later, to rectify these 4685 /// differences. 4686 class Designator { 4687 /// The kind of designator this describes. 4688 enum { 4689 FieldDesignator, 4690 ArrayDesignator, 4691 ArrayRangeDesignator 4692 } Kind; 4693 4694 union { 4695 /// A field designator, e.g., ".x". 4696 struct FieldDesignator Field; 4697 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". 4698 struct ArrayOrRangeDesignator ArrayOrRange; 4699 }; 4700 friend class DesignatedInitExpr; 4701 4702 public: 4703 Designator() {} 4704 4705 /// Initializes a field designator. 4706 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, 4707 SourceLocation FieldLoc) 4708 : Kind(FieldDesignator) { 4709 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; 4710 Field.DotLoc = DotLoc.getRawEncoding(); 4711 Field.FieldLoc = FieldLoc.getRawEncoding(); 4712 } 4713 4714 /// Initializes an array designator. 4715 Designator(unsigned Index, SourceLocation LBracketLoc, 4716 SourceLocation RBracketLoc) 4717 : Kind(ArrayDesignator) { 4718 ArrayOrRange.Index = Index; 4719 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4720 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); 4721 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4722 } 4723 4724 /// Initializes a GNU array-range designator. 4725 Designator(unsigned Index, SourceLocation LBracketLoc, 4726 SourceLocation EllipsisLoc, SourceLocation RBracketLoc) 4727 : Kind(ArrayRangeDesignator) { 4728 ArrayOrRange.Index = Index; 4729 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); 4730 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); 4731 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); 4732 } 4733 4734 bool isFieldDesignator() const { return Kind == FieldDesignator; } 4735 bool isArrayDesignator() const { return Kind == ArrayDesignator; } 4736 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } 4737 4738 IdentifierInfo *getFieldName() const; 4739 4740 FieldDecl *getField() const { 4741 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4742 if (Field.NameOrField & 0x01) 4743 return nullptr; 4744 else 4745 return reinterpret_cast<FieldDecl *>(Field.NameOrField); 4746 } 4747 4748 void setField(FieldDecl *FD) { 4749 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4750 Field.NameOrField = reinterpret_cast<uintptr_t>(FD); 4751 } 4752 4753 SourceLocation getDotLoc() const { 4754 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4755 return SourceLocation::getFromRawEncoding(Field.DotLoc); 4756 } 4757 4758 SourceLocation getFieldLoc() const { 4759 assert(Kind == FieldDesignator && "Only valid on a field designator"); 4760 return SourceLocation::getFromRawEncoding(Field.FieldLoc); 4761 } 4762 4763 SourceLocation getLBracketLoc() const { 4764 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4765 "Only valid on an array or array-range designator"); 4766 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); 4767 } 4768 4769 SourceLocation getRBracketLoc() const { 4770 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4771 "Only valid on an array or array-range designator"); 4772 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); 4773 } 4774 4775 SourceLocation getEllipsisLoc() const { 4776 assert(Kind == ArrayRangeDesignator && 4777 "Only valid on an array-range designator"); 4778 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); 4779 } 4780 4781 unsigned getFirstExprIndex() const { 4782 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && 4783 "Only valid on an array or array-range designator"); 4784 return ArrayOrRange.Index; 4785 } 4786 4787 SourceLocation getBeginLoc() const LLVM_READONLY { 4788 if (Kind == FieldDesignator) 4789 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); 4790 else 4791 return getLBracketLoc(); 4792 } 4793 SourceLocation getEndLoc() const LLVM_READONLY { 4794 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); 4795 } 4796 SourceRange getSourceRange() const LLVM_READONLY { 4797 return SourceRange(getBeginLoc(), getEndLoc()); 4798 } 4799 }; 4800 4801 static DesignatedInitExpr *Create(const ASTContext &C, 4802 llvm::ArrayRef<Designator> Designators, 4803 ArrayRef<Expr*> IndexExprs, 4804 SourceLocation EqualOrColonLoc, 4805 bool GNUSyntax, Expr *Init); 4806 4807 static DesignatedInitExpr *CreateEmpty(const ASTContext &C, 4808 unsigned NumIndexExprs); 4809 4810 /// Returns the number of designators in this initializer. 4811 unsigned size() const { return NumDesignators; } 4812 4813 // Iterator access to the designators. 4814 llvm::MutableArrayRef<Designator> designators() { 4815 return {Designators, NumDesignators}; 4816 } 4817 4818 llvm::ArrayRef<Designator> designators() const { 4819 return {Designators, NumDesignators}; 4820 } 4821 4822 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } 4823 const Designator *getDesignator(unsigned Idx) const { 4824 return &designators()[Idx]; 4825 } 4826 4827 void setDesignators(const ASTContext &C, const Designator *Desigs, 4828 unsigned NumDesigs); 4829 4830 Expr *getArrayIndex(const Designator &D) const; 4831 Expr *getArrayRangeStart(const Designator &D) const; 4832 Expr *getArrayRangeEnd(const Designator &D) const; 4833 4834 /// Retrieve the location of the '=' that precedes the 4835 /// initializer value itself, if present. 4836 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } 4837 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } 4838 4839 /// Whether this designated initializer should result in direct-initialization 4840 /// of the designated subobject (eg, '{.foo{1, 2, 3}}'). 4841 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); } 4842 4843 /// Determines whether this designated initializer used the 4844 /// deprecated GNU syntax for designated initializers. 4845 bool usesGNUSyntax() const { return GNUSyntax; } 4846 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } 4847 4848 /// Retrieve the initializer value. 4849 Expr *getInit() const { 4850 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); 4851 } 4852 4853 void setInit(Expr *init) { 4854 *child_begin() = init; 4855 } 4856 4857 /// Retrieve the total number of subexpressions in this 4858 /// designated initializer expression, including the actual 4859 /// initialized value and any expressions that occur within array 4860 /// and array-range designators. 4861 unsigned getNumSubExprs() const { return NumSubExprs; } 4862 4863 Expr *getSubExpr(unsigned Idx) const { 4864 assert(Idx < NumSubExprs && "Subscript out of range"); 4865 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]); 4866 } 4867 4868 void setSubExpr(unsigned Idx, Expr *E) { 4869 assert(Idx < NumSubExprs && "Subscript out of range"); 4870 getTrailingObjects<Stmt *>()[Idx] = E; 4871 } 4872 4873 /// Replaces the designator at index @p Idx with the series 4874 /// of designators in [First, Last). 4875 void ExpandDesignator(const ASTContext &C, unsigned Idx, 4876 const Designator *First, const Designator *Last); 4877 4878 SourceRange getDesignatorsSourceRange() const; 4879 4880 SourceLocation getBeginLoc() const LLVM_READONLY; 4881 SourceLocation getEndLoc() const LLVM_READONLY; 4882 4883 static bool classof(const Stmt *T) { 4884 return T->getStmtClass() == DesignatedInitExprClass; 4885 } 4886 4887 // Iterators 4888 child_range children() { 4889 Stmt **begin = getTrailingObjects<Stmt *>(); 4890 return child_range(begin, begin + NumSubExprs); 4891 } 4892 const_child_range children() const { 4893 Stmt * const *begin = getTrailingObjects<Stmt *>(); 4894 return const_child_range(begin, begin + NumSubExprs); 4895 } 4896 4897 friend TrailingObjects; 4898 }; 4899 4900 /// Represents a place-holder for an object not to be initialized by 4901 /// anything. 4902 /// 4903 /// This only makes sense when it appears as part of an updater of a 4904 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE 4905 /// initializes a big object, and the NoInitExpr's mark the spots within the 4906 /// big object not to be overwritten by the updater. 4907 /// 4908 /// \see DesignatedInitUpdateExpr 4909 class NoInitExpr : public Expr { 4910 public: 4911 explicit NoInitExpr(QualType ty) 4912 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary, 4913 false, false, ty->isInstantiationDependentType(), false) { } 4914 4915 explicit NoInitExpr(EmptyShell Empty) 4916 : Expr(NoInitExprClass, Empty) { } 4917 4918 static bool classof(const Stmt *T) { 4919 return T->getStmtClass() == NoInitExprClass; 4920 } 4921 4922 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 4923 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 4924 4925 // Iterators 4926 child_range children() { 4927 return child_range(child_iterator(), child_iterator()); 4928 } 4929 const_child_range children() const { 4930 return const_child_range(const_child_iterator(), const_child_iterator()); 4931 } 4932 }; 4933 4934 // In cases like: 4935 // struct Q { int a, b, c; }; 4936 // Q *getQ(); 4937 // void foo() { 4938 // struct A { Q q; } a = { *getQ(), .q.b = 3 }; 4939 // } 4940 // 4941 // We will have an InitListExpr for a, with type A, and then a 4942 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE 4943 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" 4944 // 4945 class DesignatedInitUpdateExpr : public Expr { 4946 // BaseAndUpdaterExprs[0] is the base expression; 4947 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. 4948 Stmt *BaseAndUpdaterExprs[2]; 4949 4950 public: 4951 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, 4952 Expr *baseExprs, SourceLocation rBraceLoc); 4953 4954 explicit DesignatedInitUpdateExpr(EmptyShell Empty) 4955 : Expr(DesignatedInitUpdateExprClass, Empty) { } 4956 4957 SourceLocation getBeginLoc() const LLVM_READONLY; 4958 SourceLocation getEndLoc() const LLVM_READONLY; 4959 4960 static bool classof(const Stmt *T) { 4961 return T->getStmtClass() == DesignatedInitUpdateExprClass; 4962 } 4963 4964 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); } 4965 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } 4966 4967 InitListExpr *getUpdater() const { 4968 return cast<InitListExpr>(BaseAndUpdaterExprs[1]); 4969 } 4970 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } 4971 4972 // Iterators 4973 // children = the base and the updater 4974 child_range children() { 4975 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); 4976 } 4977 const_child_range children() const { 4978 return const_child_range(&BaseAndUpdaterExprs[0], 4979 &BaseAndUpdaterExprs[0] + 2); 4980 } 4981 }; 4982 4983 /// Represents a loop initializing the elements of an array. 4984 /// 4985 /// The need to initialize the elements of an array occurs in a number of 4986 /// contexts: 4987 /// 4988 /// * in the implicit copy/move constructor for a class with an array member 4989 /// * when a lambda-expression captures an array by value 4990 /// * when a decomposition declaration decomposes an array 4991 /// 4992 /// There are two subexpressions: a common expression (the source array) 4993 /// that is evaluated once up-front, and a per-element initializer that 4994 /// runs once for each array element. 4995 /// 4996 /// Within the per-element initializer, the common expression may be referenced 4997 /// via an OpaqueValueExpr, and the current index may be obtained via an 4998 /// ArrayInitIndexExpr. 4999 class ArrayInitLoopExpr : public Expr { 5000 Stmt *SubExprs[2]; 5001 5002 explicit ArrayInitLoopExpr(EmptyShell Empty) 5003 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} 5004 5005 public: 5006 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) 5007 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false, 5008 CommonInit->isValueDependent() || ElementInit->isValueDependent(), 5009 T->isInstantiationDependentType(), 5010 CommonInit->containsUnexpandedParameterPack() || 5011 ElementInit->containsUnexpandedParameterPack()), 5012 SubExprs{CommonInit, ElementInit} {} 5013 5014 /// Get the common subexpression shared by all initializations (the source 5015 /// array). 5016 OpaqueValueExpr *getCommonExpr() const { 5017 return cast<OpaqueValueExpr>(SubExprs[0]); 5018 } 5019 5020 /// Get the initializer to use for each array element. 5021 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); } 5022 5023 llvm::APInt getArraySize() const { 5024 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe()) 5025 ->getSize(); 5026 } 5027 5028 static bool classof(const Stmt *S) { 5029 return S->getStmtClass() == ArrayInitLoopExprClass; 5030 } 5031 5032 SourceLocation getBeginLoc() const LLVM_READONLY { 5033 return getCommonExpr()->getBeginLoc(); 5034 } 5035 SourceLocation getEndLoc() const LLVM_READONLY { 5036 return getCommonExpr()->getEndLoc(); 5037 } 5038 5039 child_range children() { 5040 return child_range(SubExprs, SubExprs + 2); 5041 } 5042 const_child_range children() const { 5043 return const_child_range(SubExprs, SubExprs + 2); 5044 } 5045 5046 friend class ASTReader; 5047 friend class ASTStmtReader; 5048 friend class ASTStmtWriter; 5049 }; 5050 5051 /// Represents the index of the current element of an array being 5052 /// initialized by an ArrayInitLoopExpr. This can only appear within the 5053 /// subexpression of an ArrayInitLoopExpr. 5054 class ArrayInitIndexExpr : public Expr { 5055 explicit ArrayInitIndexExpr(EmptyShell Empty) 5056 : Expr(ArrayInitIndexExprClass, Empty) {} 5057 5058 public: 5059 explicit ArrayInitIndexExpr(QualType T) 5060 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary, 5061 false, false, false, false) {} 5062 5063 static bool classof(const Stmt *S) { 5064 return S->getStmtClass() == ArrayInitIndexExprClass; 5065 } 5066 5067 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5068 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5069 5070 child_range children() { 5071 return child_range(child_iterator(), child_iterator()); 5072 } 5073 const_child_range children() const { 5074 return const_child_range(const_child_iterator(), const_child_iterator()); 5075 } 5076 5077 friend class ASTReader; 5078 friend class ASTStmtReader; 5079 }; 5080 5081 /// Represents an implicitly-generated value initialization of 5082 /// an object of a given type. 5083 /// 5084 /// Implicit value initializations occur within semantic initializer 5085 /// list expressions (InitListExpr) as placeholders for subobject 5086 /// initializations not explicitly specified by the user. 5087 /// 5088 /// \see InitListExpr 5089 class ImplicitValueInitExpr : public Expr { 5090 public: 5091 explicit ImplicitValueInitExpr(QualType ty) 5092 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, 5093 false, false, ty->isInstantiationDependentType(), false) { } 5094 5095 /// Construct an empty implicit value initialization. 5096 explicit ImplicitValueInitExpr(EmptyShell Empty) 5097 : Expr(ImplicitValueInitExprClass, Empty) { } 5098 5099 static bool classof(const Stmt *T) { 5100 return T->getStmtClass() == ImplicitValueInitExprClass; 5101 } 5102 5103 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5104 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5105 5106 // Iterators 5107 child_range children() { 5108 return child_range(child_iterator(), child_iterator()); 5109 } 5110 const_child_range children() const { 5111 return const_child_range(const_child_iterator(), const_child_iterator()); 5112 } 5113 }; 5114 5115 class ParenListExpr final 5116 : public Expr, 5117 private llvm::TrailingObjects<ParenListExpr, Stmt *> { 5118 friend class ASTStmtReader; 5119 friend TrailingObjects; 5120 5121 /// The location of the left and right parentheses. 5122 SourceLocation LParenLoc, RParenLoc; 5123 5124 /// Build a paren list. 5125 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, 5126 SourceLocation RParenLoc); 5127 5128 /// Build an empty paren list. 5129 ParenListExpr(EmptyShell Empty, unsigned NumExprs); 5130 5131 public: 5132 /// Create a paren list. 5133 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc, 5134 ArrayRef<Expr *> Exprs, 5135 SourceLocation RParenLoc); 5136 5137 /// Create an empty paren list. 5138 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs); 5139 5140 /// Return the number of expressions in this paren list. 5141 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; } 5142 5143 Expr *getExpr(unsigned Init) { 5144 assert(Init < getNumExprs() && "Initializer access out of range!"); 5145 return getExprs()[Init]; 5146 } 5147 5148 const Expr *getExpr(unsigned Init) const { 5149 return const_cast<ParenListExpr *>(this)->getExpr(Init); 5150 } 5151 5152 Expr **getExprs() { 5153 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>()); 5154 } 5155 5156 ArrayRef<Expr *> exprs() { 5157 return llvm::makeArrayRef(getExprs(), getNumExprs()); 5158 } 5159 5160 SourceLocation getLParenLoc() const { return LParenLoc; } 5161 SourceLocation getRParenLoc() const { return RParenLoc; } 5162 SourceLocation getBeginLoc() const { return getLParenLoc(); } 5163 SourceLocation getEndLoc() const { return getRParenLoc(); } 5164 5165 static bool classof(const Stmt *T) { 5166 return T->getStmtClass() == ParenListExprClass; 5167 } 5168 5169 // Iterators 5170 child_range children() { 5171 return child_range(getTrailingObjects<Stmt *>(), 5172 getTrailingObjects<Stmt *>() + getNumExprs()); 5173 } 5174 const_child_range children() const { 5175 return const_child_range(getTrailingObjects<Stmt *>(), 5176 getTrailingObjects<Stmt *>() + getNumExprs()); 5177 } 5178 }; 5179 5180 /// Represents a C11 generic selection. 5181 /// 5182 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling 5183 /// expression, followed by one or more generic associations. Each generic 5184 /// association specifies a type name and an expression, or "default" and an 5185 /// expression (in which case it is known as a default generic association). 5186 /// The type and value of the generic selection are identical to those of its 5187 /// result expression, which is defined as the expression in the generic 5188 /// association with a type name that is compatible with the type of the 5189 /// controlling expression, or the expression in the default generic association 5190 /// if no types are compatible. For example: 5191 /// 5192 /// @code 5193 /// _Generic(X, double: 1, float: 2, default: 3) 5194 /// @endcode 5195 /// 5196 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f 5197 /// or 3 if "hello". 5198 /// 5199 /// As an extension, generic selections are allowed in C++, where the following 5200 /// additional semantics apply: 5201 /// 5202 /// Any generic selection whose controlling expression is type-dependent or 5203 /// which names a dependent type in its association list is result-dependent, 5204 /// which means that the choice of result expression is dependent. 5205 /// Result-dependent generic associations are both type- and value-dependent. 5206 class GenericSelectionExpr final 5207 : public Expr, 5208 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *, 5209 TypeSourceInfo *> { 5210 friend class ASTStmtReader; 5211 friend class ASTStmtWriter; 5212 friend TrailingObjects; 5213 5214 /// The number of association expressions and the index of the result 5215 /// expression in the case where the generic selection expression is not 5216 /// result-dependent. The result index is equal to ResultDependentIndex 5217 /// if and only if the generic selection expression is result-dependent. 5218 unsigned NumAssocs, ResultIndex; 5219 enum : unsigned { 5220 ResultDependentIndex = std::numeric_limits<unsigned>::max(), 5221 ControllingIndex = 0, 5222 AssocExprStartIndex = 1 5223 }; 5224 5225 /// The location of the "default" and of the right parenthesis. 5226 SourceLocation DefaultLoc, RParenLoc; 5227 5228 // GenericSelectionExpr is followed by several trailing objects. 5229 // They are (in order): 5230 // 5231 // * A single Stmt * for the controlling expression. 5232 // * An array of getNumAssocs() Stmt * for the association expressions. 5233 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the 5234 // association expressions. 5235 unsigned numTrailingObjects(OverloadToken<Stmt *>) const { 5236 // Add one to account for the controlling expression; the remainder 5237 // are the associated expressions. 5238 return 1 + getNumAssocs(); 5239 } 5240 5241 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { 5242 return getNumAssocs(); 5243 } 5244 5245 template <bool Const> class AssociationIteratorTy; 5246 /// Bundle together an association expression and its TypeSourceInfo. 5247 /// The Const template parameter is for the const and non-const versions 5248 /// of AssociationTy. 5249 template <bool Const> class AssociationTy { 5250 friend class GenericSelectionExpr; 5251 template <bool OtherConst> friend class AssociationIteratorTy; 5252 using ExprPtrTy = 5253 typename std::conditional<Const, const Expr *, Expr *>::type; 5254 using TSIPtrTy = typename std::conditional<Const, const TypeSourceInfo *, 5255 TypeSourceInfo *>::type; 5256 ExprPtrTy E; 5257 TSIPtrTy TSI; 5258 bool Selected; 5259 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected) 5260 : E(E), TSI(TSI), Selected(Selected) {} 5261 5262 public: 5263 ExprPtrTy getAssociationExpr() const { return E; } 5264 TSIPtrTy getTypeSourceInfo() const { return TSI; } 5265 QualType getType() const { return TSI ? TSI->getType() : QualType(); } 5266 bool isSelected() const { return Selected; } 5267 AssociationTy *operator->() { return this; } 5268 const AssociationTy *operator->() const { return this; } 5269 }; // class AssociationTy 5270 5271 /// Iterator over const and non-const Association objects. The Association 5272 /// objects are created on the fly when the iterator is dereferenced. 5273 /// This abstract over how exactly the association expressions and the 5274 /// corresponding TypeSourceInfo * are stored. 5275 template <bool Const> 5276 class AssociationIteratorTy 5277 : public llvm::iterator_facade_base< 5278 AssociationIteratorTy<Const>, std::input_iterator_tag, 5279 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>, 5280 AssociationTy<Const>> { 5281 friend class GenericSelectionExpr; 5282 // FIXME: This iterator could conceptually be a random access iterator, and 5283 // it would be nice if we could strengthen the iterator category someday. 5284 // However this iterator does not satisfy two requirements of forward 5285 // iterators: 5286 // a) reference = T& or reference = const T& 5287 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only 5288 // if *It1 and *It2 are bound to the same objects. 5289 // An alternative design approach was discussed during review; 5290 // store an Association object inside the iterator, and return a reference 5291 // to it when dereferenced. This idea was discarded beacuse of nasty 5292 // lifetime issues: 5293 // AssociationIterator It = ...; 5294 // const Association &Assoc = *It++; // Oops, Assoc is dangling. 5295 using BaseTy = typename AssociationIteratorTy::iterator_facade_base; 5296 using StmtPtrPtrTy = 5297 typename std::conditional<Const, const Stmt *const *, Stmt **>::type; 5298 using TSIPtrPtrTy = 5299 typename std::conditional<Const, const TypeSourceInfo *const *, 5300 TypeSourceInfo **>::type; 5301 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped. 5302 TSIPtrPtrTy TSI; // Kept in sync with E. 5303 unsigned Offset = 0, SelectedOffset = 0; 5304 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset, 5305 unsigned SelectedOffset) 5306 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {} 5307 5308 public: 5309 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {} 5310 typename BaseTy::reference operator*() const { 5311 return AssociationTy<Const>(cast<Expr>(*E), *TSI, 5312 Offset == SelectedOffset); 5313 } 5314 typename BaseTy::pointer operator->() const { return **this; } 5315 using BaseTy::operator++; 5316 AssociationIteratorTy &operator++() { 5317 ++E; 5318 ++TSI; 5319 ++Offset; 5320 return *this; 5321 } 5322 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; } 5323 }; // class AssociationIterator 5324 5325 /// Build a non-result-dependent generic selection expression. 5326 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5327 Expr *ControllingExpr, 5328 ArrayRef<TypeSourceInfo *> AssocTypes, 5329 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5330 SourceLocation RParenLoc, 5331 bool ContainsUnexpandedParameterPack, 5332 unsigned ResultIndex); 5333 5334 /// Build a result-dependent generic selection expression. 5335 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, 5336 Expr *ControllingExpr, 5337 ArrayRef<TypeSourceInfo *> AssocTypes, 5338 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5339 SourceLocation RParenLoc, 5340 bool ContainsUnexpandedParameterPack); 5341 5342 /// Build an empty generic selection expression for deserialization. 5343 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs); 5344 5345 public: 5346 /// Create a non-result-dependent generic selection expression. 5347 static GenericSelectionExpr * 5348 Create(const ASTContext &Context, SourceLocation GenericLoc, 5349 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5350 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5351 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, 5352 unsigned ResultIndex); 5353 5354 /// Create a result-dependent generic selection expression. 5355 static GenericSelectionExpr * 5356 Create(const ASTContext &Context, SourceLocation GenericLoc, 5357 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, 5358 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, 5359 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); 5360 5361 /// Create an empty generic selection expression for deserialization. 5362 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context, 5363 unsigned NumAssocs); 5364 5365 using Association = AssociationTy<false>; 5366 using ConstAssociation = AssociationTy<true>; 5367 using AssociationIterator = AssociationIteratorTy<false>; 5368 using ConstAssociationIterator = AssociationIteratorTy<true>; 5369 using association_range = llvm::iterator_range<AssociationIterator>; 5370 using const_association_range = 5371 llvm::iterator_range<ConstAssociationIterator>; 5372 5373 /// The number of association expressions. 5374 unsigned getNumAssocs() const { return NumAssocs; } 5375 5376 /// The zero-based index of the result expression's generic association in 5377 /// the generic selection's association list. Defined only if the 5378 /// generic selection is not result-dependent. 5379 unsigned getResultIndex() const { 5380 assert(!isResultDependent() && 5381 "Generic selection is result-dependent but getResultIndex called!"); 5382 return ResultIndex; 5383 } 5384 5385 /// Whether this generic selection is result-dependent. 5386 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; } 5387 5388 /// Return the controlling expression of this generic selection expression. 5389 Expr *getControllingExpr() { 5390 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); 5391 } 5392 const Expr *getControllingExpr() const { 5393 return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); 5394 } 5395 5396 /// Return the result expression of this controlling expression. Defined if 5397 /// and only if the generic selection expression is not result-dependent. 5398 Expr *getResultExpr() { 5399 return cast<Expr>( 5400 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); 5401 } 5402 const Expr *getResultExpr() const { 5403 return cast<Expr>( 5404 getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); 5405 } 5406 5407 ArrayRef<Expr *> getAssocExprs() const { 5408 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() + 5409 AssocExprStartIndex), 5410 NumAssocs}; 5411 } 5412 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const { 5413 return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs}; 5414 } 5415 5416 /// Return the Ith association expression with its TypeSourceInfo, 5417 /// bundled together in GenericSelectionExpr::(Const)Association. 5418 Association getAssociation(unsigned I) { 5419 assert(I < getNumAssocs() && 5420 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 5421 return Association( 5422 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), 5423 getTrailingObjects<TypeSourceInfo *>()[I], 5424 !isResultDependent() && (getResultIndex() == I)); 5425 } 5426 ConstAssociation getAssociation(unsigned I) const { 5427 assert(I < getNumAssocs() && 5428 "Out-of-range index in GenericSelectionExpr::getAssociation!"); 5429 return ConstAssociation( 5430 cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), 5431 getTrailingObjects<TypeSourceInfo *>()[I], 5432 !isResultDependent() && (getResultIndex() == I)); 5433 } 5434 5435 association_range associations() { 5436 AssociationIterator Begin(getTrailingObjects<Stmt *>() + 5437 AssocExprStartIndex, 5438 getTrailingObjects<TypeSourceInfo *>(), 5439 /*Offset=*/0, ResultIndex); 5440 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 5441 /*Offset=*/NumAssocs, ResultIndex); 5442 return llvm::make_range(Begin, End); 5443 } 5444 5445 const_association_range associations() const { 5446 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() + 5447 AssocExprStartIndex, 5448 getTrailingObjects<TypeSourceInfo *>(), 5449 /*Offset=*/0, ResultIndex); 5450 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, 5451 /*Offset=*/NumAssocs, ResultIndex); 5452 return llvm::make_range(Begin, End); 5453 } 5454 5455 SourceLocation getGenericLoc() const { 5456 return GenericSelectionExprBits.GenericLoc; 5457 } 5458 SourceLocation getDefaultLoc() const { return DefaultLoc; } 5459 SourceLocation getRParenLoc() const { return RParenLoc; } 5460 SourceLocation getBeginLoc() const { return getGenericLoc(); } 5461 SourceLocation getEndLoc() const { return getRParenLoc(); } 5462 5463 static bool classof(const Stmt *T) { 5464 return T->getStmtClass() == GenericSelectionExprClass; 5465 } 5466 5467 child_range children() { 5468 return child_range(getTrailingObjects<Stmt *>(), 5469 getTrailingObjects<Stmt *>() + 5470 numTrailingObjects(OverloadToken<Stmt *>())); 5471 } 5472 const_child_range children() const { 5473 return const_child_range(getTrailingObjects<Stmt *>(), 5474 getTrailingObjects<Stmt *>() + 5475 numTrailingObjects(OverloadToken<Stmt *>())); 5476 } 5477 }; 5478 5479 //===----------------------------------------------------------------------===// 5480 // Clang Extensions 5481 //===----------------------------------------------------------------------===// 5482 5483 /// ExtVectorElementExpr - This represents access to specific elements of a 5484 /// vector, and may occur on the left hand side or right hand side. For example 5485 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. 5486 /// 5487 /// Note that the base may have either vector or pointer to vector type, just 5488 /// like a struct field reference. 5489 /// 5490 class ExtVectorElementExpr : public Expr { 5491 Stmt *Base; 5492 IdentifierInfo *Accessor; 5493 SourceLocation AccessorLoc; 5494 public: 5495 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, 5496 IdentifierInfo &accessor, SourceLocation loc) 5497 : Expr(ExtVectorElementExprClass, ty, VK, 5498 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), 5499 base->isTypeDependent(), base->isValueDependent(), 5500 base->isInstantiationDependent(), 5501 base->containsUnexpandedParameterPack()), 5502 Base(base), Accessor(&accessor), AccessorLoc(loc) {} 5503 5504 /// Build an empty vector element expression. 5505 explicit ExtVectorElementExpr(EmptyShell Empty) 5506 : Expr(ExtVectorElementExprClass, Empty) { } 5507 5508 const Expr *getBase() const { return cast<Expr>(Base); } 5509 Expr *getBase() { return cast<Expr>(Base); } 5510 void setBase(Expr *E) { Base = E; } 5511 5512 IdentifierInfo &getAccessor() const { return *Accessor; } 5513 void setAccessor(IdentifierInfo *II) { Accessor = II; } 5514 5515 SourceLocation getAccessorLoc() const { return AccessorLoc; } 5516 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } 5517 5518 /// getNumElements - Get the number of components being selected. 5519 unsigned getNumElements() const; 5520 5521 /// containsDuplicateElements - Return true if any element access is 5522 /// repeated. 5523 bool containsDuplicateElements() const; 5524 5525 /// getEncodedElementAccess - Encode the elements accessed into an llvm 5526 /// aggregate Constant of ConstantInt(s). 5527 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const; 5528 5529 SourceLocation getBeginLoc() const LLVM_READONLY { 5530 return getBase()->getBeginLoc(); 5531 } 5532 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; } 5533 5534 /// isArrow - Return true if the base expression is a pointer to vector, 5535 /// return false if the base expression is a vector. 5536 bool isArrow() const; 5537 5538 static bool classof(const Stmt *T) { 5539 return T->getStmtClass() == ExtVectorElementExprClass; 5540 } 5541 5542 // Iterators 5543 child_range children() { return child_range(&Base, &Base+1); } 5544 const_child_range children() const { 5545 return const_child_range(&Base, &Base + 1); 5546 } 5547 }; 5548 5549 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. 5550 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 5551 class BlockExpr : public Expr { 5552 protected: 5553 BlockDecl *TheBlock; 5554 public: 5555 BlockExpr(BlockDecl *BD, QualType ty) 5556 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, 5557 ty->isDependentType(), ty->isDependentType(), 5558 ty->isInstantiationDependentType() || BD->isDependentContext(), 5559 false), 5560 TheBlock(BD) {} 5561 5562 /// Build an empty block expression. 5563 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } 5564 5565 const BlockDecl *getBlockDecl() const { return TheBlock; } 5566 BlockDecl *getBlockDecl() { return TheBlock; } 5567 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } 5568 5569 // Convenience functions for probing the underlying BlockDecl. 5570 SourceLocation getCaretLocation() const; 5571 const Stmt *getBody() const; 5572 Stmt *getBody(); 5573 5574 SourceLocation getBeginLoc() const LLVM_READONLY { 5575 return getCaretLocation(); 5576 } 5577 SourceLocation getEndLoc() const LLVM_READONLY { 5578 return getBody()->getEndLoc(); 5579 } 5580 5581 /// getFunctionType - Return the underlying function type for this block. 5582 const FunctionProtoType *getFunctionType() const; 5583 5584 static bool classof(const Stmt *T) { 5585 return T->getStmtClass() == BlockExprClass; 5586 } 5587 5588 // Iterators 5589 child_range children() { 5590 return child_range(child_iterator(), child_iterator()); 5591 } 5592 const_child_range children() const { 5593 return const_child_range(const_child_iterator(), const_child_iterator()); 5594 } 5595 }; 5596 5597 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] 5598 /// This AST node provides support for reinterpreting a type to another 5599 /// type of the same size. 5600 class AsTypeExpr : public Expr { 5601 private: 5602 Stmt *SrcExpr; 5603 SourceLocation BuiltinLoc, RParenLoc; 5604 5605 friend class ASTReader; 5606 friend class ASTStmtReader; 5607 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} 5608 5609 public: 5610 AsTypeExpr(Expr* SrcExpr, QualType DstType, 5611 ExprValueKind VK, ExprObjectKind OK, 5612 SourceLocation BuiltinLoc, SourceLocation RParenLoc) 5613 : Expr(AsTypeExprClass, DstType, VK, OK, 5614 DstType->isDependentType(), 5615 DstType->isDependentType() || SrcExpr->isValueDependent(), 5616 (DstType->isInstantiationDependentType() || 5617 SrcExpr->isInstantiationDependent()), 5618 (DstType->containsUnexpandedParameterPack() || 5619 SrcExpr->containsUnexpandedParameterPack())), 5620 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} 5621 5622 /// getSrcExpr - Return the Expr to be converted. 5623 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } 5624 5625 /// getBuiltinLoc - Return the location of the __builtin_astype token. 5626 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 5627 5628 /// getRParenLoc - Return the location of final right parenthesis. 5629 SourceLocation getRParenLoc() const { return RParenLoc; } 5630 5631 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 5632 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 5633 5634 static bool classof(const Stmt *T) { 5635 return T->getStmtClass() == AsTypeExprClass; 5636 } 5637 5638 // Iterators 5639 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } 5640 const_child_range children() const { 5641 return const_child_range(&SrcExpr, &SrcExpr + 1); 5642 } 5643 }; 5644 5645 /// PseudoObjectExpr - An expression which accesses a pseudo-object 5646 /// l-value. A pseudo-object is an abstract object, accesses to which 5647 /// are translated to calls. The pseudo-object expression has a 5648 /// syntactic form, which shows how the expression was actually 5649 /// written in the source code, and a semantic form, which is a series 5650 /// of expressions to be executed in order which detail how the 5651 /// operation is actually evaluated. Optionally, one of the semantic 5652 /// forms may also provide a result value for the expression. 5653 /// 5654 /// If any of the semantic-form expressions is an OpaqueValueExpr, 5655 /// that OVE is required to have a source expression, and it is bound 5656 /// to the result of that source expression. Such OVEs may appear 5657 /// only in subsequent semantic-form expressions and as 5658 /// sub-expressions of the syntactic form. 5659 /// 5660 /// PseudoObjectExpr should be used only when an operation can be 5661 /// usefully described in terms of fairly simple rewrite rules on 5662 /// objects and functions that are meant to be used by end-developers. 5663 /// For example, under the Itanium ABI, dynamic casts are implemented 5664 /// as a call to a runtime function called __dynamic_cast; using this 5665 /// class to describe that would be inappropriate because that call is 5666 /// not really part of the user-visible semantics, and instead the 5667 /// cast is properly reflected in the AST and IR-generation has been 5668 /// taught to generate the call as necessary. In contrast, an 5669 /// Objective-C property access is semantically defined to be 5670 /// equivalent to a particular message send, and this is very much 5671 /// part of the user model. The name of this class encourages this 5672 /// modelling design. 5673 class PseudoObjectExpr final 5674 : public Expr, 5675 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> { 5676 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. 5677 // Always at least two, because the first sub-expression is the 5678 // syntactic form. 5679 5680 // PseudoObjectExprBits.ResultIndex - The index of the 5681 // sub-expression holding the result. 0 means the result is void, 5682 // which is unambiguous because it's the index of the syntactic 5683 // form. Note that this is therefore 1 higher than the value passed 5684 // in to Create, which is an index within the semantic forms. 5685 // Note also that ASTStmtWriter assumes this encoding. 5686 5687 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); } 5688 const Expr * const *getSubExprsBuffer() const { 5689 return getTrailingObjects<Expr *>(); 5690 } 5691 5692 PseudoObjectExpr(QualType type, ExprValueKind VK, 5693 Expr *syntactic, ArrayRef<Expr*> semantic, 5694 unsigned resultIndex); 5695 5696 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); 5697 5698 unsigned getNumSubExprs() const { 5699 return PseudoObjectExprBits.NumSubExprs; 5700 } 5701 5702 public: 5703 /// NoResult - A value for the result index indicating that there is 5704 /// no semantic result. 5705 enum : unsigned { NoResult = ~0U }; 5706 5707 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, 5708 ArrayRef<Expr*> semantic, 5709 unsigned resultIndex); 5710 5711 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, 5712 unsigned numSemanticExprs); 5713 5714 /// Return the syntactic form of this expression, i.e. the 5715 /// expression it actually looks like. Likely to be expressed in 5716 /// terms of OpaqueValueExprs bound in the semantic form. 5717 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } 5718 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } 5719 5720 /// Return the index of the result-bearing expression into the semantics 5721 /// expressions, or PseudoObjectExpr::NoResult if there is none. 5722 unsigned getResultExprIndex() const { 5723 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; 5724 return PseudoObjectExprBits.ResultIndex - 1; 5725 } 5726 5727 /// Return the result-bearing expression, or null if there is none. 5728 Expr *getResultExpr() { 5729 if (PseudoObjectExprBits.ResultIndex == 0) 5730 return nullptr; 5731 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; 5732 } 5733 const Expr *getResultExpr() const { 5734 return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); 5735 } 5736 5737 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } 5738 5739 typedef Expr * const *semantics_iterator; 5740 typedef const Expr * const *const_semantics_iterator; 5741 semantics_iterator semantics_begin() { 5742 return getSubExprsBuffer() + 1; 5743 } 5744 const_semantics_iterator semantics_begin() const { 5745 return getSubExprsBuffer() + 1; 5746 } 5747 semantics_iterator semantics_end() { 5748 return getSubExprsBuffer() + getNumSubExprs(); 5749 } 5750 const_semantics_iterator semantics_end() const { 5751 return getSubExprsBuffer() + getNumSubExprs(); 5752 } 5753 5754 llvm::iterator_range<semantics_iterator> semantics() { 5755 return llvm::make_range(semantics_begin(), semantics_end()); 5756 } 5757 llvm::iterator_range<const_semantics_iterator> semantics() const { 5758 return llvm::make_range(semantics_begin(), semantics_end()); 5759 } 5760 5761 Expr *getSemanticExpr(unsigned index) { 5762 assert(index + 1 < getNumSubExprs()); 5763 return getSubExprsBuffer()[index + 1]; 5764 } 5765 const Expr *getSemanticExpr(unsigned index) const { 5766 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); 5767 } 5768 5769 SourceLocation getExprLoc() const LLVM_READONLY { 5770 return getSyntacticForm()->getExprLoc(); 5771 } 5772 5773 SourceLocation getBeginLoc() const LLVM_READONLY { 5774 return getSyntacticForm()->getBeginLoc(); 5775 } 5776 SourceLocation getEndLoc() const LLVM_READONLY { 5777 return getSyntacticForm()->getEndLoc(); 5778 } 5779 5780 child_range children() { 5781 const_child_range CCR = 5782 const_cast<const PseudoObjectExpr *>(this)->children(); 5783 return child_range(cast_away_const(CCR.begin()), 5784 cast_away_const(CCR.end())); 5785 } 5786 const_child_range children() const { 5787 Stmt *const *cs = const_cast<Stmt *const *>( 5788 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer())); 5789 return const_child_range(cs, cs + getNumSubExprs()); 5790 } 5791 5792 static bool classof(const Stmt *T) { 5793 return T->getStmtClass() == PseudoObjectExprClass; 5794 } 5795 5796 friend TrailingObjects; 5797 friend class ASTStmtReader; 5798 }; 5799 5800 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, 5801 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the 5802 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, 5803 /// and corresponding __opencl_atomic_* for OpenCL 2.0. 5804 /// All of these instructions take one primary pointer, at least one memory 5805 /// order. The instructions for which getScopeModel returns non-null value 5806 /// take one synch scope. 5807 class AtomicExpr : public Expr { 5808 public: 5809 enum AtomicOp { 5810 #define BUILTIN(ID, TYPE, ATTRS) 5811 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, 5812 #include "clang/Basic/Builtins.def" 5813 // Avoid trailing comma 5814 BI_First = 0 5815 }; 5816 5817 private: 5818 /// Location of sub-expressions. 5819 /// The location of Scope sub-expression is NumSubExprs - 1, which is 5820 /// not fixed, therefore is not defined in enum. 5821 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; 5822 Stmt *SubExprs[END_EXPR + 1]; 5823 unsigned NumSubExprs; 5824 SourceLocation BuiltinLoc, RParenLoc; 5825 AtomicOp Op; 5826 5827 friend class ASTStmtReader; 5828 public: 5829 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, 5830 AtomicOp op, SourceLocation RP); 5831 5832 /// Determine the number of arguments the specified atomic builtin 5833 /// should have. 5834 static unsigned getNumSubExprs(AtomicOp Op); 5835 5836 /// Build an empty AtomicExpr. 5837 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } 5838 5839 Expr *getPtr() const { 5840 return cast<Expr>(SubExprs[PTR]); 5841 } 5842 Expr *getOrder() const { 5843 return cast<Expr>(SubExprs[ORDER]); 5844 } 5845 Expr *getScope() const { 5846 assert(getScopeModel() && "No scope"); 5847 return cast<Expr>(SubExprs[NumSubExprs - 1]); 5848 } 5849 Expr *getVal1() const { 5850 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init) 5851 return cast<Expr>(SubExprs[ORDER]); 5852 assert(NumSubExprs > VAL1); 5853 return cast<Expr>(SubExprs[VAL1]); 5854 } 5855 Expr *getOrderFail() const { 5856 assert(NumSubExprs > ORDER_FAIL); 5857 return cast<Expr>(SubExprs[ORDER_FAIL]); 5858 } 5859 Expr *getVal2() const { 5860 if (Op == AO__atomic_exchange) 5861 return cast<Expr>(SubExprs[ORDER_FAIL]); 5862 assert(NumSubExprs > VAL2); 5863 return cast<Expr>(SubExprs[VAL2]); 5864 } 5865 Expr *getWeak() const { 5866 assert(NumSubExprs > WEAK); 5867 return cast<Expr>(SubExprs[WEAK]); 5868 } 5869 QualType getValueType() const; 5870 5871 AtomicOp getOp() const { return Op; } 5872 unsigned getNumSubExprs() const { return NumSubExprs; } 5873 5874 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } 5875 const Expr * const *getSubExprs() const { 5876 return reinterpret_cast<Expr * const *>(SubExprs); 5877 } 5878 5879 bool isVolatile() const { 5880 return getPtr()->getType()->getPointeeType().isVolatileQualified(); 5881 } 5882 5883 bool isCmpXChg() const { 5884 return getOp() == AO__c11_atomic_compare_exchange_strong || 5885 getOp() == AO__c11_atomic_compare_exchange_weak || 5886 getOp() == AO__opencl_atomic_compare_exchange_strong || 5887 getOp() == AO__opencl_atomic_compare_exchange_weak || 5888 getOp() == AO__atomic_compare_exchange || 5889 getOp() == AO__atomic_compare_exchange_n; 5890 } 5891 5892 bool isOpenCL() const { 5893 return getOp() >= AO__opencl_atomic_init && 5894 getOp() <= AO__opencl_atomic_fetch_max; 5895 } 5896 5897 SourceLocation getBuiltinLoc() const { return BuiltinLoc; } 5898 SourceLocation getRParenLoc() const { return RParenLoc; } 5899 5900 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; } 5901 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } 5902 5903 static bool classof(const Stmt *T) { 5904 return T->getStmtClass() == AtomicExprClass; 5905 } 5906 5907 // Iterators 5908 child_range children() { 5909 return child_range(SubExprs, SubExprs+NumSubExprs); 5910 } 5911 const_child_range children() const { 5912 return const_child_range(SubExprs, SubExprs + NumSubExprs); 5913 } 5914 5915 /// Get atomic scope model for the atomic op code. 5916 /// \return empty atomic scope model if the atomic op code does not have 5917 /// scope operand. 5918 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) { 5919 auto Kind = 5920 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max) 5921 ? AtomicScopeModelKind::OpenCL 5922 : AtomicScopeModelKind::None; 5923 return AtomicScopeModel::create(Kind); 5924 } 5925 5926 /// Get atomic scope model. 5927 /// \return empty atomic scope model if this atomic expression does not have 5928 /// scope operand. 5929 std::unique_ptr<AtomicScopeModel> getScopeModel() const { 5930 return getScopeModel(getOp()); 5931 } 5932 }; 5933 5934 /// TypoExpr - Internal placeholder for expressions where typo correction 5935 /// still needs to be performed and/or an error diagnostic emitted. 5936 class TypoExpr : public Expr { 5937 public: 5938 TypoExpr(QualType T) 5939 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary, 5940 /*isTypeDependent*/ true, 5941 /*isValueDependent*/ true, 5942 /*isInstantiationDependent*/ true, 5943 /*containsUnexpandedParameterPack*/ false) { 5944 assert(T->isDependentType() && "TypoExpr given a non-dependent type"); 5945 } 5946 5947 child_range children() { 5948 return child_range(child_iterator(), child_iterator()); 5949 } 5950 const_child_range children() const { 5951 return const_child_range(const_child_iterator(), const_child_iterator()); 5952 } 5953 5954 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); } 5955 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); } 5956 5957 static bool classof(const Stmt *T) { 5958 return T->getStmtClass() == TypoExprClass; 5959 } 5960 5961 }; 5962 } // end namespace clang 5963 5964 #endif // LLVM_CLANG_AST_EXPR_H 5965