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.
281 MLV_NoSetterProperty,
283 MLV_SubObjCPropertySetting,
284 MLV_InvalidMessageExpression,
288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289 /// does not have an incomplete type, does not have a const-qualified type,
290 /// and if it is a structure or union, does not have any member (including,
291 /// recursively, any member or element of all contained aggregates or unions)
292 /// with a const-qualified type.
294 /// \param Loc [in,out] - A source location which *may* be filled
295 /// in with the location of the expression making this a
296 /// non-modifiable lvalue, if specified.
297 isModifiableLvalueResult
298 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
300 /// \brief The return type of classify(). Represents the C++11 expression
302 class Classification {
304 /// \brief The various classification results. Most of these mean prvalue.
308 CL_Function, // Functions cannot be lvalues in C.
309 CL_Void, // Void cannot be an lvalue in C.
310 CL_AddressableVoid, // Void expression whose address can be taken in C.
311 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312 CL_MemberFunction, // An expression referring to a member function
313 CL_SubObjCPropertySetting,
314 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315 CL_ArrayTemporary, // A temporary of array type.
316 CL_ObjCMessageRValue, // ObjC message is an rvalue
317 CL_PRValue // A prvalue for any other reason, of any other type
319 /// \brief The results of modification testing.
320 enum ModifiableType {
321 CM_Untested, // testModifiable was false.
323 CM_RValue, // Not modifiable because it's an rvalue
324 CM_Function, // Not modifiable because it's a function; C++ only
325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
337 unsigned short Modifiable;
339 explicit Classification(Kinds k, ModifiableType m)
340 : Kind(k), Modifiable(m)
346 Kinds getKind() const { return static_cast<Kinds>(Kind); }
347 ModifiableType getModifiable() const {
348 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
349 return static_cast<ModifiableType>(Modifiable);
351 bool isLValue() const { return Kind == CL_LValue; }
352 bool isXValue() const { return Kind == CL_XValue; }
353 bool isGLValue() const { return Kind <= CL_XValue; }
354 bool isPRValue() const { return Kind >= CL_Function; }
355 bool isRValue() const { return Kind >= CL_XValue; }
356 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
358 /// \brief Create a simple, modifiably lvalue
359 static Classification makeSimpleLValue() {
360 return Classification(CL_LValue, CM_Modifiable);
364 /// \brief Classify - Classify this expression according to the C++11
365 /// expression taxonomy.
367 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
368 /// old lvalue vs rvalue. This function determines the type of expression this
369 /// is. There are three expression types:
370 /// - lvalues are classical lvalues as in C++03.
371 /// - prvalues are equivalent to rvalues in C++03.
372 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
373 /// function returning an rvalue reference.
374 /// lvalues and xvalues are collectively referred to as glvalues, while
375 /// prvalues and xvalues together form rvalues.
376 Classification Classify(ASTContext &Ctx) const {
377 return ClassifyImpl(Ctx, nullptr);
380 /// \brief ClassifyModifiable - Classify this expression according to the
381 /// C++11 expression taxonomy, and see if it is valid on the left side
382 /// of an assignment.
384 /// This function extends classify in that it also tests whether the
385 /// expression is modifiable (C99 6.3.2.1p1).
386 /// \param Loc A source location that might be filled with a relevant location
387 /// if the expression is not modifiable.
388 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
389 return ClassifyImpl(Ctx, &Loc);
392 /// getValueKindForType - Given a formal return or parameter type,
393 /// give its value kind.
394 static ExprValueKind getValueKindForType(QualType T) {
395 if (const ReferenceType *RT = T->getAs<ReferenceType>())
396 return (isa<LValueReferenceType>(RT)
398 : (RT->getPointeeType()->isFunctionType()
399 ? VK_LValue : VK_XValue));
403 /// getValueKind - The value kind that this expression produces.
404 ExprValueKind getValueKind() const {
405 return static_cast<ExprValueKind>(ExprBits.ValueKind);
408 /// getObjectKind - The object kind that this expression produces.
409 /// Object kinds are meaningful only for expressions that yield an
410 /// l-value or x-value.
411 ExprObjectKind getObjectKind() const {
412 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
415 bool isOrdinaryOrBitFieldObject() const {
416 ExprObjectKind OK = getObjectKind();
417 return (OK == OK_Ordinary || OK == OK_BitField);
420 /// setValueKind - Set the value kind produced by this expression.
421 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
423 /// setObjectKind - Set the object kind produced by this expression.
424 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
427 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
431 /// \brief Returns true if this expression is a gl-value that
432 /// potentially refers to a bit-field.
434 /// In C++, whether a gl-value refers to a bitfield is essentially
435 /// an aspect of the value-kind type system.
436 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
438 /// \brief If this expression refers to a bit-field, retrieve the
439 /// declaration of that bit-field.
441 /// Note that this returns a non-null pointer in subtly different
442 /// places than refersToBitField returns true. In particular, this can
443 /// return a non-null pointer even for r-values loaded from
444 /// bit-fields, but it will return null for a conditional bit-field.
445 FieldDecl *getSourceBitField();
447 const FieldDecl *getSourceBitField() const {
448 return const_cast<Expr*>(this)->getSourceBitField();
451 /// \brief If this expression is an l-value for an Objective C
452 /// property, find the underlying property reference expression.
453 const ObjCPropertyRefExpr *getObjCProperty() const;
455 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
456 bool isObjCSelfExpr() const;
458 /// \brief Returns whether this expression refers to a vector element.
459 bool refersToVectorElement() const;
461 /// \brief Returns whether this expression has a placeholder type.
462 bool hasPlaceholderType() const {
463 return getType()->isPlaceholderType();
466 /// \brief Returns whether this expression has a specific placeholder type.
467 bool hasPlaceholderType(BuiltinType::Kind K) const {
468 assert(BuiltinType::isPlaceholderTypeKind(K));
469 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
470 return BT->getKind() == K;
474 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
475 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
476 /// but also int expressions which are produced by things like comparisons in
478 bool isKnownToHaveBooleanValue() const;
480 /// isIntegerConstantExpr - Return true if this expression is a valid integer
481 /// constant expression, and, if so, return its value in Result. If not a
482 /// valid i-c-e, return false and fill in Loc (if specified) with the location
483 /// of the invalid expression.
485 /// Note: This does not perform the implicit conversions required by C++11
487 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
488 SourceLocation *Loc = nullptr,
489 bool isEvaluated = true) const;
490 bool isIntegerConstantExpr(const ASTContext &Ctx,
491 SourceLocation *Loc = nullptr) const;
493 /// isCXX98IntegralConstantExpr - Return true if this expression is an
494 /// integral constant expression in C++98. Can only be used in C++.
495 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
497 /// isCXX11ConstantExpr - Return true if this expression is a constant
498 /// expression in C++11. Can only be used in C++.
500 /// Note: This does not perform the implicit conversions required by C++11
502 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
503 SourceLocation *Loc = nullptr) const;
505 /// isPotentialConstantExpr - Return true if this function's definition
506 /// might be usable in a constant expression in C++11, if it were marked
507 /// constexpr. Return false if the function can never produce a constant
508 /// expression, along with diagnostics describing why not.
509 static bool isPotentialConstantExpr(const FunctionDecl *FD,
511 PartialDiagnosticAt> &Diags);
513 /// isPotentialConstantExprUnevaluted - Return true if this expression might
514 /// be usable in a constant expression in C++11 in an unevaluated context, if
515 /// it were in function FD marked constexpr. Return false if the function can
516 /// never produce a constant expression, along with diagnostics describing
518 static bool isPotentialConstantExprUnevaluated(Expr *E,
519 const FunctionDecl *FD,
521 PartialDiagnosticAt> &Diags);
523 /// isConstantInitializer - Returns true if this expression can be emitted to
524 /// IR as a constant, and thus can be used as a constant initializer in C.
525 /// If this expression is not constant and Culprit is non-null,
526 /// it is used to store the address of first non constant expr.
527 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
528 const Expr **Culprit = nullptr) const;
530 /// EvalStatus is a struct with detailed info about an evaluation in progress.
532 /// HasSideEffects - Whether the evaluated expression has side effects.
533 /// For example, (f() && 0) can be folded, but it still has side effects.
536 /// Diag - If this is non-null, it will be filled in with a stack of notes
537 /// indicating why evaluation failed (or why it failed to produce a constant
539 /// If the expression is unfoldable, the notes will indicate why it's not
540 /// foldable. If the expression is foldable, but not a constant expression,
541 /// the notes will describes why it isn't a constant expression. If the
542 /// expression *is* a constant expression, no notes will be produced.
543 SmallVectorImpl<PartialDiagnosticAt> *Diag;
545 EvalStatus() : HasSideEffects(false), Diag(nullptr) {}
547 // hasSideEffects - Return true if the evaluated expression has
549 bool hasSideEffects() const {
550 return HasSideEffects;
554 /// EvalResult is a struct with detailed info about an evaluated expression.
555 struct EvalResult : EvalStatus {
556 /// Val - This is the value the expression can be folded to.
559 // isGlobalLValue - Return true if the evaluated lvalue expression
561 bool isGlobalLValue() const;
564 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
565 /// an rvalue using any crazy technique (that has nothing to do with language
566 /// standards) that we want to, even if the expression has side-effects. If
567 /// this function returns true, it returns the folded constant in Result. If
568 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
570 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
572 /// EvaluateAsBooleanCondition - Return true if this is a constant
573 /// which we we can fold and convert to a boolean condition using
574 /// any crazy technique that we want to, even if the expression has
576 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
578 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
580 /// EvaluateAsInt - Return true if this is a constant which we can fold and
581 /// convert to an integer, using any crazy technique that we want to.
582 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
583 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
585 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
586 /// constant folded without side-effects, but discard the result.
587 bool isEvaluatable(const ASTContext &Ctx) const;
589 /// HasSideEffects - This routine returns true for all those expressions
590 /// which have any effect other than producing a value. Example is a function
591 /// call, volatile variable read, or throwing an exception. If
592 /// IncludePossibleEffects is false, this call treats certain expressions with
593 /// potential side effects (such as function call-like expressions,
594 /// instantiation-dependent expressions, or invocations from a macro) as not
595 /// having side effects.
596 bool HasSideEffects(const ASTContext &Ctx,
597 bool IncludePossibleEffects = true) const;
599 /// \brief Determine whether this expression involves a call to any function
600 /// that is not trivial.
601 bool hasNonTrivialCall(ASTContext &Ctx);
603 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
604 /// integer. This must be called on an expression that constant folds to an
606 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
607 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
609 void EvaluateForOverflow(const ASTContext &Ctx) const;
611 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
612 /// lvalue with link time known address, with no side-effects.
613 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
615 /// EvaluateAsInitializer - Evaluate an expression as if it were the
616 /// initializer of the given declaration. Returns true if the initializer
617 /// can be folded to a constant, and produces any relevant notes. In C++11,
618 /// notes will be produced if the expression is not a constant expression.
619 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
621 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
623 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
624 /// of a call to the given function with the given arguments, inside an
625 /// unevaluated context. Returns true if the expression could be folded to a
627 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
628 const FunctionDecl *Callee,
629 ArrayRef<const Expr*> Args) const;
631 /// \brief Enumeration used to describe the kind of Null pointer constant
632 /// returned from \c isNullPointerConstant().
633 enum NullPointerConstantKind {
634 /// \brief Expression is not a Null pointer constant.
637 /// \brief Expression is a Null pointer constant built from a zero integer
638 /// expression that is not a simple, possibly parenthesized, zero literal.
639 /// C++ Core Issue 903 will classify these expressions as "not pointers"
640 /// once it is adopted.
641 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
644 /// \brief Expression is a Null pointer constant built from a literal zero.
647 /// \brief Expression is a C++11 nullptr.
650 /// \brief Expression is a GNU-style __null constant.
654 /// \brief Enumeration used to describe how \c isNullPointerConstant()
655 /// should cope with value-dependent expressions.
656 enum NullPointerConstantValueDependence {
657 /// \brief Specifies that the expression should never be value-dependent.
658 NPC_NeverValueDependent = 0,
660 /// \brief Specifies that a value-dependent expression of integral or
661 /// dependent type should be considered a null pointer constant.
662 NPC_ValueDependentIsNull,
664 /// \brief Specifies that a value-dependent expression should be considered
665 /// to never be a null pointer constant.
666 NPC_ValueDependentIsNotNull
669 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
670 /// a Null pointer constant. The return value can further distinguish the
671 /// kind of NULL pointer constant that was detected.
672 NullPointerConstantKind isNullPointerConstant(
674 NullPointerConstantValueDependence NPC) const;
676 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
678 bool isOBJCGCCandidate(ASTContext &Ctx) const;
680 /// \brief Returns true if this expression is a bound member function.
681 bool isBoundMemberFunction(ASTContext &Ctx) const;
683 /// \brief Given an expression of bound-member type, find the type
684 /// of the member. Returns null if this is an *overloaded* bound
685 /// member expression.
686 static QualType findBoundMemberType(const Expr *expr);
688 /// IgnoreImpCasts - Skip past any implicit casts which might
689 /// surround this expression. Only skips ImplicitCastExprs.
690 Expr *IgnoreImpCasts() LLVM_READONLY;
692 /// IgnoreImplicit - Skip past any implicit AST nodes which might
693 /// surround this expression.
694 Expr *IgnoreImplicit() LLVM_READONLY {
695 return cast<Expr>(Stmt::IgnoreImplicit());
698 const Expr *IgnoreImplicit() const LLVM_READONLY {
699 return const_cast<Expr*>(this)->IgnoreImplicit();
702 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
703 /// its subexpression. If that subexpression is also a ParenExpr,
704 /// then this method recursively returns its subexpression, and so forth.
705 /// Otherwise, the method returns the current Expr.
706 Expr *IgnoreParens() LLVM_READONLY;
708 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
709 /// or CastExprs, returning their operand.
710 Expr *IgnoreParenCasts() LLVM_READONLY;
712 /// Ignore casts. Strip off any CastExprs, returning their operand.
713 Expr *IgnoreCasts() LLVM_READONLY;
715 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
716 /// any ParenExpr or ImplicitCastExprs, returning their operand.
717 Expr *IgnoreParenImpCasts() LLVM_READONLY;
719 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
720 /// call to a conversion operator, return the argument.
721 Expr *IgnoreConversionOperator() LLVM_READONLY;
723 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
724 return const_cast<Expr*>(this)->IgnoreConversionOperator();
727 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
728 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
731 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
732 /// CastExprs that represent lvalue casts, returning their operand.
733 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
735 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
736 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
739 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
740 /// value (including ptr->int casts of the same size). Strip off any
741 /// ParenExpr or CastExprs, returning their operand.
742 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
744 /// Ignore parentheses and derived-to-base casts.
745 Expr *ignoreParenBaseCasts() LLVM_READONLY;
747 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
748 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
751 /// \brief Determine whether this expression is a default function argument.
753 /// Default arguments are implicitly generated in the abstract syntax tree
754 /// by semantic analysis for function calls, object constructions, etc. in
755 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
756 /// this routine also looks through any implicit casts to determine whether
757 /// the expression is a default argument.
758 bool isDefaultArgument() const;
760 /// \brief Determine whether the result of this expression is a
761 /// temporary object of the given class type.
762 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
764 /// \brief Whether this expression is an implicit reference to 'this' in C++.
765 bool isImplicitCXXThis() const;
767 const Expr *IgnoreImpCasts() const LLVM_READONLY {
768 return const_cast<Expr*>(this)->IgnoreImpCasts();
770 const Expr *IgnoreParens() const LLVM_READONLY {
771 return const_cast<Expr*>(this)->IgnoreParens();
773 const Expr *IgnoreParenCasts() const LLVM_READONLY {
774 return const_cast<Expr*>(this)->IgnoreParenCasts();
776 /// Strip off casts, but keep parentheses.
777 const Expr *IgnoreCasts() const LLVM_READONLY {
778 return const_cast<Expr*>(this)->IgnoreCasts();
781 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
782 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
785 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
787 /// \brief For an expression of class type or pointer to class type,
788 /// return the most derived class decl the expression is known to refer to.
790 /// If this expression is a cast, this method looks through it to find the
791 /// most derived decl that can be inferred from the expression.
792 /// This is valid because derived-to-base conversions have undefined
793 /// behavior if the object isn't dynamically of the derived type.
794 const CXXRecordDecl *getBestDynamicClassType() const;
796 /// Walk outwards from an expression we want to bind a reference to and
797 /// find the expression whose lifetime needs to be extended. Record
798 /// the LHSs of comma expressions and adjustments needed along the path.
799 const Expr *skipRValueSubobjectAdjustments(
800 SmallVectorImpl<const Expr *> &CommaLHS,
801 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
803 static bool classof(const Stmt *T) {
804 return T->getStmtClass() >= firstExprConstant &&
805 T->getStmtClass() <= lastExprConstant;
810 //===----------------------------------------------------------------------===//
811 // Primary Expressions.
812 //===----------------------------------------------------------------------===//
814 /// OpaqueValueExpr - An expression referring to an opaque object of a
815 /// fixed type and value class. These don't correspond to concrete
816 /// syntax; instead they're used to express operations (usually copy
817 /// operations) on values whose source is generally obvious from
819 class OpaqueValueExpr : public Expr {
820 friend class ASTStmtReader;
825 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
826 ExprObjectKind OK = OK_Ordinary,
827 Expr *SourceExpr = nullptr)
828 : Expr(OpaqueValueExprClass, T, VK, OK,
829 T->isDependentType(),
830 T->isDependentType() ||
831 (SourceExpr && SourceExpr->isValueDependent()),
832 T->isInstantiationDependentType(),
834 SourceExpr(SourceExpr), Loc(Loc) {
837 /// Given an expression which invokes a copy constructor --- i.e. a
838 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
839 /// find the OpaqueValueExpr that's the source of the construction.
840 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
842 explicit OpaqueValueExpr(EmptyShell Empty)
843 : Expr(OpaqueValueExprClass, Empty) { }
845 /// \brief Retrieve the location of this expression.
846 SourceLocation getLocation() const { return Loc; }
848 SourceLocation getLocStart() const LLVM_READONLY {
849 return SourceExpr ? SourceExpr->getLocStart() : Loc;
851 SourceLocation getLocEnd() const LLVM_READONLY {
852 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
854 SourceLocation getExprLoc() const LLVM_READONLY {
855 if (SourceExpr) return SourceExpr->getExprLoc();
859 child_range children() { return child_range(); }
861 /// The source expression of an opaque value expression is the
862 /// expression which originally generated the value. This is
863 /// provided as a convenience for analyses that don't wish to
864 /// precisely model the execution behavior of the program.
866 /// The source expression is typically set when building the
867 /// expression which binds the opaque value expression in the first
869 Expr *getSourceExpr() const { return SourceExpr; }
871 static bool classof(const Stmt *T) {
872 return T->getStmtClass() == OpaqueValueExprClass;
876 /// \brief A reference to a declared variable, function, enum, etc.
879 /// This encodes all the information about how a declaration is referenced
880 /// within an expression.
882 /// There are several optional constructs attached to DeclRefExprs only when
883 /// they apply in order to conserve memory. These are laid out past the end of
884 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
886 /// DeclRefExprBits.HasQualifier:
887 /// Specifies when this declaration reference expression has a C++
888 /// nested-name-specifier.
889 /// DeclRefExprBits.HasFoundDecl:
890 /// Specifies when this declaration reference expression has a record of
891 /// a NamedDecl (different from the referenced ValueDecl) which was found
892 /// during name lookup and/or overload resolution.
893 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
894 /// Specifies when this declaration reference expression has an explicit
895 /// C++ template keyword and/or template argument list.
896 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
897 /// Specifies when this declaration reference expression (validly)
898 /// refers to an enclosed local or a captured variable.
899 class DeclRefExpr : public Expr {
900 /// \brief The declaration that we are referencing.
903 /// \brief The location of the declaration name itself.
906 /// \brief Provides source/type location info for the declaration name
908 DeclarationNameLoc DNLoc;
910 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
911 NestedNameSpecifierLoc &getInternalQualifierLoc() {
912 assert(hasQualifier());
913 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
916 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
917 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
918 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
921 /// \brief Test whether there is a distinct FoundDecl attached to the end of
923 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
925 /// \brief Helper to retrieve the optional NamedDecl through which this
926 /// reference occurred.
927 NamedDecl *&getInternalFoundDecl() {
928 assert(hasFoundDecl());
930 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
931 return *reinterpret_cast<NamedDecl **>(this + 1);
934 /// \brief Helper to retrieve the optional NamedDecl through which this
935 /// reference occurred.
936 NamedDecl *getInternalFoundDecl() const {
937 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
940 DeclRefExpr(const ASTContext &Ctx,
941 NestedNameSpecifierLoc QualifierLoc,
942 SourceLocation TemplateKWLoc,
943 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
944 const DeclarationNameInfo &NameInfo,
946 const TemplateArgumentListInfo *TemplateArgs,
947 QualType T, ExprValueKind VK);
949 /// \brief Construct an empty declaration reference expression.
950 explicit DeclRefExpr(EmptyShell Empty)
951 : Expr(DeclRefExprClass, Empty) { }
953 /// \brief Computes the type- and value-dependence flags for this
954 /// declaration reference expression.
955 void computeDependence(const ASTContext &C);
958 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
959 ExprValueKind VK, SourceLocation L,
960 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
961 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
962 D(D), Loc(L), DNLoc(LocInfo) {
963 DeclRefExprBits.HasQualifier = 0;
964 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
965 DeclRefExprBits.HasFoundDecl = 0;
966 DeclRefExprBits.HadMultipleCandidates = 0;
967 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
968 RefersToEnclosingVariableOrCapture;
969 computeDependence(D->getASTContext());
973 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
974 SourceLocation TemplateKWLoc, ValueDecl *D,
975 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
976 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
977 const TemplateArgumentListInfo *TemplateArgs = nullptr);
980 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
981 SourceLocation TemplateKWLoc, ValueDecl *D,
982 bool RefersToEnclosingVariableOrCapture,
983 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
984 NamedDecl *FoundD = nullptr,
985 const TemplateArgumentListInfo *TemplateArgs = nullptr);
987 /// \brief Construct an empty declaration reference expression.
988 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
991 bool HasTemplateKWAndArgsInfo,
992 unsigned NumTemplateArgs);
994 ValueDecl *getDecl() { return D; }
995 const ValueDecl *getDecl() const { return D; }
996 void setDecl(ValueDecl *NewD) { D = NewD; }
998 DeclarationNameInfo getNameInfo() const {
999 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1002 SourceLocation getLocation() const { return Loc; }
1003 void setLocation(SourceLocation L) { Loc = L; }
1004 SourceLocation getLocStart() const LLVM_READONLY;
1005 SourceLocation getLocEnd() const LLVM_READONLY;
1007 /// \brief Determine whether this declaration reference was preceded by a
1008 /// C++ nested-name-specifier, e.g., \c N::foo.
1009 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1011 /// \brief If the name was qualified, retrieves the nested-name-specifier
1012 /// that precedes the name. Otherwise, returns NULL.
1013 NestedNameSpecifier *getQualifier() const {
1014 if (!hasQualifier())
1017 return getInternalQualifierLoc().getNestedNameSpecifier();
1020 /// \brief If the name was qualified, retrieves the nested-name-specifier
1021 /// that precedes the name, with source-location information.
1022 NestedNameSpecifierLoc getQualifierLoc() const {
1023 if (!hasQualifier())
1024 return NestedNameSpecifierLoc();
1026 return getInternalQualifierLoc();
1029 /// \brief Get the NamedDecl through which this reference occurred.
1031 /// This Decl may be different from the ValueDecl actually referred to in the
1032 /// presence of using declarations, etc. It always returns non-NULL, and may
1033 /// simple return the ValueDecl when appropriate.
1034 NamedDecl *getFoundDecl() {
1035 return hasFoundDecl() ? getInternalFoundDecl() : D;
1038 /// \brief Get the NamedDecl through which this reference occurred.
1039 /// See non-const variant.
1040 const NamedDecl *getFoundDecl() const {
1041 return hasFoundDecl() ? getInternalFoundDecl() : D;
1044 bool hasTemplateKWAndArgsInfo() const {
1045 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1048 /// \brief Return the optional template keyword and arguments info.
1049 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1050 if (!hasTemplateKWAndArgsInfo())
1054 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1055 &getInternalFoundDecl() + 1);
1058 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1059 &getInternalQualifierLoc() + 1);
1061 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1064 /// \brief Return the optional template keyword and arguments info.
1065 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1066 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1069 /// \brief Retrieve the location of the template keyword preceding
1070 /// this name, if any.
1071 SourceLocation getTemplateKeywordLoc() const {
1072 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1073 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1076 /// \brief Retrieve the location of the left angle bracket starting the
1077 /// explicit template argument list following the name, if any.
1078 SourceLocation getLAngleLoc() const {
1079 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1080 return getTemplateKWAndArgsInfo()->LAngleLoc;
1083 /// \brief Retrieve the location of the right angle bracket ending the
1084 /// explicit template argument list following the name, if any.
1085 SourceLocation getRAngleLoc() const {
1086 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1087 return getTemplateKWAndArgsInfo()->RAngleLoc;
1090 /// \brief Determines whether the name in this declaration reference
1091 /// was preceded by the template keyword.
1092 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1094 /// \brief Determines whether this declaration reference was followed by an
1095 /// explicit template argument list.
1096 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1098 /// \brief Retrieve the explicit template argument list that followed the
1099 /// member template name.
1100 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1101 assert(hasExplicitTemplateArgs());
1102 return *getTemplateKWAndArgsInfo();
1105 /// \brief Retrieve the explicit template argument list that followed the
1106 /// member template name.
1107 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1108 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1111 /// \brief Retrieves the optional explicit template arguments.
1112 /// This points to the same data as getExplicitTemplateArgs(), but
1113 /// returns null if there are no explicit template arguments.
1114 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1115 if (!hasExplicitTemplateArgs()) return nullptr;
1116 return &getExplicitTemplateArgs();
1119 /// \brief Copies the template arguments (if present) into the given
1121 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1122 if (hasExplicitTemplateArgs())
1123 getExplicitTemplateArgs().copyInto(List);
1126 /// \brief Retrieve the template arguments provided as part of this
1128 const TemplateArgumentLoc *getTemplateArgs() const {
1129 if (!hasExplicitTemplateArgs())
1132 return getExplicitTemplateArgs().getTemplateArgs();
1135 /// \brief Retrieve the number of template arguments provided as part of this
1137 unsigned getNumTemplateArgs() const {
1138 if (!hasExplicitTemplateArgs())
1141 return getExplicitTemplateArgs().NumTemplateArgs;
1144 /// \brief Returns true if this expression refers to a function that
1145 /// was resolved from an overloaded set having size greater than 1.
1146 bool hadMultipleCandidates() const {
1147 return DeclRefExprBits.HadMultipleCandidates;
1149 /// \brief Sets the flag telling whether this expression refers to
1150 /// a function that was resolved from an overloaded set having size
1152 void setHadMultipleCandidates(bool V = true) {
1153 DeclRefExprBits.HadMultipleCandidates = V;
1156 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1158 bool refersToEnclosingVariableOrCapture() const {
1159 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1162 static bool classof(const Stmt *T) {
1163 return T->getStmtClass() == DeclRefExprClass;
1167 child_range children() { return child_range(); }
1169 friend class ASTStmtReader;
1170 friend class ASTStmtWriter;
1173 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1174 class PredefinedExpr : public Expr {
1179 LFunction, // Same as Function, but as wide string.
1183 /// \brief The same as PrettyFunction, except that the
1184 /// 'virtual' keyword is omitted for virtual member functions.
1185 PrettyFunctionNoVirtual
1194 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1197 /// \brief Construct an empty predefined expression.
1198 explicit PredefinedExpr(EmptyShell Empty)
1199 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1201 IdentType getIdentType() const { return Type; }
1203 SourceLocation getLocation() const { return Loc; }
1204 void setLocation(SourceLocation L) { Loc = L; }
1206 StringLiteral *getFunctionName();
1207 const StringLiteral *getFunctionName() const {
1208 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1211 static StringRef getIdentTypeName(IdentType IT);
1212 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1214 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1215 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1217 static bool classof(const Stmt *T) {
1218 return T->getStmtClass() == PredefinedExprClass;
1222 child_range children() { return child_range(&FnName, &FnName + 1); }
1224 friend class ASTStmtReader;
1227 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1230 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1231 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1232 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1233 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1234 /// ASTContext's allocator for memory allocation.
1235 class APNumericStorage {
1237 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1238 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1242 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1244 APNumericStorage(const APNumericStorage &) = delete;
1245 void operator=(const APNumericStorage &) = delete;
1248 APNumericStorage() : VAL(0), BitWidth(0) { }
1250 llvm::APInt getIntValue() const {
1251 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1253 return llvm::APInt(BitWidth, NumWords, pVal);
1255 return llvm::APInt(BitWidth, VAL);
1257 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1260 class APIntStorage : private APNumericStorage {
1262 llvm::APInt getValue() const { return getIntValue(); }
1263 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1264 setIntValue(C, Val);
1268 class APFloatStorage : private APNumericStorage {
1270 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1271 return llvm::APFloat(Semantics, getIntValue());
1273 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1274 setIntValue(C, Val.bitcastToAPInt());
1278 class IntegerLiteral : public Expr, public APIntStorage {
1281 /// \brief Construct an empty integer literal.
1282 explicit IntegerLiteral(EmptyShell Empty)
1283 : Expr(IntegerLiteralClass, Empty) { }
1286 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1287 // or UnsignedLongLongTy
1288 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1291 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1292 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1293 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1294 /// \param V - the value that the returned integer literal contains.
1295 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1296 QualType type, SourceLocation l);
1297 /// \brief Returns a new empty integer literal.
1298 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1300 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1301 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1303 /// \brief Retrieve the location of the literal.
1304 SourceLocation getLocation() const { return Loc; }
1306 void setLocation(SourceLocation Location) { Loc = Location; }
1308 static bool classof(const Stmt *T) {
1309 return T->getStmtClass() == IntegerLiteralClass;
1313 child_range children() { return child_range(); }
1316 class CharacterLiteral : public Expr {
1318 enum CharacterKind {
1329 // type should be IntTy
1330 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1332 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1334 Value(value), Loc(l) {
1335 CharacterLiteralBits.Kind = kind;
1338 /// \brief Construct an empty character literal.
1339 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1341 SourceLocation getLocation() const { return Loc; }
1342 CharacterKind getKind() const {
1343 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1346 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1347 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1349 unsigned getValue() const { return Value; }
1351 void setLocation(SourceLocation Location) { Loc = Location; }
1352 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1353 void setValue(unsigned Val) { Value = Val; }
1355 static bool classof(const Stmt *T) {
1356 return T->getStmtClass() == CharacterLiteralClass;
1360 child_range children() { return child_range(); }
1363 class FloatingLiteral : public Expr, private APFloatStorage {
1366 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1367 QualType Type, SourceLocation L);
1369 /// \brief Construct an empty floating-point literal.
1370 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1373 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1374 bool isexact, QualType Type, SourceLocation L);
1375 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1377 llvm::APFloat getValue() const {
1378 return APFloatStorage::getValue(getSemantics());
1380 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1381 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1382 APFloatStorage::setValue(C, Val);
1385 /// Get a raw enumeration value representing the floating-point semantics of
1386 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1387 APFloatSemantics getRawSemantics() const {
1388 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1391 /// Set the raw enumeration value representing the floating-point semantics of
1392 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1393 void setRawSemantics(APFloatSemantics Sem) {
1394 FloatingLiteralBits.Semantics = Sem;
1397 /// Return the APFloat semantics this literal uses.
1398 const llvm::fltSemantics &getSemantics() const;
1400 /// Set the APFloat semantics this literal uses.
1401 void setSemantics(const llvm::fltSemantics &Sem);
1403 bool isExact() const { return FloatingLiteralBits.IsExact; }
1404 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1406 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1407 /// double. Note that this may cause loss of precision, but is useful for
1408 /// debugging dumps, etc.
1409 double getValueAsApproximateDouble() const;
1411 SourceLocation getLocation() const { return Loc; }
1412 void setLocation(SourceLocation L) { Loc = L; }
1414 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1415 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1417 static bool classof(const Stmt *T) {
1418 return T->getStmtClass() == FloatingLiteralClass;
1422 child_range children() { return child_range(); }
1425 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1426 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1427 /// IntegerLiteral classes. Instances of this class always have a Complex type
1428 /// whose element type matches the subexpression.
1430 class ImaginaryLiteral : public Expr {
1433 ImaginaryLiteral(Expr *val, QualType Ty)
1434 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1438 /// \brief Build an empty imaginary literal.
1439 explicit ImaginaryLiteral(EmptyShell Empty)
1440 : Expr(ImaginaryLiteralClass, Empty) { }
1442 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1443 Expr *getSubExpr() { return cast<Expr>(Val); }
1444 void setSubExpr(Expr *E) { Val = E; }
1446 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1447 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1449 static bool classof(const Stmt *T) {
1450 return T->getStmtClass() == ImaginaryLiteralClass;
1454 child_range children() { return child_range(&Val, &Val+1); }
1457 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1458 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1459 /// is NOT null-terminated, and the length of the string is determined by
1460 /// calling getByteLength(). The C type for a string is always a
1461 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1464 /// Note that strings in C can be formed by concatenation of multiple string
1465 /// literal pptokens in translation phase #6. This keeps track of the locations
1466 /// of each of these pieces.
1468 /// Strings in C can also be truncated and extended by assigning into arrays,
1469 /// e.g. with constructs like:
1470 /// char X[2] = "foobar";
1471 /// In this case, getByteLength() will return 6, but the string literal will
1472 /// have type "char[2]".
1473 class StringLiteral : public Expr {
1484 friend class ASTStmtReader;
1488 const uint16_t *asUInt16;
1489 const uint32_t *asUInt32;
1492 unsigned CharByteWidth : 4;
1494 unsigned IsPascal : 1;
1495 unsigned NumConcatenated;
1496 SourceLocation TokLocs[1];
1498 StringLiteral(QualType Ty) :
1499 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1502 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1505 /// This is the "fully general" constructor that allows representation of
1506 /// strings formed from multiple concatenated tokens.
1507 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1508 StringKind Kind, bool Pascal, QualType Ty,
1509 const SourceLocation *Loc, unsigned NumStrs);
1511 /// Simple constructor for string literals made from one token.
1512 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1513 StringKind Kind, bool Pascal, QualType Ty,
1514 SourceLocation Loc) {
1515 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1518 /// \brief Construct an empty string literal.
1519 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1521 StringRef getString() const {
1522 assert(CharByteWidth==1
1523 && "This function is used in places that assume strings use char");
1524 return StringRef(StrData.asChar, getByteLength());
1527 /// Allow access to clients that need the byte representation, such as
1528 /// ASTWriterStmt::VisitStringLiteral().
1529 StringRef getBytes() const {
1530 // FIXME: StringRef may not be the right type to use as a result for this.
1531 if (CharByteWidth == 1)
1532 return StringRef(StrData.asChar, getByteLength());
1533 if (CharByteWidth == 4)
1534 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1536 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1537 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1541 void outputString(raw_ostream &OS) const;
1543 uint32_t getCodeUnit(size_t i) const {
1544 assert(i < Length && "out of bounds access");
1545 if (CharByteWidth == 1)
1546 return static_cast<unsigned char>(StrData.asChar[i]);
1547 if (CharByteWidth == 4)
1548 return StrData.asUInt32[i];
1549 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1550 return StrData.asUInt16[i];
1553 unsigned getByteLength() const { return CharByteWidth*Length; }
1554 unsigned getLength() const { return Length; }
1555 unsigned getCharByteWidth() const { return CharByteWidth; }
1557 /// \brief Sets the string data to the given string data.
1558 void setString(const ASTContext &C, StringRef Str,
1559 StringKind Kind, bool IsPascal);
1561 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1564 bool isAscii() const { return Kind == Ascii; }
1565 bool isWide() const { return Kind == Wide; }
1566 bool isUTF8() const { return Kind == UTF8; }
1567 bool isUTF16() const { return Kind == UTF16; }
1568 bool isUTF32() const { return Kind == UTF32; }
1569 bool isPascal() const { return IsPascal; }
1571 bool containsNonAsciiOrNull() const {
1572 StringRef Str = getString();
1573 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1574 if (!isASCII(Str[i]) || !Str[i])
1579 /// getNumConcatenated - Get the number of string literal tokens that were
1580 /// concatenated in translation phase #6 to form this string literal.
1581 unsigned getNumConcatenated() const { return NumConcatenated; }
1583 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1584 assert(TokNum < NumConcatenated && "Invalid tok number");
1585 return TokLocs[TokNum];
1587 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1588 assert(TokNum < NumConcatenated && "Invalid tok number");
1589 TokLocs[TokNum] = L;
1592 /// getLocationOfByte - Return a source location that points to the specified
1593 /// byte of this string literal.
1595 /// Strings are amazingly complex. They can be formed from multiple tokens
1596 /// and can have escape sequences in them in addition to the usual trigraph
1597 /// and escaped newline business. This routine handles this complexity.
1599 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1600 const LangOptions &Features,
1601 const TargetInfo &Target) const;
1603 typedef const SourceLocation *tokloc_iterator;
1604 tokloc_iterator tokloc_begin() const { return TokLocs; }
1605 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1607 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1608 SourceLocation getLocEnd() const LLVM_READONLY {
1609 return TokLocs[NumConcatenated - 1];
1612 static bool classof(const Stmt *T) {
1613 return T->getStmtClass() == StringLiteralClass;
1617 child_range children() { return child_range(); }
1620 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1621 /// AST node is only formed if full location information is requested.
1622 class ParenExpr : public Expr {
1623 SourceLocation L, R;
1626 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1627 : Expr(ParenExprClass, val->getType(),
1628 val->getValueKind(), val->getObjectKind(),
1629 val->isTypeDependent(), val->isValueDependent(),
1630 val->isInstantiationDependent(),
1631 val->containsUnexpandedParameterPack()),
1632 L(l), R(r), Val(val) {}
1634 /// \brief Construct an empty parenthesized expression.
1635 explicit ParenExpr(EmptyShell Empty)
1636 : Expr(ParenExprClass, Empty) { }
1638 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1639 Expr *getSubExpr() { return cast<Expr>(Val); }
1640 void setSubExpr(Expr *E) { Val = E; }
1642 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1643 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1645 /// \brief Get the location of the left parentheses '('.
1646 SourceLocation getLParen() const { return L; }
1647 void setLParen(SourceLocation Loc) { L = Loc; }
1649 /// \brief Get the location of the right parentheses ')'.
1650 SourceLocation getRParen() const { return R; }
1651 void setRParen(SourceLocation Loc) { R = Loc; }
1653 static bool classof(const Stmt *T) {
1654 return T->getStmtClass() == ParenExprClass;
1658 child_range children() { return child_range(&Val, &Val+1); }
1662 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1663 /// alignof), the postinc/postdec operators from postfix-expression, and various
1666 /// Notes on various nodes:
1668 /// Real/Imag - These return the real/imag part of a complex operand. If
1669 /// applied to a non-complex value, the former returns its operand and the
1670 /// later returns zero in the type of the operand.
1672 class UnaryOperator : public Expr {
1674 typedef UnaryOperatorKind Opcode;
1682 UnaryOperator(Expr *input, Opcode opc, QualType type,
1683 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1684 : Expr(UnaryOperatorClass, type, VK, OK,
1685 input->isTypeDependent() || type->isDependentType(),
1686 input->isValueDependent(),
1687 (input->isInstantiationDependent() ||
1688 type->isInstantiationDependentType()),
1689 input->containsUnexpandedParameterPack()),
1690 Opc(opc), Loc(l), Val(input) {}
1692 /// \brief Build an empty unary operator.
1693 explicit UnaryOperator(EmptyShell Empty)
1694 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1696 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1697 void setOpcode(Opcode O) { Opc = O; }
1699 Expr *getSubExpr() const { return cast<Expr>(Val); }
1700 void setSubExpr(Expr *E) { Val = E; }
1702 /// getOperatorLoc - Return the location of the operator.
1703 SourceLocation getOperatorLoc() const { return Loc; }
1704 void setOperatorLoc(SourceLocation L) { Loc = L; }
1706 /// isPostfix - Return true if this is a postfix operation, like x++.
1707 static bool isPostfix(Opcode Op) {
1708 return Op == UO_PostInc || Op == UO_PostDec;
1711 /// isPrefix - Return true if this is a prefix operation, like --x.
1712 static bool isPrefix(Opcode Op) {
1713 return Op == UO_PreInc || Op == UO_PreDec;
1716 bool isPrefix() const { return isPrefix(getOpcode()); }
1717 bool isPostfix() const { return isPostfix(getOpcode()); }
1719 static bool isIncrementOp(Opcode Op) {
1720 return Op == UO_PreInc || Op == UO_PostInc;
1722 bool isIncrementOp() const {
1723 return isIncrementOp(getOpcode());
1726 static bool isDecrementOp(Opcode Op) {
1727 return Op == UO_PreDec || Op == UO_PostDec;
1729 bool isDecrementOp() const {
1730 return isDecrementOp(getOpcode());
1733 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1734 bool isIncrementDecrementOp() const {
1735 return isIncrementDecrementOp(getOpcode());
1738 static bool isArithmeticOp(Opcode Op) {
1739 return Op >= UO_Plus && Op <= UO_LNot;
1741 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1743 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1744 /// corresponds to, e.g. "sizeof" or "[pre]++"
1745 static StringRef getOpcodeStr(Opcode Op);
1747 /// \brief Retrieve the unary opcode that corresponds to the given
1748 /// overloaded operator.
1749 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1751 /// \brief Retrieve the overloaded operator kind that corresponds to
1752 /// the given unary opcode.
1753 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1755 SourceLocation getLocStart() const LLVM_READONLY {
1756 return isPostfix() ? Val->getLocStart() : Loc;
1758 SourceLocation getLocEnd() const LLVM_READONLY {
1759 return isPostfix() ? Loc : Val->getLocEnd();
1761 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1763 static bool classof(const Stmt *T) {
1764 return T->getStmtClass() == UnaryOperatorClass;
1768 child_range children() { return child_range(&Val, &Val+1); }
1771 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1772 /// offsetof(record-type, member-designator). For example, given:
1783 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1785 class OffsetOfExpr : public Expr {
1787 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1788 class OffsetOfNode {
1790 /// \brief The kind of offsetof node we have.
1792 /// \brief An index into an array.
1796 /// \brief A field in a dependent type, known only by its name.
1798 /// \brief An implicit indirection through a C++ base class, when the
1799 /// field found is in a base class.
1804 enum { MaskBits = 2, Mask = 0x03 };
1806 /// \brief The source range that covers this part of the designator.
1809 /// \brief The data describing the designator, which comes in three
1810 /// different forms, depending on the lower two bits.
1811 /// - An unsigned index into the array of Expr*'s stored after this node
1812 /// in memory, for [constant-expression] designators.
1813 /// - A FieldDecl*, for references to a known field.
1814 /// - An IdentifierInfo*, for references to a field with a given name
1815 /// when the class type is dependent.
1816 /// - A CXXBaseSpecifier*, for references that look at a field in a
1821 /// \brief Create an offsetof node that refers to an array element.
1822 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1823 SourceLocation RBracketLoc)
1824 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1826 /// \brief Create an offsetof node that refers to a field.
1827 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1828 SourceLocation NameLoc)
1829 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1830 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1832 /// \brief Create an offsetof node that refers to an identifier.
1833 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1834 SourceLocation NameLoc)
1835 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1836 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1838 /// \brief Create an offsetof node that refers into a C++ base class.
1839 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1840 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1842 /// \brief Determine what kind of offsetof node this is.
1843 Kind getKind() const {
1844 return static_cast<Kind>(Data & Mask);
1847 /// \brief For an array element node, returns the index into the array
1849 unsigned getArrayExprIndex() const {
1850 assert(getKind() == Array);
1854 /// \brief For a field offsetof node, returns the field.
1855 FieldDecl *getField() const {
1856 assert(getKind() == Field);
1857 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1860 /// \brief For a field or identifier offsetof node, returns the name of
1862 IdentifierInfo *getFieldName() const;
1864 /// \brief For a base class node, returns the base specifier.
1865 CXXBaseSpecifier *getBase() const {
1866 assert(getKind() == Base);
1867 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1870 /// \brief Retrieve the source range that covers this offsetof node.
1872 /// For an array element node, the source range contains the locations of
1873 /// the square brackets. For a field or identifier node, the source range
1874 /// contains the location of the period (if there is one) and the
1876 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1877 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1878 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1883 SourceLocation OperatorLoc, RParenLoc;
1885 TypeSourceInfo *TSInfo;
1886 // Number of sub-components (i.e. instances of OffsetOfNode).
1888 // Number of sub-expressions (i.e. array subscript expressions).
1891 OffsetOfExpr(const ASTContext &C, QualType type,
1892 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1893 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1894 SourceLocation RParenLoc);
1896 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1897 : Expr(OffsetOfExprClass, EmptyShell()),
1898 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1902 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1903 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1904 ArrayRef<OffsetOfNode> comps,
1905 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1907 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1908 unsigned NumComps, unsigned NumExprs);
1910 /// getOperatorLoc - Return the location of the operator.
1911 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1912 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1914 /// \brief Return the location of the right parentheses.
1915 SourceLocation getRParenLoc() const { return RParenLoc; }
1916 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1918 TypeSourceInfo *getTypeSourceInfo() const {
1921 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1925 const OffsetOfNode &getComponent(unsigned Idx) const {
1926 assert(Idx < NumComps && "Subscript out of range");
1927 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1930 void setComponent(unsigned Idx, OffsetOfNode ON) {
1931 assert(Idx < NumComps && "Subscript out of range");
1932 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1935 unsigned getNumComponents() const {
1939 Expr* getIndexExpr(unsigned Idx) {
1940 assert(Idx < NumExprs && "Subscript out of range");
1941 return reinterpret_cast<Expr **>(
1942 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1944 const Expr *getIndexExpr(unsigned Idx) const {
1945 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1948 void setIndexExpr(unsigned Idx, Expr* E) {
1949 assert(Idx < NumComps && "Subscript out of range");
1950 reinterpret_cast<Expr **>(
1951 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1954 unsigned getNumExpressions() const {
1958 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1959 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1961 static bool classof(const Stmt *T) {
1962 return T->getStmtClass() == OffsetOfExprClass;
1966 child_range children() {
1968 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1970 return child_range(begin, begin + NumExprs);
1974 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1975 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1976 /// vec_step (OpenCL 1.1 6.11.12).
1977 class UnaryExprOrTypeTraitExpr : public Expr {
1982 SourceLocation OpLoc, RParenLoc;
1985 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1986 QualType resultType, SourceLocation op,
1987 SourceLocation rp) :
1988 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1989 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1990 // Value-dependent if the argument is type-dependent.
1991 TInfo->getType()->isDependentType(),
1992 TInfo->getType()->isInstantiationDependentType(),
1993 TInfo->getType()->containsUnexpandedParameterPack()),
1994 OpLoc(op), RParenLoc(rp) {
1995 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1996 UnaryExprOrTypeTraitExprBits.IsType = true;
1997 Argument.Ty = TInfo;
2000 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2001 QualType resultType, SourceLocation op,
2004 /// \brief Construct an empty sizeof/alignof expression.
2005 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2006 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2008 UnaryExprOrTypeTrait getKind() const {
2009 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2011 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2013 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2014 QualType getArgumentType() const {
2015 return getArgumentTypeInfo()->getType();
2017 TypeSourceInfo *getArgumentTypeInfo() const {
2018 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2021 Expr *getArgumentExpr() {
2022 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2023 return static_cast<Expr*>(Argument.Ex);
2025 const Expr *getArgumentExpr() const {
2026 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2029 void setArgument(Expr *E) {
2031 UnaryExprOrTypeTraitExprBits.IsType = false;
2033 void setArgument(TypeSourceInfo *TInfo) {
2034 Argument.Ty = TInfo;
2035 UnaryExprOrTypeTraitExprBits.IsType = true;
2038 /// Gets the argument type, or the type of the argument expression, whichever
2040 QualType getTypeOfArgument() const {
2041 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2044 SourceLocation getOperatorLoc() const { return OpLoc; }
2045 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2047 SourceLocation getRParenLoc() const { return RParenLoc; }
2048 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2050 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2051 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2053 static bool classof(const Stmt *T) {
2054 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2058 child_range children();
2061 //===----------------------------------------------------------------------===//
2062 // Postfix Operators.
2063 //===----------------------------------------------------------------------===//
2065 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2066 class ArraySubscriptExpr : public Expr {
2067 enum { LHS, RHS, END_EXPR=2 };
2068 Stmt* SubExprs[END_EXPR];
2069 SourceLocation RBracketLoc;
2071 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2072 ExprValueKind VK, ExprObjectKind OK,
2073 SourceLocation rbracketloc)
2074 : Expr(ArraySubscriptExprClass, t, VK, OK,
2075 lhs->isTypeDependent() || rhs->isTypeDependent(),
2076 lhs->isValueDependent() || rhs->isValueDependent(),
2077 (lhs->isInstantiationDependent() ||
2078 rhs->isInstantiationDependent()),
2079 (lhs->containsUnexpandedParameterPack() ||
2080 rhs->containsUnexpandedParameterPack())),
2081 RBracketLoc(rbracketloc) {
2082 SubExprs[LHS] = lhs;
2083 SubExprs[RHS] = rhs;
2086 /// \brief Create an empty array subscript expression.
2087 explicit ArraySubscriptExpr(EmptyShell Shell)
2088 : Expr(ArraySubscriptExprClass, Shell) { }
2090 /// An array access can be written A[4] or 4[A] (both are equivalent).
2091 /// - getBase() and getIdx() always present the normalized view: A[4].
2092 /// In this case getBase() returns "A" and getIdx() returns "4".
2093 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2094 /// 4[A] getLHS() returns "4".
2095 /// Note: Because vector element access is also written A[4] we must
2096 /// predicate the format conversion in getBase and getIdx only on the
2097 /// the type of the RHS, as it is possible for the LHS to be a vector of
2099 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2100 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2101 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2103 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2104 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2105 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2108 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2111 const Expr *getBase() const {
2112 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2116 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2119 const Expr *getIdx() const {
2120 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2123 SourceLocation getLocStart() const LLVM_READONLY {
2124 return getLHS()->getLocStart();
2126 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2128 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2129 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2131 SourceLocation getExprLoc() const LLVM_READONLY {
2132 return getBase()->getExprLoc();
2135 static bool classof(const Stmt *T) {
2136 return T->getStmtClass() == ArraySubscriptExprClass;
2140 child_range children() {
2141 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2146 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2147 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2148 /// while its subclasses may represent alternative syntax that (semantically)
2149 /// results in a function call. For example, CXXOperatorCallExpr is
2150 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2151 /// "str1 + str2" to resolve to a function call.
2152 class CallExpr : public Expr {
2153 enum { FN=0, PREARGS_START=1 };
2156 SourceLocation RParenLoc;
2159 // These versions of the constructor are for derived classes.
2160 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2161 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2162 SourceLocation rparenloc);
2163 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2166 Stmt *getPreArg(unsigned i) {
2167 assert(i < getNumPreArgs() && "Prearg access out of range!");
2168 return SubExprs[PREARGS_START+i];
2170 const Stmt *getPreArg(unsigned i) const {
2171 assert(i < getNumPreArgs() && "Prearg access out of range!");
2172 return SubExprs[PREARGS_START+i];
2174 void setPreArg(unsigned i, Stmt *PreArg) {
2175 assert(i < getNumPreArgs() && "Prearg access out of range!");
2176 SubExprs[PREARGS_START+i] = PreArg;
2179 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2182 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2183 ExprValueKind VK, SourceLocation rparenloc);
2185 /// \brief Build an empty call expression.
2186 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2188 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2189 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2190 void setCallee(Expr *F) { SubExprs[FN] = F; }
2192 Decl *getCalleeDecl();
2193 const Decl *getCalleeDecl() const {
2194 return const_cast<CallExpr*>(this)->getCalleeDecl();
2197 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2198 FunctionDecl *getDirectCallee();
2199 const FunctionDecl *getDirectCallee() const {
2200 return const_cast<CallExpr*>(this)->getDirectCallee();
2203 /// getNumArgs - Return the number of actual arguments to this call.
2205 unsigned getNumArgs() const { return NumArgs; }
2207 /// \brief Retrieve the call arguments.
2209 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2211 const Expr *const *getArgs() const {
2212 return const_cast<CallExpr*>(this)->getArgs();
2215 /// getArg - Return the specified argument.
2216 Expr *getArg(unsigned Arg) {
2217 assert(Arg < NumArgs && "Arg access out of range!");
2218 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2220 const Expr *getArg(unsigned Arg) const {
2221 assert(Arg < NumArgs && "Arg access out of range!");
2222 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2225 /// setArg - Set the specified argument.
2226 void setArg(unsigned Arg, Expr *ArgExpr) {
2227 assert(Arg < NumArgs && "Arg access out of range!");
2228 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2231 /// setNumArgs - This changes the number of arguments present in this call.
2232 /// Any orphaned expressions are deleted by this, and any new operands are set
2234 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2236 typedef ExprIterator arg_iterator;
2237 typedef ConstExprIterator const_arg_iterator;
2238 typedef llvm::iterator_range<arg_iterator> arg_range;
2239 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2241 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2242 arg_const_range arguments() const {
2243 return arg_const_range(arg_begin(), arg_end());
2246 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2247 arg_iterator arg_end() {
2248 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2250 const_arg_iterator arg_begin() const {
2251 return SubExprs+PREARGS_START+getNumPreArgs();
2253 const_arg_iterator arg_end() const {
2254 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2257 /// This method provides fast access to all the subexpressions of
2258 /// a CallExpr without going through the slower virtual child_iterator
2259 /// interface. This provides efficient reverse iteration of the
2260 /// subexpressions. This is currently used for CFG construction.
2261 ArrayRef<Stmt*> getRawSubExprs() {
2262 return llvm::makeArrayRef(SubExprs,
2263 getNumPreArgs() + PREARGS_START + getNumArgs());
2266 /// getNumCommas - Return the number of commas that must have been present in
2267 /// this function call.
2268 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2270 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2271 /// of the callee. If not, return 0.
2272 unsigned getBuiltinCallee() const;
2274 /// \brief Returns \c true if this is a call to a builtin which does not
2275 /// evaluate side-effects within its arguments.
2276 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2278 /// getCallReturnType - Get the return type of the call expr. This is not
2279 /// always the type of the expr itself, if the return type is a reference
2281 QualType getCallReturnType(const ASTContext &Ctx) const;
2283 SourceLocation getRParenLoc() const { return RParenLoc; }
2284 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2286 SourceLocation getLocStart() const LLVM_READONLY;
2287 SourceLocation getLocEnd() const LLVM_READONLY;
2289 static bool classof(const Stmt *T) {
2290 return T->getStmtClass() >= firstCallExprConstant &&
2291 T->getStmtClass() <= lastCallExprConstant;
2295 child_range children() {
2296 return child_range(&SubExprs[0],
2297 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2301 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2303 class MemberExpr : public Expr {
2304 /// Extra data stored in some member expressions.
2305 struct MemberNameQualifier {
2306 /// \brief The nested-name-specifier that qualifies the name, including
2307 /// source-location information.
2308 NestedNameSpecifierLoc QualifierLoc;
2310 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2311 /// name qualifiers.
2312 DeclAccessPair FoundDecl;
2315 /// Base - the expression for the base pointer or structure references. In
2316 /// X.F, this is "X".
2319 /// MemberDecl - This is the decl being referenced by the field/member name.
2320 /// In X.F, this is the decl referenced by F.
2321 ValueDecl *MemberDecl;
2323 /// MemberDNLoc - Provides source/type location info for the
2324 /// declaration name embedded in MemberDecl.
2325 DeclarationNameLoc MemberDNLoc;
2327 /// MemberLoc - This is the location of the member name.
2328 SourceLocation MemberLoc;
2330 /// This is the location of the -> or . in the expression.
2331 SourceLocation OperatorLoc;
2333 /// IsArrow - True if this is "X->F", false if this is "X.F".
2336 /// \brief True if this member expression used a nested-name-specifier to
2337 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2338 /// declaration. When true, a MemberNameQualifier
2339 /// structure is allocated immediately after the MemberExpr.
2340 bool HasQualifierOrFoundDecl : 1;
2342 /// \brief True if this member expression specified a template keyword
2343 /// and/or a template argument list explicitly, e.g., x->f<int>,
2344 /// x->template f, x->template f<int>.
2345 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2346 /// TemplateArguments (if any) are allocated immediately after
2347 /// the MemberExpr or, if the member expression also has a qualifier,
2348 /// after the MemberNameQualifier structure.
2349 bool HasTemplateKWAndArgsInfo : 1;
2351 /// \brief True if this member expression refers to a method that
2352 /// was resolved from an overloaded set having size greater than 1.
2353 bool HadMultipleCandidates : 1;
2355 /// \brief Retrieve the qualifier that preceded the member name, if any.
2356 MemberNameQualifier *getMemberQualifier() {
2357 assert(HasQualifierOrFoundDecl);
2358 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2361 /// \brief Retrieve the qualifier that preceded the member name, if any.
2362 const MemberNameQualifier *getMemberQualifier() const {
2363 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2367 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2368 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2369 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2370 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2371 base->isValueDependent(), base->isInstantiationDependent(),
2372 base->containsUnexpandedParameterPack()),
2373 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2374 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2375 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2376 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2377 assert(memberdecl->getDeclName() == NameInfo.getName());
2380 // NOTE: this constructor should be used only when it is known that
2381 // the member name can not provide additional syntactic info
2382 // (i.e., source locations for C++ operator names or type source info
2383 // for constructors, destructors and conversion operators).
2384 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2385 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2386 ExprValueKind VK, ExprObjectKind OK)
2387 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2388 base->isValueDependent(), base->isInstantiationDependent(),
2389 base->containsUnexpandedParameterPack()),
2390 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2391 OperatorLoc(operatorloc), IsArrow(isarrow),
2392 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2393 HadMultipleCandidates(false) {}
2395 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2396 SourceLocation OperatorLoc,
2397 NestedNameSpecifierLoc QualifierLoc,
2398 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2399 DeclAccessPair founddecl,
2400 DeclarationNameInfo MemberNameInfo,
2401 const TemplateArgumentListInfo *targs, QualType ty,
2402 ExprValueKind VK, ExprObjectKind OK);
2404 void setBase(Expr *E) { Base = E; }
2405 Expr *getBase() const { return cast<Expr>(Base); }
2407 /// \brief Retrieve the member declaration to which this expression refers.
2409 /// The returned declaration will either be a FieldDecl or (in C++)
2410 /// a CXXMethodDecl.
2411 ValueDecl *getMemberDecl() const { return MemberDecl; }
2412 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2414 /// \brief Retrieves the declaration found by lookup.
2415 DeclAccessPair getFoundDecl() const {
2416 if (!HasQualifierOrFoundDecl)
2417 return DeclAccessPair::make(getMemberDecl(),
2418 getMemberDecl()->getAccess());
2419 return getMemberQualifier()->FoundDecl;
2422 /// \brief Determines whether this member expression actually had
2423 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2425 bool hasQualifier() const { return getQualifier() != nullptr; }
2427 /// \brief If the member name was qualified, retrieves the
2428 /// nested-name-specifier that precedes the member name. Otherwise, returns
2430 NestedNameSpecifier *getQualifier() const {
2431 if (!HasQualifierOrFoundDecl)
2434 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2437 /// \brief If the member name was qualified, retrieves the
2438 /// nested-name-specifier that precedes the member name, with source-location
2440 NestedNameSpecifierLoc getQualifierLoc() const {
2441 if (!hasQualifier())
2442 return NestedNameSpecifierLoc();
2444 return getMemberQualifier()->QualifierLoc;
2447 /// \brief Return the optional template keyword and arguments info.
2448 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2449 if (!HasTemplateKWAndArgsInfo)
2452 if (!HasQualifierOrFoundDecl)
2453 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2455 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2456 getMemberQualifier() + 1);
2459 /// \brief Return the optional template keyword and arguments info.
2460 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2461 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2464 /// \brief Retrieve the location of the template keyword preceding
2465 /// the member name, if any.
2466 SourceLocation getTemplateKeywordLoc() const {
2467 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2468 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2471 /// \brief Retrieve the location of the left angle bracket starting the
2472 /// explicit template argument list following the member name, if any.
2473 SourceLocation getLAngleLoc() const {
2474 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2475 return getTemplateKWAndArgsInfo()->LAngleLoc;
2478 /// \brief Retrieve the location of the right angle bracket ending the
2479 /// explicit template argument list following the member name, if any.
2480 SourceLocation getRAngleLoc() const {
2481 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2482 return getTemplateKWAndArgsInfo()->RAngleLoc;
2485 /// Determines whether the member name was preceded by the template keyword.
2486 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2488 /// \brief Determines whether the member name was followed by an
2489 /// explicit template argument list.
2490 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2492 /// \brief Copies the template arguments (if present) into the given
2494 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2495 if (hasExplicitTemplateArgs())
2496 getExplicitTemplateArgs().copyInto(List);
2499 /// \brief Retrieve the explicit template argument list that
2500 /// follow the member template name. This must only be called on an
2501 /// expression with explicit template arguments.
2502 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2503 assert(hasExplicitTemplateArgs());
2504 return *getTemplateKWAndArgsInfo();
2507 /// \brief Retrieve the explicit template argument list that
2508 /// followed the member template name. This must only be called on
2509 /// an expression with explicit template arguments.
2510 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2511 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2514 /// \brief Retrieves the optional explicit template arguments.
2515 /// This points to the same data as getExplicitTemplateArgs(), but
2516 /// returns null if there are no explicit template arguments.
2517 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2518 if (!hasExplicitTemplateArgs()) return nullptr;
2519 return &getExplicitTemplateArgs();
2522 /// \brief Retrieve the template arguments provided as part of this
2524 const TemplateArgumentLoc *getTemplateArgs() const {
2525 if (!hasExplicitTemplateArgs())
2528 return getExplicitTemplateArgs().getTemplateArgs();
2531 /// \brief Retrieve the number of template arguments provided as part of this
2533 unsigned getNumTemplateArgs() const {
2534 if (!hasExplicitTemplateArgs())
2537 return getExplicitTemplateArgs().NumTemplateArgs;
2540 /// \brief Retrieve the member declaration name info.
2541 DeclarationNameInfo getMemberNameInfo() const {
2542 return DeclarationNameInfo(MemberDecl->getDeclName(),
2543 MemberLoc, MemberDNLoc);
2546 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2548 bool isArrow() const { return IsArrow; }
2549 void setArrow(bool A) { IsArrow = A; }
2551 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2552 /// location of 'F'.
2553 SourceLocation getMemberLoc() const { return MemberLoc; }
2554 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2556 SourceLocation getLocStart() const LLVM_READONLY;
2557 SourceLocation getLocEnd() const LLVM_READONLY;
2559 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2561 /// \brief Determine whether the base of this explicit is implicit.
2562 bool isImplicitAccess() const {
2563 return getBase() && getBase()->isImplicitCXXThis();
2566 /// \brief Returns true if this member expression refers to a method that
2567 /// was resolved from an overloaded set having size greater than 1.
2568 bool hadMultipleCandidates() const {
2569 return HadMultipleCandidates;
2571 /// \brief Sets the flag telling whether this expression refers to
2572 /// a method that was resolved from an overloaded set having size
2574 void setHadMultipleCandidates(bool V = true) {
2575 HadMultipleCandidates = V;
2578 static bool classof(const Stmt *T) {
2579 return T->getStmtClass() == MemberExprClass;
2583 child_range children() { return child_range(&Base, &Base+1); }
2585 friend class ASTReader;
2586 friend class ASTStmtWriter;
2589 /// CompoundLiteralExpr - [C99 6.5.2.5]
2591 class CompoundLiteralExpr : public Expr {
2592 /// LParenLoc - If non-null, this is the location of the left paren in a
2593 /// compound literal like "(int){4}". This can be null if this is a
2594 /// synthesized compound expression.
2595 SourceLocation LParenLoc;
2597 /// The type as written. This can be an incomplete array type, in
2598 /// which case the actual expression type will be different.
2599 /// The int part of the pair stores whether this expr is file scope.
2600 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2603 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2604 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2605 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2606 tinfo->getType()->isDependentType(),
2607 init->isValueDependent(),
2608 (init->isInstantiationDependent() ||
2609 tinfo->getType()->isInstantiationDependentType()),
2610 init->containsUnexpandedParameterPack()),
2611 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2613 /// \brief Construct an empty compound literal.
2614 explicit CompoundLiteralExpr(EmptyShell Empty)
2615 : Expr(CompoundLiteralExprClass, Empty) { }
2617 const Expr *getInitializer() const { return cast<Expr>(Init); }
2618 Expr *getInitializer() { return cast<Expr>(Init); }
2619 void setInitializer(Expr *E) { Init = E; }
2621 bool isFileScope() const { return TInfoAndScope.getInt(); }
2622 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2624 SourceLocation getLParenLoc() const { return LParenLoc; }
2625 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2627 TypeSourceInfo *getTypeSourceInfo() const {
2628 return TInfoAndScope.getPointer();
2630 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2631 TInfoAndScope.setPointer(tinfo);
2634 SourceLocation getLocStart() const LLVM_READONLY {
2635 // FIXME: Init should never be null.
2637 return SourceLocation();
2638 if (LParenLoc.isInvalid())
2639 return Init->getLocStart();
2642 SourceLocation getLocEnd() const LLVM_READONLY {
2643 // FIXME: Init should never be null.
2645 return SourceLocation();
2646 return Init->getLocEnd();
2649 static bool classof(const Stmt *T) {
2650 return T->getStmtClass() == CompoundLiteralExprClass;
2654 child_range children() { return child_range(&Init, &Init+1); }
2657 /// CastExpr - Base class for type casts, including both implicit
2658 /// casts (ImplicitCastExpr) and explicit casts that have some
2659 /// representation in the source code (ExplicitCastExpr's derived
2661 class CastExpr : public Expr {
2665 bool CastConsistency() const;
2667 const CXXBaseSpecifier * const *path_buffer() const {
2668 return const_cast<CastExpr*>(this)->path_buffer();
2670 CXXBaseSpecifier **path_buffer();
2672 void setBasePathSize(unsigned basePathSize) {
2673 CastExprBits.BasePathSize = basePathSize;
2674 assert(CastExprBits.BasePathSize == basePathSize &&
2675 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2679 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2680 Expr *op, unsigned BasePathSize)
2681 : Expr(SC, ty, VK, OK_Ordinary,
2682 // Cast expressions are type-dependent if the type is
2683 // dependent (C++ [temp.dep.expr]p3).
2684 ty->isDependentType(),
2685 // Cast expressions are value-dependent if the type is
2686 // dependent or if the subexpression is value-dependent.
2687 ty->isDependentType() || (op && op->isValueDependent()),
2688 (ty->isInstantiationDependentType() ||
2689 (op && op->isInstantiationDependent())),
2690 // An implicit cast expression doesn't (lexically) contain an
2691 // unexpanded pack, even if its target type does.
2692 ((SC != ImplicitCastExprClass &&
2693 ty->containsUnexpandedParameterPack()) ||
2694 (op && op->containsUnexpandedParameterPack()))),
2696 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2697 CastExprBits.Kind = kind;
2698 setBasePathSize(BasePathSize);
2699 assert(CastConsistency());
2702 /// \brief Construct an empty cast.
2703 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2705 setBasePathSize(BasePathSize);
2709 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2710 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2711 const char *getCastKindName() const;
2713 Expr *getSubExpr() { return cast<Expr>(Op); }
2714 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2715 void setSubExpr(Expr *E) { Op = E; }
2717 /// \brief Retrieve the cast subexpression as it was written in the source
2718 /// code, looking through any implicit casts or other intermediate nodes
2719 /// introduced by semantic analysis.
2720 Expr *getSubExprAsWritten();
2721 const Expr *getSubExprAsWritten() const {
2722 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2725 typedef CXXBaseSpecifier **path_iterator;
2726 typedef const CXXBaseSpecifier * const *path_const_iterator;
2727 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2728 unsigned path_size() const { return CastExprBits.BasePathSize; }
2729 path_iterator path_begin() { return path_buffer(); }
2730 path_iterator path_end() { return path_buffer() + path_size(); }
2731 path_const_iterator path_begin() const { return path_buffer(); }
2732 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2734 void setCastPath(const CXXCastPath &Path);
2736 static bool classof(const Stmt *T) {
2737 return T->getStmtClass() >= firstCastExprConstant &&
2738 T->getStmtClass() <= lastCastExprConstant;
2742 child_range children() { return child_range(&Op, &Op+1); }
2745 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2746 /// conversions, which have no direct representation in the original
2747 /// source code. For example: converting T[]->T*, void f()->void
2748 /// (*f)(), float->double, short->int, etc.
2750 /// In C, implicit casts always produce rvalues. However, in C++, an
2751 /// implicit cast whose result is being bound to a reference will be
2752 /// an lvalue or xvalue. For example:
2756 /// class Derived : public Base { };
2757 /// Derived &&ref();
2758 /// void f(Derived d) {
2759 /// Base& b = d; // initializer is an ImplicitCastExpr
2760 /// // to an lvalue of type Base
2761 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2762 /// // to an xvalue of type Base
2765 class ImplicitCastExpr : public CastExpr {
2767 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2768 unsigned BasePathLength, ExprValueKind VK)
2769 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2772 /// \brief Construct an empty implicit cast.
2773 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2774 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2777 enum OnStack_t { OnStack };
2778 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2780 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2783 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2784 CastKind Kind, Expr *Operand,
2785 const CXXCastPath *BasePath,
2788 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2791 SourceLocation getLocStart() const LLVM_READONLY {
2792 return getSubExpr()->getLocStart();
2794 SourceLocation getLocEnd() const LLVM_READONLY {
2795 return getSubExpr()->getLocEnd();
2798 static bool classof(const Stmt *T) {
2799 return T->getStmtClass() == ImplicitCastExprClass;
2803 inline Expr *Expr::IgnoreImpCasts() {
2805 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2806 e = ice->getSubExpr();
2810 /// ExplicitCastExpr - An explicit cast written in the source
2813 /// This class is effectively an abstract class, because it provides
2814 /// the basic representation of an explicitly-written cast without
2815 /// specifying which kind of cast (C cast, functional cast, static
2816 /// cast, etc.) was written; specific derived classes represent the
2817 /// particular style of cast and its location information.
2819 /// Unlike implicit casts, explicit cast nodes have two different
2820 /// types: the type that was written into the source code, and the
2821 /// actual type of the expression as determined by semantic
2822 /// analysis. These types may differ slightly. For example, in C++ one
2823 /// can cast to a reference type, which indicates that the resulting
2824 /// expression will be an lvalue or xvalue. The reference type, however,
2825 /// will not be used as the type of the expression.
2826 class ExplicitCastExpr : public CastExpr {
2827 /// TInfo - Source type info for the (written) type
2828 /// this expression is casting to.
2829 TypeSourceInfo *TInfo;
2832 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2833 CastKind kind, Expr *op, unsigned PathSize,
2834 TypeSourceInfo *writtenTy)
2835 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2837 /// \brief Construct an empty explicit cast.
2838 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2839 : CastExpr(SC, Shell, PathSize) { }
2842 /// getTypeInfoAsWritten - Returns the type source info for the type
2843 /// that this expression is casting to.
2844 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2845 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2847 /// getTypeAsWritten - Returns the type that this expression is
2848 /// casting to, as written in the source code.
2849 QualType getTypeAsWritten() const { return TInfo->getType(); }
2851 static bool classof(const Stmt *T) {
2852 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2853 T->getStmtClass() <= lastExplicitCastExprConstant;
2857 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2858 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2859 /// (Type)expr. For example: @c (int)f.
2860 class CStyleCastExpr : public ExplicitCastExpr {
2861 SourceLocation LPLoc; // the location of the left paren
2862 SourceLocation RPLoc; // the location of the right paren
2864 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2865 unsigned PathSize, TypeSourceInfo *writtenTy,
2866 SourceLocation l, SourceLocation r)
2867 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2868 writtenTy), LPLoc(l), RPLoc(r) {}
2870 /// \brief Construct an empty C-style explicit cast.
2871 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2872 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2875 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2876 ExprValueKind VK, CastKind K,
2877 Expr *Op, const CXXCastPath *BasePath,
2878 TypeSourceInfo *WrittenTy, SourceLocation L,
2881 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2884 SourceLocation getLParenLoc() const { return LPLoc; }
2885 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2887 SourceLocation getRParenLoc() const { return RPLoc; }
2888 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2890 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2891 SourceLocation getLocEnd() const LLVM_READONLY {
2892 return getSubExpr()->getLocEnd();
2895 static bool classof(const Stmt *T) {
2896 return T->getStmtClass() == CStyleCastExprClass;
2900 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2902 /// This expression node kind describes a builtin binary operation,
2903 /// such as "x + y" for integer values "x" and "y". The operands will
2904 /// already have been converted to appropriate types (e.g., by
2905 /// performing promotions or conversions).
2907 /// In C++, where operators may be overloaded, a different kind of
2908 /// expression node (CXXOperatorCallExpr) is used to express the
2909 /// invocation of an overloaded operator with operator syntax. Within
2910 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2911 /// used to store an expression "x + y" depends on the subexpressions
2912 /// for x and y. If neither x or y is type-dependent, and the "+"
2913 /// operator resolves to a built-in operation, BinaryOperator will be
2914 /// used to express the computation (x and y may still be
2915 /// value-dependent). If either x or y is type-dependent, or if the
2916 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2917 /// be used to express the computation.
2918 class BinaryOperator : public Expr {
2920 typedef BinaryOperatorKind Opcode;
2925 // Records the FP_CONTRACT pragma status at the point that this binary
2926 // operator was parsed. This bit is only meaningful for operations on
2927 // floating point types. For all other types it should default to
2929 unsigned FPContractable : 1;
2930 SourceLocation OpLoc;
2932 enum { LHS, RHS, END_EXPR };
2933 Stmt* SubExprs[END_EXPR];
2936 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2937 ExprValueKind VK, ExprObjectKind OK,
2938 SourceLocation opLoc, bool fpContractable)
2939 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2940 lhs->isTypeDependent() || rhs->isTypeDependent(),
2941 lhs->isValueDependent() || rhs->isValueDependent(),
2942 (lhs->isInstantiationDependent() ||
2943 rhs->isInstantiationDependent()),
2944 (lhs->containsUnexpandedParameterPack() ||
2945 rhs->containsUnexpandedParameterPack())),
2946 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2947 SubExprs[LHS] = lhs;
2948 SubExprs[RHS] = rhs;
2949 assert(!isCompoundAssignmentOp() &&
2950 "Use CompoundAssignOperator for compound assignments");
2953 /// \brief Construct an empty binary operator.
2954 explicit BinaryOperator(EmptyShell Empty)
2955 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2957 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2958 SourceLocation getOperatorLoc() const { return OpLoc; }
2959 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2961 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2962 void setOpcode(Opcode O) { Opc = O; }
2964 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2965 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2966 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2967 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2969 SourceLocation getLocStart() const LLVM_READONLY {
2970 return getLHS()->getLocStart();
2972 SourceLocation getLocEnd() const LLVM_READONLY {
2973 return getRHS()->getLocEnd();
2976 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2977 /// corresponds to, e.g. "<<=".
2978 static StringRef getOpcodeStr(Opcode Op);
2980 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2982 /// \brief Retrieve the binary opcode that corresponds to the given
2983 /// overloaded operator.
2984 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2986 /// \brief Retrieve the overloaded operator kind that corresponds to
2987 /// the given binary opcode.
2988 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2990 /// predicates to categorize the respective opcodes.
2991 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2992 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2993 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2994 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2995 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2996 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2998 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2999 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3001 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3002 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3004 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3005 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3007 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3008 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3010 static Opcode negateComparisonOp(Opcode Opc) {
3013 llvm_unreachable("Not a comparsion operator.");
3014 case BO_LT: return BO_GE;
3015 case BO_GT: return BO_LE;
3016 case BO_LE: return BO_GT;
3017 case BO_GE: return BO_LT;
3018 case BO_EQ: return BO_NE;
3019 case BO_NE: return BO_EQ;
3023 static Opcode reverseComparisonOp(Opcode Opc) {
3026 llvm_unreachable("Not a comparsion operator.");
3027 case BO_LT: return BO_GT;
3028 case BO_GT: return BO_LT;
3029 case BO_LE: return BO_GE;
3030 case BO_GE: return BO_LE;
3037 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3038 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3040 static bool isAssignmentOp(Opcode Opc) {
3041 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3043 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3045 static bool isCompoundAssignmentOp(Opcode Opc) {
3046 return Opc > BO_Assign && Opc <= BO_OrAssign;
3048 bool isCompoundAssignmentOp() const {
3049 return isCompoundAssignmentOp(getOpcode());
3051 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3052 assert(isCompoundAssignmentOp(Opc));
3053 if (Opc >= BO_AndAssign)
3054 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3056 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3059 static bool isShiftAssignOp(Opcode Opc) {
3060 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3062 bool isShiftAssignOp() const {
3063 return isShiftAssignOp(getOpcode());
3066 static bool classof(const Stmt *S) {
3067 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3068 S->getStmtClass() <= lastBinaryOperatorConstant;
3072 child_range children() {
3073 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3076 // Set the FP contractability status of this operator. Only meaningful for
3077 // operations on floating point types.
3078 void setFPContractable(bool FPC) { FPContractable = FPC; }
3080 // Get the FP contractability status of this operator. Only meaningful for
3081 // operations on floating point types.
3082 bool isFPContractable() const { return FPContractable; }
3085 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3086 ExprValueKind VK, ExprObjectKind OK,
3087 SourceLocation opLoc, bool fpContractable, bool dead2)
3088 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3089 lhs->isTypeDependent() || rhs->isTypeDependent(),
3090 lhs->isValueDependent() || rhs->isValueDependent(),
3091 (lhs->isInstantiationDependent() ||
3092 rhs->isInstantiationDependent()),
3093 (lhs->containsUnexpandedParameterPack() ||
3094 rhs->containsUnexpandedParameterPack())),
3095 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3096 SubExprs[LHS] = lhs;
3097 SubExprs[RHS] = rhs;
3100 BinaryOperator(StmtClass SC, EmptyShell Empty)
3101 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3104 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3105 /// track of the type the operation is performed in. Due to the semantics of
3106 /// these operators, the operands are promoted, the arithmetic performed, an
3107 /// implicit conversion back to the result type done, then the assignment takes
3108 /// place. This captures the intermediate type which the computation is done
3110 class CompoundAssignOperator : public BinaryOperator {
3111 QualType ComputationLHSType;
3112 QualType ComputationResultType;
3114 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3115 ExprValueKind VK, ExprObjectKind OK,
3116 QualType CompLHSType, QualType CompResultType,
3117 SourceLocation OpLoc, bool fpContractable)
3118 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3120 ComputationLHSType(CompLHSType),
3121 ComputationResultType(CompResultType) {
3122 assert(isCompoundAssignmentOp() &&
3123 "Only should be used for compound assignments");
3126 /// \brief Build an empty compound assignment operator expression.
3127 explicit CompoundAssignOperator(EmptyShell Empty)
3128 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3130 // The two computation types are the type the LHS is converted
3131 // to for the computation and the type of the result; the two are
3132 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3133 QualType getComputationLHSType() const { return ComputationLHSType; }
3134 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3136 QualType getComputationResultType() const { return ComputationResultType; }
3137 void setComputationResultType(QualType T) { ComputationResultType = T; }
3139 static bool classof(const Stmt *S) {
3140 return S->getStmtClass() == CompoundAssignOperatorClass;
3144 /// AbstractConditionalOperator - An abstract base class for
3145 /// ConditionalOperator and BinaryConditionalOperator.
3146 class AbstractConditionalOperator : public Expr {
3147 SourceLocation QuestionLoc, ColonLoc;
3148 friend class ASTStmtReader;
3151 AbstractConditionalOperator(StmtClass SC, QualType T,
3152 ExprValueKind VK, ExprObjectKind OK,
3153 bool TD, bool VD, bool ID,
3154 bool ContainsUnexpandedParameterPack,
3155 SourceLocation qloc,
3156 SourceLocation cloc)
3157 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3158 QuestionLoc(qloc), ColonLoc(cloc) {}
3160 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3161 : Expr(SC, Empty) { }
3164 // getCond - Return the expression representing the condition for
3166 Expr *getCond() const;
3168 // getTrueExpr - Return the subexpression representing the value of
3169 // the expression if the condition evaluates to true.
3170 Expr *getTrueExpr() const;
3172 // getFalseExpr - Return the subexpression representing the value of
3173 // the expression if the condition evaluates to false. This is
3174 // the same as getRHS.
3175 Expr *getFalseExpr() const;
3177 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3178 SourceLocation getColonLoc() const { return ColonLoc; }
3180 static bool classof(const Stmt *T) {
3181 return T->getStmtClass() == ConditionalOperatorClass ||
3182 T->getStmtClass() == BinaryConditionalOperatorClass;
3186 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3187 /// middle" extension is a BinaryConditionalOperator.
3188 class ConditionalOperator : public AbstractConditionalOperator {
3189 enum { COND, LHS, RHS, END_EXPR };
3190 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3192 friend class ASTStmtReader;
3194 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3195 SourceLocation CLoc, Expr *rhs,
3196 QualType t, ExprValueKind VK, ExprObjectKind OK)
3197 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3198 // FIXME: the type of the conditional operator doesn't
3199 // depend on the type of the conditional, but the standard
3200 // seems to imply that it could. File a bug!
3201 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3202 (cond->isValueDependent() || lhs->isValueDependent() ||
3203 rhs->isValueDependent()),
3204 (cond->isInstantiationDependent() ||
3205 lhs->isInstantiationDependent() ||
3206 rhs->isInstantiationDependent()),
3207 (cond->containsUnexpandedParameterPack() ||
3208 lhs->containsUnexpandedParameterPack() ||
3209 rhs->containsUnexpandedParameterPack()),
3211 SubExprs[COND] = cond;
3212 SubExprs[LHS] = lhs;
3213 SubExprs[RHS] = rhs;
3216 /// \brief Build an empty conditional operator.
3217 explicit ConditionalOperator(EmptyShell Empty)
3218 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3220 // getCond - Return the expression representing the condition for
3222 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3224 // getTrueExpr - Return the subexpression representing the value of
3225 // the expression if the condition evaluates to true.
3226 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3228 // getFalseExpr - Return the subexpression representing the value of
3229 // the expression if the condition evaluates to false. This is
3230 // the same as getRHS.
3231 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3233 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3234 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3236 SourceLocation getLocStart() const LLVM_READONLY {
3237 return getCond()->getLocStart();
3239 SourceLocation getLocEnd() const LLVM_READONLY {
3240 return getRHS()->getLocEnd();
3243 static bool classof(const Stmt *T) {
3244 return T->getStmtClass() == ConditionalOperatorClass;
3248 child_range children() {
3249 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3253 /// BinaryConditionalOperator - The GNU extension to the conditional
3254 /// operator which allows the middle operand to be omitted.
3256 /// This is a different expression kind on the assumption that almost
3257 /// every client ends up needing to know that these are different.
3258 class BinaryConditionalOperator : public AbstractConditionalOperator {
3259 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3261 /// - the common condition/left-hand-side expression, which will be
3262 /// evaluated as the opaque value
3263 /// - the condition, expressed in terms of the opaque value
3264 /// - the left-hand-side, expressed in terms of the opaque value
3265 /// - the right-hand-side
3266 Stmt *SubExprs[NUM_SUBEXPRS];
3267 OpaqueValueExpr *OpaqueValue;
3269 friend class ASTStmtReader;
3271 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3272 Expr *cond, Expr *lhs, Expr *rhs,
3273 SourceLocation qloc, SourceLocation cloc,
3274 QualType t, ExprValueKind VK, ExprObjectKind OK)
3275 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3276 (common->isTypeDependent() || rhs->isTypeDependent()),
3277 (common->isValueDependent() || rhs->isValueDependent()),
3278 (common->isInstantiationDependent() ||
3279 rhs->isInstantiationDependent()),
3280 (common->containsUnexpandedParameterPack() ||
3281 rhs->containsUnexpandedParameterPack()),
3283 OpaqueValue(opaqueValue) {
3284 SubExprs[COMMON] = common;
3285 SubExprs[COND] = cond;
3286 SubExprs[LHS] = lhs;
3287 SubExprs[RHS] = rhs;
3288 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3291 /// \brief Build an empty conditional operator.
3292 explicit BinaryConditionalOperator(EmptyShell Empty)
3293 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3295 /// \brief getCommon - Return the common expression, written to the
3296 /// left of the condition. The opaque value will be bound to the
3297 /// result of this expression.
3298 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3300 /// \brief getOpaqueValue - Return the opaque value placeholder.
3301 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3303 /// \brief getCond - Return the condition expression; this is defined
3304 /// in terms of the opaque value.
3305 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3307 /// \brief getTrueExpr - Return the subexpression which will be
3308 /// evaluated if the condition evaluates to true; this is defined
3309 /// in terms of the opaque value.
3310 Expr *getTrueExpr() const {
3311 return cast<Expr>(SubExprs[LHS]);
3314 /// \brief getFalseExpr - Return the subexpression which will be
3315 /// evaluated if the condnition evaluates to false; this is
3316 /// defined in terms of the opaque value.
3317 Expr *getFalseExpr() const {
3318 return cast<Expr>(SubExprs[RHS]);
3321 SourceLocation getLocStart() const LLVM_READONLY {
3322 return getCommon()->getLocStart();
3324 SourceLocation getLocEnd() const LLVM_READONLY {
3325 return getFalseExpr()->getLocEnd();
3328 static bool classof(const Stmt *T) {
3329 return T->getStmtClass() == BinaryConditionalOperatorClass;
3333 child_range children() {
3334 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3338 inline Expr *AbstractConditionalOperator::getCond() const {
3339 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3340 return co->getCond();
3341 return cast<BinaryConditionalOperator>(this)->getCond();
3344 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3345 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3346 return co->getTrueExpr();
3347 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3350 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3351 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3352 return co->getFalseExpr();
3353 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3356 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3357 class AddrLabelExpr : public Expr {
3358 SourceLocation AmpAmpLoc, LabelLoc;
3361 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3363 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3365 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3367 /// \brief Build an empty address of a label expression.
3368 explicit AddrLabelExpr(EmptyShell Empty)
3369 : Expr(AddrLabelExprClass, Empty) { }
3371 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3372 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3373 SourceLocation getLabelLoc() const { return LabelLoc; }
3374 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3376 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3377 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3379 LabelDecl *getLabel() const { return Label; }
3380 void setLabel(LabelDecl *L) { Label = L; }
3382 static bool classof(const Stmt *T) {
3383 return T->getStmtClass() == AddrLabelExprClass;
3387 child_range children() { return child_range(); }
3390 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3391 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3392 /// takes the value of the last subexpression.
3394 /// A StmtExpr is always an r-value; values "returned" out of a
3395 /// StmtExpr will be copied.
3396 class StmtExpr : public Expr {
3398 SourceLocation LParenLoc, RParenLoc;
3400 // FIXME: Does type-dependence need to be computed differently?
3401 // FIXME: Do we need to compute instantiation instantiation-dependence for
3402 // statements? (ugh!)
3403 StmtExpr(CompoundStmt *substmt, QualType T,
3404 SourceLocation lp, SourceLocation rp) :
3405 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3406 T->isDependentType(), false, false, false),
3407 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3409 /// \brief Build an empty statement expression.
3410 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3412 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3413 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3414 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3416 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3417 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3419 SourceLocation getLParenLoc() const { return LParenLoc; }
3420 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3421 SourceLocation getRParenLoc() const { return RParenLoc; }
3422 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3424 static bool classof(const Stmt *T) {
3425 return T->getStmtClass() == StmtExprClass;
3429 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3433 /// ShuffleVectorExpr - clang-specific builtin-in function
3434 /// __builtin_shufflevector.
3435 /// This AST node represents a operator that does a constant
3436 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3437 /// two vectors and a variable number of constant indices,
3438 /// and returns the appropriately shuffled vector.
3439 class ShuffleVectorExpr : public Expr {
3440 SourceLocation BuiltinLoc, RParenLoc;
3442 // SubExprs - the list of values passed to the __builtin_shufflevector
3443 // function. The first two are vectors, and the rest are constant
3444 // indices. The number of values in this list is always
3445 // 2+the number of indices in the vector type.
3450 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3451 SourceLocation BLoc, SourceLocation RP);
3453 /// \brief Build an empty vector-shuffle expression.
3454 explicit ShuffleVectorExpr(EmptyShell Empty)
3455 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3457 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3458 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3460 SourceLocation getRParenLoc() const { return RParenLoc; }
3461 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3463 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3464 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3466 static bool classof(const Stmt *T) {
3467 return T->getStmtClass() == ShuffleVectorExprClass;
3470 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3471 /// constant expression, the actual arguments passed in, and the function
3473 unsigned getNumSubExprs() const { return NumExprs; }
3475 /// \brief Retrieve the array of expressions.
3476 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3478 /// getExpr - Return the Expr at the specified index.
3479 Expr *getExpr(unsigned Index) {
3480 assert((Index < NumExprs) && "Arg access out of range!");
3481 return cast<Expr>(SubExprs[Index]);
3483 const Expr *getExpr(unsigned Index) const {
3484 assert((Index < NumExprs) && "Arg access out of range!");
3485 return cast<Expr>(SubExprs[Index]);
3488 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3490 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3491 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3492 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3496 child_range children() {
3497 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3501 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3502 /// This AST node provides support for converting a vector type to another
3503 /// vector type of the same arity.
3504 class ConvertVectorExpr : public Expr {
3507 TypeSourceInfo *TInfo;
3508 SourceLocation BuiltinLoc, RParenLoc;
3510 friend class ASTReader;
3511 friend class ASTStmtReader;
3512 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3515 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3516 ExprValueKind VK, ExprObjectKind OK,
3517 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3518 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3519 DstType->isDependentType(),
3520 DstType->isDependentType() || SrcExpr->isValueDependent(),
3521 (DstType->isInstantiationDependentType() ||
3522 SrcExpr->isInstantiationDependent()),
3523 (DstType->containsUnexpandedParameterPack() ||
3524 SrcExpr->containsUnexpandedParameterPack())),
3525 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3527 /// getSrcExpr - Return the Expr to be converted.
3528 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3530 /// getTypeSourceInfo - Return the destination type.
3531 TypeSourceInfo *getTypeSourceInfo() const {
3534 void setTypeSourceInfo(TypeSourceInfo *ti) {
3538 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3539 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3541 /// getRParenLoc - Return the location of final right parenthesis.
3542 SourceLocation getRParenLoc() const { return RParenLoc; }
3544 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3545 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3547 static bool classof(const Stmt *T) {
3548 return T->getStmtClass() == ConvertVectorExprClass;
3552 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3555 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3556 /// This AST node is similar to the conditional operator (?:) in C, with
3557 /// the following exceptions:
3558 /// - the test expression must be a integer constant expression.
3559 /// - the expression returned acts like the chosen subexpression in every
3560 /// visible way: the type is the same as that of the chosen subexpression,
3561 /// and all predicates (whether it's an l-value, whether it's an integer
3562 /// constant expression, etc.) return the same result as for the chosen
3564 class ChooseExpr : public Expr {
3565 enum { COND, LHS, RHS, END_EXPR };
3566 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3567 SourceLocation BuiltinLoc, RParenLoc;
3570 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3571 QualType t, ExprValueKind VK, ExprObjectKind OK,
3572 SourceLocation RP, bool condIsTrue,
3573 bool TypeDependent, bool ValueDependent)
3574 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3575 (cond->isInstantiationDependent() ||
3576 lhs->isInstantiationDependent() ||
3577 rhs->isInstantiationDependent()),
3578 (cond->containsUnexpandedParameterPack() ||
3579 lhs->containsUnexpandedParameterPack() ||
3580 rhs->containsUnexpandedParameterPack())),
3581 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3582 SubExprs[COND] = cond;
3583 SubExprs[LHS] = lhs;
3584 SubExprs[RHS] = rhs;
3587 /// \brief Build an empty __builtin_choose_expr.
3588 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3590 /// isConditionTrue - Return whether the condition is true (i.e. not
3592 bool isConditionTrue() const {
3593 assert(!isConditionDependent() &&
3594 "Dependent condition isn't true or false");
3597 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3599 bool isConditionDependent() const {
3600 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3603 /// getChosenSubExpr - Return the subexpression chosen according to the
3605 Expr *getChosenSubExpr() const {
3606 return isConditionTrue() ? getLHS() : getRHS();
3609 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3610 void setCond(Expr *E) { SubExprs[COND] = E; }
3611 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3612 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3613 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3614 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3616 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3617 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3619 SourceLocation getRParenLoc() const { return RParenLoc; }
3620 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3622 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3623 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3625 static bool classof(const Stmt *T) {
3626 return T->getStmtClass() == ChooseExprClass;
3630 child_range children() {
3631 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3635 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3636 /// for a null pointer constant that has integral type (e.g., int or
3637 /// long) and is the same size and alignment as a pointer. The __null
3638 /// extension is typically only used by system headers, which define
3639 /// NULL as __null in C++ rather than using 0 (which is an integer
3640 /// that may not match the size of a pointer).
3641 class GNUNullExpr : public Expr {
3642 /// TokenLoc - The location of the __null keyword.
3643 SourceLocation TokenLoc;
3646 GNUNullExpr(QualType Ty, SourceLocation Loc)
3647 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3651 /// \brief Build an empty GNU __null expression.
3652 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3654 /// getTokenLocation - The location of the __null token.
3655 SourceLocation getTokenLocation() const { return TokenLoc; }
3656 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3658 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3659 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3661 static bool classof(const Stmt *T) {
3662 return T->getStmtClass() == GNUNullExprClass;
3666 child_range children() { return child_range(); }
3669 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3670 class VAArgExpr : public Expr {
3672 TypeSourceInfo *TInfo;
3673 SourceLocation BuiltinLoc, RParenLoc;
3675 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3676 SourceLocation RPLoc, QualType t)
3677 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3678 t->isDependentType(), false,
3679 (TInfo->getType()->isInstantiationDependentType() ||
3680 e->isInstantiationDependent()),
3681 (TInfo->getType()->containsUnexpandedParameterPack() ||
3682 e->containsUnexpandedParameterPack())),
3683 Val(e), TInfo(TInfo),
3685 RParenLoc(RPLoc) { }
3687 /// \brief Create an empty __builtin_va_arg expression.
3688 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3690 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3691 Expr *getSubExpr() { return cast<Expr>(Val); }
3692 void setSubExpr(Expr *E) { Val = E; }
3694 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3695 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3697 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3698 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3700 SourceLocation getRParenLoc() const { return RParenLoc; }
3701 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3703 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3704 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3706 static bool classof(const Stmt *T) {
3707 return T->getStmtClass() == VAArgExprClass;
3711 child_range children() { return child_range(&Val, &Val+1); }
3714 /// @brief Describes an C or C++ initializer list.
3716 /// InitListExpr describes an initializer list, which can be used to
3717 /// initialize objects of different types, including
3718 /// struct/class/union types, arrays, and vectors. For example:
3721 /// struct foo x = { 1, { 2, 3 } };
3724 /// Prior to semantic analysis, an initializer list will represent the
3725 /// initializer list as written by the user, but will have the
3726 /// placeholder type "void". This initializer list is called the
3727 /// syntactic form of the initializer, and may contain C99 designated
3728 /// initializers (represented as DesignatedInitExprs), initializations
3729 /// of subobject members without explicit braces, and so on. Clients
3730 /// interested in the original syntax of the initializer list should
3731 /// use the syntactic form of the initializer list.
3733 /// After semantic analysis, the initializer list will represent the
3734 /// semantic form of the initializer, where the initializations of all
3735 /// subobjects are made explicit with nested InitListExpr nodes and
3736 /// C99 designators have been eliminated by placing the designated
3737 /// initializations into the subobject they initialize. Additionally,
3738 /// any "holes" in the initialization, where no initializer has been
3739 /// specified for a particular subobject, will be replaced with
3740 /// implicitly-generated ImplicitValueInitExpr expressions that
3741 /// value-initialize the subobjects. Note, however, that the
3742 /// initializer lists may still have fewer initializers than there are
3743 /// elements to initialize within the object.
3745 /// After semantic analysis has completed, given an initializer list,
3746 /// method isSemanticForm() returns true if and only if this is the
3747 /// semantic form of the initializer list (note: the same AST node
3748 /// may at the same time be the syntactic form).
3749 /// Given the semantic form of the initializer list, one can retrieve
3750 /// the syntactic form of that initializer list (when different)
3751 /// using method getSyntacticForm(); the method returns null if applied
3752 /// to a initializer list which is already in syntactic form.
3753 /// Similarly, given the syntactic form (i.e., an initializer list such
3754 /// that isSemanticForm() returns false), one can retrieve the semantic
3755 /// form using method getSemanticForm().
3756 /// Since many initializer lists have the same syntactic and semantic forms,
3757 /// getSyntacticForm() may return NULL, indicating that the current
3758 /// semantic initializer list also serves as its syntactic form.
3759 class InitListExpr : public Expr {
3760 // FIXME: Eliminate this vector in favor of ASTContext allocation
3761 typedef ASTVector<Stmt *> InitExprsTy;
3762 InitExprsTy InitExprs;
3763 SourceLocation LBraceLoc, RBraceLoc;
3765 /// The alternative form of the initializer list (if it exists).
3766 /// The int part of the pair stores whether this initializer list is
3767 /// in semantic form. If not null, the pointer points to:
3768 /// - the syntactic form, if this is in semantic form;
3769 /// - the semantic form, if this is in syntactic form.
3770 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3773 /// If this initializer list initializes an array with more elements than
3774 /// there are initializers in the list, specifies an expression to be used
3775 /// for value initialization of the rest of the elements.
3777 /// If this initializer list initializes a union, specifies which
3778 /// field within the union will be initialized.
3779 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3782 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3783 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3785 /// \brief Build an empty initializer list.
3786 explicit InitListExpr(EmptyShell Empty)
3787 : Expr(InitListExprClass, Empty) { }
3789 unsigned getNumInits() const { return InitExprs.size(); }
3791 /// \brief Retrieve the set of initializers.
3792 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3794 const Expr *getInit(unsigned Init) const {
3795 assert(Init < getNumInits() && "Initializer access out of range!");
3796 return cast_or_null<Expr>(InitExprs[Init]);
3799 Expr *getInit(unsigned Init) {
3800 assert(Init < getNumInits() && "Initializer access out of range!");
3801 return cast_or_null<Expr>(InitExprs[Init]);
3804 void setInit(unsigned Init, Expr *expr) {
3805 assert(Init < getNumInits() && "Initializer access out of range!");
3806 InitExprs[Init] = expr;
3809 ExprBits.TypeDependent |= expr->isTypeDependent();
3810 ExprBits.ValueDependent |= expr->isValueDependent();
3811 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3812 ExprBits.ContainsUnexpandedParameterPack |=
3813 expr->containsUnexpandedParameterPack();
3817 /// \brief Reserve space for some number of initializers.
3818 void reserveInits(const ASTContext &C, unsigned NumInits);
3820 /// @brief Specify the number of initializers
3822 /// If there are more than @p NumInits initializers, the remaining
3823 /// initializers will be destroyed. If there are fewer than @p
3824 /// NumInits initializers, NULL expressions will be added for the
3825 /// unknown initializers.
3826 void resizeInits(const ASTContext &Context, unsigned NumInits);
3828 /// @brief Updates the initializer at index @p Init with the new
3829 /// expression @p expr, and returns the old expression at that
3832 /// When @p Init is out of range for this initializer list, the
3833 /// initializer list will be extended with NULL expressions to
3834 /// accommodate the new entry.
3835 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3837 /// \brief If this initializer list initializes an array with more elements
3838 /// than there are initializers in the list, specifies an expression to be
3839 /// used for value initialization of the rest of the elements.
3840 Expr *getArrayFiller() {
3841 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3843 const Expr *getArrayFiller() const {
3844 return const_cast<InitListExpr *>(this)->getArrayFiller();
3846 void setArrayFiller(Expr *filler);
3848 /// \brief Return true if this is an array initializer and its array "filler"
3850 bool hasArrayFiller() const { return getArrayFiller(); }
3852 /// \brief If this initializes a union, specifies which field in the
3853 /// union to initialize.
3855 /// Typically, this field is the first named field within the
3856 /// union. However, a designated initializer can specify the
3857 /// initialization of a different field within the union.
3858 FieldDecl *getInitializedFieldInUnion() {
3859 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3861 const FieldDecl *getInitializedFieldInUnion() const {
3862 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3864 void setInitializedFieldInUnion(FieldDecl *FD) {
3865 assert((FD == nullptr
3866 || getInitializedFieldInUnion() == nullptr
3867 || getInitializedFieldInUnion() == FD)
3868 && "Only one field of a union may be initialized at a time!");
3869 ArrayFillerOrUnionFieldInit = FD;
3872 // Explicit InitListExpr's originate from source code (and have valid source
3873 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3875 return LBraceLoc.isValid() && RBraceLoc.isValid();
3878 // Is this an initializer for an array of characters, initialized by a string
3879 // literal or an @encode?
3880 bool isStringLiteralInit() const;
3882 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3883 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3884 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3885 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3887 bool isSemanticForm() const { return AltForm.getInt(); }
3888 InitListExpr *getSemanticForm() const {
3889 return isSemanticForm() ? nullptr : AltForm.getPointer();
3891 InitListExpr *getSyntacticForm() const {
3892 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3895 void setSyntacticForm(InitListExpr *Init) {
3896 AltForm.setPointer(Init);
3897 AltForm.setInt(true);
3898 Init->AltForm.setPointer(this);
3899 Init->AltForm.setInt(false);
3902 bool hadArrayRangeDesignator() const {
3903 return InitListExprBits.HadArrayRangeDesignator != 0;
3905 void sawArrayRangeDesignator(bool ARD = true) {
3906 InitListExprBits.HadArrayRangeDesignator = ARD;
3909 SourceLocation getLocStart() const LLVM_READONLY;
3910 SourceLocation getLocEnd() const LLVM_READONLY;
3912 static bool classof(const Stmt *T) {
3913 return T->getStmtClass() == InitListExprClass;
3917 child_range children() {
3918 // FIXME: This does not include the array filler expression.
3919 if (InitExprs.empty()) return child_range();
3920 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3923 typedef InitExprsTy::iterator iterator;
3924 typedef InitExprsTy::const_iterator const_iterator;
3925 typedef InitExprsTy::reverse_iterator reverse_iterator;
3926 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3928 iterator begin() { return InitExprs.begin(); }
3929 const_iterator begin() const { return InitExprs.begin(); }
3930 iterator end() { return InitExprs.end(); }
3931 const_iterator end() const { return InitExprs.end(); }
3932 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3933 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3934 reverse_iterator rend() { return InitExprs.rend(); }
3935 const_reverse_iterator rend() const { return InitExprs.rend(); }
3937 friend class ASTStmtReader;
3938 friend class ASTStmtWriter;
3941 /// @brief Represents a C99 designated initializer expression.
3943 /// A designated initializer expression (C99 6.7.8) contains one or
3944 /// more designators (which can be field designators, array
3945 /// designators, or GNU array-range designators) followed by an
3946 /// expression that initializes the field or element(s) that the
3947 /// designators refer to. For example, given:
3954 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3957 /// The InitListExpr contains three DesignatedInitExprs, the first of
3958 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3959 /// designators, one array designator for @c [2] followed by one field
3960 /// designator for @c .y. The initialization expression will be 1.0.
3961 class DesignatedInitExpr : public Expr {
3963 /// \brief Forward declaration of the Designator class.
3967 /// The location of the '=' or ':' prior to the actual initializer
3969 SourceLocation EqualOrColonLoc;
3971 /// Whether this designated initializer used the GNU deprecated
3972 /// syntax rather than the C99 '=' syntax.
3975 /// The number of designators in this initializer expression.
3976 unsigned NumDesignators : 15;
3978 /// The number of subexpressions of this initializer expression,
3979 /// which contains both the initializer and any additional
3980 /// expressions used by array and array-range designators.
3981 unsigned NumSubExprs : 16;
3983 /// \brief The designators in this designated initialization
3985 Designator *Designators;
3988 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3989 const Designator *Designators,
3990 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3991 ArrayRef<Expr*> IndexExprs, Expr *Init);
3993 explicit DesignatedInitExpr(unsigned NumSubExprs)
3994 : Expr(DesignatedInitExprClass, EmptyShell()),
3995 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3998 /// A field designator, e.g., ".x".
3999 struct FieldDesignator {
4000 /// Refers to the field that is being initialized. The low bit
4001 /// of this field determines whether this is actually a pointer
4002 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4003 /// initially constructed, a field designator will store an
4004 /// IdentifierInfo*. After semantic analysis has resolved that
4005 /// name, the field designator will instead store a FieldDecl*.
4006 uintptr_t NameOrField;
4008 /// The location of the '.' in the designated initializer.
4011 /// The location of the field name in the designated initializer.
4015 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4016 struct ArrayOrRangeDesignator {
4017 /// Location of the first index expression within the designated
4018 /// initializer expression's list of subexpressions.
4020 /// The location of the '[' starting the array range designator.
4021 unsigned LBracketLoc;
4022 /// The location of the ellipsis separating the start and end
4023 /// indices. Only valid for GNU array-range designators.
4024 unsigned EllipsisLoc;
4025 /// The location of the ']' terminating the array range designator.
4026 unsigned RBracketLoc;
4029 /// @brief Represents a single C99 designator.
4031 /// @todo This class is infuriatingly similar to clang::Designator,
4032 /// but minor differences (storing indices vs. storing pointers)
4033 /// keep us from reusing it. Try harder, later, to rectify these
4036 /// @brief The kind of designator this describes.
4040 ArrayRangeDesignator
4044 /// A field designator, e.g., ".x".
4045 struct FieldDesignator Field;
4046 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4047 struct ArrayOrRangeDesignator ArrayOrRange;
4049 friend class DesignatedInitExpr;
4054 /// @brief Initializes a field designator.
4055 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4056 SourceLocation FieldLoc)
4057 : Kind(FieldDesignator) {
4058 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4059 Field.DotLoc = DotLoc.getRawEncoding();
4060 Field.FieldLoc = FieldLoc.getRawEncoding();
4063 /// @brief Initializes an array designator.
4064 Designator(unsigned Index, SourceLocation LBracketLoc,
4065 SourceLocation RBracketLoc)
4066 : Kind(ArrayDesignator) {
4067 ArrayOrRange.Index = Index;
4068 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4069 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4070 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4073 /// @brief Initializes a GNU array-range designator.
4074 Designator(unsigned Index, SourceLocation LBracketLoc,
4075 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4076 : Kind(ArrayRangeDesignator) {
4077 ArrayOrRange.Index = Index;
4078 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4079 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4080 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4083 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4084 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4085 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4087 IdentifierInfo *getFieldName() const;
4089 FieldDecl *getField() const {
4090 assert(Kind == FieldDesignator && "Only valid on a field designator");
4091 if (Field.NameOrField & 0x01)
4094 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4097 void setField(FieldDecl *FD) {
4098 assert(Kind == FieldDesignator && "Only valid on a field designator");
4099 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4102 SourceLocation getDotLoc() const {
4103 assert(Kind == FieldDesignator && "Only valid on a field designator");
4104 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4107 SourceLocation getFieldLoc() const {
4108 assert(Kind == FieldDesignator && "Only valid on a field designator");
4109 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4112 SourceLocation getLBracketLoc() const {
4113 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4114 "Only valid on an array or array-range designator");
4115 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4118 SourceLocation getRBracketLoc() const {
4119 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4120 "Only valid on an array or array-range designator");
4121 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4124 SourceLocation getEllipsisLoc() const {
4125 assert(Kind == ArrayRangeDesignator &&
4126 "Only valid on an array-range designator");
4127 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4130 unsigned getFirstExprIndex() const {
4131 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4132 "Only valid on an array or array-range designator");
4133 return ArrayOrRange.Index;
4136 SourceLocation getLocStart() const LLVM_READONLY {
4137 if (Kind == FieldDesignator)
4138 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4140 return getLBracketLoc();
4142 SourceLocation getLocEnd() const LLVM_READONLY {
4143 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4145 SourceRange getSourceRange() const LLVM_READONLY {
4146 return SourceRange(getLocStart(), getLocEnd());
4150 static DesignatedInitExpr *Create(const ASTContext &C,
4151 Designator *Designators,
4152 unsigned NumDesignators,
4153 ArrayRef<Expr*> IndexExprs,
4154 SourceLocation EqualOrColonLoc,
4155 bool GNUSyntax, Expr *Init);
4157 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4158 unsigned NumIndexExprs);
4160 /// @brief Returns the number of designators in this initializer.
4161 unsigned size() const { return NumDesignators; }
4163 // Iterator access to the designators.
4164 typedef Designator *designators_iterator;
4165 designators_iterator designators_begin() { return Designators; }
4166 designators_iterator designators_end() {
4167 return Designators + NumDesignators;
4170 typedef const Designator *const_designators_iterator;
4171 const_designators_iterator designators_begin() const { return Designators; }
4172 const_designators_iterator designators_end() const {
4173 return Designators + NumDesignators;
4176 typedef llvm::iterator_range<designators_iterator> designators_range;
4177 designators_range designators() {
4178 return designators_range(designators_begin(), designators_end());
4181 typedef llvm::iterator_range<const_designators_iterator>
4182 designators_const_range;
4183 designators_const_range designators() const {
4184 return designators_const_range(designators_begin(), designators_end());
4187 typedef std::reverse_iterator<designators_iterator>
4188 reverse_designators_iterator;
4189 reverse_designators_iterator designators_rbegin() {
4190 return reverse_designators_iterator(designators_end());
4192 reverse_designators_iterator designators_rend() {
4193 return reverse_designators_iterator(designators_begin());
4196 typedef std::reverse_iterator<const_designators_iterator>
4197 const_reverse_designators_iterator;
4198 const_reverse_designators_iterator designators_rbegin() const {
4199 return const_reverse_designators_iterator(designators_end());
4201 const_reverse_designators_iterator designators_rend() const {
4202 return const_reverse_designators_iterator(designators_begin());
4205 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4207 void setDesignators(const ASTContext &C, const Designator *Desigs,
4208 unsigned NumDesigs);
4210 Expr *getArrayIndex(const Designator &D) const;
4211 Expr *getArrayRangeStart(const Designator &D) const;
4212 Expr *getArrayRangeEnd(const Designator &D) const;
4214 /// @brief Retrieve the location of the '=' that precedes the
4215 /// initializer value itself, if present.
4216 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4217 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4219 /// @brief Determines whether this designated initializer used the
4220 /// deprecated GNU syntax for designated initializers.
4221 bool usesGNUSyntax() const { return GNUSyntax; }
4222 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4224 /// @brief Retrieve the initializer value.
4225 Expr *getInit() const {
4226 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4229 void setInit(Expr *init) {
4230 *child_begin() = init;
4233 /// \brief Retrieve the total number of subexpressions in this
4234 /// designated initializer expression, including the actual
4235 /// initialized value and any expressions that occur within array
4236 /// and array-range designators.
4237 unsigned getNumSubExprs() const { return NumSubExprs; }
4239 Expr *getSubExpr(unsigned Idx) const {
4240 assert(Idx < NumSubExprs && "Subscript out of range");
4241 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4244 void setSubExpr(unsigned Idx, Expr *E) {
4245 assert(Idx < NumSubExprs && "Subscript out of range");
4246 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4249 /// \brief Replaces the designator at index @p Idx with the series
4250 /// of designators in [First, Last).
4251 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4252 const Designator *First, const Designator *Last);
4254 SourceRange getDesignatorsSourceRange() const;
4256 SourceLocation getLocStart() const LLVM_READONLY;
4257 SourceLocation getLocEnd() const LLVM_READONLY;
4259 static bool classof(const Stmt *T) {
4260 return T->getStmtClass() == DesignatedInitExprClass;
4264 child_range children() {
4265 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4266 return child_range(begin, begin + NumSubExprs);
4270 /// \brief Represents an implicitly-generated value initialization of
4271 /// an object of a given type.
4273 /// Implicit value initializations occur within semantic initializer
4274 /// list expressions (InitListExpr) as placeholders for subobject
4275 /// initializations not explicitly specified by the user.
4277 /// \see InitListExpr
4278 class ImplicitValueInitExpr : public Expr {
4280 explicit ImplicitValueInitExpr(QualType ty)
4281 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4282 false, false, ty->isInstantiationDependentType(), false) { }
4284 /// \brief Construct an empty implicit value initialization.
4285 explicit ImplicitValueInitExpr(EmptyShell Empty)
4286 : Expr(ImplicitValueInitExprClass, Empty) { }
4288 static bool classof(const Stmt *T) {
4289 return T->getStmtClass() == ImplicitValueInitExprClass;
4292 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4293 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4296 child_range children() { return child_range(); }
4300 class ParenListExpr : public Expr {
4303 SourceLocation LParenLoc, RParenLoc;
4306 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4307 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4309 /// \brief Build an empty paren list.
4310 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4312 unsigned getNumExprs() const { return NumExprs; }
4314 const Expr* getExpr(unsigned Init) const {
4315 assert(Init < getNumExprs() && "Initializer access out of range!");
4316 return cast_or_null<Expr>(Exprs[Init]);
4319 Expr* getExpr(unsigned Init) {
4320 assert(Init < getNumExprs() && "Initializer access out of range!");
4321 return cast_or_null<Expr>(Exprs[Init]);
4324 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4326 SourceLocation getLParenLoc() const { return LParenLoc; }
4327 SourceLocation getRParenLoc() const { return RParenLoc; }
4329 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4330 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4332 static bool classof(const Stmt *T) {
4333 return T->getStmtClass() == ParenListExprClass;
4337 child_range children() {
4338 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4341 friend class ASTStmtReader;
4342 friend class ASTStmtWriter;
4346 /// \brief Represents a C11 generic selection.
4348 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4349 /// expression, followed by one or more generic associations. Each generic
4350 /// association specifies a type name and an expression, or "default" and an
4351 /// expression (in which case it is known as a default generic association).
4352 /// The type and value of the generic selection are identical to those of its
4353 /// result expression, which is defined as the expression in the generic
4354 /// association with a type name that is compatible with the type of the
4355 /// controlling expression, or the expression in the default generic association
4356 /// if no types are compatible. For example:
4359 /// _Generic(X, double: 1, float: 2, default: 3)
4362 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4363 /// or 3 if "hello".
4365 /// As an extension, generic selections are allowed in C++, where the following
4366 /// additional semantics apply:
4368 /// Any generic selection whose controlling expression is type-dependent or
4369 /// which names a dependent type in its association list is result-dependent,
4370 /// which means that the choice of result expression is dependent.
4371 /// Result-dependent generic associations are both type- and value-dependent.
4372 class GenericSelectionExpr : public Expr {
4373 enum { CONTROLLING, END_EXPR };
4374 TypeSourceInfo **AssocTypes;
4376 unsigned NumAssocs, ResultIndex;
4377 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4380 GenericSelectionExpr(const ASTContext &Context,
4381 SourceLocation GenericLoc, Expr *ControllingExpr,
4382 ArrayRef<TypeSourceInfo*> AssocTypes,
4383 ArrayRef<Expr*> AssocExprs,
4384 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4385 bool ContainsUnexpandedParameterPack,
4386 unsigned ResultIndex);
4388 /// This constructor is used in the result-dependent case.
4389 GenericSelectionExpr(const ASTContext &Context,
4390 SourceLocation GenericLoc, Expr *ControllingExpr,
4391 ArrayRef<TypeSourceInfo*> AssocTypes,
4392 ArrayRef<Expr*> AssocExprs,
4393 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4394 bool ContainsUnexpandedParameterPack);
4396 explicit GenericSelectionExpr(EmptyShell Empty)
4397 : Expr(GenericSelectionExprClass, Empty) { }
4399 unsigned getNumAssocs() const { return NumAssocs; }
4401 SourceLocation getGenericLoc() const { return GenericLoc; }
4402 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4403 SourceLocation getRParenLoc() const { return RParenLoc; }
4405 const Expr *getAssocExpr(unsigned i) const {
4406 return cast<Expr>(SubExprs[END_EXPR+i]);
4408 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4410 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4411 return AssocTypes[i];
4413 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4415 QualType getAssocType(unsigned i) const {
4416 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4417 return TS->getType();
4422 const Expr *getControllingExpr() const {
4423 return cast<Expr>(SubExprs[CONTROLLING]);
4425 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4427 /// Whether this generic selection is result-dependent.
4428 bool isResultDependent() const { return ResultIndex == -1U; }
4430 /// The zero-based index of the result expression's generic association in
4431 /// the generic selection's association list. Defined only if the
4432 /// generic selection is not result-dependent.
4433 unsigned getResultIndex() const {
4434 assert(!isResultDependent() && "Generic selection is result-dependent");
4438 /// The generic selection's result expression. Defined only if the
4439 /// generic selection is not result-dependent.
4440 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4441 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4443 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4444 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4446 static bool classof(const Stmt *T) {
4447 return T->getStmtClass() == GenericSelectionExprClass;
4450 child_range children() {
4451 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4454 friend class ASTStmtReader;
4457 //===----------------------------------------------------------------------===//
4459 //===----------------------------------------------------------------------===//
4462 /// ExtVectorElementExpr - This represents access to specific elements of a
4463 /// vector, and may occur on the left hand side or right hand side. For example
4464 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4466 /// Note that the base may have either vector or pointer to vector type, just
4467 /// like a struct field reference.
4469 class ExtVectorElementExpr : public Expr {
4471 IdentifierInfo *Accessor;
4472 SourceLocation AccessorLoc;
4474 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4475 IdentifierInfo &accessor, SourceLocation loc)
4476 : Expr(ExtVectorElementExprClass, ty, VK,
4477 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4478 base->isTypeDependent(), base->isValueDependent(),
4479 base->isInstantiationDependent(),
4480 base->containsUnexpandedParameterPack()),
4481 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4483 /// \brief Build an empty vector element expression.
4484 explicit ExtVectorElementExpr(EmptyShell Empty)
4485 : Expr(ExtVectorElementExprClass, Empty) { }
4487 const Expr *getBase() const { return cast<Expr>(Base); }
4488 Expr *getBase() { return cast<Expr>(Base); }
4489 void setBase(Expr *E) { Base = E; }
4491 IdentifierInfo &getAccessor() const { return *Accessor; }
4492 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4494 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4495 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4497 /// getNumElements - Get the number of components being selected.
4498 unsigned getNumElements() const;
4500 /// containsDuplicateElements - Return true if any element access is
4502 bool containsDuplicateElements() const;
4504 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4505 /// aggregate Constant of ConstantInt(s).
4506 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4508 SourceLocation getLocStart() const LLVM_READONLY {
4509 return getBase()->getLocStart();
4511 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4513 /// isArrow - Return true if the base expression is a pointer to vector,
4514 /// return false if the base expression is a vector.
4515 bool isArrow() const;
4517 static bool classof(const Stmt *T) {
4518 return T->getStmtClass() == ExtVectorElementExprClass;
4522 child_range children() { return child_range(&Base, &Base+1); }
4526 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4527 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4528 class BlockExpr : public Expr {
4530 BlockDecl *TheBlock;
4532 BlockExpr(BlockDecl *BD, QualType ty)
4533 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4534 ty->isDependentType(), ty->isDependentType(),
4535 ty->isInstantiationDependentType() || BD->isDependentContext(),
4539 /// \brief Build an empty block expression.
4540 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4542 const BlockDecl *getBlockDecl() const { return TheBlock; }
4543 BlockDecl *getBlockDecl() { return TheBlock; }
4544 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4546 // Convenience functions for probing the underlying BlockDecl.
4547 SourceLocation getCaretLocation() const;
4548 const Stmt *getBody() const;
4551 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4552 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4554 /// getFunctionType - Return the underlying function type for this block.
4555 const FunctionProtoType *getFunctionType() const;
4557 static bool classof(const Stmt *T) {
4558 return T->getStmtClass() == BlockExprClass;
4562 child_range children() { return child_range(); }
4565 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4566 /// This AST node provides support for reinterpreting a type to another
4567 /// type of the same size.
4568 class AsTypeExpr : public Expr {
4571 SourceLocation BuiltinLoc, RParenLoc;
4573 friend class ASTReader;
4574 friend class ASTStmtReader;
4575 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4578 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4579 ExprValueKind VK, ExprObjectKind OK,
4580 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4581 : Expr(AsTypeExprClass, DstType, VK, OK,
4582 DstType->isDependentType(),
4583 DstType->isDependentType() || SrcExpr->isValueDependent(),
4584 (DstType->isInstantiationDependentType() ||
4585 SrcExpr->isInstantiationDependent()),
4586 (DstType->containsUnexpandedParameterPack() ||
4587 SrcExpr->containsUnexpandedParameterPack())),
4588 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4590 /// getSrcExpr - Return the Expr to be converted.
4591 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4593 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4594 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4596 /// getRParenLoc - Return the location of final right parenthesis.
4597 SourceLocation getRParenLoc() const { return RParenLoc; }
4599 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4600 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4602 static bool classof(const Stmt *T) {
4603 return T->getStmtClass() == AsTypeExprClass;
4607 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4610 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4611 /// l-value. A pseudo-object is an abstract object, accesses to which
4612 /// are translated to calls. The pseudo-object expression has a
4613 /// syntactic form, which shows how the expression was actually
4614 /// written in the source code, and a semantic form, which is a series
4615 /// of expressions to be executed in order which detail how the
4616 /// operation is actually evaluated. Optionally, one of the semantic
4617 /// forms may also provide a result value for the expression.
4619 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4620 /// that OVE is required to have a source expression, and it is bound
4621 /// to the result of that source expression. Such OVEs may appear
4622 /// only in subsequent semantic-form expressions and as
4623 /// sub-expressions of the syntactic form.
4625 /// PseudoObjectExpr should be used only when an operation can be
4626 /// usefully described in terms of fairly simple rewrite rules on
4627 /// objects and functions that are meant to be used by end-developers.
4628 /// For example, under the Itanium ABI, dynamic casts are implemented
4629 /// as a call to a runtime function called __dynamic_cast; using this
4630 /// class to describe that would be inappropriate because that call is
4631 /// not really part of the user-visible semantics, and instead the
4632 /// cast is properly reflected in the AST and IR-generation has been
4633 /// taught to generate the call as necessary. In contrast, an
4634 /// Objective-C property access is semantically defined to be
4635 /// equivalent to a particular message send, and this is very much
4636 /// part of the user model. The name of this class encourages this
4637 /// modelling design.
4638 class PseudoObjectExpr : public Expr {
4639 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4640 // Always at least two, because the first sub-expression is the
4643 // PseudoObjectExprBits.ResultIndex - The index of the
4644 // sub-expression holding the result. 0 means the result is void,
4645 // which is unambiguous because it's the index of the syntactic
4646 // form. Note that this is therefore 1 higher than the value passed
4647 // in to Create, which is an index within the semantic forms.
4648 // Note also that ASTStmtWriter assumes this encoding.
4650 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4651 const Expr * const *getSubExprsBuffer() const {
4652 return reinterpret_cast<const Expr * const *>(this + 1);
4655 friend class ASTStmtReader;
4657 PseudoObjectExpr(QualType type, ExprValueKind VK,
4658 Expr *syntactic, ArrayRef<Expr*> semantic,
4659 unsigned resultIndex);
4661 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4663 unsigned getNumSubExprs() const {
4664 return PseudoObjectExprBits.NumSubExprs;
4668 /// NoResult - A value for the result index indicating that there is
4669 /// no semantic result.
4670 enum : unsigned { NoResult = ~0U };
4672 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4673 ArrayRef<Expr*> semantic,
4674 unsigned resultIndex);
4676 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4677 unsigned numSemanticExprs);
4679 /// Return the syntactic form of this expression, i.e. the
4680 /// expression it actually looks like. Likely to be expressed in
4681 /// terms of OpaqueValueExprs bound in the semantic form.
4682 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4683 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4685 /// Return the index of the result-bearing expression into the semantics
4686 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4687 unsigned getResultExprIndex() const {
4688 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4689 return PseudoObjectExprBits.ResultIndex - 1;
4692 /// Return the result-bearing expression, or null if there is none.
4693 Expr *getResultExpr() {
4694 if (PseudoObjectExprBits.ResultIndex == 0)
4696 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4698 const Expr *getResultExpr() const {
4699 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4702 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4704 typedef Expr * const *semantics_iterator;
4705 typedef const Expr * const *const_semantics_iterator;
4706 semantics_iterator semantics_begin() {
4707 return getSubExprsBuffer() + 1;
4709 const_semantics_iterator semantics_begin() const {
4710 return getSubExprsBuffer() + 1;
4712 semantics_iterator semantics_end() {
4713 return getSubExprsBuffer() + getNumSubExprs();
4715 const_semantics_iterator semantics_end() const {
4716 return getSubExprsBuffer() + getNumSubExprs();
4718 Expr *getSemanticExpr(unsigned index) {
4719 assert(index + 1 < getNumSubExprs());
4720 return getSubExprsBuffer()[index + 1];
4722 const Expr *getSemanticExpr(unsigned index) const {
4723 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4726 SourceLocation getExprLoc() const LLVM_READONLY {
4727 return getSyntacticForm()->getExprLoc();
4730 SourceLocation getLocStart() const LLVM_READONLY {
4731 return getSyntacticForm()->getLocStart();
4733 SourceLocation getLocEnd() const LLVM_READONLY {
4734 return getSyntacticForm()->getLocEnd();
4737 child_range children() {
4738 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4739 return child_range(cs, cs + getNumSubExprs());
4742 static bool classof(const Stmt *T) {
4743 return T->getStmtClass() == PseudoObjectExprClass;
4747 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4748 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4749 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4750 /// All of these instructions take one primary pointer and at least one memory
4752 class AtomicExpr : public Expr {
4755 #define BUILTIN(ID, TYPE, ATTRS)
4756 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4757 #include "clang/Basic/Builtins.def"
4758 // Avoid trailing comma
4762 // The ABI values for various atomic memory orderings.
4763 enum AtomicOrderingKind {
4764 AO_ABI_memory_order_relaxed = 0,
4765 AO_ABI_memory_order_consume = 1,
4766 AO_ABI_memory_order_acquire = 2,
4767 AO_ABI_memory_order_release = 3,
4768 AO_ABI_memory_order_acq_rel = 4,
4769 AO_ABI_memory_order_seq_cst = 5
4773 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4774 Stmt* SubExprs[END_EXPR];
4775 unsigned NumSubExprs;
4776 SourceLocation BuiltinLoc, RParenLoc;
4779 friend class ASTStmtReader;
4782 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4783 AtomicOp op, SourceLocation RP);
4785 /// \brief Determine the number of arguments the specified atomic builtin
4787 static unsigned getNumSubExprs(AtomicOp Op);
4789 /// \brief Build an empty AtomicExpr.
4790 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4792 Expr *getPtr() const {
4793 return cast<Expr>(SubExprs[PTR]);
4795 Expr *getOrder() const {
4796 return cast<Expr>(SubExprs[ORDER]);
4798 Expr *getVal1() const {
4799 if (Op == AO__c11_atomic_init)
4800 return cast<Expr>(SubExprs[ORDER]);
4801 assert(NumSubExprs > VAL1);
4802 return cast<Expr>(SubExprs[VAL1]);
4804 Expr *getOrderFail() const {
4805 assert(NumSubExprs > ORDER_FAIL);
4806 return cast<Expr>(SubExprs[ORDER_FAIL]);
4808 Expr *getVal2() const {
4809 if (Op == AO__atomic_exchange)
4810 return cast<Expr>(SubExprs[ORDER_FAIL]);
4811 assert(NumSubExprs > VAL2);
4812 return cast<Expr>(SubExprs[VAL2]);
4814 Expr *getWeak() const {
4815 assert(NumSubExprs > WEAK);
4816 return cast<Expr>(SubExprs[WEAK]);
4819 AtomicOp getOp() const { return Op; }
4820 unsigned getNumSubExprs() { return NumSubExprs; }
4822 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4824 bool isVolatile() const {
4825 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4828 bool isCmpXChg() const {
4829 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4830 getOp() == AO__c11_atomic_compare_exchange_weak ||
4831 getOp() == AO__atomic_compare_exchange ||
4832 getOp() == AO__atomic_compare_exchange_n;
4835 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4836 SourceLocation getRParenLoc() const { return RParenLoc; }
4838 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4839 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4841 static bool classof(const Stmt *T) {
4842 return T->getStmtClass() == AtomicExprClass;
4846 child_range children() {
4847 return child_range(SubExprs, SubExprs+NumSubExprs);
4851 /// TypoExpr - Internal placeholder for expressions where typo correction
4852 /// still needs to be performed and/or an error diagnostic emitted.
4853 class TypoExpr : public Expr {
4855 TypoExpr(QualType T)
4856 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4857 /*isTypeDependent*/ true,
4858 /*isValueDependent*/ true,
4859 /*isInstantiationDependent*/ true,
4860 /*containsUnexpandedParameterPack*/ false) {
4861 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4864 child_range children() { return child_range(); }
4865 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4866 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4868 } // end namespace clang