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