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