1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Expr interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/TypeTraits.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APSInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Compiler.h"
37 class CXXBaseSpecifier;
38 class CXXMemberCallExpr;
39 class CXXOperatorCallExpr;
43 class MaterializeTemporaryExpr;
45 class ObjCPropertyRefExpr;
46 class OpaqueValueExpr;
52 /// \brief A simple array of base specifiers.
53 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
55 /// \brief An adjustment to be made to the temporary created when emitting a
56 /// reference binding, which accesses a particular subobject of that temporary.
57 struct SubobjectAdjustment {
59 DerivedToBaseAdjustment,
61 MemberPointerAdjustment
66 const CastExpr *BasePath;
67 const CXXRecordDecl *DerivedClass;
71 const MemberPointerType *MPT;
76 struct DTB DerivedToBase;
81 SubobjectAdjustment(const CastExpr *BasePath,
82 const CXXRecordDecl *DerivedClass)
83 : Kind(DerivedToBaseAdjustment) {
84 DerivedToBase.BasePath = BasePath;
85 DerivedToBase.DerivedClass = DerivedClass;
88 SubobjectAdjustment(FieldDecl *Field)
89 : Kind(FieldAdjustment) {
93 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
94 : Kind(MemberPointerAdjustment) {
100 /// Expr - This represents one expression. Note that Expr's are subclasses of
101 /// Stmt. This allows an expression to be transparently used any place a Stmt
104 class Expr : public Stmt {
108 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
109 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112 ExprBits.TypeDependent = TD;
113 ExprBits.ValueDependent = VD;
114 ExprBits.InstantiationDependent = ID;
115 ExprBits.ValueKind = VK;
116 ExprBits.ObjectKind = OK;
117 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121 /// \brief Construct an empty expression.
122 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
125 QualType getType() const { return TR; }
126 void setType(QualType t) {
127 // In C++, the type of an expression is always adjusted so that it
128 // will not have reference type (C++ [expr]p6). Use
129 // QualType::getNonReferenceType() to retrieve the non-reference
130 // type. Additionally, inspect Expr::isLvalue to determine whether
131 // an expression that is adjusted in this manner should be
132 // considered an lvalue.
133 assert((t.isNull() || !t->isReferenceType()) &&
134 "Expressions can't have reference type");
139 /// isValueDependent - Determines whether this expression is
140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141 /// array bound of "Chars" in the following example is
144 /// template<int Size, char (&Chars)[Size]> struct meta_string;
146 bool isValueDependent() const { return ExprBits.ValueDependent; }
148 /// \brief Set whether this expression is value-dependent or not.
149 void setValueDependent(bool VD) {
150 ExprBits.ValueDependent = VD;
152 ExprBits.InstantiationDependent = true;
155 /// isTypeDependent - Determines whether this expression is
156 /// type-dependent (C++ [temp.dep.expr]), which means that its type
157 /// could change from one template instantiation to the next. For
158 /// example, the expressions "x" and "x + y" are type-dependent in
159 /// the following code, but "y" is not type-dependent:
161 /// template<typename T>
162 /// void add(T x, int y) {
166 bool isTypeDependent() const { return ExprBits.TypeDependent; }
168 /// \brief Set whether this expression is type-dependent or not.
169 void setTypeDependent(bool TD) {
170 ExprBits.TypeDependent = TD;
172 ExprBits.InstantiationDependent = true;
175 /// \brief Whether this expression is instantiation-dependent, meaning that
176 /// it depends in some way on a template parameter, even if neither its type
177 /// nor (constant) value can change due to the template instantiation.
179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
180 /// instantiation-dependent (since it involves a template parameter \c T), but
181 /// is neither type- nor value-dependent, since the type of the inner
182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
183 /// \c sizeof is known.
186 /// template<typename T>
187 /// void f(T x, T y) {
188 /// sizeof(sizeof(T() + T());
192 bool isInstantiationDependent() const {
193 return ExprBits.InstantiationDependent;
196 /// \brief Set whether this expression is instantiation-dependent or not.
197 void setInstantiationDependent(bool ID) {
198 ExprBits.InstantiationDependent = ID;
201 /// \brief Whether this expression contains an unexpanded parameter
202 /// pack (for C++11 variadic templates).
204 /// Given the following function template:
207 /// template<typename F, typename ...Types>
208 /// void forward(const F &f, Types &&...args) {
209 /// f(static_cast<Types&&>(args)...);
213 /// The expressions \c args and \c static_cast<Types&&>(args) both
214 /// contain parameter packs.
215 bool containsUnexpandedParameterPack() const {
216 return ExprBits.ContainsUnexpandedParameterPack;
219 /// \brief Set the bit that describes whether this expression
220 /// contains an unexpanded parameter pack.
221 void setContainsUnexpandedParameterPack(bool PP = true) {
222 ExprBits.ContainsUnexpandedParameterPack = PP;
225 /// getExprLoc - Return the preferred location for the arrow when diagnosing
226 /// a problem with a generic expression.
227 SourceLocation getExprLoc() const LLVM_READONLY;
229 /// isUnusedResultAWarning - Return true if this immediate expression should
230 /// be warned about if the result is unused. If so, fill in expr, location,
231 /// and ranges with expr to warn on and source locations/ranges appropriate
233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
234 SourceRange &R1, SourceRange &R2,
235 ASTContext &Ctx) const;
237 /// isLValue - True if this expression is an "l-value" according to
238 /// the rules of the current language. C and C++ give somewhat
239 /// different rules for this concept, but in general, the result of
240 /// an l-value expression identifies a specific object whereas the
241 /// result of an r-value expression is a value detached from any
242 /// specific storage.
244 /// C++11 divides the concept of "r-value" into pure r-values
245 /// ("pr-values") and so-called expiring values ("x-values"), which
246 /// identify specific objects that can be safely cannibalized for
247 /// their resources. This is an unfortunate abuse of terminology on
248 /// the part of the C++ committee. In Clang, when we say "r-value",
249 /// we generally mean a pr-value.
250 bool isLValue() const { return getValueKind() == VK_LValue; }
251 bool isRValue() const { return getValueKind() == VK_RValue; }
252 bool isXValue() const { return getValueKind() == VK_XValue; }
253 bool isGLValue() const { return getValueKind() != VK_RValue; }
255 enum LValueClassification {
258 LV_IncompleteVoidType,
259 LV_DuplicateVectorComponents,
260 LV_InvalidExpression,
261 LV_InvalidMessageExpression,
263 LV_SubObjCPropertySetting,
267 /// Reasons why an expression might not be an l-value.
268 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
270 enum isModifiableLvalueResult {
273 MLV_IncompleteVoidType,
274 MLV_DuplicateVectorComponents,
275 MLV_InvalidExpression,
276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
280 MLV_NoSetterProperty,
282 MLV_SubObjCPropertySetting,
283 MLV_InvalidMessageExpression,
287 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
288 /// does not have an incomplete type, does not have a const-qualified type,
289 /// and if it is a structure or union, does not have any member (including,
290 /// recursively, any member or element of all contained aggregates or unions)
291 /// with a const-qualified type.
293 /// \param Loc [in,out] - A source location which *may* be filled
294 /// in with the location of the expression making this a
295 /// non-modifiable lvalue, if specified.
296 isModifiableLvalueResult
297 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299 /// \brief The return type of classify(). Represents the C++11 expression
301 class Classification {
303 /// \brief The various classification results. Most of these mean prvalue.
307 CL_Function, // Functions cannot be lvalues in C.
308 CL_Void, // Void cannot be an lvalue in C.
309 CL_AddressableVoid, // Void expression whose address can be taken in C.
310 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
311 CL_MemberFunction, // An expression referring to a member function
312 CL_SubObjCPropertySetting,
313 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
314 CL_ArrayTemporary, // A temporary of array type.
315 CL_ObjCMessageRValue, // ObjC message is an rvalue
316 CL_PRValue // A prvalue for any other reason, of any other type
318 /// \brief The results of modification testing.
319 enum ModifiableType {
320 CM_Untested, // testModifiable was false.
322 CM_RValue, // Not modifiable because it's an rvalue
323 CM_Function, // Not modifiable because it's a function; C++ only
324 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
325 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
335 unsigned short Modifiable;
337 explicit Classification(Kinds k, ModifiableType m)
338 : Kind(k), Modifiable(m)
344 Kinds getKind() const { return static_cast<Kinds>(Kind); }
345 ModifiableType getModifiable() const {
346 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
347 return static_cast<ModifiableType>(Modifiable);
349 bool isLValue() const { return Kind == CL_LValue; }
350 bool isXValue() const { return Kind == CL_XValue; }
351 bool isGLValue() const { return Kind <= CL_XValue; }
352 bool isPRValue() const { return Kind >= CL_Function; }
353 bool isRValue() const { return Kind >= CL_XValue; }
354 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
356 /// \brief Create a simple, modifiably lvalue
357 static Classification makeSimpleLValue() {
358 return Classification(CL_LValue, CM_Modifiable);
362 /// \brief Classify - Classify this expression according to the C++11
363 /// expression taxonomy.
365 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
366 /// old lvalue vs rvalue. This function determines the type of expression this
367 /// is. There are three expression types:
368 /// - lvalues are classical lvalues as in C++03.
369 /// - prvalues are equivalent to rvalues in C++03.
370 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
371 /// function returning an rvalue reference.
372 /// lvalues and xvalues are collectively referred to as glvalues, while
373 /// prvalues and xvalues together form rvalues.
374 Classification Classify(ASTContext &Ctx) const {
375 return ClassifyImpl(Ctx, nullptr);
378 /// \brief ClassifyModifiable - Classify this expression according to the
379 /// C++11 expression taxonomy, and see if it is valid on the left side
380 /// of an assignment.
382 /// This function extends classify in that it also tests whether the
383 /// expression is modifiable (C99 6.3.2.1p1).
384 /// \param Loc A source location that might be filled with a relevant location
385 /// if the expression is not modifiable.
386 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
387 return ClassifyImpl(Ctx, &Loc);
390 /// getValueKindForType - Given a formal return or parameter type,
391 /// give its value kind.
392 static ExprValueKind getValueKindForType(QualType T) {
393 if (const ReferenceType *RT = T->getAs<ReferenceType>())
394 return (isa<LValueReferenceType>(RT)
396 : (RT->getPointeeType()->isFunctionType()
397 ? VK_LValue : VK_XValue));
401 /// getValueKind - The value kind that this expression produces.
402 ExprValueKind getValueKind() const {
403 return static_cast<ExprValueKind>(ExprBits.ValueKind);
406 /// getObjectKind - The object kind that this expression produces.
407 /// Object kinds are meaningful only for expressions that yield an
408 /// l-value or x-value.
409 ExprObjectKind getObjectKind() const {
410 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
413 bool isOrdinaryOrBitFieldObject() const {
414 ExprObjectKind OK = getObjectKind();
415 return (OK == OK_Ordinary || OK == OK_BitField);
418 /// setValueKind - Set the value kind produced by this expression.
419 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
421 /// setObjectKind - Set the object kind produced by this expression.
422 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
425 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429 /// \brief Returns true if this expression is a gl-value that
430 /// potentially refers to a bit-field.
432 /// In C++, whether a gl-value refers to a bitfield is essentially
433 /// an aspect of the value-kind type system.
434 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
436 /// \brief If this expression refers to a bit-field, retrieve the
437 /// declaration of that bit-field.
439 /// Note that this returns a non-null pointer in subtly different
440 /// places than refersToBitField returns true. In particular, this can
441 /// return a non-null pointer even for r-values loaded from
442 /// bit-fields, but it will return null for a conditional bit-field.
443 FieldDecl *getSourceBitField();
445 const FieldDecl *getSourceBitField() const {
446 return const_cast<Expr*>(this)->getSourceBitField();
449 /// \brief If this expression is an l-value for an Objective C
450 /// property, find the underlying property reference expression.
451 const ObjCPropertyRefExpr *getObjCProperty() const;
453 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
454 bool isObjCSelfExpr() const;
456 /// \brief Returns whether this expression refers to a vector element.
457 bool refersToVectorElement() const;
459 /// \brief Returns whether this expression has a placeholder type.
460 bool hasPlaceholderType() const {
461 return getType()->isPlaceholderType();
464 /// \brief Returns whether this expression has a specific placeholder type.
465 bool hasPlaceholderType(BuiltinType::Kind K) const {
466 assert(BuiltinType::isPlaceholderTypeKind(K));
467 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
468 return BT->getKind() == K;
472 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
473 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
474 /// but also int expressions which are produced by things like comparisons in
476 bool isKnownToHaveBooleanValue() const;
478 /// isIntegerConstantExpr - Return true if this expression is a valid integer
479 /// constant expression, and, if so, return its value in Result. If not a
480 /// valid i-c-e, return false and fill in Loc (if specified) with the location
481 /// of the invalid expression.
483 /// Note: This does not perform the implicit conversions required by C++11
485 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
486 SourceLocation *Loc = nullptr,
487 bool isEvaluated = true) const;
488 bool isIntegerConstantExpr(const ASTContext &Ctx,
489 SourceLocation *Loc = nullptr) const;
491 /// isCXX98IntegralConstantExpr - Return true if this expression is an
492 /// integral constant expression in C++98. Can only be used in C++.
493 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
495 /// isCXX11ConstantExpr - Return true if this expression is a constant
496 /// expression in C++11. Can only be used in C++.
498 /// Note: This does not perform the implicit conversions required by C++11
500 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
501 SourceLocation *Loc = nullptr) const;
503 /// isPotentialConstantExpr - Return true if this function's definition
504 /// might be usable in a constant expression in C++11, if it were marked
505 /// constexpr. Return false if the function can never produce a constant
506 /// expression, along with diagnostics describing why not.
507 static bool isPotentialConstantExpr(const FunctionDecl *FD,
509 PartialDiagnosticAt> &Diags);
511 /// isPotentialConstantExprUnevaluted - Return true if this expression might
512 /// be usable in a constant expression in C++11 in an unevaluated context, if
513 /// it were in function FD marked constexpr. Return false if the function can
514 /// never produce a constant expression, along with diagnostics describing
516 static bool isPotentialConstantExprUnevaluated(Expr *E,
517 const FunctionDecl *FD,
519 PartialDiagnosticAt> &Diags);
521 /// isConstantInitializer - Returns true if this expression can be emitted to
522 /// IR as a constant, and thus can be used as a constant initializer in C.
523 /// If this expression is not constant and Culprit is non-null,
524 /// it is used to store the address of first non constant expr.
525 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
526 const Expr **Culprit = nullptr) const;
528 /// EvalStatus is a struct with detailed info about an evaluation in progress.
530 /// HasSideEffects - Whether the evaluated expression has side effects.
531 /// For example, (f() && 0) can be folded, but it still has side effects.
534 /// Diag - If this is non-null, it will be filled in with a stack of notes
535 /// indicating why evaluation failed (or why it failed to produce a constant
537 /// If the expression is unfoldable, the notes will indicate why it's not
538 /// foldable. If the expression is foldable, but not a constant expression,
539 /// the notes will describes why it isn't a constant expression. If the
540 /// expression *is* a constant expression, no notes will be produced.
541 SmallVectorImpl<PartialDiagnosticAt> *Diag;
543 EvalStatus() : HasSideEffects(false), Diag(nullptr) {}
545 // hasSideEffects - Return true if the evaluated expression has
547 bool hasSideEffects() const {
548 return HasSideEffects;
552 /// EvalResult is a struct with detailed info about an evaluated expression.
553 struct EvalResult : EvalStatus {
554 /// Val - This is the value the expression can be folded to.
557 // isGlobalLValue - Return true if the evaluated lvalue expression
559 bool isGlobalLValue() const;
562 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
563 /// an rvalue using any crazy technique (that has nothing to do with language
564 /// standards) that we want to, even if the expression has side-effects. If
565 /// this function returns true, it returns the folded constant in Result. If
566 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
568 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
570 /// EvaluateAsBooleanCondition - Return true if this is a constant
571 /// which we we can fold and convert to a boolean condition using
572 /// any crazy technique that we want to, even if the expression has
574 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
576 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
578 /// EvaluateAsInt - Return true if this is a constant which we can fold and
579 /// convert to an integer, using any crazy technique that we want to.
580 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
581 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
583 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
584 /// constant folded without side-effects, but discard the result.
585 bool isEvaluatable(const ASTContext &Ctx) const;
587 /// HasSideEffects - This routine returns true for all those expressions
588 /// which have any effect other than producing a value. Example is a function
589 /// call, volatile variable read, or throwing an exception. If
590 /// IncludePossibleEffects is false, this call treats certain expressions with
591 /// potential side effects (such as function call-like expressions,
592 /// instantiation-dependent expressions, or invocations from a macro) as not
593 /// having side effects.
594 bool HasSideEffects(const ASTContext &Ctx,
595 bool IncludePossibleEffects = true) const;
597 /// \brief Determine whether this expression involves a call to any function
598 /// that is not trivial.
599 bool hasNonTrivialCall(ASTContext &Ctx);
601 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
602 /// integer. This must be called on an expression that constant folds to an
604 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
605 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
607 void EvaluateForOverflow(const ASTContext &Ctx) const;
609 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
610 /// lvalue with link time known address, with no side-effects.
611 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
613 /// EvaluateAsInitializer - Evaluate an expression as if it were the
614 /// initializer of the given declaration. Returns true if the initializer
615 /// can be folded to a constant, and produces any relevant notes. In C++11,
616 /// notes will be produced if the expression is not a constant expression.
617 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
619 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
621 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
622 /// of a call to the given function with the given arguments, inside an
623 /// unevaluated context. Returns true if the expression could be folded to a
625 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
626 const FunctionDecl *Callee,
627 ArrayRef<const Expr*> Args) const;
629 /// \brief Enumeration used to describe the kind of Null pointer constant
630 /// returned from \c isNullPointerConstant().
631 enum NullPointerConstantKind {
632 /// \brief Expression is not a Null pointer constant.
635 /// \brief Expression is a Null pointer constant built from a zero integer
636 /// expression that is not a simple, possibly parenthesized, zero literal.
637 /// C++ Core Issue 903 will classify these expressions as "not pointers"
638 /// once it is adopted.
639 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
642 /// \brief Expression is a Null pointer constant built from a literal zero.
645 /// \brief Expression is a C++11 nullptr.
648 /// \brief Expression is a GNU-style __null constant.
652 /// \brief Enumeration used to describe how \c isNullPointerConstant()
653 /// should cope with value-dependent expressions.
654 enum NullPointerConstantValueDependence {
655 /// \brief Specifies that the expression should never be value-dependent.
656 NPC_NeverValueDependent = 0,
658 /// \brief Specifies that a value-dependent expression of integral or
659 /// dependent type should be considered a null pointer constant.
660 NPC_ValueDependentIsNull,
662 /// \brief Specifies that a value-dependent expression should be considered
663 /// to never be a null pointer constant.
664 NPC_ValueDependentIsNotNull
667 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
668 /// a Null pointer constant. The return value can further distinguish the
669 /// kind of NULL pointer constant that was detected.
670 NullPointerConstantKind isNullPointerConstant(
672 NullPointerConstantValueDependence NPC) const;
674 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
676 bool isOBJCGCCandidate(ASTContext &Ctx) const;
678 /// \brief Returns true if this expression is a bound member function.
679 bool isBoundMemberFunction(ASTContext &Ctx) const;
681 /// \brief Given an expression of bound-member type, find the type
682 /// of the member. Returns null if this is an *overloaded* bound
683 /// member expression.
684 static QualType findBoundMemberType(const Expr *expr);
686 /// IgnoreImpCasts - Skip past any implicit casts which might
687 /// surround this expression. Only skips ImplicitCastExprs.
688 Expr *IgnoreImpCasts() LLVM_READONLY;
690 /// IgnoreImplicit - Skip past any implicit AST nodes which might
691 /// surround this expression.
692 Expr *IgnoreImplicit() LLVM_READONLY {
693 return cast<Expr>(Stmt::IgnoreImplicit());
696 const Expr *IgnoreImplicit() const LLVM_READONLY {
697 return const_cast<Expr*>(this)->IgnoreImplicit();
700 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
701 /// its subexpression. If that subexpression is also a ParenExpr,
702 /// then this method recursively returns its subexpression, and so forth.
703 /// Otherwise, the method returns the current Expr.
704 Expr *IgnoreParens() LLVM_READONLY;
706 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
707 /// or CastExprs, returning their operand.
708 Expr *IgnoreParenCasts() LLVM_READONLY;
710 /// Ignore casts. Strip off any CastExprs, returning their operand.
711 Expr *IgnoreCasts() LLVM_READONLY;
713 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
714 /// any ParenExpr or ImplicitCastExprs, returning their operand.
715 Expr *IgnoreParenImpCasts() LLVM_READONLY;
717 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
718 /// call to a conversion operator, return the argument.
719 Expr *IgnoreConversionOperator() LLVM_READONLY;
721 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
722 return const_cast<Expr*>(this)->IgnoreConversionOperator();
725 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
726 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
729 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
730 /// CastExprs that represent lvalue casts, returning their operand.
731 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
733 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
734 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
737 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
738 /// value (including ptr->int casts of the same size). Strip off any
739 /// ParenExpr or CastExprs, returning their operand.
740 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
742 /// Ignore parentheses and derived-to-base casts.
743 Expr *ignoreParenBaseCasts() LLVM_READONLY;
745 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
749 /// \brief Determine whether this expression is a default function argument.
751 /// Default arguments are implicitly generated in the abstract syntax tree
752 /// by semantic analysis for function calls, object constructions, etc. in
753 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
754 /// this routine also looks through any implicit casts to determine whether
755 /// the expression is a default argument.
756 bool isDefaultArgument() const;
758 /// \brief Determine whether the result of this expression is a
759 /// temporary object of the given class type.
760 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
762 /// \brief Whether this expression is an implicit reference to 'this' in C++.
763 bool isImplicitCXXThis() const;
765 const Expr *IgnoreImpCasts() const LLVM_READONLY {
766 return const_cast<Expr*>(this)->IgnoreImpCasts();
768 const Expr *IgnoreParens() const LLVM_READONLY {
769 return const_cast<Expr*>(this)->IgnoreParens();
771 const Expr *IgnoreParenCasts() const LLVM_READONLY {
772 return const_cast<Expr*>(this)->IgnoreParenCasts();
774 /// Strip off casts, but keep parentheses.
775 const Expr *IgnoreCasts() const LLVM_READONLY {
776 return const_cast<Expr*>(this)->IgnoreCasts();
779 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
780 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
783 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
785 /// \brief For an expression of class type or pointer to class type,
786 /// return the most derived class decl the expression is known to refer to.
788 /// If this expression is a cast, this method looks through it to find the
789 /// most derived decl that can be inferred from the expression.
790 /// This is valid because derived-to-base conversions have undefined
791 /// behavior if the object isn't dynamically of the derived type.
792 const CXXRecordDecl *getBestDynamicClassType() const;
794 /// Walk outwards from an expression we want to bind a reference to and
795 /// find the expression whose lifetime needs to be extended. Record
796 /// the LHSs of comma expressions and adjustments needed along the path.
797 const Expr *skipRValueSubobjectAdjustments(
798 SmallVectorImpl<const Expr *> &CommaLHS,
799 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
801 static bool classof(const Stmt *T) {
802 return T->getStmtClass() >= firstExprConstant &&
803 T->getStmtClass() <= lastExprConstant;
808 //===----------------------------------------------------------------------===//
809 // Primary Expressions.
810 //===----------------------------------------------------------------------===//
812 /// OpaqueValueExpr - An expression referring to an opaque object of a
813 /// fixed type and value class. These don't correspond to concrete
814 /// syntax; instead they're used to express operations (usually copy
815 /// operations) on values whose source is generally obvious from
817 class OpaqueValueExpr : public Expr {
818 friend class ASTStmtReader;
823 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
824 ExprObjectKind OK = OK_Ordinary,
825 Expr *SourceExpr = nullptr)
826 : Expr(OpaqueValueExprClass, T, VK, OK,
827 T->isDependentType(),
828 T->isDependentType() ||
829 (SourceExpr && SourceExpr->isValueDependent()),
830 T->isInstantiationDependentType(),
832 SourceExpr(SourceExpr), Loc(Loc) {
835 /// Given an expression which invokes a copy constructor --- i.e. a
836 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
837 /// find the OpaqueValueExpr that's the source of the construction.
838 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
840 explicit OpaqueValueExpr(EmptyShell Empty)
841 : Expr(OpaqueValueExprClass, Empty) { }
843 /// \brief Retrieve the location of this expression.
844 SourceLocation getLocation() const { return Loc; }
846 SourceLocation getLocStart() const LLVM_READONLY {
847 return SourceExpr ? SourceExpr->getLocStart() : Loc;
849 SourceLocation getLocEnd() const LLVM_READONLY {
850 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
852 SourceLocation getExprLoc() const LLVM_READONLY {
853 if (SourceExpr) return SourceExpr->getExprLoc();
857 child_range children() { return child_range(); }
859 /// The source expression of an opaque value expression is the
860 /// expression which originally generated the value. This is
861 /// provided as a convenience for analyses that don't wish to
862 /// precisely model the execution behavior of the program.
864 /// The source expression is typically set when building the
865 /// expression which binds the opaque value expression in the first
867 Expr *getSourceExpr() const { return SourceExpr; }
869 static bool classof(const Stmt *T) {
870 return T->getStmtClass() == OpaqueValueExprClass;
874 /// \brief A reference to a declared variable, function, enum, etc.
877 /// This encodes all the information about how a declaration is referenced
878 /// within an expression.
880 /// There are several optional constructs attached to DeclRefExprs only when
881 /// they apply in order to conserve memory. These are laid out past the end of
882 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
884 /// DeclRefExprBits.HasQualifier:
885 /// Specifies when this declaration reference expression has a C++
886 /// nested-name-specifier.
887 /// DeclRefExprBits.HasFoundDecl:
888 /// Specifies when this declaration reference expression has a record of
889 /// a NamedDecl (different from the referenced ValueDecl) which was found
890 /// during name lookup and/or overload resolution.
891 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
892 /// Specifies when this declaration reference expression has an explicit
893 /// C++ template keyword and/or template argument list.
894 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
895 /// Specifies when this declaration reference expression (validly)
896 /// refers to an enclosed local or a captured variable.
897 class DeclRefExpr : public Expr {
898 /// \brief The declaration that we are referencing.
901 /// \brief The location of the declaration name itself.
904 /// \brief Provides source/type location info for the declaration name
906 DeclarationNameLoc DNLoc;
908 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
909 NestedNameSpecifierLoc &getInternalQualifierLoc() {
910 assert(hasQualifier());
911 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
914 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
915 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
916 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
919 /// \brief Test whether there is a distinct FoundDecl attached to the end of
921 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
923 /// \brief Helper to retrieve the optional NamedDecl through which this
924 /// reference occurred.
925 NamedDecl *&getInternalFoundDecl() {
926 assert(hasFoundDecl());
928 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
929 return *reinterpret_cast<NamedDecl **>(this + 1);
932 /// \brief Helper to retrieve the optional NamedDecl through which this
933 /// reference occurred.
934 NamedDecl *getInternalFoundDecl() const {
935 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
938 DeclRefExpr(const ASTContext &Ctx,
939 NestedNameSpecifierLoc QualifierLoc,
940 SourceLocation TemplateKWLoc,
941 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
942 const DeclarationNameInfo &NameInfo,
944 const TemplateArgumentListInfo *TemplateArgs,
945 QualType T, ExprValueKind VK);
947 /// \brief Construct an empty declaration reference expression.
948 explicit DeclRefExpr(EmptyShell Empty)
949 : Expr(DeclRefExprClass, Empty) { }
951 /// \brief Computes the type- and value-dependence flags for this
952 /// declaration reference expression.
953 void computeDependence(const ASTContext &C);
956 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
957 ExprValueKind VK, SourceLocation L,
958 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
959 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
960 D(D), Loc(L), DNLoc(LocInfo) {
961 DeclRefExprBits.HasQualifier = 0;
962 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
963 DeclRefExprBits.HasFoundDecl = 0;
964 DeclRefExprBits.HadMultipleCandidates = 0;
965 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
966 RefersToEnclosingVariableOrCapture;
967 computeDependence(D->getASTContext());
971 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
972 SourceLocation TemplateKWLoc, ValueDecl *D,
973 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
974 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
975 const TemplateArgumentListInfo *TemplateArgs = nullptr);
978 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
979 SourceLocation TemplateKWLoc, ValueDecl *D,
980 bool RefersToEnclosingVariableOrCapture,
981 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
982 NamedDecl *FoundD = nullptr,
983 const TemplateArgumentListInfo *TemplateArgs = nullptr);
985 /// \brief Construct an empty declaration reference expression.
986 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
989 bool HasTemplateKWAndArgsInfo,
990 unsigned NumTemplateArgs);
992 ValueDecl *getDecl() { return D; }
993 const ValueDecl *getDecl() const { return D; }
994 void setDecl(ValueDecl *NewD) { D = NewD; }
996 DeclarationNameInfo getNameInfo() const {
997 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1000 SourceLocation getLocation() const { return Loc; }
1001 void setLocation(SourceLocation L) { Loc = L; }
1002 SourceLocation getLocStart() const LLVM_READONLY;
1003 SourceLocation getLocEnd() const LLVM_READONLY;
1005 /// \brief Determine whether this declaration reference was preceded by a
1006 /// C++ nested-name-specifier, e.g., \c N::foo.
1007 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1009 /// \brief If the name was qualified, retrieves the nested-name-specifier
1010 /// that precedes the name. Otherwise, returns NULL.
1011 NestedNameSpecifier *getQualifier() const {
1012 if (!hasQualifier())
1015 return getInternalQualifierLoc().getNestedNameSpecifier();
1018 /// \brief If the name was qualified, retrieves the nested-name-specifier
1019 /// that precedes the name, with source-location information.
1020 NestedNameSpecifierLoc getQualifierLoc() const {
1021 if (!hasQualifier())
1022 return NestedNameSpecifierLoc();
1024 return getInternalQualifierLoc();
1027 /// \brief Get the NamedDecl through which this reference occurred.
1029 /// This Decl may be different from the ValueDecl actually referred to in the
1030 /// presence of using declarations, etc. It always returns non-NULL, and may
1031 /// simple return the ValueDecl when appropriate.
1032 NamedDecl *getFoundDecl() {
1033 return hasFoundDecl() ? getInternalFoundDecl() : D;
1036 /// \brief Get the NamedDecl through which this reference occurred.
1037 /// See non-const variant.
1038 const NamedDecl *getFoundDecl() const {
1039 return hasFoundDecl() ? getInternalFoundDecl() : D;
1042 bool hasTemplateKWAndArgsInfo() const {
1043 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1046 /// \brief Return the optional template keyword and arguments info.
1047 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1048 if (!hasTemplateKWAndArgsInfo())
1052 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1053 &getInternalFoundDecl() + 1);
1056 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1057 &getInternalQualifierLoc() + 1);
1059 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1062 /// \brief Return the optional template keyword and arguments info.
1063 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1064 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1067 /// \brief Retrieve the location of the template keyword preceding
1068 /// this name, if any.
1069 SourceLocation getTemplateKeywordLoc() const {
1070 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1071 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1074 /// \brief Retrieve the location of the left angle bracket starting the
1075 /// explicit template argument list following the name, if any.
1076 SourceLocation getLAngleLoc() const {
1077 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1078 return getTemplateKWAndArgsInfo()->LAngleLoc;
1081 /// \brief Retrieve the location of the right angle bracket ending the
1082 /// explicit template argument list following the name, if any.
1083 SourceLocation getRAngleLoc() const {
1084 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1085 return getTemplateKWAndArgsInfo()->RAngleLoc;
1088 /// \brief Determines whether the name in this declaration reference
1089 /// was preceded by the template keyword.
1090 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1092 /// \brief Determines whether this declaration reference was followed by an
1093 /// explicit template argument list.
1094 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1096 /// \brief Retrieve the explicit template argument list that followed the
1097 /// member template name.
1098 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1099 assert(hasExplicitTemplateArgs());
1100 return *getTemplateKWAndArgsInfo();
1103 /// \brief Retrieve the explicit template argument list that followed the
1104 /// member template name.
1105 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1106 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1109 /// \brief Retrieves the optional explicit template arguments.
1110 /// This points to the same data as getExplicitTemplateArgs(), but
1111 /// returns null if there are no explicit template arguments.
1112 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1113 if (!hasExplicitTemplateArgs()) return nullptr;
1114 return &getExplicitTemplateArgs();
1117 /// \brief Copies the template arguments (if present) into the given
1119 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1120 if (hasExplicitTemplateArgs())
1121 getExplicitTemplateArgs().copyInto(List);
1124 /// \brief Retrieve the template arguments provided as part of this
1126 const TemplateArgumentLoc *getTemplateArgs() const {
1127 if (!hasExplicitTemplateArgs())
1130 return getExplicitTemplateArgs().getTemplateArgs();
1133 /// \brief Retrieve the number of template arguments provided as part of this
1135 unsigned getNumTemplateArgs() const {
1136 if (!hasExplicitTemplateArgs())
1139 return getExplicitTemplateArgs().NumTemplateArgs;
1142 /// \brief Returns true if this expression refers to a function that
1143 /// was resolved from an overloaded set having size greater than 1.
1144 bool hadMultipleCandidates() const {
1145 return DeclRefExprBits.HadMultipleCandidates;
1147 /// \brief Sets the flag telling whether this expression refers to
1148 /// a function that was resolved from an overloaded set having size
1150 void setHadMultipleCandidates(bool V = true) {
1151 DeclRefExprBits.HadMultipleCandidates = V;
1154 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1156 bool refersToEnclosingVariableOrCapture() const {
1157 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1160 static bool classof(const Stmt *T) {
1161 return T->getStmtClass() == DeclRefExprClass;
1165 child_range children() { return child_range(); }
1167 friend class ASTStmtReader;
1168 friend class ASTStmtWriter;
1171 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1172 class PredefinedExpr : public Expr {
1177 LFunction, // Same as Function, but as wide string.
1181 /// \brief The same as PrettyFunction, except that the
1182 /// 'virtual' keyword is omitted for virtual member functions.
1183 PrettyFunctionNoVirtual
1192 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1195 /// \brief Construct an empty predefined expression.
1196 explicit PredefinedExpr(EmptyShell Empty)
1197 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1199 IdentType getIdentType() const { return Type; }
1201 SourceLocation getLocation() const { return Loc; }
1202 void setLocation(SourceLocation L) { Loc = L; }
1204 StringLiteral *getFunctionName();
1205 const StringLiteral *getFunctionName() const {
1206 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1209 static StringRef getIdentTypeName(IdentType IT);
1210 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1212 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1213 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1215 static bool classof(const Stmt *T) {
1216 return T->getStmtClass() == PredefinedExprClass;
1220 child_range children() { return child_range(&FnName, &FnName + 1); }
1222 friend class ASTStmtReader;
1225 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1228 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1229 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1230 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1231 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1232 /// ASTContext's allocator for memory allocation.
1233 class APNumericStorage {
1235 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1236 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1240 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1242 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1243 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1246 APNumericStorage() : VAL(0), BitWidth(0) { }
1248 llvm::APInt getIntValue() const {
1249 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1251 return llvm::APInt(BitWidth, NumWords, pVal);
1253 return llvm::APInt(BitWidth, VAL);
1255 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1258 class APIntStorage : private APNumericStorage {
1260 llvm::APInt getValue() const { return getIntValue(); }
1261 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1262 setIntValue(C, Val);
1266 class APFloatStorage : private APNumericStorage {
1268 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1269 return llvm::APFloat(Semantics, getIntValue());
1271 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1272 setIntValue(C, Val.bitcastToAPInt());
1276 class IntegerLiteral : public Expr, public APIntStorage {
1279 /// \brief Construct an empty integer literal.
1280 explicit IntegerLiteral(EmptyShell Empty)
1281 : Expr(IntegerLiteralClass, Empty) { }
1284 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1285 // or UnsignedLongLongTy
1286 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1289 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1290 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1291 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1292 /// \param V - the value that the returned integer literal contains.
1293 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1294 QualType type, SourceLocation l);
1295 /// \brief Returns a new empty integer literal.
1296 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1298 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1299 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1301 /// \brief Retrieve the location of the literal.
1302 SourceLocation getLocation() const { return Loc; }
1304 void setLocation(SourceLocation Location) { Loc = Location; }
1306 static bool classof(const Stmt *T) {
1307 return T->getStmtClass() == IntegerLiteralClass;
1311 child_range children() { return child_range(); }
1314 class CharacterLiteral : public Expr {
1316 enum CharacterKind {
1327 // type should be IntTy
1328 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1330 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1332 Value(value), Loc(l) {
1333 CharacterLiteralBits.Kind = kind;
1336 /// \brief Construct an empty character literal.
1337 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1339 SourceLocation getLocation() const { return Loc; }
1340 CharacterKind getKind() const {
1341 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1344 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1345 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1347 unsigned getValue() const { return Value; }
1349 void setLocation(SourceLocation Location) { Loc = Location; }
1350 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1351 void setValue(unsigned Val) { Value = Val; }
1353 static bool classof(const Stmt *T) {
1354 return T->getStmtClass() == CharacterLiteralClass;
1358 child_range children() { return child_range(); }
1361 class FloatingLiteral : public Expr, private APFloatStorage {
1364 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1365 QualType Type, SourceLocation L);
1367 /// \brief Construct an empty floating-point literal.
1368 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1371 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1372 bool isexact, QualType Type, SourceLocation L);
1373 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1375 llvm::APFloat getValue() const {
1376 return APFloatStorage::getValue(getSemantics());
1378 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1379 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1380 APFloatStorage::setValue(C, Val);
1383 /// Get a raw enumeration value representing the floating-point semantics of
1384 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1385 APFloatSemantics getRawSemantics() const {
1386 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1389 /// Set the raw enumeration value representing the floating-point semantics of
1390 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1391 void setRawSemantics(APFloatSemantics Sem) {
1392 FloatingLiteralBits.Semantics = Sem;
1395 /// Return the APFloat semantics this literal uses.
1396 const llvm::fltSemantics &getSemantics() const;
1398 /// Set the APFloat semantics this literal uses.
1399 void setSemantics(const llvm::fltSemantics &Sem);
1401 bool isExact() const { return FloatingLiteralBits.IsExact; }
1402 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1404 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1405 /// double. Note that this may cause loss of precision, but is useful for
1406 /// debugging dumps, etc.
1407 double getValueAsApproximateDouble() const;
1409 SourceLocation getLocation() const { return Loc; }
1410 void setLocation(SourceLocation L) { Loc = L; }
1412 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1413 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1415 static bool classof(const Stmt *T) {
1416 return T->getStmtClass() == FloatingLiteralClass;
1420 child_range children() { return child_range(); }
1423 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1424 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1425 /// IntegerLiteral classes. Instances of this class always have a Complex type
1426 /// whose element type matches the subexpression.
1428 class ImaginaryLiteral : public Expr {
1431 ImaginaryLiteral(Expr *val, QualType Ty)
1432 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1436 /// \brief Build an empty imaginary literal.
1437 explicit ImaginaryLiteral(EmptyShell Empty)
1438 : Expr(ImaginaryLiteralClass, Empty) { }
1440 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1441 Expr *getSubExpr() { return cast<Expr>(Val); }
1442 void setSubExpr(Expr *E) { Val = E; }
1444 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1445 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1447 static bool classof(const Stmt *T) {
1448 return T->getStmtClass() == ImaginaryLiteralClass;
1452 child_range children() { return child_range(&Val, &Val+1); }
1455 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1456 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1457 /// is NOT null-terminated, and the length of the string is determined by
1458 /// calling getByteLength(). The C type for a string is always a
1459 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1462 /// Note that strings in C can be formed by concatenation of multiple string
1463 /// literal pptokens in translation phase #6. This keeps track of the locations
1464 /// of each of these pieces.
1466 /// Strings in C can also be truncated and extended by assigning into arrays,
1467 /// e.g. with constructs like:
1468 /// char X[2] = "foobar";
1469 /// In this case, getByteLength() will return 6, but the string literal will
1470 /// have type "char[2]".
1471 class StringLiteral : public Expr {
1482 friend class ASTStmtReader;
1486 const uint16_t *asUInt16;
1487 const uint32_t *asUInt32;
1490 unsigned CharByteWidth : 4;
1492 unsigned IsPascal : 1;
1493 unsigned NumConcatenated;
1494 SourceLocation TokLocs[1];
1496 StringLiteral(QualType Ty) :
1497 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1500 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1503 /// This is the "fully general" constructor that allows representation of
1504 /// strings formed from multiple concatenated tokens.
1505 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1506 StringKind Kind, bool Pascal, QualType Ty,
1507 const SourceLocation *Loc, unsigned NumStrs);
1509 /// Simple constructor for string literals made from one token.
1510 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1511 StringKind Kind, bool Pascal, QualType Ty,
1512 SourceLocation Loc) {
1513 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1516 /// \brief Construct an empty string literal.
1517 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1519 StringRef getString() const {
1520 assert(CharByteWidth==1
1521 && "This function is used in places that assume strings use char");
1522 return StringRef(StrData.asChar, getByteLength());
1525 /// Allow access to clients that need the byte representation, such as
1526 /// ASTWriterStmt::VisitStringLiteral().
1527 StringRef getBytes() const {
1528 // FIXME: StringRef may not be the right type to use as a result for this.
1529 if (CharByteWidth == 1)
1530 return StringRef(StrData.asChar, getByteLength());
1531 if (CharByteWidth == 4)
1532 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1534 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1535 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1539 void outputString(raw_ostream &OS) const;
1541 uint32_t getCodeUnit(size_t i) const {
1542 assert(i < Length && "out of bounds access");
1543 if (CharByteWidth == 1)
1544 return static_cast<unsigned char>(StrData.asChar[i]);
1545 if (CharByteWidth == 4)
1546 return StrData.asUInt32[i];
1547 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1548 return StrData.asUInt16[i];
1551 unsigned getByteLength() const { return CharByteWidth*Length; }
1552 unsigned getLength() const { return Length; }
1553 unsigned getCharByteWidth() const { return CharByteWidth; }
1555 /// \brief Sets the string data to the given string data.
1556 void setString(const ASTContext &C, StringRef Str,
1557 StringKind Kind, bool IsPascal);
1559 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1562 bool isAscii() const { return Kind == Ascii; }
1563 bool isWide() const { return Kind == Wide; }
1564 bool isUTF8() const { return Kind == UTF8; }
1565 bool isUTF16() const { return Kind == UTF16; }
1566 bool isUTF32() const { return Kind == UTF32; }
1567 bool isPascal() const { return IsPascal; }
1569 bool containsNonAsciiOrNull() const {
1570 StringRef Str = getString();
1571 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1572 if (!isASCII(Str[i]) || !Str[i])
1577 /// getNumConcatenated - Get the number of string literal tokens that were
1578 /// concatenated in translation phase #6 to form this string literal.
1579 unsigned getNumConcatenated() const { return NumConcatenated; }
1581 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1582 assert(TokNum < NumConcatenated && "Invalid tok number");
1583 return TokLocs[TokNum];
1585 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1586 assert(TokNum < NumConcatenated && "Invalid tok number");
1587 TokLocs[TokNum] = L;
1590 /// getLocationOfByte - Return a source location that points to the specified
1591 /// byte of this string literal.
1593 /// Strings are amazingly complex. They can be formed from multiple tokens
1594 /// and can have escape sequences in them in addition to the usual trigraph
1595 /// and escaped newline business. This routine handles this complexity.
1597 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1598 const LangOptions &Features,
1599 const TargetInfo &Target) const;
1601 typedef const SourceLocation *tokloc_iterator;
1602 tokloc_iterator tokloc_begin() const { return TokLocs; }
1603 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1605 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1606 SourceLocation getLocEnd() const LLVM_READONLY {
1607 return TokLocs[NumConcatenated - 1];
1610 static bool classof(const Stmt *T) {
1611 return T->getStmtClass() == StringLiteralClass;
1615 child_range children() { return child_range(); }
1618 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1619 /// AST node is only formed if full location information is requested.
1620 class ParenExpr : public Expr {
1621 SourceLocation L, R;
1624 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1625 : Expr(ParenExprClass, val->getType(),
1626 val->getValueKind(), val->getObjectKind(),
1627 val->isTypeDependent(), val->isValueDependent(),
1628 val->isInstantiationDependent(),
1629 val->containsUnexpandedParameterPack()),
1630 L(l), R(r), Val(val) {}
1632 /// \brief Construct an empty parenthesized expression.
1633 explicit ParenExpr(EmptyShell Empty)
1634 : Expr(ParenExprClass, Empty) { }
1636 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1637 Expr *getSubExpr() { return cast<Expr>(Val); }
1638 void setSubExpr(Expr *E) { Val = E; }
1640 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1641 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1643 /// \brief Get the location of the left parentheses '('.
1644 SourceLocation getLParen() const { return L; }
1645 void setLParen(SourceLocation Loc) { L = Loc; }
1647 /// \brief Get the location of the right parentheses ')'.
1648 SourceLocation getRParen() const { return R; }
1649 void setRParen(SourceLocation Loc) { R = Loc; }
1651 static bool classof(const Stmt *T) {
1652 return T->getStmtClass() == ParenExprClass;
1656 child_range children() { return child_range(&Val, &Val+1); }
1660 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1661 /// alignof), the postinc/postdec operators from postfix-expression, and various
1664 /// Notes on various nodes:
1666 /// Real/Imag - These return the real/imag part of a complex operand. If
1667 /// applied to a non-complex value, the former returns its operand and the
1668 /// later returns zero in the type of the operand.
1670 class UnaryOperator : public Expr {
1672 typedef UnaryOperatorKind Opcode;
1680 UnaryOperator(Expr *input, Opcode opc, QualType type,
1681 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1682 : Expr(UnaryOperatorClass, type, VK, OK,
1683 input->isTypeDependent() || type->isDependentType(),
1684 input->isValueDependent(),
1685 (input->isInstantiationDependent() ||
1686 type->isInstantiationDependentType()),
1687 input->containsUnexpandedParameterPack()),
1688 Opc(opc), Loc(l), Val(input) {}
1690 /// \brief Build an empty unary operator.
1691 explicit UnaryOperator(EmptyShell Empty)
1692 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1694 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1695 void setOpcode(Opcode O) { Opc = O; }
1697 Expr *getSubExpr() const { return cast<Expr>(Val); }
1698 void setSubExpr(Expr *E) { Val = E; }
1700 /// getOperatorLoc - Return the location of the operator.
1701 SourceLocation getOperatorLoc() const { return Loc; }
1702 void setOperatorLoc(SourceLocation L) { Loc = L; }
1704 /// isPostfix - Return true if this is a postfix operation, like x++.
1705 static bool isPostfix(Opcode Op) {
1706 return Op == UO_PostInc || Op == UO_PostDec;
1709 /// isPrefix - Return true if this is a prefix operation, like --x.
1710 static bool isPrefix(Opcode Op) {
1711 return Op == UO_PreInc || Op == UO_PreDec;
1714 bool isPrefix() const { return isPrefix(getOpcode()); }
1715 bool isPostfix() const { return isPostfix(getOpcode()); }
1717 static bool isIncrementOp(Opcode Op) {
1718 return Op == UO_PreInc || Op == UO_PostInc;
1720 bool isIncrementOp() const {
1721 return isIncrementOp(getOpcode());
1724 static bool isDecrementOp(Opcode Op) {
1725 return Op == UO_PreDec || Op == UO_PostDec;
1727 bool isDecrementOp() const {
1728 return isDecrementOp(getOpcode());
1731 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1732 bool isIncrementDecrementOp() const {
1733 return isIncrementDecrementOp(getOpcode());
1736 static bool isArithmeticOp(Opcode Op) {
1737 return Op >= UO_Plus && Op <= UO_LNot;
1739 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1741 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1742 /// corresponds to, e.g. "sizeof" or "[pre]++"
1743 static StringRef getOpcodeStr(Opcode Op);
1745 /// \brief Retrieve the unary opcode that corresponds to the given
1746 /// overloaded operator.
1747 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1749 /// \brief Retrieve the overloaded operator kind that corresponds to
1750 /// the given unary opcode.
1751 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1753 SourceLocation getLocStart() const LLVM_READONLY {
1754 return isPostfix() ? Val->getLocStart() : Loc;
1756 SourceLocation getLocEnd() const LLVM_READONLY {
1757 return isPostfix() ? Loc : Val->getLocEnd();
1759 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1761 static bool classof(const Stmt *T) {
1762 return T->getStmtClass() == UnaryOperatorClass;
1766 child_range children() { return child_range(&Val, &Val+1); }
1769 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1770 /// offsetof(record-type, member-designator). For example, given:
1781 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1783 class OffsetOfExpr : public Expr {
1785 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1786 class OffsetOfNode {
1788 /// \brief The kind of offsetof node we have.
1790 /// \brief An index into an array.
1794 /// \brief A field in a dependent type, known only by its name.
1796 /// \brief An implicit indirection through a C++ base class, when the
1797 /// field found is in a base class.
1802 enum { MaskBits = 2, Mask = 0x03 };
1804 /// \brief The source range that covers this part of the designator.
1807 /// \brief The data describing the designator, which comes in three
1808 /// different forms, depending on the lower two bits.
1809 /// - An unsigned index into the array of Expr*'s stored after this node
1810 /// in memory, for [constant-expression] designators.
1811 /// - A FieldDecl*, for references to a known field.
1812 /// - An IdentifierInfo*, for references to a field with a given name
1813 /// when the class type is dependent.
1814 /// - A CXXBaseSpecifier*, for references that look at a field in a
1819 /// \brief Create an offsetof node that refers to an array element.
1820 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1821 SourceLocation RBracketLoc)
1822 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1824 /// \brief Create an offsetof node that refers to a field.
1825 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1826 SourceLocation NameLoc)
1827 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1828 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1830 /// \brief Create an offsetof node that refers to an identifier.
1831 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1832 SourceLocation NameLoc)
1833 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1834 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1836 /// \brief Create an offsetof node that refers into a C++ base class.
1837 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1838 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1840 /// \brief Determine what kind of offsetof node this is.
1841 Kind getKind() const {
1842 return static_cast<Kind>(Data & Mask);
1845 /// \brief For an array element node, returns the index into the array
1847 unsigned getArrayExprIndex() const {
1848 assert(getKind() == Array);
1852 /// \brief For a field offsetof node, returns the field.
1853 FieldDecl *getField() const {
1854 assert(getKind() == Field);
1855 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1858 /// \brief For a field or identifier offsetof node, returns the name of
1860 IdentifierInfo *getFieldName() const;
1862 /// \brief For a base class node, returns the base specifier.
1863 CXXBaseSpecifier *getBase() const {
1864 assert(getKind() == Base);
1865 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1868 /// \brief Retrieve the source range that covers this offsetof node.
1870 /// For an array element node, the source range contains the locations of
1871 /// the square brackets. For a field or identifier node, the source range
1872 /// contains the location of the period (if there is one) and the
1874 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1875 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1876 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1881 SourceLocation OperatorLoc, RParenLoc;
1883 TypeSourceInfo *TSInfo;
1884 // Number of sub-components (i.e. instances of OffsetOfNode).
1886 // Number of sub-expressions (i.e. array subscript expressions).
1889 OffsetOfExpr(const ASTContext &C, QualType type,
1890 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1891 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1892 SourceLocation RParenLoc);
1894 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1895 : Expr(OffsetOfExprClass, EmptyShell()),
1896 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1900 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1901 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1902 ArrayRef<OffsetOfNode> comps,
1903 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1905 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1906 unsigned NumComps, unsigned NumExprs);
1908 /// getOperatorLoc - Return the location of the operator.
1909 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1910 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1912 /// \brief Return the location of the right parentheses.
1913 SourceLocation getRParenLoc() const { return RParenLoc; }
1914 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1916 TypeSourceInfo *getTypeSourceInfo() const {
1919 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1923 const OffsetOfNode &getComponent(unsigned Idx) const {
1924 assert(Idx < NumComps && "Subscript out of range");
1925 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1928 void setComponent(unsigned Idx, OffsetOfNode ON) {
1929 assert(Idx < NumComps && "Subscript out of range");
1930 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1933 unsigned getNumComponents() const {
1937 Expr* getIndexExpr(unsigned Idx) {
1938 assert(Idx < NumExprs && "Subscript out of range");
1939 return reinterpret_cast<Expr **>(
1940 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1942 const Expr *getIndexExpr(unsigned Idx) const {
1943 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1946 void setIndexExpr(unsigned Idx, Expr* E) {
1947 assert(Idx < NumComps && "Subscript out of range");
1948 reinterpret_cast<Expr **>(
1949 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1952 unsigned getNumExpressions() const {
1956 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1957 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1959 static bool classof(const Stmt *T) {
1960 return T->getStmtClass() == OffsetOfExprClass;
1964 child_range children() {
1966 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1968 return child_range(begin, begin + NumExprs);
1972 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1973 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1974 /// vec_step (OpenCL 1.1 6.11.12).
1975 class UnaryExprOrTypeTraitExpr : public Expr {
1980 SourceLocation OpLoc, RParenLoc;
1983 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1984 QualType resultType, SourceLocation op,
1985 SourceLocation rp) :
1986 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1987 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1988 // Value-dependent if the argument is type-dependent.
1989 TInfo->getType()->isDependentType(),
1990 TInfo->getType()->isInstantiationDependentType(),
1991 TInfo->getType()->containsUnexpandedParameterPack()),
1992 OpLoc(op), RParenLoc(rp) {
1993 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1994 UnaryExprOrTypeTraitExprBits.IsType = true;
1995 Argument.Ty = TInfo;
1998 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1999 QualType resultType, SourceLocation op,
2000 SourceLocation rp) :
2001 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2002 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2003 // Value-dependent if the argument is type-dependent.
2004 E->isTypeDependent(),
2005 E->isInstantiationDependent(),
2006 E->containsUnexpandedParameterPack()),
2007 OpLoc(op), RParenLoc(rp) {
2008 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2009 UnaryExprOrTypeTraitExprBits.IsType = false;
2013 /// \brief Construct an empty sizeof/alignof expression.
2014 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2015 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2017 UnaryExprOrTypeTrait getKind() const {
2018 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2020 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2022 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2023 QualType getArgumentType() const {
2024 return getArgumentTypeInfo()->getType();
2026 TypeSourceInfo *getArgumentTypeInfo() const {
2027 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2030 Expr *getArgumentExpr() {
2031 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2032 return static_cast<Expr*>(Argument.Ex);
2034 const Expr *getArgumentExpr() const {
2035 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2038 void setArgument(Expr *E) {
2040 UnaryExprOrTypeTraitExprBits.IsType = false;
2042 void setArgument(TypeSourceInfo *TInfo) {
2043 Argument.Ty = TInfo;
2044 UnaryExprOrTypeTraitExprBits.IsType = true;
2047 /// Gets the argument type, or the type of the argument expression, whichever
2049 QualType getTypeOfArgument() const {
2050 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2053 SourceLocation getOperatorLoc() const { return OpLoc; }
2054 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2056 SourceLocation getRParenLoc() const { return RParenLoc; }
2057 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2059 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2060 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2062 static bool classof(const Stmt *T) {
2063 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2067 child_range children();
2070 //===----------------------------------------------------------------------===//
2071 // Postfix Operators.
2072 //===----------------------------------------------------------------------===//
2074 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2075 class ArraySubscriptExpr : public Expr {
2076 enum { LHS, RHS, END_EXPR=2 };
2077 Stmt* SubExprs[END_EXPR];
2078 SourceLocation RBracketLoc;
2080 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2081 ExprValueKind VK, ExprObjectKind OK,
2082 SourceLocation rbracketloc)
2083 : Expr(ArraySubscriptExprClass, t, VK, OK,
2084 lhs->isTypeDependent() || rhs->isTypeDependent(),
2085 lhs->isValueDependent() || rhs->isValueDependent(),
2086 (lhs->isInstantiationDependent() ||
2087 rhs->isInstantiationDependent()),
2088 (lhs->containsUnexpandedParameterPack() ||
2089 rhs->containsUnexpandedParameterPack())),
2090 RBracketLoc(rbracketloc) {
2091 SubExprs[LHS] = lhs;
2092 SubExprs[RHS] = rhs;
2095 /// \brief Create an empty array subscript expression.
2096 explicit ArraySubscriptExpr(EmptyShell Shell)
2097 : Expr(ArraySubscriptExprClass, Shell) { }
2099 /// An array access can be written A[4] or 4[A] (both are equivalent).
2100 /// - getBase() and getIdx() always present the normalized view: A[4].
2101 /// In this case getBase() returns "A" and getIdx() returns "4".
2102 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2103 /// 4[A] getLHS() returns "4".
2104 /// Note: Because vector element access is also written A[4] we must
2105 /// predicate the format conversion in getBase and getIdx only on the
2106 /// the type of the RHS, as it is possible for the LHS to be a vector of
2108 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2109 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2110 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2112 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2113 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2114 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2117 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2120 const Expr *getBase() const {
2121 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2125 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2128 const Expr *getIdx() const {
2129 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2132 SourceLocation getLocStart() const LLVM_READONLY {
2133 return getLHS()->getLocStart();
2135 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2137 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2138 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2140 SourceLocation getExprLoc() const LLVM_READONLY {
2141 return getBase()->getExprLoc();
2144 static bool classof(const Stmt *T) {
2145 return T->getStmtClass() == ArraySubscriptExprClass;
2149 child_range children() {
2150 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2155 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2156 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2157 /// while its subclasses may represent alternative syntax that (semantically)
2158 /// results in a function call. For example, CXXOperatorCallExpr is
2159 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2160 /// "str1 + str2" to resolve to a function call.
2161 class CallExpr : public Expr {
2162 enum { FN=0, PREARGS_START=1 };
2165 SourceLocation RParenLoc;
2168 // These versions of the constructor are for derived classes.
2169 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2170 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2171 SourceLocation rparenloc);
2172 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2175 Stmt *getPreArg(unsigned i) {
2176 assert(i < getNumPreArgs() && "Prearg access out of range!");
2177 return SubExprs[PREARGS_START+i];
2179 const Stmt *getPreArg(unsigned i) const {
2180 assert(i < getNumPreArgs() && "Prearg access out of range!");
2181 return SubExprs[PREARGS_START+i];
2183 void setPreArg(unsigned i, Stmt *PreArg) {
2184 assert(i < getNumPreArgs() && "Prearg access out of range!");
2185 SubExprs[PREARGS_START+i] = PreArg;
2188 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2191 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2192 ExprValueKind VK, SourceLocation rparenloc);
2194 /// \brief Build an empty call expression.
2195 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2197 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2198 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2199 void setCallee(Expr *F) { SubExprs[FN] = F; }
2201 Decl *getCalleeDecl();
2202 const Decl *getCalleeDecl() const {
2203 return const_cast<CallExpr*>(this)->getCalleeDecl();
2206 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2207 FunctionDecl *getDirectCallee();
2208 const FunctionDecl *getDirectCallee() const {
2209 return const_cast<CallExpr*>(this)->getDirectCallee();
2212 /// getNumArgs - Return the number of actual arguments to this call.
2214 unsigned getNumArgs() const { return NumArgs; }
2216 /// \brief Retrieve the call arguments.
2218 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2220 const Expr *const *getArgs() const {
2221 return const_cast<CallExpr*>(this)->getArgs();
2224 /// getArg - Return the specified argument.
2225 Expr *getArg(unsigned Arg) {
2226 assert(Arg < NumArgs && "Arg access out of range!");
2227 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2229 const Expr *getArg(unsigned Arg) const {
2230 assert(Arg < NumArgs && "Arg access out of range!");
2231 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2234 /// setArg - Set the specified argument.
2235 void setArg(unsigned Arg, Expr *ArgExpr) {
2236 assert(Arg < NumArgs && "Arg access out of range!");
2237 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2240 /// setNumArgs - This changes the number of arguments present in this call.
2241 /// Any orphaned expressions are deleted by this, and any new operands are set
2243 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2245 typedef ExprIterator arg_iterator;
2246 typedef ConstExprIterator const_arg_iterator;
2247 typedef llvm::iterator_range<arg_iterator> arg_range;
2248 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2250 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2251 arg_const_range arguments() const {
2252 return arg_const_range(arg_begin(), arg_end());
2255 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2256 arg_iterator arg_end() {
2257 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2259 const_arg_iterator arg_begin() const {
2260 return SubExprs+PREARGS_START+getNumPreArgs();
2262 const_arg_iterator arg_end() const {
2263 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2266 /// This method provides fast access to all the subexpressions of
2267 /// a CallExpr without going through the slower virtual child_iterator
2268 /// interface. This provides efficient reverse iteration of the
2269 /// subexpressions. This is currently used for CFG construction.
2270 ArrayRef<Stmt*> getRawSubExprs() {
2271 return llvm::makeArrayRef(SubExprs,
2272 getNumPreArgs() + PREARGS_START + getNumArgs());
2275 /// getNumCommas - Return the number of commas that must have been present in
2276 /// this function call.
2277 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2279 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2280 /// of the callee. If not, return 0.
2281 unsigned getBuiltinCallee() const;
2283 /// \brief Returns \c true if this is a call to a builtin which does not
2284 /// evaluate side-effects within its arguments.
2285 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2287 /// getCallReturnType - Get the return type of the call expr. This is not
2288 /// always the type of the expr itself, if the return type is a reference
2290 QualType getCallReturnType() const;
2292 SourceLocation getRParenLoc() const { return RParenLoc; }
2293 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2295 SourceLocation getLocStart() const LLVM_READONLY;
2296 SourceLocation getLocEnd() const LLVM_READONLY;
2298 static bool classof(const Stmt *T) {
2299 return T->getStmtClass() >= firstCallExprConstant &&
2300 T->getStmtClass() <= lastCallExprConstant;
2304 child_range children() {
2305 return child_range(&SubExprs[0],
2306 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2310 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2312 class MemberExpr : public Expr {
2313 /// Extra data stored in some member expressions.
2314 struct MemberNameQualifier {
2315 /// \brief The nested-name-specifier that qualifies the name, including
2316 /// source-location information.
2317 NestedNameSpecifierLoc QualifierLoc;
2319 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2320 /// name qualifiers.
2321 DeclAccessPair FoundDecl;
2324 /// Base - the expression for the base pointer or structure references. In
2325 /// X.F, this is "X".
2328 /// MemberDecl - This is the decl being referenced by the field/member name.
2329 /// In X.F, this is the decl referenced by F.
2330 ValueDecl *MemberDecl;
2332 /// MemberDNLoc - Provides source/type location info for the
2333 /// declaration name embedded in MemberDecl.
2334 DeclarationNameLoc MemberDNLoc;
2336 /// MemberLoc - This is the location of the member name.
2337 SourceLocation MemberLoc;
2339 /// IsArrow - True if this is "X->F", false if this is "X.F".
2342 /// \brief True if this member expression used a nested-name-specifier to
2343 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2344 /// declaration. When true, a MemberNameQualifier
2345 /// structure is allocated immediately after the MemberExpr.
2346 bool HasQualifierOrFoundDecl : 1;
2348 /// \brief True if this member expression specified a template keyword
2349 /// and/or a template argument list explicitly, e.g., x->f<int>,
2350 /// x->template f, x->template f<int>.
2351 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2352 /// TemplateArguments (if any) are allocated immediately after
2353 /// the MemberExpr or, if the member expression also has a qualifier,
2354 /// after the MemberNameQualifier structure.
2355 bool HasTemplateKWAndArgsInfo : 1;
2357 /// \brief True if this member expression refers to a method that
2358 /// was resolved from an overloaded set having size greater than 1.
2359 bool HadMultipleCandidates : 1;
2361 /// \brief Retrieve the qualifier that preceded the member name, if any.
2362 MemberNameQualifier *getMemberQualifier() {
2363 assert(HasQualifierOrFoundDecl);
2364 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2367 /// \brief Retrieve the qualifier that preceded the member name, if any.
2368 const MemberNameQualifier *getMemberQualifier() const {
2369 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2373 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2374 const DeclarationNameInfo &NameInfo, QualType ty,
2375 ExprValueKind VK, ExprObjectKind OK)
2376 : Expr(MemberExprClass, ty, VK, OK,
2377 base->isTypeDependent(),
2378 base->isValueDependent(),
2379 base->isInstantiationDependent(),
2380 base->containsUnexpandedParameterPack()),
2381 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2382 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
2383 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2384 HadMultipleCandidates(false) {
2385 assert(memberdecl->getDeclName() == NameInfo.getName());
2388 // NOTE: this constructor should be used only when it is known that
2389 // the member name can not provide additional syntactic info
2390 // (i.e., source locations for C++ operator names or type source info
2391 // for constructors, destructors and conversion operators).
2392 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2393 SourceLocation l, QualType ty,
2394 ExprValueKind VK, ExprObjectKind OK)
2395 : Expr(MemberExprClass, ty, VK, OK,
2396 base->isTypeDependent(), base->isValueDependent(),
2397 base->isInstantiationDependent(),
2398 base->containsUnexpandedParameterPack()),
2399 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2401 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2402 HadMultipleCandidates(false) {}
2404 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2405 NestedNameSpecifierLoc QualifierLoc,
2406 SourceLocation TemplateKWLoc,
2407 ValueDecl *memberdecl, DeclAccessPair founddecl,
2408 DeclarationNameInfo MemberNameInfo,
2409 const TemplateArgumentListInfo *targs,
2410 QualType ty, ExprValueKind VK, ExprObjectKind OK);
2412 void setBase(Expr *E) { Base = E; }
2413 Expr *getBase() const { return cast<Expr>(Base); }
2415 /// \brief Retrieve the member declaration to which this expression refers.
2417 /// The returned declaration will either be a FieldDecl or (in C++)
2418 /// a CXXMethodDecl.
2419 ValueDecl *getMemberDecl() const { return MemberDecl; }
2420 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2422 /// \brief Retrieves the declaration found by lookup.
2423 DeclAccessPair getFoundDecl() const {
2424 if (!HasQualifierOrFoundDecl)
2425 return DeclAccessPair::make(getMemberDecl(),
2426 getMemberDecl()->getAccess());
2427 return getMemberQualifier()->FoundDecl;
2430 /// \brief Determines whether this member expression actually had
2431 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2433 bool hasQualifier() const { return getQualifier() != nullptr; }
2435 /// \brief If the member name was qualified, retrieves the
2436 /// nested-name-specifier that precedes the member name. Otherwise, returns
2438 NestedNameSpecifier *getQualifier() const {
2439 if (!HasQualifierOrFoundDecl)
2442 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2445 /// \brief If the member name was qualified, retrieves the
2446 /// nested-name-specifier that precedes the member name, with source-location
2448 NestedNameSpecifierLoc getQualifierLoc() const {
2449 if (!hasQualifier())
2450 return NestedNameSpecifierLoc();
2452 return getMemberQualifier()->QualifierLoc;
2455 /// \brief Return the optional template keyword and arguments info.
2456 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2457 if (!HasTemplateKWAndArgsInfo)
2460 if (!HasQualifierOrFoundDecl)
2461 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2463 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2464 getMemberQualifier() + 1);
2467 /// \brief Return the optional template keyword and arguments info.
2468 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2469 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2472 /// \brief Retrieve the location of the template keyword preceding
2473 /// the member name, if any.
2474 SourceLocation getTemplateKeywordLoc() const {
2475 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2476 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2479 /// \brief Retrieve the location of the left angle bracket starting the
2480 /// explicit template argument list following the member name, if any.
2481 SourceLocation getLAngleLoc() const {
2482 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2483 return getTemplateKWAndArgsInfo()->LAngleLoc;
2486 /// \brief Retrieve the location of the right angle bracket ending the
2487 /// explicit template argument list following the member name, if any.
2488 SourceLocation getRAngleLoc() const {
2489 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2490 return getTemplateKWAndArgsInfo()->RAngleLoc;
2493 /// Determines whether the member name was preceded by the template keyword.
2494 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2496 /// \brief Determines whether the member name was followed by an
2497 /// explicit template argument list.
2498 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2500 /// \brief Copies the template arguments (if present) into the given
2502 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2503 if (hasExplicitTemplateArgs())
2504 getExplicitTemplateArgs().copyInto(List);
2507 /// \brief Retrieve the explicit template argument list that
2508 /// follow the member template name. This must only be called on an
2509 /// expression with explicit template arguments.
2510 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2511 assert(hasExplicitTemplateArgs());
2512 return *getTemplateKWAndArgsInfo();
2515 /// \brief Retrieve the explicit template argument list that
2516 /// followed the member template name. This must only be called on
2517 /// an expression with explicit template arguments.
2518 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2519 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2522 /// \brief Retrieves the optional explicit template arguments.
2523 /// This points to the same data as getExplicitTemplateArgs(), but
2524 /// returns null if there are no explicit template arguments.
2525 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2526 if (!hasExplicitTemplateArgs()) return nullptr;
2527 return &getExplicitTemplateArgs();
2530 /// \brief Retrieve the template arguments provided as part of this
2532 const TemplateArgumentLoc *getTemplateArgs() const {
2533 if (!hasExplicitTemplateArgs())
2536 return getExplicitTemplateArgs().getTemplateArgs();
2539 /// \brief Retrieve the number of template arguments provided as part of this
2541 unsigned getNumTemplateArgs() const {
2542 if (!hasExplicitTemplateArgs())
2545 return getExplicitTemplateArgs().NumTemplateArgs;
2548 /// \brief Retrieve the member declaration name info.
2549 DeclarationNameInfo getMemberNameInfo() const {
2550 return DeclarationNameInfo(MemberDecl->getDeclName(),
2551 MemberLoc, MemberDNLoc);
2554 bool isArrow() const { return IsArrow; }
2555 void setArrow(bool A) { IsArrow = A; }
2557 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2558 /// location of 'F'.
2559 SourceLocation getMemberLoc() const { return MemberLoc; }
2560 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2562 SourceLocation getLocStart() const LLVM_READONLY;
2563 SourceLocation getLocEnd() const LLVM_READONLY;
2565 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2567 /// \brief Determine whether the base of this explicit is implicit.
2568 bool isImplicitAccess() const {
2569 return getBase() && getBase()->isImplicitCXXThis();
2572 /// \brief Returns true if this member expression refers to a method that
2573 /// was resolved from an overloaded set having size greater than 1.
2574 bool hadMultipleCandidates() const {
2575 return HadMultipleCandidates;
2577 /// \brief Sets the flag telling whether this expression refers to
2578 /// a method that was resolved from an overloaded set having size
2580 void setHadMultipleCandidates(bool V = true) {
2581 HadMultipleCandidates = V;
2584 static bool classof(const Stmt *T) {
2585 return T->getStmtClass() == MemberExprClass;
2589 child_range children() { return child_range(&Base, &Base+1); }
2591 friend class ASTReader;
2592 friend class ASTStmtWriter;
2595 /// CompoundLiteralExpr - [C99 6.5.2.5]
2597 class CompoundLiteralExpr : public Expr {
2598 /// LParenLoc - If non-null, this is the location of the left paren in a
2599 /// compound literal like "(int){4}". This can be null if this is a
2600 /// synthesized compound expression.
2601 SourceLocation LParenLoc;
2603 /// The type as written. This can be an incomplete array type, in
2604 /// which case the actual expression type will be different.
2605 /// The int part of the pair stores whether this expr is file scope.
2606 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2609 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2610 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2611 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2612 tinfo->getType()->isDependentType(),
2613 init->isValueDependent(),
2614 (init->isInstantiationDependent() ||
2615 tinfo->getType()->isInstantiationDependentType()),
2616 init->containsUnexpandedParameterPack()),
2617 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2619 /// \brief Construct an empty compound literal.
2620 explicit CompoundLiteralExpr(EmptyShell Empty)
2621 : Expr(CompoundLiteralExprClass, Empty) { }
2623 const Expr *getInitializer() const { return cast<Expr>(Init); }
2624 Expr *getInitializer() { return cast<Expr>(Init); }
2625 void setInitializer(Expr *E) { Init = E; }
2627 bool isFileScope() const { return TInfoAndScope.getInt(); }
2628 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2630 SourceLocation getLParenLoc() const { return LParenLoc; }
2631 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2633 TypeSourceInfo *getTypeSourceInfo() const {
2634 return TInfoAndScope.getPointer();
2636 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2637 TInfoAndScope.setPointer(tinfo);
2640 SourceLocation getLocStart() const LLVM_READONLY {
2641 // FIXME: Init should never be null.
2643 return SourceLocation();
2644 if (LParenLoc.isInvalid())
2645 return Init->getLocStart();
2648 SourceLocation getLocEnd() const LLVM_READONLY {
2649 // FIXME: Init should never be null.
2651 return SourceLocation();
2652 return Init->getLocEnd();
2655 static bool classof(const Stmt *T) {
2656 return T->getStmtClass() == CompoundLiteralExprClass;
2660 child_range children() { return child_range(&Init, &Init+1); }
2663 /// CastExpr - Base class for type casts, including both implicit
2664 /// casts (ImplicitCastExpr) and explicit casts that have some
2665 /// representation in the source code (ExplicitCastExpr's derived
2667 class CastExpr : public Expr {
2671 bool CastConsistency() const;
2673 const CXXBaseSpecifier * const *path_buffer() const {
2674 return const_cast<CastExpr*>(this)->path_buffer();
2676 CXXBaseSpecifier **path_buffer();
2678 void setBasePathSize(unsigned basePathSize) {
2679 CastExprBits.BasePathSize = basePathSize;
2680 assert(CastExprBits.BasePathSize == basePathSize &&
2681 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2685 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2686 Expr *op, unsigned BasePathSize)
2687 : Expr(SC, ty, VK, OK_Ordinary,
2688 // Cast expressions are type-dependent if the type is
2689 // dependent (C++ [temp.dep.expr]p3).
2690 ty->isDependentType(),
2691 // Cast expressions are value-dependent if the type is
2692 // dependent or if the subexpression is value-dependent.
2693 ty->isDependentType() || (op && op->isValueDependent()),
2694 (ty->isInstantiationDependentType() ||
2695 (op && op->isInstantiationDependent())),
2696 // An implicit cast expression doesn't (lexically) contain an
2697 // unexpanded pack, even if its target type does.
2698 ((SC != ImplicitCastExprClass &&
2699 ty->containsUnexpandedParameterPack()) ||
2700 (op && op->containsUnexpandedParameterPack()))),
2702 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2703 CastExprBits.Kind = kind;
2704 setBasePathSize(BasePathSize);
2705 assert(CastConsistency());
2708 /// \brief Construct an empty cast.
2709 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2711 setBasePathSize(BasePathSize);
2715 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2716 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2717 const char *getCastKindName() const;
2719 Expr *getSubExpr() { return cast<Expr>(Op); }
2720 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2721 void setSubExpr(Expr *E) { Op = E; }
2723 /// \brief Retrieve the cast subexpression as it was written in the source
2724 /// code, looking through any implicit casts or other intermediate nodes
2725 /// introduced by semantic analysis.
2726 Expr *getSubExprAsWritten();
2727 const Expr *getSubExprAsWritten() const {
2728 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2731 typedef CXXBaseSpecifier **path_iterator;
2732 typedef const CXXBaseSpecifier * const *path_const_iterator;
2733 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2734 unsigned path_size() const { return CastExprBits.BasePathSize; }
2735 path_iterator path_begin() { return path_buffer(); }
2736 path_iterator path_end() { return path_buffer() + path_size(); }
2737 path_const_iterator path_begin() const { return path_buffer(); }
2738 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2740 void setCastPath(const CXXCastPath &Path);
2742 static bool classof(const Stmt *T) {
2743 return T->getStmtClass() >= firstCastExprConstant &&
2744 T->getStmtClass() <= lastCastExprConstant;
2748 child_range children() { return child_range(&Op, &Op+1); }
2751 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2752 /// conversions, which have no direct representation in the original
2753 /// source code. For example: converting T[]->T*, void f()->void
2754 /// (*f)(), float->double, short->int, etc.
2756 /// In C, implicit casts always produce rvalues. However, in C++, an
2757 /// implicit cast whose result is being bound to a reference will be
2758 /// an lvalue or xvalue. For example:
2762 /// class Derived : public Base { };
2763 /// Derived &&ref();
2764 /// void f(Derived d) {
2765 /// Base& b = d; // initializer is an ImplicitCastExpr
2766 /// // to an lvalue of type Base
2767 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2768 /// // to an xvalue of type Base
2771 class ImplicitCastExpr : public CastExpr {
2773 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2774 unsigned BasePathLength, ExprValueKind VK)
2775 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2778 /// \brief Construct an empty implicit cast.
2779 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2780 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2783 enum OnStack_t { OnStack };
2784 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2786 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2789 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2790 CastKind Kind, Expr *Operand,
2791 const CXXCastPath *BasePath,
2794 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2797 SourceLocation getLocStart() const LLVM_READONLY {
2798 return getSubExpr()->getLocStart();
2800 SourceLocation getLocEnd() const LLVM_READONLY {
2801 return getSubExpr()->getLocEnd();
2804 static bool classof(const Stmt *T) {
2805 return T->getStmtClass() == ImplicitCastExprClass;
2809 inline Expr *Expr::IgnoreImpCasts() {
2811 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2812 e = ice->getSubExpr();
2816 /// ExplicitCastExpr - An explicit cast written in the source
2819 /// This class is effectively an abstract class, because it provides
2820 /// the basic representation of an explicitly-written cast without
2821 /// specifying which kind of cast (C cast, functional cast, static
2822 /// cast, etc.) was written; specific derived classes represent the
2823 /// particular style of cast and its location information.
2825 /// Unlike implicit casts, explicit cast nodes have two different
2826 /// types: the type that was written into the source code, and the
2827 /// actual type of the expression as determined by semantic
2828 /// analysis. These types may differ slightly. For example, in C++ one
2829 /// can cast to a reference type, which indicates that the resulting
2830 /// expression will be an lvalue or xvalue. The reference type, however,
2831 /// will not be used as the type of the expression.
2832 class ExplicitCastExpr : public CastExpr {
2833 /// TInfo - Source type info for the (written) type
2834 /// this expression is casting to.
2835 TypeSourceInfo *TInfo;
2838 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2839 CastKind kind, Expr *op, unsigned PathSize,
2840 TypeSourceInfo *writtenTy)
2841 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2843 /// \brief Construct an empty explicit cast.
2844 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2845 : CastExpr(SC, Shell, PathSize) { }
2848 /// getTypeInfoAsWritten - Returns the type source info for the type
2849 /// that this expression is casting to.
2850 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2851 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2853 /// getTypeAsWritten - Returns the type that this expression is
2854 /// casting to, as written in the source code.
2855 QualType getTypeAsWritten() const { return TInfo->getType(); }
2857 static bool classof(const Stmt *T) {
2858 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2859 T->getStmtClass() <= lastExplicitCastExprConstant;
2863 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2864 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2865 /// (Type)expr. For example: @c (int)f.
2866 class CStyleCastExpr : public ExplicitCastExpr {
2867 SourceLocation LPLoc; // the location of the left paren
2868 SourceLocation RPLoc; // the location of the right paren
2870 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2871 unsigned PathSize, TypeSourceInfo *writtenTy,
2872 SourceLocation l, SourceLocation r)
2873 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2874 writtenTy), LPLoc(l), RPLoc(r) {}
2876 /// \brief Construct an empty C-style explicit cast.
2877 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2878 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2881 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2882 ExprValueKind VK, CastKind K,
2883 Expr *Op, const CXXCastPath *BasePath,
2884 TypeSourceInfo *WrittenTy, SourceLocation L,
2887 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2890 SourceLocation getLParenLoc() const { return LPLoc; }
2891 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2893 SourceLocation getRParenLoc() const { return RPLoc; }
2894 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2896 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2897 SourceLocation getLocEnd() const LLVM_READONLY {
2898 return getSubExpr()->getLocEnd();
2901 static bool classof(const Stmt *T) {
2902 return T->getStmtClass() == CStyleCastExprClass;
2906 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2908 /// This expression node kind describes a builtin binary operation,
2909 /// such as "x + y" for integer values "x" and "y". The operands will
2910 /// already have been converted to appropriate types (e.g., by
2911 /// performing promotions or conversions).
2913 /// In C++, where operators may be overloaded, a different kind of
2914 /// expression node (CXXOperatorCallExpr) is used to express the
2915 /// invocation of an overloaded operator with operator syntax. Within
2916 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2917 /// used to store an expression "x + y" depends on the subexpressions
2918 /// for x and y. If neither x or y is type-dependent, and the "+"
2919 /// operator resolves to a built-in operation, BinaryOperator will be
2920 /// used to express the computation (x and y may still be
2921 /// value-dependent). If either x or y is type-dependent, or if the
2922 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2923 /// be used to express the computation.
2924 class BinaryOperator : public Expr {
2926 typedef BinaryOperatorKind Opcode;
2931 // Records the FP_CONTRACT pragma status at the point that this binary
2932 // operator was parsed. This bit is only meaningful for operations on
2933 // floating point types. For all other types it should default to
2935 unsigned FPContractable : 1;
2936 SourceLocation OpLoc;
2938 enum { LHS, RHS, END_EXPR };
2939 Stmt* SubExprs[END_EXPR];
2942 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2943 ExprValueKind VK, ExprObjectKind OK,
2944 SourceLocation opLoc, bool fpContractable)
2945 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2946 lhs->isTypeDependent() || rhs->isTypeDependent(),
2947 lhs->isValueDependent() || rhs->isValueDependent(),
2948 (lhs->isInstantiationDependent() ||
2949 rhs->isInstantiationDependent()),
2950 (lhs->containsUnexpandedParameterPack() ||
2951 rhs->containsUnexpandedParameterPack())),
2952 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2953 SubExprs[LHS] = lhs;
2954 SubExprs[RHS] = rhs;
2955 assert(!isCompoundAssignmentOp() &&
2956 "Use CompoundAssignOperator for compound assignments");
2959 /// \brief Construct an empty binary operator.
2960 explicit BinaryOperator(EmptyShell Empty)
2961 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2963 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2964 SourceLocation getOperatorLoc() const { return OpLoc; }
2965 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2967 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2968 void setOpcode(Opcode O) { Opc = O; }
2970 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2971 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2972 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2973 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2975 SourceLocation getLocStart() const LLVM_READONLY {
2976 return getLHS()->getLocStart();
2978 SourceLocation getLocEnd() const LLVM_READONLY {
2979 return getRHS()->getLocEnd();
2982 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2983 /// corresponds to, e.g. "<<=".
2984 static StringRef getOpcodeStr(Opcode Op);
2986 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2988 /// \brief Retrieve the binary opcode that corresponds to the given
2989 /// overloaded operator.
2990 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2992 /// \brief Retrieve the overloaded operator kind that corresponds to
2993 /// the given binary opcode.
2994 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2996 /// predicates to categorize the respective opcodes.
2997 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2998 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2999 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3000 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3001 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3002 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3004 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3005 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3007 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3008 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3010 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3011 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3013 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3014 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3016 static Opcode negateComparisonOp(Opcode Opc) {
3019 llvm_unreachable("Not a comparsion operator.");
3020 case BO_LT: return BO_GE;
3021 case BO_GT: return BO_LE;
3022 case BO_LE: return BO_GT;
3023 case BO_GE: return BO_LT;
3024 case BO_EQ: return BO_NE;
3025 case BO_NE: return BO_EQ;
3029 static Opcode reverseComparisonOp(Opcode Opc) {
3032 llvm_unreachable("Not a comparsion operator.");
3033 case BO_LT: return BO_GT;
3034 case BO_GT: return BO_LT;
3035 case BO_LE: return BO_GE;
3036 case BO_GE: return BO_LE;
3043 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3044 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3046 static bool isAssignmentOp(Opcode Opc) {
3047 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3049 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3051 static bool isCompoundAssignmentOp(Opcode Opc) {
3052 return Opc > BO_Assign && Opc <= BO_OrAssign;
3054 bool isCompoundAssignmentOp() const {
3055 return isCompoundAssignmentOp(getOpcode());
3057 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3058 assert(isCompoundAssignmentOp(Opc));
3059 if (Opc >= BO_AndAssign)
3060 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3062 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3065 static bool isShiftAssignOp(Opcode Opc) {
3066 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3068 bool isShiftAssignOp() const {
3069 return isShiftAssignOp(getOpcode());
3072 static bool classof(const Stmt *S) {
3073 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3074 S->getStmtClass() <= lastBinaryOperatorConstant;
3078 child_range children() {
3079 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3082 // Set the FP contractability status of this operator. Only meaningful for
3083 // operations on floating point types.
3084 void setFPContractable(bool FPC) { FPContractable = FPC; }
3086 // Get the FP contractability status of this operator. Only meaningful for
3087 // operations on floating point types.
3088 bool isFPContractable() const { return FPContractable; }
3091 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3092 ExprValueKind VK, ExprObjectKind OK,
3093 SourceLocation opLoc, bool fpContractable, bool dead2)
3094 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3095 lhs->isTypeDependent() || rhs->isTypeDependent(),
3096 lhs->isValueDependent() || rhs->isValueDependent(),
3097 (lhs->isInstantiationDependent() ||
3098 rhs->isInstantiationDependent()),
3099 (lhs->containsUnexpandedParameterPack() ||
3100 rhs->containsUnexpandedParameterPack())),
3101 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3102 SubExprs[LHS] = lhs;
3103 SubExprs[RHS] = rhs;
3106 BinaryOperator(StmtClass SC, EmptyShell Empty)
3107 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3110 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3111 /// track of the type the operation is performed in. Due to the semantics of
3112 /// these operators, the operands are promoted, the arithmetic performed, an
3113 /// implicit conversion back to the result type done, then the assignment takes
3114 /// place. This captures the intermediate type which the computation is done
3116 class CompoundAssignOperator : public BinaryOperator {
3117 QualType ComputationLHSType;
3118 QualType ComputationResultType;
3120 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3121 ExprValueKind VK, ExprObjectKind OK,
3122 QualType CompLHSType, QualType CompResultType,
3123 SourceLocation OpLoc, bool fpContractable)
3124 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3126 ComputationLHSType(CompLHSType),
3127 ComputationResultType(CompResultType) {
3128 assert(isCompoundAssignmentOp() &&
3129 "Only should be used for compound assignments");
3132 /// \brief Build an empty compound assignment operator expression.
3133 explicit CompoundAssignOperator(EmptyShell Empty)
3134 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3136 // The two computation types are the type the LHS is converted
3137 // to for the computation and the type of the result; the two are
3138 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3139 QualType getComputationLHSType() const { return ComputationLHSType; }
3140 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3142 QualType getComputationResultType() const { return ComputationResultType; }
3143 void setComputationResultType(QualType T) { ComputationResultType = T; }
3145 static bool classof(const Stmt *S) {
3146 return S->getStmtClass() == CompoundAssignOperatorClass;
3150 /// AbstractConditionalOperator - An abstract base class for
3151 /// ConditionalOperator and BinaryConditionalOperator.
3152 class AbstractConditionalOperator : public Expr {
3153 SourceLocation QuestionLoc, ColonLoc;
3154 friend class ASTStmtReader;
3157 AbstractConditionalOperator(StmtClass SC, QualType T,
3158 ExprValueKind VK, ExprObjectKind OK,
3159 bool TD, bool VD, bool ID,
3160 bool ContainsUnexpandedParameterPack,
3161 SourceLocation qloc,
3162 SourceLocation cloc)
3163 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3164 QuestionLoc(qloc), ColonLoc(cloc) {}
3166 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3167 : Expr(SC, Empty) { }
3170 // getCond - Return the expression representing the condition for
3172 Expr *getCond() const;
3174 // getTrueExpr - Return the subexpression representing the value of
3175 // the expression if the condition evaluates to true.
3176 Expr *getTrueExpr() const;
3178 // getFalseExpr - Return the subexpression representing the value of
3179 // the expression if the condition evaluates to false. This is
3180 // the same as getRHS.
3181 Expr *getFalseExpr() const;
3183 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3184 SourceLocation getColonLoc() const { return ColonLoc; }
3186 static bool classof(const Stmt *T) {
3187 return T->getStmtClass() == ConditionalOperatorClass ||
3188 T->getStmtClass() == BinaryConditionalOperatorClass;
3192 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3193 /// middle" extension is a BinaryConditionalOperator.
3194 class ConditionalOperator : public AbstractConditionalOperator {
3195 enum { COND, LHS, RHS, END_EXPR };
3196 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3198 friend class ASTStmtReader;
3200 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3201 SourceLocation CLoc, Expr *rhs,
3202 QualType t, ExprValueKind VK, ExprObjectKind OK)
3203 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3204 // FIXME: the type of the conditional operator doesn't
3205 // depend on the type of the conditional, but the standard
3206 // seems to imply that it could. File a bug!
3207 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3208 (cond->isValueDependent() || lhs->isValueDependent() ||
3209 rhs->isValueDependent()),
3210 (cond->isInstantiationDependent() ||
3211 lhs->isInstantiationDependent() ||
3212 rhs->isInstantiationDependent()),
3213 (cond->containsUnexpandedParameterPack() ||
3214 lhs->containsUnexpandedParameterPack() ||
3215 rhs->containsUnexpandedParameterPack()),
3217 SubExprs[COND] = cond;
3218 SubExprs[LHS] = lhs;
3219 SubExprs[RHS] = rhs;
3222 /// \brief Build an empty conditional operator.
3223 explicit ConditionalOperator(EmptyShell Empty)
3224 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3226 // getCond - Return the expression representing the condition for
3228 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3230 // getTrueExpr - Return the subexpression representing the value of
3231 // the expression if the condition evaluates to true.
3232 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3234 // getFalseExpr - Return the subexpression representing the value of
3235 // the expression if the condition evaluates to false. This is
3236 // the same as getRHS.
3237 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3239 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3240 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3242 SourceLocation getLocStart() const LLVM_READONLY {
3243 return getCond()->getLocStart();
3245 SourceLocation getLocEnd() const LLVM_READONLY {
3246 return getRHS()->getLocEnd();
3249 static bool classof(const Stmt *T) {
3250 return T->getStmtClass() == ConditionalOperatorClass;
3254 child_range children() {
3255 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3259 /// BinaryConditionalOperator - The GNU extension to the conditional
3260 /// operator which allows the middle operand to be omitted.
3262 /// This is a different expression kind on the assumption that almost
3263 /// every client ends up needing to know that these are different.
3264 class BinaryConditionalOperator : public AbstractConditionalOperator {
3265 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3267 /// - the common condition/left-hand-side expression, which will be
3268 /// evaluated as the opaque value
3269 /// - the condition, expressed in terms of the opaque value
3270 /// - the left-hand-side, expressed in terms of the opaque value
3271 /// - the right-hand-side
3272 Stmt *SubExprs[NUM_SUBEXPRS];
3273 OpaqueValueExpr *OpaqueValue;
3275 friend class ASTStmtReader;
3277 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3278 Expr *cond, Expr *lhs, Expr *rhs,
3279 SourceLocation qloc, SourceLocation cloc,
3280 QualType t, ExprValueKind VK, ExprObjectKind OK)
3281 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3282 (common->isTypeDependent() || rhs->isTypeDependent()),
3283 (common->isValueDependent() || rhs->isValueDependent()),
3284 (common->isInstantiationDependent() ||
3285 rhs->isInstantiationDependent()),
3286 (common->containsUnexpandedParameterPack() ||
3287 rhs->containsUnexpandedParameterPack()),
3289 OpaqueValue(opaqueValue) {
3290 SubExprs[COMMON] = common;
3291 SubExprs[COND] = cond;
3292 SubExprs[LHS] = lhs;
3293 SubExprs[RHS] = rhs;
3294 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3297 /// \brief Build an empty conditional operator.
3298 explicit BinaryConditionalOperator(EmptyShell Empty)
3299 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3301 /// \brief getCommon - Return the common expression, written to the
3302 /// left of the condition. The opaque value will be bound to the
3303 /// result of this expression.
3304 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3306 /// \brief getOpaqueValue - Return the opaque value placeholder.
3307 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3309 /// \brief getCond - Return the condition expression; this is defined
3310 /// in terms of the opaque value.
3311 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3313 /// \brief getTrueExpr - Return the subexpression which will be
3314 /// evaluated if the condition evaluates to true; this is defined
3315 /// in terms of the opaque value.
3316 Expr *getTrueExpr() const {
3317 return cast<Expr>(SubExprs[LHS]);
3320 /// \brief getFalseExpr - Return the subexpression which will be
3321 /// evaluated if the condnition evaluates to false; this is
3322 /// defined in terms of the opaque value.
3323 Expr *getFalseExpr() const {
3324 return cast<Expr>(SubExprs[RHS]);
3327 SourceLocation getLocStart() const LLVM_READONLY {
3328 return getCommon()->getLocStart();
3330 SourceLocation getLocEnd() const LLVM_READONLY {
3331 return getFalseExpr()->getLocEnd();
3334 static bool classof(const Stmt *T) {
3335 return T->getStmtClass() == BinaryConditionalOperatorClass;
3339 child_range children() {
3340 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3344 inline Expr *AbstractConditionalOperator::getCond() const {
3345 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3346 return co->getCond();
3347 return cast<BinaryConditionalOperator>(this)->getCond();
3350 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3351 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3352 return co->getTrueExpr();
3353 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3356 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3357 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3358 return co->getFalseExpr();
3359 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3362 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3363 class AddrLabelExpr : public Expr {
3364 SourceLocation AmpAmpLoc, LabelLoc;
3367 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3369 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3371 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3373 /// \brief Build an empty address of a label expression.
3374 explicit AddrLabelExpr(EmptyShell Empty)
3375 : Expr(AddrLabelExprClass, Empty) { }
3377 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3378 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3379 SourceLocation getLabelLoc() const { return LabelLoc; }
3380 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3382 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3383 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3385 LabelDecl *getLabel() const { return Label; }
3386 void setLabel(LabelDecl *L) { Label = L; }
3388 static bool classof(const Stmt *T) {
3389 return T->getStmtClass() == AddrLabelExprClass;
3393 child_range children() { return child_range(); }
3396 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3397 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3398 /// takes the value of the last subexpression.
3400 /// A StmtExpr is always an r-value; values "returned" out of a
3401 /// StmtExpr will be copied.
3402 class StmtExpr : public Expr {
3404 SourceLocation LParenLoc, RParenLoc;
3406 // FIXME: Does type-dependence need to be computed differently?
3407 // FIXME: Do we need to compute instantiation instantiation-dependence for
3408 // statements? (ugh!)
3409 StmtExpr(CompoundStmt *substmt, QualType T,
3410 SourceLocation lp, SourceLocation rp) :
3411 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3412 T->isDependentType(), false, false, false),
3413 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3415 /// \brief Build an empty statement expression.
3416 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3418 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3419 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3420 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3422 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3423 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3425 SourceLocation getLParenLoc() const { return LParenLoc; }
3426 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3427 SourceLocation getRParenLoc() const { return RParenLoc; }
3428 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3430 static bool classof(const Stmt *T) {
3431 return T->getStmtClass() == StmtExprClass;
3435 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3439 /// ShuffleVectorExpr - clang-specific builtin-in function
3440 /// __builtin_shufflevector.
3441 /// This AST node represents a operator that does a constant
3442 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3443 /// two vectors and a variable number of constant indices,
3444 /// and returns the appropriately shuffled vector.
3445 class ShuffleVectorExpr : public Expr {
3446 SourceLocation BuiltinLoc, RParenLoc;
3448 // SubExprs - the list of values passed to the __builtin_shufflevector
3449 // function. The first two are vectors, and the rest are constant
3450 // indices. The number of values in this list is always
3451 // 2+the number of indices in the vector type.
3456 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3457 SourceLocation BLoc, SourceLocation RP);
3459 /// \brief Build an empty vector-shuffle expression.
3460 explicit ShuffleVectorExpr(EmptyShell Empty)
3461 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3463 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3464 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3466 SourceLocation getRParenLoc() const { return RParenLoc; }
3467 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3469 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3470 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3472 static bool classof(const Stmt *T) {
3473 return T->getStmtClass() == ShuffleVectorExprClass;
3476 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3477 /// constant expression, the actual arguments passed in, and the function
3479 unsigned getNumSubExprs() const { return NumExprs; }
3481 /// \brief Retrieve the array of expressions.
3482 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3484 /// getExpr - Return the Expr at the specified index.
3485 Expr *getExpr(unsigned Index) {
3486 assert((Index < NumExprs) && "Arg access out of range!");
3487 return cast<Expr>(SubExprs[Index]);
3489 const Expr *getExpr(unsigned Index) const {
3490 assert((Index < NumExprs) && "Arg access out of range!");
3491 return cast<Expr>(SubExprs[Index]);
3494 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3496 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3497 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3498 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3502 child_range children() {
3503 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3507 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3508 /// This AST node provides support for converting a vector type to another
3509 /// vector type of the same arity.
3510 class ConvertVectorExpr : public Expr {
3513 TypeSourceInfo *TInfo;
3514 SourceLocation BuiltinLoc, RParenLoc;
3516 friend class ASTReader;
3517 friend class ASTStmtReader;
3518 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3521 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3522 ExprValueKind VK, ExprObjectKind OK,
3523 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3524 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3525 DstType->isDependentType(),
3526 DstType->isDependentType() || SrcExpr->isValueDependent(),
3527 (DstType->isInstantiationDependentType() ||
3528 SrcExpr->isInstantiationDependent()),
3529 (DstType->containsUnexpandedParameterPack() ||
3530 SrcExpr->containsUnexpandedParameterPack())),
3531 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3533 /// getSrcExpr - Return the Expr to be converted.
3534 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3536 /// getTypeSourceInfo - Return the destination type.
3537 TypeSourceInfo *getTypeSourceInfo() const {
3540 void setTypeSourceInfo(TypeSourceInfo *ti) {
3544 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3545 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3547 /// getRParenLoc - Return the location of final right parenthesis.
3548 SourceLocation getRParenLoc() const { return RParenLoc; }
3550 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3551 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3553 static bool classof(const Stmt *T) {
3554 return T->getStmtClass() == ConvertVectorExprClass;
3558 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3561 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3562 /// This AST node is similar to the conditional operator (?:) in C, with
3563 /// the following exceptions:
3564 /// - the test expression must be a integer constant expression.
3565 /// - the expression returned acts like the chosen subexpression in every
3566 /// visible way: the type is the same as that of the chosen subexpression,
3567 /// and all predicates (whether it's an l-value, whether it's an integer
3568 /// constant expression, etc.) return the same result as for the chosen
3570 class ChooseExpr : public Expr {
3571 enum { COND, LHS, RHS, END_EXPR };
3572 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3573 SourceLocation BuiltinLoc, RParenLoc;
3576 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3577 QualType t, ExprValueKind VK, ExprObjectKind OK,
3578 SourceLocation RP, bool condIsTrue,
3579 bool TypeDependent, bool ValueDependent)
3580 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3581 (cond->isInstantiationDependent() ||
3582 lhs->isInstantiationDependent() ||
3583 rhs->isInstantiationDependent()),
3584 (cond->containsUnexpandedParameterPack() ||
3585 lhs->containsUnexpandedParameterPack() ||
3586 rhs->containsUnexpandedParameterPack())),
3587 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3588 SubExprs[COND] = cond;
3589 SubExprs[LHS] = lhs;
3590 SubExprs[RHS] = rhs;
3593 /// \brief Build an empty __builtin_choose_expr.
3594 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3596 /// isConditionTrue - Return whether the condition is true (i.e. not
3598 bool isConditionTrue() const {
3599 assert(!isConditionDependent() &&
3600 "Dependent condition isn't true or false");
3603 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3605 bool isConditionDependent() const {
3606 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3609 /// getChosenSubExpr - Return the subexpression chosen according to the
3611 Expr *getChosenSubExpr() const {
3612 return isConditionTrue() ? getLHS() : getRHS();
3615 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3616 void setCond(Expr *E) { SubExprs[COND] = E; }
3617 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3618 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3619 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3620 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3622 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3623 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3625 SourceLocation getRParenLoc() const { return RParenLoc; }
3626 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3628 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3629 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3631 static bool classof(const Stmt *T) {
3632 return T->getStmtClass() == ChooseExprClass;
3636 child_range children() {
3637 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3641 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3642 /// for a null pointer constant that has integral type (e.g., int or
3643 /// long) and is the same size and alignment as a pointer. The __null
3644 /// extension is typically only used by system headers, which define
3645 /// NULL as __null in C++ rather than using 0 (which is an integer
3646 /// that may not match the size of a pointer).
3647 class GNUNullExpr : public Expr {
3648 /// TokenLoc - The location of the __null keyword.
3649 SourceLocation TokenLoc;
3652 GNUNullExpr(QualType Ty, SourceLocation Loc)
3653 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3657 /// \brief Build an empty GNU __null expression.
3658 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3660 /// getTokenLocation - The location of the __null token.
3661 SourceLocation getTokenLocation() const { return TokenLoc; }
3662 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3664 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3665 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3667 static bool classof(const Stmt *T) {
3668 return T->getStmtClass() == GNUNullExprClass;
3672 child_range children() { return child_range(); }
3675 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3676 class VAArgExpr : public Expr {
3678 TypeSourceInfo *TInfo;
3679 SourceLocation BuiltinLoc, RParenLoc;
3681 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3682 SourceLocation RPLoc, QualType t)
3683 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3684 t->isDependentType(), false,
3685 (TInfo->getType()->isInstantiationDependentType() ||
3686 e->isInstantiationDependent()),
3687 (TInfo->getType()->containsUnexpandedParameterPack() ||
3688 e->containsUnexpandedParameterPack())),
3689 Val(e), TInfo(TInfo),
3691 RParenLoc(RPLoc) { }
3693 /// \brief Create an empty __builtin_va_arg expression.
3694 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3696 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3697 Expr *getSubExpr() { return cast<Expr>(Val); }
3698 void setSubExpr(Expr *E) { Val = E; }
3700 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3701 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3703 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3704 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3706 SourceLocation getRParenLoc() const { return RParenLoc; }
3707 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3709 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3710 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3712 static bool classof(const Stmt *T) {
3713 return T->getStmtClass() == VAArgExprClass;
3717 child_range children() { return child_range(&Val, &Val+1); }
3720 /// @brief Describes an C or C++ initializer list.
3722 /// InitListExpr describes an initializer list, which can be used to
3723 /// initialize objects of different types, including
3724 /// struct/class/union types, arrays, and vectors. For example:
3727 /// struct foo x = { 1, { 2, 3 } };
3730 /// Prior to semantic analysis, an initializer list will represent the
3731 /// initializer list as written by the user, but will have the
3732 /// placeholder type "void". This initializer list is called the
3733 /// syntactic form of the initializer, and may contain C99 designated
3734 /// initializers (represented as DesignatedInitExprs), initializations
3735 /// of subobject members without explicit braces, and so on. Clients
3736 /// interested in the original syntax of the initializer list should
3737 /// use the syntactic form of the initializer list.
3739 /// After semantic analysis, the initializer list will represent the
3740 /// semantic form of the initializer, where the initializations of all
3741 /// subobjects are made explicit with nested InitListExpr nodes and
3742 /// C99 designators have been eliminated by placing the designated
3743 /// initializations into the subobject they initialize. Additionally,
3744 /// any "holes" in the initialization, where no initializer has been
3745 /// specified for a particular subobject, will be replaced with
3746 /// implicitly-generated ImplicitValueInitExpr expressions that
3747 /// value-initialize the subobjects. Note, however, that the
3748 /// initializer lists may still have fewer initializers than there are
3749 /// elements to initialize within the object.
3751 /// After semantic analysis has completed, given an initializer list,
3752 /// method isSemanticForm() returns true if and only if this is the
3753 /// semantic form of the initializer list (note: the same AST node
3754 /// may at the same time be the syntactic form).
3755 /// Given the semantic form of the initializer list, one can retrieve
3756 /// the syntactic form of that initializer list (when different)
3757 /// using method getSyntacticForm(); the method returns null if applied
3758 /// to a initializer list which is already in syntactic form.
3759 /// Similarly, given the syntactic form (i.e., an initializer list such
3760 /// that isSemanticForm() returns false), one can retrieve the semantic
3761 /// form using method getSemanticForm().
3762 /// Since many initializer lists have the same syntactic and semantic forms,
3763 /// getSyntacticForm() may return NULL, indicating that the current
3764 /// semantic initializer list also serves as its syntactic form.
3765 class InitListExpr : public Expr {
3766 // FIXME: Eliminate this vector in favor of ASTContext allocation
3767 typedef ASTVector<Stmt *> InitExprsTy;
3768 InitExprsTy InitExprs;
3769 SourceLocation LBraceLoc, RBraceLoc;
3771 /// The alternative form of the initializer list (if it exists).
3772 /// The int part of the pair stores whether this initializer list is
3773 /// in semantic form. If not null, the pointer points to:
3774 /// - the syntactic form, if this is in semantic form;
3775 /// - the semantic form, if this is in syntactic form.
3776 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3779 /// If this initializer list initializes an array with more elements than
3780 /// there are initializers in the list, specifies an expression to be used
3781 /// for value initialization of the rest of the elements.
3783 /// If this initializer list initializes a union, specifies which
3784 /// field within the union will be initialized.
3785 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3788 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3789 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3791 /// \brief Build an empty initializer list.
3792 explicit InitListExpr(EmptyShell Empty)
3793 : Expr(InitListExprClass, Empty) { }
3795 unsigned getNumInits() const { return InitExprs.size(); }
3797 /// \brief Retrieve the set of initializers.
3798 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3800 const Expr *getInit(unsigned Init) const {
3801 assert(Init < getNumInits() && "Initializer access out of range!");
3802 return cast_or_null<Expr>(InitExprs[Init]);
3805 Expr *getInit(unsigned Init) {
3806 assert(Init < getNumInits() && "Initializer access out of range!");
3807 return cast_or_null<Expr>(InitExprs[Init]);
3810 void setInit(unsigned Init, Expr *expr) {
3811 assert(Init < getNumInits() && "Initializer access out of range!");
3812 InitExprs[Init] = expr;
3815 ExprBits.TypeDependent |= expr->isTypeDependent();
3816 ExprBits.ValueDependent |= expr->isValueDependent();
3817 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3818 ExprBits.ContainsUnexpandedParameterPack |=
3819 expr->containsUnexpandedParameterPack();
3823 /// \brief Reserve space for some number of initializers.
3824 void reserveInits(const ASTContext &C, unsigned NumInits);
3826 /// @brief Specify the number of initializers
3828 /// If there are more than @p NumInits initializers, the remaining
3829 /// initializers will be destroyed. If there are fewer than @p
3830 /// NumInits initializers, NULL expressions will be added for the
3831 /// unknown initializers.
3832 void resizeInits(const ASTContext &Context, unsigned NumInits);
3834 /// @brief Updates the initializer at index @p Init with the new
3835 /// expression @p expr, and returns the old expression at that
3838 /// When @p Init is out of range for this initializer list, the
3839 /// initializer list will be extended with NULL expressions to
3840 /// accommodate the new entry.
3841 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3843 /// \brief If this initializer list initializes an array with more elements
3844 /// than there are initializers in the list, specifies an expression to be
3845 /// used for value initialization of the rest of the elements.
3846 Expr *getArrayFiller() {
3847 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3849 const Expr *getArrayFiller() const {
3850 return const_cast<InitListExpr *>(this)->getArrayFiller();
3852 void setArrayFiller(Expr *filler);
3854 /// \brief Return true if this is an array initializer and its array "filler"
3856 bool hasArrayFiller() const { return getArrayFiller(); }
3858 /// \brief If this initializes a union, specifies which field in the
3859 /// union to initialize.
3861 /// Typically, this field is the first named field within the
3862 /// union. However, a designated initializer can specify the
3863 /// initialization of a different field within the union.
3864 FieldDecl *getInitializedFieldInUnion() {
3865 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3867 const FieldDecl *getInitializedFieldInUnion() const {
3868 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3870 void setInitializedFieldInUnion(FieldDecl *FD) {
3871 assert((FD == nullptr
3872 || getInitializedFieldInUnion() == nullptr
3873 || getInitializedFieldInUnion() == FD)
3874 && "Only one field of a union may be initialized at a time!");
3875 ArrayFillerOrUnionFieldInit = FD;
3878 // Explicit InitListExpr's originate from source code (and have valid source
3879 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3881 return LBraceLoc.isValid() && RBraceLoc.isValid();
3884 // Is this an initializer for an array of characters, initialized by a string
3885 // literal or an @encode?
3886 bool isStringLiteralInit() const;
3888 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3889 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3890 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3891 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3893 bool isSemanticForm() const { return AltForm.getInt(); }
3894 InitListExpr *getSemanticForm() const {
3895 return isSemanticForm() ? nullptr : AltForm.getPointer();
3897 InitListExpr *getSyntacticForm() const {
3898 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3901 void setSyntacticForm(InitListExpr *Init) {
3902 AltForm.setPointer(Init);
3903 AltForm.setInt(true);
3904 Init->AltForm.setPointer(this);
3905 Init->AltForm.setInt(false);
3908 bool hadArrayRangeDesignator() const {
3909 return InitListExprBits.HadArrayRangeDesignator != 0;
3911 void sawArrayRangeDesignator(bool ARD = true) {
3912 InitListExprBits.HadArrayRangeDesignator = ARD;
3915 SourceLocation getLocStart() const LLVM_READONLY;
3916 SourceLocation getLocEnd() const LLVM_READONLY;
3918 static bool classof(const Stmt *T) {
3919 return T->getStmtClass() == InitListExprClass;
3923 child_range children() {
3924 // FIXME: This does not include the array filler expression.
3925 if (InitExprs.empty()) return child_range();
3926 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3929 typedef InitExprsTy::iterator iterator;
3930 typedef InitExprsTy::const_iterator const_iterator;
3931 typedef InitExprsTy::reverse_iterator reverse_iterator;
3932 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3934 iterator begin() { return InitExprs.begin(); }
3935 const_iterator begin() const { return InitExprs.begin(); }
3936 iterator end() { return InitExprs.end(); }
3937 const_iterator end() const { return InitExprs.end(); }
3938 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3939 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3940 reverse_iterator rend() { return InitExprs.rend(); }
3941 const_reverse_iterator rend() const { return InitExprs.rend(); }
3943 friend class ASTStmtReader;
3944 friend class ASTStmtWriter;
3947 /// @brief Represents a C99 designated initializer expression.
3949 /// A designated initializer expression (C99 6.7.8) contains one or
3950 /// more designators (which can be field designators, array
3951 /// designators, or GNU array-range designators) followed by an
3952 /// expression that initializes the field or element(s) that the
3953 /// designators refer to. For example, given:
3960 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3963 /// The InitListExpr contains three DesignatedInitExprs, the first of
3964 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3965 /// designators, one array designator for @c [2] followed by one field
3966 /// designator for @c .y. The initialization expression will be 1.0.
3967 class DesignatedInitExpr : public Expr {
3969 /// \brief Forward declaration of the Designator class.
3973 /// The location of the '=' or ':' prior to the actual initializer
3975 SourceLocation EqualOrColonLoc;
3977 /// Whether this designated initializer used the GNU deprecated
3978 /// syntax rather than the C99 '=' syntax.
3981 /// The number of designators in this initializer expression.
3982 unsigned NumDesignators : 15;
3984 /// The number of subexpressions of this initializer expression,
3985 /// which contains both the initializer and any additional
3986 /// expressions used by array and array-range designators.
3987 unsigned NumSubExprs : 16;
3989 /// \brief The designators in this designated initialization
3991 Designator *Designators;
3994 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3995 const Designator *Designators,
3996 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3997 ArrayRef<Expr*> IndexExprs, Expr *Init);
3999 explicit DesignatedInitExpr(unsigned NumSubExprs)
4000 : Expr(DesignatedInitExprClass, EmptyShell()),
4001 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4004 /// A field designator, e.g., ".x".
4005 struct FieldDesignator {
4006 /// Refers to the field that is being initialized. The low bit
4007 /// of this field determines whether this is actually a pointer
4008 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4009 /// initially constructed, a field designator will store an
4010 /// IdentifierInfo*. After semantic analysis has resolved that
4011 /// name, the field designator will instead store a FieldDecl*.
4012 uintptr_t NameOrField;
4014 /// The location of the '.' in the designated initializer.
4017 /// The location of the field name in the designated initializer.
4021 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4022 struct ArrayOrRangeDesignator {
4023 /// Location of the first index expression within the designated
4024 /// initializer expression's list of subexpressions.
4026 /// The location of the '[' starting the array range designator.
4027 unsigned LBracketLoc;
4028 /// The location of the ellipsis separating the start and end
4029 /// indices. Only valid for GNU array-range designators.
4030 unsigned EllipsisLoc;
4031 /// The location of the ']' terminating the array range designator.
4032 unsigned RBracketLoc;
4035 /// @brief Represents a single C99 designator.
4037 /// @todo This class is infuriatingly similar to clang::Designator,
4038 /// but minor differences (storing indices vs. storing pointers)
4039 /// keep us from reusing it. Try harder, later, to rectify these
4042 /// @brief The kind of designator this describes.
4046 ArrayRangeDesignator
4050 /// A field designator, e.g., ".x".
4051 struct FieldDesignator Field;
4052 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4053 struct ArrayOrRangeDesignator ArrayOrRange;
4055 friend class DesignatedInitExpr;
4060 /// @brief Initializes a field designator.
4061 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4062 SourceLocation FieldLoc)
4063 : Kind(FieldDesignator) {
4064 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4065 Field.DotLoc = DotLoc.getRawEncoding();
4066 Field.FieldLoc = FieldLoc.getRawEncoding();
4069 /// @brief Initializes an array designator.
4070 Designator(unsigned Index, SourceLocation LBracketLoc,
4071 SourceLocation RBracketLoc)
4072 : Kind(ArrayDesignator) {
4073 ArrayOrRange.Index = Index;
4074 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4075 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4076 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4079 /// @brief Initializes a GNU array-range designator.
4080 Designator(unsigned Index, SourceLocation LBracketLoc,
4081 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4082 : Kind(ArrayRangeDesignator) {
4083 ArrayOrRange.Index = Index;
4084 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4085 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4086 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4089 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4090 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4091 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4093 IdentifierInfo *getFieldName() const;
4095 FieldDecl *getField() const {
4096 assert(Kind == FieldDesignator && "Only valid on a field designator");
4097 if (Field.NameOrField & 0x01)
4100 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4103 void setField(FieldDecl *FD) {
4104 assert(Kind == FieldDesignator && "Only valid on a field designator");
4105 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4108 SourceLocation getDotLoc() const {
4109 assert(Kind == FieldDesignator && "Only valid on a field designator");
4110 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4113 SourceLocation getFieldLoc() const {
4114 assert(Kind == FieldDesignator && "Only valid on a field designator");
4115 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4118 SourceLocation getLBracketLoc() const {
4119 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4120 "Only valid on an array or array-range designator");
4121 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4124 SourceLocation getRBracketLoc() const {
4125 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4126 "Only valid on an array or array-range designator");
4127 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4130 SourceLocation getEllipsisLoc() const {
4131 assert(Kind == ArrayRangeDesignator &&
4132 "Only valid on an array-range designator");
4133 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4136 unsigned getFirstExprIndex() const {
4137 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4138 "Only valid on an array or array-range designator");
4139 return ArrayOrRange.Index;
4142 SourceLocation getLocStart() const LLVM_READONLY {
4143 if (Kind == FieldDesignator)
4144 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4146 return getLBracketLoc();
4148 SourceLocation getLocEnd() const LLVM_READONLY {
4149 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4151 SourceRange getSourceRange() const LLVM_READONLY {
4152 return SourceRange(getLocStart(), getLocEnd());
4156 static DesignatedInitExpr *Create(const ASTContext &C,
4157 Designator *Designators,
4158 unsigned NumDesignators,
4159 ArrayRef<Expr*> IndexExprs,
4160 SourceLocation EqualOrColonLoc,
4161 bool GNUSyntax, Expr *Init);
4163 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4164 unsigned NumIndexExprs);
4166 /// @brief Returns the number of designators in this initializer.
4167 unsigned size() const { return NumDesignators; }
4169 // Iterator access to the designators.
4170 typedef Designator *designators_iterator;
4171 designators_iterator designators_begin() { return Designators; }
4172 designators_iterator designators_end() {
4173 return Designators + NumDesignators;
4176 typedef const Designator *const_designators_iterator;
4177 const_designators_iterator designators_begin() const { return Designators; }
4178 const_designators_iterator designators_end() const {
4179 return Designators + NumDesignators;
4182 typedef llvm::iterator_range<designators_iterator> designators_range;
4183 designators_range designators() {
4184 return designators_range(designators_begin(), designators_end());
4187 typedef llvm::iterator_range<const_designators_iterator>
4188 designators_const_range;
4189 designators_const_range designators() const {
4190 return designators_const_range(designators_begin(), designators_end());
4193 typedef std::reverse_iterator<designators_iterator>
4194 reverse_designators_iterator;
4195 reverse_designators_iterator designators_rbegin() {
4196 return reverse_designators_iterator(designators_end());
4198 reverse_designators_iterator designators_rend() {
4199 return reverse_designators_iterator(designators_begin());
4202 typedef std::reverse_iterator<const_designators_iterator>
4203 const_reverse_designators_iterator;
4204 const_reverse_designators_iterator designators_rbegin() const {
4205 return const_reverse_designators_iterator(designators_end());
4207 const_reverse_designators_iterator designators_rend() const {
4208 return const_reverse_designators_iterator(designators_begin());
4211 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4213 void setDesignators(const ASTContext &C, const Designator *Desigs,
4214 unsigned NumDesigs);
4216 Expr *getArrayIndex(const Designator &D) const;
4217 Expr *getArrayRangeStart(const Designator &D) const;
4218 Expr *getArrayRangeEnd(const Designator &D) const;
4220 /// @brief Retrieve the location of the '=' that precedes the
4221 /// initializer value itself, if present.
4222 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4223 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4225 /// @brief Determines whether this designated initializer used the
4226 /// deprecated GNU syntax for designated initializers.
4227 bool usesGNUSyntax() const { return GNUSyntax; }
4228 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4230 /// @brief Retrieve the initializer value.
4231 Expr *getInit() const {
4232 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4235 void setInit(Expr *init) {
4236 *child_begin() = init;
4239 /// \brief Retrieve the total number of subexpressions in this
4240 /// designated initializer expression, including the actual
4241 /// initialized value and any expressions that occur within array
4242 /// and array-range designators.
4243 unsigned getNumSubExprs() const { return NumSubExprs; }
4245 Expr *getSubExpr(unsigned Idx) const {
4246 assert(Idx < NumSubExprs && "Subscript out of range");
4247 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4250 void setSubExpr(unsigned Idx, Expr *E) {
4251 assert(Idx < NumSubExprs && "Subscript out of range");
4252 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4255 /// \brief Replaces the designator at index @p Idx with the series
4256 /// of designators in [First, Last).
4257 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4258 const Designator *First, const Designator *Last);
4260 SourceRange getDesignatorsSourceRange() const;
4262 SourceLocation getLocStart() const LLVM_READONLY;
4263 SourceLocation getLocEnd() const LLVM_READONLY;
4265 static bool classof(const Stmt *T) {
4266 return T->getStmtClass() == DesignatedInitExprClass;
4270 child_range children() {
4271 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4272 return child_range(begin, begin + NumSubExprs);
4276 /// \brief Represents an implicitly-generated value initialization of
4277 /// an object of a given type.
4279 /// Implicit value initializations occur within semantic initializer
4280 /// list expressions (InitListExpr) as placeholders for subobject
4281 /// initializations not explicitly specified by the user.
4283 /// \see InitListExpr
4284 class ImplicitValueInitExpr : public Expr {
4286 explicit ImplicitValueInitExpr(QualType ty)
4287 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4288 false, false, ty->isInstantiationDependentType(), false) { }
4290 /// \brief Construct an empty implicit value initialization.
4291 explicit ImplicitValueInitExpr(EmptyShell Empty)
4292 : Expr(ImplicitValueInitExprClass, Empty) { }
4294 static bool classof(const Stmt *T) {
4295 return T->getStmtClass() == ImplicitValueInitExprClass;
4298 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4299 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4302 child_range children() { return child_range(); }
4306 class ParenListExpr : public Expr {
4309 SourceLocation LParenLoc, RParenLoc;
4312 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4313 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4315 /// \brief Build an empty paren list.
4316 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4318 unsigned getNumExprs() const { return NumExprs; }
4320 const Expr* getExpr(unsigned Init) const {
4321 assert(Init < getNumExprs() && "Initializer access out of range!");
4322 return cast_or_null<Expr>(Exprs[Init]);
4325 Expr* getExpr(unsigned Init) {
4326 assert(Init < getNumExprs() && "Initializer access out of range!");
4327 return cast_or_null<Expr>(Exprs[Init]);
4330 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4332 SourceLocation getLParenLoc() const { return LParenLoc; }
4333 SourceLocation getRParenLoc() const { return RParenLoc; }
4335 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4336 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4338 static bool classof(const Stmt *T) {
4339 return T->getStmtClass() == ParenListExprClass;
4343 child_range children() {
4344 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4347 friend class ASTStmtReader;
4348 friend class ASTStmtWriter;
4352 /// \brief Represents a C11 generic selection.
4354 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4355 /// expression, followed by one or more generic associations. Each generic
4356 /// association specifies a type name and an expression, or "default" and an
4357 /// expression (in which case it is known as a default generic association).
4358 /// The type and value of the generic selection are identical to those of its
4359 /// result expression, which is defined as the expression in the generic
4360 /// association with a type name that is compatible with the type of the
4361 /// controlling expression, or the expression in the default generic association
4362 /// if no types are compatible. For example:
4365 /// _Generic(X, double: 1, float: 2, default: 3)
4368 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4369 /// or 3 if "hello".
4371 /// As an extension, generic selections are allowed in C++, where the following
4372 /// additional semantics apply:
4374 /// Any generic selection whose controlling expression is type-dependent or
4375 /// which names a dependent type in its association list is result-dependent,
4376 /// which means that the choice of result expression is dependent.
4377 /// Result-dependent generic associations are both type- and value-dependent.
4378 class GenericSelectionExpr : public Expr {
4379 enum { CONTROLLING, END_EXPR };
4380 TypeSourceInfo **AssocTypes;
4382 unsigned NumAssocs, ResultIndex;
4383 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4386 GenericSelectionExpr(const ASTContext &Context,
4387 SourceLocation GenericLoc, Expr *ControllingExpr,
4388 ArrayRef<TypeSourceInfo*> AssocTypes,
4389 ArrayRef<Expr*> AssocExprs,
4390 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4391 bool ContainsUnexpandedParameterPack,
4392 unsigned ResultIndex);
4394 /// This constructor is used in the result-dependent case.
4395 GenericSelectionExpr(const ASTContext &Context,
4396 SourceLocation GenericLoc, Expr *ControllingExpr,
4397 ArrayRef<TypeSourceInfo*> AssocTypes,
4398 ArrayRef<Expr*> AssocExprs,
4399 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4400 bool ContainsUnexpandedParameterPack);
4402 explicit GenericSelectionExpr(EmptyShell Empty)
4403 : Expr(GenericSelectionExprClass, Empty) { }
4405 unsigned getNumAssocs() const { return NumAssocs; }
4407 SourceLocation getGenericLoc() const { return GenericLoc; }
4408 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4409 SourceLocation getRParenLoc() const { return RParenLoc; }
4411 const Expr *getAssocExpr(unsigned i) const {
4412 return cast<Expr>(SubExprs[END_EXPR+i]);
4414 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4416 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4417 return AssocTypes[i];
4419 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4421 QualType getAssocType(unsigned i) const {
4422 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4423 return TS->getType();
4428 const Expr *getControllingExpr() const {
4429 return cast<Expr>(SubExprs[CONTROLLING]);
4431 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4433 /// Whether this generic selection is result-dependent.
4434 bool isResultDependent() const { return ResultIndex == -1U; }
4436 /// The zero-based index of the result expression's generic association in
4437 /// the generic selection's association list. Defined only if the
4438 /// generic selection is not result-dependent.
4439 unsigned getResultIndex() const {
4440 assert(!isResultDependent() && "Generic selection is result-dependent");
4444 /// The generic selection's result expression. Defined only if the
4445 /// generic selection is not result-dependent.
4446 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4447 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4449 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4450 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4452 static bool classof(const Stmt *T) {
4453 return T->getStmtClass() == GenericSelectionExprClass;
4456 child_range children() {
4457 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4460 friend class ASTStmtReader;
4463 //===----------------------------------------------------------------------===//
4465 //===----------------------------------------------------------------------===//
4468 /// ExtVectorElementExpr - This represents access to specific elements of a
4469 /// vector, and may occur on the left hand side or right hand side. For example
4470 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4472 /// Note that the base may have either vector or pointer to vector type, just
4473 /// like a struct field reference.
4475 class ExtVectorElementExpr : public Expr {
4477 IdentifierInfo *Accessor;
4478 SourceLocation AccessorLoc;
4480 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4481 IdentifierInfo &accessor, SourceLocation loc)
4482 : Expr(ExtVectorElementExprClass, ty, VK,
4483 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4484 base->isTypeDependent(), base->isValueDependent(),
4485 base->isInstantiationDependent(),
4486 base->containsUnexpandedParameterPack()),
4487 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4489 /// \brief Build an empty vector element expression.
4490 explicit ExtVectorElementExpr(EmptyShell Empty)
4491 : Expr(ExtVectorElementExprClass, Empty) { }
4493 const Expr *getBase() const { return cast<Expr>(Base); }
4494 Expr *getBase() { return cast<Expr>(Base); }
4495 void setBase(Expr *E) { Base = E; }
4497 IdentifierInfo &getAccessor() const { return *Accessor; }
4498 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4500 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4501 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4503 /// getNumElements - Get the number of components being selected.
4504 unsigned getNumElements() const;
4506 /// containsDuplicateElements - Return true if any element access is
4508 bool containsDuplicateElements() const;
4510 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4511 /// aggregate Constant of ConstantInt(s).
4512 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4514 SourceLocation getLocStart() const LLVM_READONLY {
4515 return getBase()->getLocStart();
4517 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4519 /// isArrow - Return true if the base expression is a pointer to vector,
4520 /// return false if the base expression is a vector.
4521 bool isArrow() const;
4523 static bool classof(const Stmt *T) {
4524 return T->getStmtClass() == ExtVectorElementExprClass;
4528 child_range children() { return child_range(&Base, &Base+1); }
4532 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4533 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4534 class BlockExpr : public Expr {
4536 BlockDecl *TheBlock;
4538 BlockExpr(BlockDecl *BD, QualType ty)
4539 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4540 ty->isDependentType(), ty->isDependentType(),
4541 ty->isInstantiationDependentType() || BD->isDependentContext(),
4545 /// \brief Build an empty block expression.
4546 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4548 const BlockDecl *getBlockDecl() const { return TheBlock; }
4549 BlockDecl *getBlockDecl() { return TheBlock; }
4550 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4552 // Convenience functions for probing the underlying BlockDecl.
4553 SourceLocation getCaretLocation() const;
4554 const Stmt *getBody() const;
4557 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4558 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4560 /// getFunctionType - Return the underlying function type for this block.
4561 const FunctionProtoType *getFunctionType() const;
4563 static bool classof(const Stmt *T) {
4564 return T->getStmtClass() == BlockExprClass;
4568 child_range children() { return child_range(); }
4571 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4572 /// This AST node provides support for reinterpreting a type to another
4573 /// type of the same size.
4574 class AsTypeExpr : public Expr {
4577 SourceLocation BuiltinLoc, RParenLoc;
4579 friend class ASTReader;
4580 friend class ASTStmtReader;
4581 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4584 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4585 ExprValueKind VK, ExprObjectKind OK,
4586 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4587 : Expr(AsTypeExprClass, DstType, VK, OK,
4588 DstType->isDependentType(),
4589 DstType->isDependentType() || SrcExpr->isValueDependent(),
4590 (DstType->isInstantiationDependentType() ||
4591 SrcExpr->isInstantiationDependent()),
4592 (DstType->containsUnexpandedParameterPack() ||
4593 SrcExpr->containsUnexpandedParameterPack())),
4594 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4596 /// getSrcExpr - Return the Expr to be converted.
4597 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4599 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4600 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4602 /// getRParenLoc - Return the location of final right parenthesis.
4603 SourceLocation getRParenLoc() const { return RParenLoc; }
4605 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4606 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4608 static bool classof(const Stmt *T) {
4609 return T->getStmtClass() == AsTypeExprClass;
4613 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4616 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4617 /// l-value. A pseudo-object is an abstract object, accesses to which
4618 /// are translated to calls. The pseudo-object expression has a
4619 /// syntactic form, which shows how the expression was actually
4620 /// written in the source code, and a semantic form, which is a series
4621 /// of expressions to be executed in order which detail how the
4622 /// operation is actually evaluated. Optionally, one of the semantic
4623 /// forms may also provide a result value for the expression.
4625 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4626 /// that OVE is required to have a source expression, and it is bound
4627 /// to the result of that source expression. Such OVEs may appear
4628 /// only in subsequent semantic-form expressions and as
4629 /// sub-expressions of the syntactic form.
4631 /// PseudoObjectExpr should be used only when an operation can be
4632 /// usefully described in terms of fairly simple rewrite rules on
4633 /// objects and functions that are meant to be used by end-developers.
4634 /// For example, under the Itanium ABI, dynamic casts are implemented
4635 /// as a call to a runtime function called __dynamic_cast; using this
4636 /// class to describe that would be inappropriate because that call is
4637 /// not really part of the user-visible semantics, and instead the
4638 /// cast is properly reflected in the AST and IR-generation has been
4639 /// taught to generate the call as necessary. In contrast, an
4640 /// Objective-C property access is semantically defined to be
4641 /// equivalent to a particular message send, and this is very much
4642 /// part of the user model. The name of this class encourages this
4643 /// modelling design.
4644 class PseudoObjectExpr : public Expr {
4645 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4646 // Always at least two, because the first sub-expression is the
4649 // PseudoObjectExprBits.ResultIndex - The index of the
4650 // sub-expression holding the result. 0 means the result is void,
4651 // which is unambiguous because it's the index of the syntactic
4652 // form. Note that this is therefore 1 higher than the value passed
4653 // in to Create, which is an index within the semantic forms.
4654 // Note also that ASTStmtWriter assumes this encoding.
4656 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4657 const Expr * const *getSubExprsBuffer() const {
4658 return reinterpret_cast<const Expr * const *>(this + 1);
4661 friend class ASTStmtReader;
4663 PseudoObjectExpr(QualType type, ExprValueKind VK,
4664 Expr *syntactic, ArrayRef<Expr*> semantic,
4665 unsigned resultIndex);
4667 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4669 unsigned getNumSubExprs() const {
4670 return PseudoObjectExprBits.NumSubExprs;
4674 /// NoResult - A value for the result index indicating that there is
4675 /// no semantic result.
4676 enum : unsigned { NoResult = ~0U };
4678 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4679 ArrayRef<Expr*> semantic,
4680 unsigned resultIndex);
4682 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4683 unsigned numSemanticExprs);
4685 /// Return the syntactic form of this expression, i.e. the
4686 /// expression it actually looks like. Likely to be expressed in
4687 /// terms of OpaqueValueExprs bound in the semantic form.
4688 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4689 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4691 /// Return the index of the result-bearing expression into the semantics
4692 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4693 unsigned getResultExprIndex() const {
4694 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4695 return PseudoObjectExprBits.ResultIndex - 1;
4698 /// Return the result-bearing expression, or null if there is none.
4699 Expr *getResultExpr() {
4700 if (PseudoObjectExprBits.ResultIndex == 0)
4702 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4704 const Expr *getResultExpr() const {
4705 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4708 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4710 typedef Expr * const *semantics_iterator;
4711 typedef const Expr * const *const_semantics_iterator;
4712 semantics_iterator semantics_begin() {
4713 return getSubExprsBuffer() + 1;
4715 const_semantics_iterator semantics_begin() const {
4716 return getSubExprsBuffer() + 1;
4718 semantics_iterator semantics_end() {
4719 return getSubExprsBuffer() + getNumSubExprs();
4721 const_semantics_iterator semantics_end() const {
4722 return getSubExprsBuffer() + getNumSubExprs();
4724 Expr *getSemanticExpr(unsigned index) {
4725 assert(index + 1 < getNumSubExprs());
4726 return getSubExprsBuffer()[index + 1];
4728 const Expr *getSemanticExpr(unsigned index) const {
4729 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4732 SourceLocation getExprLoc() const LLVM_READONLY {
4733 return getSyntacticForm()->getExprLoc();
4736 SourceLocation getLocStart() const LLVM_READONLY {
4737 return getSyntacticForm()->getLocStart();
4739 SourceLocation getLocEnd() const LLVM_READONLY {
4740 return getSyntacticForm()->getLocEnd();
4743 child_range children() {
4744 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4745 return child_range(cs, cs + getNumSubExprs());
4748 static bool classof(const Stmt *T) {
4749 return T->getStmtClass() == PseudoObjectExprClass;
4753 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4754 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4755 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4756 /// All of these instructions take one primary pointer and at least one memory
4758 class AtomicExpr : public Expr {
4761 #define BUILTIN(ID, TYPE, ATTRS)
4762 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4763 #include "clang/Basic/Builtins.def"
4764 // Avoid trailing comma
4768 // The ABI values for various atomic memory orderings.
4769 enum AtomicOrderingKind {
4770 AO_ABI_memory_order_relaxed = 0,
4771 AO_ABI_memory_order_consume = 1,
4772 AO_ABI_memory_order_acquire = 2,
4773 AO_ABI_memory_order_release = 3,
4774 AO_ABI_memory_order_acq_rel = 4,
4775 AO_ABI_memory_order_seq_cst = 5
4779 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4780 Stmt* SubExprs[END_EXPR];
4781 unsigned NumSubExprs;
4782 SourceLocation BuiltinLoc, RParenLoc;
4785 friend class ASTStmtReader;
4788 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4789 AtomicOp op, SourceLocation RP);
4791 /// \brief Determine the number of arguments the specified atomic builtin
4793 static unsigned getNumSubExprs(AtomicOp Op);
4795 /// \brief Build an empty AtomicExpr.
4796 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4798 Expr *getPtr() const {
4799 return cast<Expr>(SubExprs[PTR]);
4801 Expr *getOrder() const {
4802 return cast<Expr>(SubExprs[ORDER]);
4804 Expr *getVal1() const {
4805 if (Op == AO__c11_atomic_init)
4806 return cast<Expr>(SubExprs[ORDER]);
4807 assert(NumSubExprs > VAL1);
4808 return cast<Expr>(SubExprs[VAL1]);
4810 Expr *getOrderFail() const {
4811 assert(NumSubExprs > ORDER_FAIL);
4812 return cast<Expr>(SubExprs[ORDER_FAIL]);
4814 Expr *getVal2() const {
4815 if (Op == AO__atomic_exchange)
4816 return cast<Expr>(SubExprs[ORDER_FAIL]);
4817 assert(NumSubExprs > VAL2);
4818 return cast<Expr>(SubExprs[VAL2]);
4820 Expr *getWeak() const {
4821 assert(NumSubExprs > WEAK);
4822 return cast<Expr>(SubExprs[WEAK]);
4825 AtomicOp getOp() const { return Op; }
4826 unsigned getNumSubExprs() { return NumSubExprs; }
4828 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4830 bool isVolatile() const {
4831 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4834 bool isCmpXChg() const {
4835 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4836 getOp() == AO__c11_atomic_compare_exchange_weak ||
4837 getOp() == AO__atomic_compare_exchange ||
4838 getOp() == AO__atomic_compare_exchange_n;
4841 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4842 SourceLocation getRParenLoc() const { return RParenLoc; }
4844 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4845 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4847 static bool classof(const Stmt *T) {
4848 return T->getStmtClass() == AtomicExprClass;
4852 child_range children() {
4853 return child_range(SubExprs, SubExprs+NumSubExprs);
4857 /// TypoExpr - Internal placeholder for expressions where typo correction
4858 /// still needs to be performed and/or an error diagnostic emitted.
4859 class TypoExpr : public Expr {
4861 TypoExpr(QualType T)
4862 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4863 /*isTypeDependent*/ true,
4864 /*isValueDependent*/ true,
4865 /*isInstantiationDependent*/ true,
4866 /*containsUnexpandedParameterPack*/ false) {
4867 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4870 child_range children() { return child_range(); }
4871 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4872 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4874 } // end namespace clang