clang 17.0.0git
Expr.h
Go to the documentation of this file.
1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Expr interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_EXPR_H
14#define LLVM_CLANG_AST_EXPR_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTVector.h"
19#include "clang/AST/Decl.h"
23#include "clang/AST/Stmt.h"
25#include "clang/AST/Type.h"
30#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APSInt.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/iterator.h"
35#include "llvm/ADT/iterator_range.h"
36#include "llvm/Support/AtomicOrdering.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/TrailingObjects.h"
39#include <optional>
40
41namespace clang {
42 class APValue;
43 class ASTContext;
44 class BlockDecl;
45 class CXXBaseSpecifier;
46 class CXXMemberCallExpr;
47 class CXXOperatorCallExpr;
48 class CastExpr;
49 class Decl;
50 class IdentifierInfo;
51 class MaterializeTemporaryExpr;
52 class NamedDecl;
53 class ObjCPropertyRefExpr;
54 class OpaqueValueExpr;
55 class ParmVarDecl;
56 class StringLiteral;
57 class TargetInfo;
58 class ValueDecl;
59
60/// A simple array of base specifiers.
62
63/// An adjustment to be made to the temporary created when emitting a
64/// reference binding, which accesses a particular subobject of that temporary.
66 enum {
71
72 struct DTB {
75 };
76
77 struct P {
80 };
81
82 union {
85 struct P Ptr;
86 };
87
89 const CXXRecordDecl *DerivedClass)
91 DerivedToBase.BasePath = BasePath;
92 DerivedToBase.DerivedClass = DerivedClass;
93 }
94
97 this->Field = Field;
98 }
99
102 this->Ptr.MPT = MPT;
103 this->Ptr.RHS = RHS;
104 }
105};
106
107/// This represents one expression. Note that Expr's are subclasses of Stmt.
108/// This allows an expression to be transparently used any place a Stmt is
109/// required.
110class Expr : public ValueStmt {
111 QualType TR;
112
113public:
114 Expr() = delete;
115 Expr(const Expr&) = delete;
116 Expr(Expr &&) = delete;
117 Expr &operator=(const Expr&) = delete;
118 Expr &operator=(Expr&&) = delete;
119
120protected:
122 : ValueStmt(SC) {
123 ExprBits.Dependent = 0;
124 ExprBits.ValueKind = VK;
125 ExprBits.ObjectKind = OK;
126 assert(ExprBits.ObjectKind == OK && "truncated kind");
127 setType(T);
128 }
129
130 /// Construct an empty expression.
131 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
132
133 /// Each concrete expr subclass is expected to compute its dependence and call
134 /// this in the constructor.
136 ExprBits.Dependent = static_cast<unsigned>(Deps);
137 }
138 friend class ASTImporter; // Sets dependence directly.
139 friend class ASTStmtReader; // Sets dependence directly.
140
141public:
142 QualType getType() const { return TR; }
144 // In C++, the type of an expression is always adjusted so that it
145 // will not have reference type (C++ [expr]p6). Use
146 // QualType::getNonReferenceType() to retrieve the non-reference
147 // type. Additionally, inspect Expr::isLvalue to determine whether
148 // an expression that is adjusted in this manner should be
149 // considered an lvalue.
150 assert((t.isNull() || !t->isReferenceType()) &&
151 "Expressions can't have reference type");
152
153 TR = t;
154 }
155
157 return static_cast<ExprDependence>(ExprBits.Dependent);
158 }
159
160 /// Determines whether the value of this expression depends on
161 /// - a template parameter (C++ [temp.dep.constexpr])
162 /// - or an error, whose resolution is unknown
163 ///
164 /// For example, the array bound of "Chars" in the following example is
165 /// value-dependent.
166 /// @code
167 /// template<int Size, char (&Chars)[Size]> struct meta_string;
168 /// @endcode
169 bool isValueDependent() const {
170 return static_cast<bool>(getDependence() & ExprDependence::Value);
171 }
172
173 /// Determines whether the type of this expression depends on
174 /// - a template parameter (C++ [temp.dep.expr], which means that its type
175 /// could change from one template instantiation to the next)
176 /// - or an error
177 ///
178 /// For example, the expressions "x" and "x + y" are type-dependent in
179 /// the following code, but "y" is not type-dependent:
180 /// @code
181 /// template<typename T>
182 /// void add(T x, int y) {
183 /// x + y;
184 /// }
185 /// @endcode
186 bool isTypeDependent() const {
187 return static_cast<bool>(getDependence() & ExprDependence::Type);
188 }
189
190 /// Whether this expression is instantiation-dependent, meaning that
191 /// it depends in some way on
192 /// - a template parameter (even if neither its type nor (constant) value
193 /// can change due to the template instantiation)
194 /// - or an error
195 ///
196 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
197 /// instantiation-dependent (since it involves a template parameter \c T), but
198 /// is neither type- nor value-dependent, since the type of the inner
199 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
200 /// \c sizeof is known.
201 ///
202 /// \code
203 /// template<typename T>
204 /// void f(T x, T y) {
205 /// sizeof(sizeof(T() + T());
206 /// }
207 /// \endcode
208 ///
209 /// \code
210 /// void func(int) {
211 /// func(); // the expression is instantiation-dependent, because it depends
212 /// // on an error.
213 /// }
214 /// \endcode
216 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
217 }
218
219 /// Whether this expression contains an unexpanded parameter
220 /// pack (for C++11 variadic templates).
221 ///
222 /// Given the following function template:
223 ///
224 /// \code
225 /// template<typename F, typename ...Types>
226 /// void forward(const F &f, Types &&...args) {
227 /// f(static_cast<Types&&>(args)...);
228 /// }
229 /// \endcode
230 ///
231 /// The expressions \c args and \c static_cast<Types&&>(args) both
232 /// contain parameter packs.
234 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
235 }
236
237 /// Whether this expression contains subexpressions which had errors, e.g. a
238 /// TypoExpr.
239 bool containsErrors() const {
240 return static_cast<bool>(getDependence() & ExprDependence::Error);
241 }
242
243 /// getExprLoc - Return the preferred location for the arrow when diagnosing
244 /// a problem with a generic expression.
245 SourceLocation getExprLoc() const LLVM_READONLY;
246
247 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
248 /// applied to this expression if it appears as a discarded-value expression
249 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
251
252 /// isUnusedResultAWarning - Return true if this immediate expression should
253 /// be warned about if the result is unused. If so, fill in expr, location,
254 /// and ranges with expr to warn on and source locations/ranges appropriate
255 /// for a warning.
256 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
257 SourceRange &R1, SourceRange &R2,
258 ASTContext &Ctx) const;
259
260 /// isLValue - True if this expression is an "l-value" according to
261 /// the rules of the current language. C and C++ give somewhat
262 /// different rules for this concept, but in general, the result of
263 /// an l-value expression identifies a specific object whereas the
264 /// result of an r-value expression is a value detached from any
265 /// specific storage.
266 ///
267 /// C++11 divides the concept of "r-value" into pure r-values
268 /// ("pr-values") and so-called expiring values ("x-values"), which
269 /// identify specific objects that can be safely cannibalized for
270 /// their resources.
271 bool isLValue() const { return getValueKind() == VK_LValue; }
272 bool isPRValue() const { return getValueKind() == VK_PRValue; }
273 bool isXValue() const { return getValueKind() == VK_XValue; }
274 bool isGLValue() const { return getValueKind() != VK_PRValue; }
275
287 };
288 /// Reasons why an expression might not be an l-value.
290
297 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
309 };
310 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
311 /// does not have an incomplete type, does not have a const-qualified type,
312 /// and if it is a structure or union, does not have any member (including,
313 /// recursively, any member or element of all contained aggregates or unions)
314 /// with a const-qualified type.
315 ///
316 /// \param Loc [in,out] - A source location which *may* be filled
317 /// in with the location of the expression making this a
318 /// non-modifiable lvalue, if specified.
320 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
321
322 /// The return type of classify(). Represents the C++11 expression
323 /// taxonomy.
325 public:
326 /// The various classification results. Most of these mean prvalue.
327 enum Kinds {
330 CL_Function, // Functions cannot be lvalues in C.
331 CL_Void, // Void cannot be an lvalue in C.
332 CL_AddressableVoid, // Void expression whose address can be taken in C.
333 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
334 CL_MemberFunction, // An expression referring to a member function
336 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
337 CL_ArrayTemporary, // A temporary of array type.
338 CL_ObjCMessageRValue, // ObjC message is an rvalue
339 CL_PRValue // A prvalue for any other reason, of any other type
340 };
341 /// The results of modification testing.
343 CM_Untested, // testModifiable was false.
345 CM_RValue, // Not modifiable because it's an rvalue
346 CM_Function, // Not modifiable because it's a function; C++ only
347 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
348 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
354 };
355
356 private:
357 friend class Expr;
358
359 unsigned short Kind;
360 unsigned short Modifiable;
361
362 explicit Classification(Kinds k, ModifiableType m)
363 : Kind(k), Modifiable(m)
364 {}
365
366 public:
368
369 Kinds getKind() const { return static_cast<Kinds>(Kind); }
371 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
372 return static_cast<ModifiableType>(Modifiable);
373 }
374 bool isLValue() const { return Kind == CL_LValue; }
375 bool isXValue() const { return Kind == CL_XValue; }
376 bool isGLValue() const { return Kind <= CL_XValue; }
377 bool isPRValue() const { return Kind >= CL_Function; }
378 bool isRValue() const { return Kind >= CL_XValue; }
379 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
380
381 /// Create a simple, modifiably lvalue
384 }
385
386 };
387 /// Classify - Classify this expression according to the C++11
388 /// expression taxonomy.
389 ///
390 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
391 /// old lvalue vs rvalue. This function determines the type of expression this
392 /// is. There are three expression types:
393 /// - lvalues are classical lvalues as in C++03.
394 /// - prvalues are equivalent to rvalues in C++03.
395 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
396 /// function returning an rvalue reference.
397 /// lvalues and xvalues are collectively referred to as glvalues, while
398 /// prvalues and xvalues together form rvalues.
400 return ClassifyImpl(Ctx, nullptr);
401 }
402
403 /// ClassifyModifiable - Classify this expression according to the
404 /// C++11 expression taxonomy, and see if it is valid on the left side
405 /// of an assignment.
406 ///
407 /// This function extends classify in that it also tests whether the
408 /// expression is modifiable (C99 6.3.2.1p1).
409 /// \param Loc A source location that might be filled with a relevant location
410 /// if the expression is not modifiable.
412 return ClassifyImpl(Ctx, &Loc);
413 }
414
415 /// Returns the set of floating point options that apply to this expression.
416 /// Only meaningful for operations on floating point values.
418
419 /// getValueKindForType - Given a formal return or parameter type,
420 /// give its value kind.
422 if (const ReferenceType *RT = T->getAs<ReferenceType>())
423 return (isa<LValueReferenceType>(RT)
424 ? VK_LValue
425 : (RT->getPointeeType()->isFunctionType()
426 ? VK_LValue : VK_XValue));
427 return VK_PRValue;
428 }
429
430 /// getValueKind - The value kind that this expression produces.
432 return static_cast<ExprValueKind>(ExprBits.ValueKind);
433 }
434
435 /// getObjectKind - The object kind that this expression produces.
436 /// Object kinds are meaningful only for expressions that yield an
437 /// l-value or x-value.
439 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
440 }
441
444 return (OK == OK_Ordinary || OK == OK_BitField);
445 }
446
447 /// setValueKind - Set the value kind produced by this expression.
448 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
449
450 /// setObjectKind - Set the object kind produced by this expression.
451 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
452
453private:
454 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
455
456public:
457
458 /// Returns true if this expression is a gl-value that
459 /// potentially refers to a bit-field.
460 ///
461 /// In C++, whether a gl-value refers to a bitfield is essentially
462 /// an aspect of the value-kind type system.
463 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
464
465 /// If this expression refers to a bit-field, retrieve the
466 /// declaration of that bit-field.
467 ///
468 /// Note that this returns a non-null pointer in subtly different
469 /// places than refersToBitField returns true. In particular, this can
470 /// return a non-null pointer even for r-values loaded from
471 /// bit-fields, but it will return null for a conditional bit-field.
473
475 return const_cast<Expr*>(this)->getSourceBitField();
476 }
477
480 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
481 }
482
483 /// If this expression is an l-value for an Objective C
484 /// property, find the underlying property reference expression.
486
487 /// Check if this expression is the ObjC 'self' implicit parameter.
488 bool isObjCSelfExpr() const;
489
490 /// Returns whether this expression refers to a vector element.
491 bool refersToVectorElement() const;
492
493 /// Returns whether this expression refers to a matrix element.
496 }
497
498 /// Returns whether this expression refers to a global register
499 /// variable.
500 bool refersToGlobalRegisterVar() const;
501
502 /// Returns whether this expression has a placeholder type.
503 bool hasPlaceholderType() const {
504 return getType()->isPlaceholderType();
505 }
506
507 /// Returns whether this expression has a specific placeholder type.
510 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
511 return BT->getKind() == K;
512 return false;
513 }
514
515 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
516 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
517 /// but also int expressions which are produced by things like comparisons in
518 /// C.
519 ///
520 /// \param Semantic If true, only return true for expressions that are known
521 /// to be semantically boolean, which might not be true even for expressions
522 /// that are known to evaluate to 0/1. For instance, reading an unsigned
523 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
524 /// semantically correspond to a bool.
525 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
526
527 /// Check whether this array fits the idiom of a flexible array member,
528 /// depending on the value of -fstrict-flex-array.
529 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
530 /// resulting from the substitution of a macro or a template as special sizes.
532 ASTContext &Context,
533 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
534 bool IgnoreTemplateOrMacroSubstitution = false) const;
535
536 /// isIntegerConstantExpr - Return the value if this expression is a valid
537 /// integer constant expression. If not a valid i-c-e, return std::nullopt
538 /// and fill in Loc (if specified) with the location of the invalid
539 /// expression.
540 ///
541 /// Note: This does not perform the implicit conversions required by C++11
542 /// [expr.const]p5.
543 std::optional<llvm::APSInt>
544 getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr,
545 bool isEvaluated = true) const;
546 bool isIntegerConstantExpr(const ASTContext &Ctx,
547 SourceLocation *Loc = nullptr) const;
548
549 /// isCXX98IntegralConstantExpr - Return true if this expression is an
550 /// integral constant expression in C++98. Can only be used in C++.
551 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
552
553 /// isCXX11ConstantExpr - Return true if this expression is a constant
554 /// expression in C++11. Can only be used in C++.
555 ///
556 /// Note: This does not perform the implicit conversions required by C++11
557 /// [expr.const]p5.
558 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
559 SourceLocation *Loc = nullptr) const;
560
561 /// isPotentialConstantExpr - Return true if this function's definition
562 /// might be usable in a constant expression in C++11, if it were marked
563 /// constexpr. Return false if the function can never produce a constant
564 /// expression, along with diagnostics describing why not.
565 static bool isPotentialConstantExpr(const FunctionDecl *FD,
567 PartialDiagnosticAt> &Diags);
568
569 /// isPotentialConstantExprUnevaluted - Return true if this expression might
570 /// be usable in a constant expression in C++11 in an unevaluated context, if
571 /// it were in function FD marked constexpr. Return false if the function can
572 /// never produce a constant expression, along with diagnostics describing
573 /// why not.
575 const FunctionDecl *FD,
577 PartialDiagnosticAt> &Diags);
578
579 /// isConstantInitializer - Returns true if this expression can be emitted to
580 /// IR as a constant, and thus can be used as a constant initializer in C.
581 /// If this expression is not constant and Culprit is non-null,
582 /// it is used to store the address of first non constant expr.
583 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
584 const Expr **Culprit = nullptr) const;
585
586 /// If this expression is an unambiguous reference to a single declaration,
587 /// in the style of __builtin_function_start, return that declaration. Note
588 /// that this may return a non-static member function or field in C++ if this
589 /// expression is a member pointer constant.
590 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
591
592 /// EvalStatus is a struct with detailed info about an evaluation in progress.
593 struct EvalStatus {
594 /// Whether the evaluated expression has side effects.
595 /// For example, (f() && 0) can be folded, but it still has side effects.
596 bool HasSideEffects = false;
597
598 /// Whether the evaluation hit undefined behavior.
599 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
600 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
602
603 /// Diag - If this is non-null, it will be filled in with a stack of notes
604 /// indicating why evaluation failed (or why it failed to produce a constant
605 /// expression).
606 /// If the expression is unfoldable, the notes will indicate why it's not
607 /// foldable. If the expression is foldable, but not a constant expression,
608 /// the notes will describes why it isn't a constant expression. If the
609 /// expression *is* a constant expression, no notes will be produced.
611
612 EvalStatus() = default;
613
614 // hasSideEffects - Return true if the evaluated expression has
615 // side effects.
616 bool hasSideEffects() const {
617 return HasSideEffects;
618 }
619 };
620
621 /// EvalResult is a struct with detailed info about an evaluated expression.
623 /// Val - This is the value the expression can be folded to.
625
626 // isGlobalLValue - Return true if the evaluated lvalue expression
627 // is global.
628 bool isGlobalLValue() const;
629 };
630
631 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
632 /// an rvalue using any crazy technique (that has nothing to do with language
633 /// standards) that we want to, even if the expression has side-effects. If
634 /// this function returns true, it returns the folded constant in Result. If
635 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
636 /// applied.
638 bool InConstantContext = false) const;
639
640 /// EvaluateAsBooleanCondition - Return true if this is a constant
641 /// which we can fold and convert to a boolean condition using
642 /// any crazy technique that we want to, even if the expression has
643 /// side-effects.
644 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
645 bool InConstantContext = false) const;
646
648 SE_NoSideEffects, ///< Strictly evaluate the expression.
649 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
650 ///< arbitrary unmodeled side effects.
651 SE_AllowSideEffects ///< Allow any unmodeled side effect.
652 };
653
654 /// EvaluateAsInt - Return true if this is a constant which we can fold and
655 /// convert to an integer, using any crazy technique that we want to.
656 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
657 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
658 bool InConstantContext = false) const;
659
660 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
661 /// convert to a floating point value, using any crazy technique that we
662 /// want to.
663 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
664 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
665 bool InConstantContext = false) const;
666
667 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
668 /// and convert to a fixed point value.
669 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
670 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
671 bool InConstantContext = false) const;
672
673 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
674 /// constant folded without side-effects, but discard the result.
675 bool isEvaluatable(const ASTContext &Ctx,
676 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
677
678 /// HasSideEffects - This routine returns true for all those expressions
679 /// which have any effect other than producing a value. Example is a function
680 /// call, volatile variable read, or throwing an exception. If
681 /// IncludePossibleEffects is false, this call treats certain expressions with
682 /// potential side effects (such as function call-like expressions,
683 /// instantiation-dependent expressions, or invocations from a macro) as not
684 /// having side effects.
685 bool HasSideEffects(const ASTContext &Ctx,
686 bool IncludePossibleEffects = true) const;
687
688 /// Determine whether this expression involves a call to any function
689 /// that is not trivial.
690 bool hasNonTrivialCall(const ASTContext &Ctx) const;
691
692 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
693 /// integer. This must be called on an expression that constant folds to an
694 /// integer.
695 llvm::APSInt EvaluateKnownConstInt(
696 const ASTContext &Ctx,
698
700 const ASTContext &Ctx,
702
703 void EvaluateForOverflow(const ASTContext &Ctx) const;
704
705 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
706 /// lvalue with link time known address, with no side-effects.
707 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
708 bool InConstantContext = false) const;
709
710 /// EvaluateAsInitializer - Evaluate an expression as if it were the
711 /// initializer of the given declaration. Returns true if the initializer
712 /// can be folded to a constant, and produces any relevant notes. In C++11,
713 /// notes will be produced if the expression is not a constant expression.
715 const VarDecl *VD,
717 bool IsConstantInitializer) const;
718
719 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
720 /// of a call to the given function with the given arguments, inside an
721 /// unevaluated context. Returns true if the expression could be folded to a
722 /// constant.
724 const FunctionDecl *Callee,
726 const Expr *This = nullptr) const;
727
728 enum class ConstantExprKind {
729 /// An integer constant expression (an array bound, enumerator, case value,
730 /// bit-field width, or similar) or similar.
731 Normal,
732 /// A non-class template argument. Such a value is only used for mangling,
733 /// not for code generation, so can refer to dllimported functions.
735 /// A class template argument. Such a value is used for code generation.
737 /// An immediate invocation. The destruction of the end result of this
738 /// evaluation is not part of the evaluation, but all other temporaries
739 /// are destroyed.
741 };
742
743 /// Evaluate an expression that is required to be a constant expression. Does
744 /// not check the syntactic constraints for C and C++98 constant expressions.
746 EvalResult &Result, const ASTContext &Ctx,
747 ConstantExprKind Kind = ConstantExprKind::Normal) const;
748
749 /// If the current Expr is a pointer, this will try to statically
750 /// determine the number of bytes available where the pointer is pointing.
751 /// Returns true if all of the above holds and we were able to figure out the
752 /// size, false otherwise.
753 ///
754 /// \param Type - How to evaluate the size of the Expr, as defined by the
755 /// "type" parameter of __builtin_object_size
756 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
757 unsigned Type) const;
758
759 /// If the current Expr is a pointer, this will try to statically
760 /// determine the strlen of the string pointed to.
761 /// Returns true if all of the above holds and we were able to figure out the
762 /// strlen, false otherwise.
763 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
764
765 /// Enumeration used to describe the kind of Null pointer constant
766 /// returned from \c isNullPointerConstant().
768 /// Expression is not a Null pointer constant.
770
771 /// Expression is a Null pointer constant built from a zero integer
772 /// expression that is not a simple, possibly parenthesized, zero literal.
773 /// C++ Core Issue 903 will classify these expressions as "not pointers"
774 /// once it is adopted.
775 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
777
778 /// Expression is a Null pointer constant built from a literal zero.
780
781 /// Expression is a C++11 nullptr.
783
784 /// Expression is a GNU-style __null constant.
786 };
787
788 /// Enumeration used to describe how \c isNullPointerConstant()
789 /// should cope with value-dependent expressions.
791 /// Specifies that the expression should never be value-dependent.
793
794 /// Specifies that a value-dependent expression of integral or
795 /// dependent type should be considered a null pointer constant.
797
798 /// Specifies that a value-dependent expression should be considered
799 /// to never be a null pointer constant.
801 };
802
803 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
804 /// a Null pointer constant. The return value can further distinguish the
805 /// kind of NULL pointer constant that was detected.
807 ASTContext &Ctx,
809
810 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
811 /// write barrier.
812 bool isOBJCGCCandidate(ASTContext &Ctx) const;
813
814 /// Returns true if this expression is a bound member function.
815 bool isBoundMemberFunction(ASTContext &Ctx) const;
816
817 /// Given an expression of bound-member type, find the type
818 /// of the member. Returns null if this is an *overloaded* bound
819 /// member expression.
820 static QualType findBoundMemberType(const Expr *expr);
821
822 /// Skip past any invisible AST nodes which might surround this
823 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
824 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
825 /// implicit conversions.
828 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
829 }
830
831 /// Skip past any implicit casts which might surround this expression until
832 /// reaching a fixed point. Skips:
833 /// * ImplicitCastExpr
834 /// * FullExpr
835 Expr *IgnoreImpCasts() LLVM_READONLY;
836 const Expr *IgnoreImpCasts() const {
837 return const_cast<Expr *>(this)->IgnoreImpCasts();
838 }
839
840 /// Skip past any casts which might surround this expression until reaching
841 /// a fixed point. Skips:
842 /// * CastExpr
843 /// * FullExpr
844 /// * MaterializeTemporaryExpr
845 /// * SubstNonTypeTemplateParmExpr
846 Expr *IgnoreCasts() LLVM_READONLY;
847 const Expr *IgnoreCasts() const {
848 return const_cast<Expr *>(this)->IgnoreCasts();
849 }
850
851 /// Skip past any implicit AST nodes which might surround this expression
852 /// until reaching a fixed point. Skips:
853 /// * What IgnoreImpCasts() skips
854 /// * MaterializeTemporaryExpr
855 /// * CXXBindTemporaryExpr
856 Expr *IgnoreImplicit() LLVM_READONLY;
857 const Expr *IgnoreImplicit() const {
858 return const_cast<Expr *>(this)->IgnoreImplicit();
859 }
860
861 /// Skip past any implicit AST nodes which might surround this expression
862 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
863 /// also skips over implicit calls to constructors and conversion functions.
864 ///
865 /// FIXME: Should IgnoreImplicit do this?
866 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
868 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
869 }
870
871 /// Skip past any parentheses which might surround this expression until
872 /// reaching a fixed point. Skips:
873 /// * ParenExpr
874 /// * UnaryOperator if `UO_Extension`
875 /// * GenericSelectionExpr if `!isResultDependent()`
876 /// * ChooseExpr if `!isConditionDependent()`
877 /// * ConstantExpr
878 Expr *IgnoreParens() LLVM_READONLY;
879 const Expr *IgnoreParens() const {
880 return const_cast<Expr *>(this)->IgnoreParens();
881 }
882
883 /// Skip past any parentheses and implicit casts which might surround this
884 /// expression until reaching a fixed point.
885 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
886 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
887 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
888 /// * What IgnoreParens() skips
889 /// * What IgnoreImpCasts() skips
890 /// * MaterializeTemporaryExpr
891 /// * SubstNonTypeTemplateParmExpr
892 Expr *IgnoreParenImpCasts() LLVM_READONLY;
893 const Expr *IgnoreParenImpCasts() const {
894 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
895 }
896
897 /// Skip past any parentheses and casts which might surround this expression
898 /// until reaching a fixed point. Skips:
899 /// * What IgnoreParens() skips
900 /// * What IgnoreCasts() skips
901 Expr *IgnoreParenCasts() LLVM_READONLY;
902 const Expr *IgnoreParenCasts() const {
903 return const_cast<Expr *>(this)->IgnoreParenCasts();
904 }
905
906 /// Skip conversion operators. If this Expr is a call to a conversion
907 /// operator, return the argument.
910 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
911 }
912
913 /// Skip past any parentheses and lvalue casts which might surround this
914 /// expression until reaching a fixed point. Skips:
915 /// * What IgnoreParens() skips
916 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
917 /// casts are skipped
918 /// FIXME: This is intended purely as a temporary workaround for code
919 /// that hasn't yet been rewritten to do the right thing about those
920 /// casts, and may disappear along with the last internal use.
921 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
923 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
924 }
925
926 /// Skip past any parentheses and casts which do not change the value
927 /// (including ptr->int casts of the same size) until reaching a fixed point.
928 /// Skips:
929 /// * What IgnoreParens() skips
930 /// * CastExpr which do not change the value
931 /// * SubstNonTypeTemplateParmExpr
932 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
933 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
934 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
935 }
936
937 /// Skip past any parentheses and derived-to-base casts until reaching a
938 /// fixed point. Skips:
939 /// * What IgnoreParens() skips
940 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
941 /// CK_UncheckedDerivedToBase and CK_NoOp)
942 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
943 const Expr *IgnoreParenBaseCasts() const {
944 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
945 }
946
947 /// Determine whether this expression is a default function argument.
948 ///
949 /// Default arguments are implicitly generated in the abstract syntax tree
950 /// by semantic analysis for function calls, object constructions, etc. in
951 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
952 /// this routine also looks through any implicit casts to determine whether
953 /// the expression is a default argument.
954 bool isDefaultArgument() const;
955
956 /// Determine whether the result of this expression is a
957 /// temporary object of the given class type.
958 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
959
960 /// Whether this expression is an implicit reference to 'this' in C++.
961 bool isImplicitCXXThis() const;
962
964
965 /// For an expression of class type or pointer to class type,
966 /// return the most derived class decl the expression is known to refer to.
967 ///
968 /// If this expression is a cast, this method looks through it to find the
969 /// most derived decl that can be inferred from the expression.
970 /// This is valid because derived-to-base conversions have undefined
971 /// behavior if the object isn't dynamically of the derived type.
973
974 /// Get the inner expression that determines the best dynamic class.
975 /// If this is a prvalue, we guarantee that it is of the most-derived type
976 /// for the object itself.
977 const Expr *getBestDynamicClassTypeExpr() const;
978
979 /// Walk outwards from an expression we want to bind a reference to and
980 /// find the expression whose lifetime needs to be extended. Record
981 /// the LHSs of comma expressions and adjustments needed along the path.
984 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
988 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
989 }
990
991 /// Checks that the two Expr's will refer to the same value as a comparison
992 /// operand. The caller must ensure that the values referenced by the Expr's
993 /// are not modified between E1 and E2 or the result my be invalid.
994 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
995
996 static bool classof(const Stmt *T) {
997 return T->getStmtClass() >= firstExprConstant &&
998 T->getStmtClass() <= lastExprConstant;
999 }
1000};
1001// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1002// Expr. Verify that we got it right.
1004 llvm::detail::ConstantLog2<alignof(Expr)>::value,
1005 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1006
1008
1009//===----------------------------------------------------------------------===//
1010// Wrapper Expressions.
1011//===----------------------------------------------------------------------===//
1012
1013/// FullExpr - Represents a "full-expression" node.
1014class FullExpr : public Expr {
1015protected:
1017
1019 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1020 subexpr->getObjectKind()),
1021 SubExpr(subexpr) {
1023 }
1025 : Expr(SC, Empty) {}
1026public:
1027 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1028 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1029
1030 /// As with any mutator of the AST, be very careful when modifying an
1031 /// existing AST to preserve its invariants.
1032 void setSubExpr(Expr *E) { SubExpr = E; }
1033
1034 static bool classof(const Stmt *T) {
1035 return T->getStmtClass() >= firstFullExprConstant &&
1036 T->getStmtClass() <= lastFullExprConstant;
1037 }
1038};
1039
1040/// ConstantExpr - An expression that occurs in a constant context and
1041/// optionally the result of evaluating the expression.
1042class ConstantExpr final
1043 : public FullExpr,
1044 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1045 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1046 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1047 "for tail-allocated storage");
1048 friend TrailingObjects;
1049 friend class ASTStmtReader;
1050 friend class ASTStmtWriter;
1051
1052public:
1053 /// Describes the kind of result that can be tail-allocated.
1055
1056private:
1057 size_t numTrailingObjects(OverloadToken<APValue>) const {
1058 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
1059 }
1060 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1061 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
1062 }
1063
1064 uint64_t &Int64Result() {
1065 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
1066 "invalid accessor");
1067 return *getTrailingObjects<uint64_t>();
1068 }
1069 const uint64_t &Int64Result() const {
1070 return const_cast<ConstantExpr *>(this)->Int64Result();
1071 }
1072 APValue &APValueResult() {
1073 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
1074 "invalid accessor");
1075 return *getTrailingObjects<APValue>();
1076 }
1077 APValue &APValueResult() const {
1078 return const_cast<ConstantExpr *>(this)->APValueResult();
1079 }
1080
1081 ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
1082 bool IsImmediateInvocation);
1083 ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
1084
1085public:
1086 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1087 const APValue &Result);
1088 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1089 ResultStorageKind Storage = RSK_None,
1090 bool IsImmediateInvocation = false);
1091 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1092 ResultStorageKind StorageKind);
1093
1094 static ResultStorageKind getStorageKind(const APValue &Value);
1095 static ResultStorageKind getStorageKind(const Type *T,
1096 const ASTContext &Context);
1097
1098 SourceLocation getBeginLoc() const LLVM_READONLY {
1099 return SubExpr->getBeginLoc();
1100 }
1101 SourceLocation getEndLoc() const LLVM_READONLY {
1102 return SubExpr->getEndLoc();
1103 }
1104
1105 static bool classof(const Stmt *T) {
1106 return T->getStmtClass() == ConstantExprClass;
1107 }
1108
1109 void SetResult(APValue Value, const ASTContext &Context) {
1110 MoveIntoResult(Value, Context);
1111 }
1112 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1113
1115 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1116 }
1118 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1119 }
1121 return ConstantExprBits.IsImmediateInvocation;
1122 }
1123 bool hasAPValueResult() const {
1124 return ConstantExprBits.APValueKind != APValue::None;
1125 }
1126 APValue getAPValueResult() const;
1127 APValue &getResultAsAPValue() const { return APValueResult(); }
1128 llvm::APSInt getResultAsAPSInt() const;
1129 // Iterators
1132 return const_child_range(&SubExpr, &SubExpr + 1);
1133 }
1134};
1135
1136//===----------------------------------------------------------------------===//
1137// Primary Expressions.
1138//===----------------------------------------------------------------------===//
1139
1140/// OpaqueValueExpr - An expression referring to an opaque object of a
1141/// fixed type and value class. These don't correspond to concrete
1142/// syntax; instead they're used to express operations (usually copy
1143/// operations) on values whose source is generally obvious from
1144/// context.
1145class OpaqueValueExpr : public Expr {
1146 friend class ASTStmtReader;
1147 Expr *SourceExpr;
1148
1149public:
1151 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1152 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1153 setIsUnique(false);
1154 OpaqueValueExprBits.Loc = Loc;
1156 }
1157
1158 /// Given an expression which invokes a copy constructor --- i.e. a
1159 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1160 /// find the OpaqueValueExpr that's the source of the construction.
1161 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1162
1164 : Expr(OpaqueValueExprClass, Empty) {}
1165
1166 /// Retrieve the location of this expression.
1168
1169 SourceLocation getBeginLoc() const LLVM_READONLY {
1170 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1171 }
1172 SourceLocation getEndLoc() const LLVM_READONLY {
1173 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1174 }
1175 SourceLocation getExprLoc() const LLVM_READONLY {
1176 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1177 }
1178
1181 }
1182
1185 }
1186
1187 /// The source expression of an opaque value expression is the
1188 /// expression which originally generated the value. This is
1189 /// provided as a convenience for analyses that don't wish to
1190 /// precisely model the execution behavior of the program.
1191 ///
1192 /// The source expression is typically set when building the
1193 /// expression which binds the opaque value expression in the first
1194 /// place.
1195 Expr *getSourceExpr() const { return SourceExpr; }
1196
1197 void setIsUnique(bool V) {
1198 assert((!V || SourceExpr) &&
1199 "unique OVEs are expected to have source expressions");
1200 OpaqueValueExprBits.IsUnique = V;
1201 }
1202
1203 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1204
1205 static bool classof(const Stmt *T) {
1206 return T->getStmtClass() == OpaqueValueExprClass;
1207 }
1208};
1209
1210/// A reference to a declared variable, function, enum, etc.
1211/// [C99 6.5.1p2]
1212///
1213/// This encodes all the information about how a declaration is referenced
1214/// within an expression.
1215///
1216/// There are several optional constructs attached to DeclRefExprs only when
1217/// they apply in order to conserve memory. These are laid out past the end of
1218/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1219///
1220/// DeclRefExprBits.HasQualifier:
1221/// Specifies when this declaration reference expression has a C++
1222/// nested-name-specifier.
1223/// DeclRefExprBits.HasFoundDecl:
1224/// Specifies when this declaration reference expression has a record of
1225/// a NamedDecl (different from the referenced ValueDecl) which was found
1226/// during name lookup and/or overload resolution.
1227/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1228/// Specifies when this declaration reference expression has an explicit
1229/// C++ template keyword and/or template argument list.
1230/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1231/// Specifies when this declaration reference expression (validly)
1232/// refers to an enclosed local or a captured variable.
1233class DeclRefExpr final
1234 : public Expr,
1235 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1236 NamedDecl *, ASTTemplateKWAndArgsInfo,
1237 TemplateArgumentLoc> {
1238 friend class ASTStmtReader;
1239 friend class ASTStmtWriter;
1240 friend TrailingObjects;
1241
1242 /// The declaration that we are referencing.
1243 ValueDecl *D;
1244
1245 /// Provides source/type location info for the declaration name
1246 /// embedded in D.
1247 DeclarationNameLoc DNLoc;
1248
1249 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1250 return hasQualifier();
1251 }
1252
1253 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1254 return hasFoundDecl();
1255 }
1256
1257 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1258 return hasTemplateKWAndArgsInfo();
1259 }
1260
1261 /// Test whether there is a distinct FoundDecl attached to the end of
1262 /// this DRE.
1263 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1264
1265 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1266 SourceLocation TemplateKWLoc, ValueDecl *D,
1267 bool RefersToEnlosingVariableOrCapture,
1268 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1269 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1271
1272 /// Construct an empty declaration reference expression.
1273 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1274
1275public:
1276 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1277 bool RefersToEnclosingVariableOrCapture, QualType T,
1278 ExprValueKind VK, SourceLocation L,
1279 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1280 NonOdrUseReason NOUR = NOUR_None);
1281
1282 static DeclRefExpr *
1283 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1284 SourceLocation TemplateKWLoc, ValueDecl *D,
1285 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1286 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1287 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1288 NonOdrUseReason NOUR = NOUR_None);
1289
1290 static DeclRefExpr *
1291 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1292 SourceLocation TemplateKWLoc, ValueDecl *D,
1293 bool RefersToEnclosingVariableOrCapture,
1294 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1295 NamedDecl *FoundD = nullptr,
1296 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1297 NonOdrUseReason NOUR = NOUR_None);
1298
1299 /// Construct an empty declaration reference expression.
1300 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1301 bool HasFoundDecl,
1302 bool HasTemplateKWAndArgsInfo,
1303 unsigned NumTemplateArgs);
1304
1305 ValueDecl *getDecl() { return D; }
1306 const ValueDecl *getDecl() const { return D; }
1307 void setDecl(ValueDecl *NewD);
1308
1310 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1311 }
1312
1315 SourceLocation getBeginLoc() const LLVM_READONLY;
1316 SourceLocation getEndLoc() const LLVM_READONLY;
1317
1318 /// Determine whether this declaration reference was preceded by a
1319 /// C++ nested-name-specifier, e.g., \c N::foo.
1320 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1321
1322 /// If the name was qualified, retrieves the nested-name-specifier
1323 /// that precedes the name, with source-location information.
1325 if (!hasQualifier())
1326 return NestedNameSpecifierLoc();
1327 return *getTrailingObjects<NestedNameSpecifierLoc>();
1328 }
1329
1330 /// If the name was qualified, retrieves the nested-name-specifier
1331 /// that precedes the name. Otherwise, returns NULL.
1334 }
1335
1336 /// Get the NamedDecl through which this reference occurred.
1337 ///
1338 /// This Decl may be different from the ValueDecl actually referred to in the
1339 /// presence of using declarations, etc. It always returns non-NULL, and may
1340 /// simple return the ValueDecl when appropriate.
1341
1343 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1344 }
1345
1346 /// Get the NamedDecl through which this reference occurred.
1347 /// See non-const variant.
1348 const NamedDecl *getFoundDecl() const {
1349 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1350 }
1351
1353 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1354 }
1355
1356 /// Retrieve the location of the template keyword preceding
1357 /// this name, if any.
1360 return SourceLocation();
1361 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1362 }
1363
1364 /// Retrieve the location of the left angle bracket starting the
1365 /// explicit template argument list following the name, if any.
1368 return SourceLocation();
1369 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1370 }
1371
1372 /// Retrieve the location of the right angle bracket ending the
1373 /// explicit template argument list following the name, if any.
1376 return SourceLocation();
1377 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1378 }
1379
1380 /// Determines whether the name in this declaration reference
1381 /// was preceded by the template keyword.
1383
1384 /// Determines whether this declaration reference was followed by an
1385 /// explicit template argument list.
1386 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1387
1388 /// Copies the template arguments (if present) into the given
1389 /// structure.
1392 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1393 getTrailingObjects<TemplateArgumentLoc>(), List);
1394 }
1395
1396 /// Retrieve the template arguments provided as part of this
1397 /// template-id.
1400 return nullptr;
1401 return getTrailingObjects<TemplateArgumentLoc>();
1402 }
1403
1404 /// Retrieve the number of template arguments provided as part of this
1405 /// template-id.
1406 unsigned getNumTemplateArgs() const {
1408 return 0;
1409 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1410 }
1411
1413 return {getTemplateArgs(), getNumTemplateArgs()};
1414 }
1415
1416 /// Returns true if this expression refers to a function that
1417 /// was resolved from an overloaded set having size greater than 1.
1419 return DeclRefExprBits.HadMultipleCandidates;
1420 }
1421 /// Sets the flag telling whether this expression refers to
1422 /// a function that was resolved from an overloaded set having size
1423 /// greater than 1.
1424 void setHadMultipleCandidates(bool V = true) {
1425 DeclRefExprBits.HadMultipleCandidates = V;
1426 }
1427
1428 /// Is this expression a non-odr-use reference, and if so, why?
1430 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1431 }
1432
1433 /// Does this DeclRefExpr refer to an enclosing local or a captured
1434 /// variable?
1436 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1437 }
1438
1440 return DeclRefExprBits.IsImmediateEscalating;
1441 }
1442
1444 DeclRefExprBits.IsImmediateEscalating = Set;
1445 }
1446
1447 static bool classof(const Stmt *T) {
1448 return T->getStmtClass() == DeclRefExprClass;
1449 }
1450
1451 // Iterators
1454 }
1455
1458 }
1459};
1460
1461/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1462/// leaking memory.
1463///
1464/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1465/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1466/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1467/// the APFloat/APInt values will never get freed. APNumericStorage uses
1468/// ASTContext's allocator for memory allocation.
1470 union {
1471 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1472 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1473 };
1474 unsigned BitWidth;
1475
1476 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1477
1478 APNumericStorage(const APNumericStorage &) = delete;
1479 void operator=(const APNumericStorage &) = delete;
1480
1481protected:
1482 APNumericStorage() : VAL(0), BitWidth(0) { }
1483
1484 llvm::APInt getIntValue() const {
1485 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1486 if (NumWords > 1)
1487 return llvm::APInt(BitWidth, NumWords, pVal);
1488 else
1489 return llvm::APInt(BitWidth, VAL);
1490 }
1491 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1492};
1493
1495public:
1496 llvm::APInt getValue() const { return getIntValue(); }
1497 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1498 setIntValue(C, Val);
1499 }
1500};
1501
1503public:
1504 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1505 return llvm::APFloat(Semantics, getIntValue());
1506 }
1507 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1508 setIntValue(C, Val.bitcastToAPInt());
1509 }
1510};
1511
1512class IntegerLiteral : public Expr, public APIntStorage {
1513 SourceLocation Loc;
1514
1515 /// Construct an empty integer literal.
1516 explicit IntegerLiteral(EmptyShell Empty)
1517 : Expr(IntegerLiteralClass, Empty) { }
1518
1519public:
1520 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1521 // or UnsignedLongLongTy
1522 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1523 SourceLocation l);
1524
1525 /// Returns a new integer literal with value 'V' and type 'type'.
1526 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1527 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1528 /// \param V - the value that the returned integer literal contains.
1529 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1531 /// Returns a new empty integer literal.
1532 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1533
1534 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1535 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1536
1537 /// Retrieve the location of the literal.
1538 SourceLocation getLocation() const { return Loc; }
1539
1540 void setLocation(SourceLocation Location) { Loc = Location; }
1541
1542 static bool classof(const Stmt *T) {
1543 return T->getStmtClass() == IntegerLiteralClass;
1544 }
1545
1546 // Iterators
1549 }
1552 }
1553};
1554
1555class FixedPointLiteral : public Expr, public APIntStorage {
1556 SourceLocation Loc;
1557 unsigned Scale;
1558
1559 /// \brief Construct an empty fixed-point literal.
1560 explicit FixedPointLiteral(EmptyShell Empty)
1561 : Expr(FixedPointLiteralClass, Empty) {}
1562
1563 public:
1564 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1565 SourceLocation l, unsigned Scale);
1566
1567 // Store the int as is without any bit shifting.
1569 const llvm::APInt &V,
1571 unsigned Scale);
1572
1573 /// Returns an empty fixed-point literal.
1574 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1575
1576 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1577 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1578
1579 /// \brief Retrieve the location of the literal.
1580 SourceLocation getLocation() const { return Loc; }
1581
1582 void setLocation(SourceLocation Location) { Loc = Location; }
1583
1584 unsigned getScale() const { return Scale; }
1585 void setScale(unsigned S) { Scale = S; }
1586
1587 static bool classof(const Stmt *T) {
1588 return T->getStmtClass() == FixedPointLiteralClass;
1589 }
1590
1591 std::string getValueAsString(unsigned Radix) const;
1592
1593 // Iterators
1596 }
1599 }
1600};
1601
1602class CharacterLiteral : public Expr {
1603public:
1609 UTF32
1611
1612private:
1613 unsigned Value;
1614 SourceLocation Loc;
1615public:
1616 // type should be IntTy
1619 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1620 Value(value), Loc(l) {
1621 CharacterLiteralBits.Kind = kind;
1622 setDependence(ExprDependence::None);
1623 }
1624
1625 /// Construct an empty character literal.
1626 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1627
1628 SourceLocation getLocation() const { return Loc; }
1630 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1631 }
1632
1633 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1634 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1635
1636 unsigned getValue() const { return Value; }
1637
1638 void setLocation(SourceLocation Location) { Loc = Location; }
1639 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1640 void setValue(unsigned Val) { Value = Val; }
1641
1642 static bool classof(const Stmt *T) {
1643 return T->getStmtClass() == CharacterLiteralClass;
1644 }
1645
1646 static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
1647
1648 // Iterators
1651 }
1654 }
1655};
1656
1657class FloatingLiteral : public Expr, private APFloatStorage {
1658 SourceLocation Loc;
1659
1660 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1662
1663 /// Construct an empty floating-point literal.
1664 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1665
1666public:
1667 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1668 bool isexact, QualType Type, SourceLocation L);
1669 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1670
1671 llvm::APFloat getValue() const {
1673 }
1674 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1675 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1677 }
1678
1679 /// Get a raw enumeration value representing the floating-point semantics of
1680 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1681 llvm::APFloatBase::Semantics getRawSemantics() const {
1682 return static_cast<llvm::APFloatBase::Semantics>(
1683 FloatingLiteralBits.Semantics);
1684 }
1685
1686 /// Set the raw enumeration value representing the floating-point semantics of
1687 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1688 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1689 FloatingLiteralBits.Semantics = Sem;
1690 }
1691
1692 /// Return the APFloat semantics this literal uses.
1693 const llvm::fltSemantics &getSemantics() const {
1694 return llvm::APFloatBase::EnumToSemantics(
1695 static_cast<llvm::APFloatBase::Semantics>(
1696 FloatingLiteralBits.Semantics));
1697 }
1698
1699 /// Set the APFloat semantics this literal uses.
1700 void setSemantics(const llvm::fltSemantics &Sem) {
1701 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1702 }
1703
1704 bool isExact() const { return FloatingLiteralBits.IsExact; }
1705 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1706
1707 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1708 /// double. Note that this may cause loss of precision, but is useful for
1709 /// debugging dumps, etc.
1710 double getValueAsApproximateDouble() const;
1711
1712 SourceLocation getLocation() const { return Loc; }
1713 void setLocation(SourceLocation L) { Loc = L; }
1714
1715 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1716 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1717
1718 static bool classof(const Stmt *T) {
1719 return T->getStmtClass() == FloatingLiteralClass;
1720 }
1721
1722 // Iterators
1725 }
1728 }
1729};
1730
1731/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1732/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1733/// IntegerLiteral classes. Instances of this class always have a Complex type
1734/// whose element type matches the subexpression.
1735///
1736class ImaginaryLiteral : public Expr {
1737 Stmt *Val;
1738public:
1740 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1741 setDependence(ExprDependence::None);
1742 }
1743
1744 /// Build an empty imaginary literal.
1746 : Expr(ImaginaryLiteralClass, Empty) { }
1747
1748 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1749 Expr *getSubExpr() { return cast<Expr>(Val); }
1750 void setSubExpr(Expr *E) { Val = E; }
1751
1752 SourceLocation getBeginLoc() const LLVM_READONLY {
1753 return Val->getBeginLoc();
1754 }
1755 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1756
1757 static bool classof(const Stmt *T) {
1758 return T->getStmtClass() == ImaginaryLiteralClass;
1759 }
1760
1761 // Iterators
1762 child_range children() { return child_range(&Val, &Val+1); }
1764 return const_child_range(&Val, &Val + 1);
1765 }
1766};
1767
1768/// StringLiteral - This represents a string literal expression, e.g. "foo"
1769/// or L"bar" (wide strings). The actual string data can be obtained with
1770/// getBytes() and is NOT null-terminated. The length of the string data is
1771/// determined by calling getByteLength().
1772///
1773/// The C type for a string is always a ConstantArrayType. In C++, the char
1774/// type is const qualified, in C it is not.
1775///
1776/// Note that strings in C can be formed by concatenation of multiple string
1777/// literal pptokens in translation phase #6. This keeps track of the locations
1778/// of each of these pieces.
1779///
1780/// Strings in C can also be truncated and extended by assigning into arrays,
1781/// e.g. with constructs like:
1782/// char X[2] = "foobar";
1783/// In this case, getByteLength() will return 6, but the string literal will
1784/// have type "char[2]".
1785class StringLiteral final
1786 : public Expr,
1787 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1788 char> {
1789 friend class ASTStmtReader;
1790 friend TrailingObjects;
1791
1792 /// StringLiteral is followed by several trailing objects. They are in order:
1793 ///
1794 /// * A single unsigned storing the length in characters of this string. The
1795 /// length in bytes is this length times the width of a single character.
1796 /// Always present and stored as a trailing objects because storing it in
1797 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1798 /// due to alignment requirements. If you add some data to StringLiteral,
1799 /// consider moving it inside StringLiteral.
1800 ///
1801 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1802 /// token this string is made of.
1803 ///
1804 /// * An array of getByteLength() char used to store the string data.
1805
1806public:
1808
1809private:
1810 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1811 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1812 return getNumConcatenated();
1813 }
1814
1815 unsigned numTrailingObjects(OverloadToken<char>) const {
1816 return getByteLength();
1817 }
1818
1819 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1820 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1821
1822 const uint16_t *getStrDataAsUInt16() const {
1823 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1824 }
1825
1826 const uint32_t *getStrDataAsUInt32() const {
1827 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1828 }
1829
1830 /// Build a string literal.
1831 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1832 bool Pascal, QualType Ty, const SourceLocation *Loc,
1833 unsigned NumConcatenated);
1834
1835 /// Build an empty string literal.
1836 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1837 unsigned CharByteWidth);
1838
1839 /// Map a target and string kind to the appropriate character width.
1840 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1841
1842 /// Set one of the string literal token.
1843 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1844 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1845 getTrailingObjects<SourceLocation>()[TokNum] = L;
1846 }
1847
1848public:
1849 /// This is the "fully general" constructor that allows representation of
1850 /// strings formed from multiple concatenated tokens.
1851 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1852 StringKind Kind, bool Pascal, QualType Ty,
1853 const SourceLocation *Loc,
1854 unsigned NumConcatenated);
1855
1856 /// Simple constructor for string literals made from one token.
1857 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1858 StringKind Kind, bool Pascal, QualType Ty,
1859 SourceLocation Loc) {
1860 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1861 }
1862
1863 /// Construct an empty string literal.
1864 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1865 unsigned NumConcatenated, unsigned Length,
1866 unsigned CharByteWidth);
1867
1868 StringRef getString() const {
1869 assert(getCharByteWidth() == 1 &&
1870 "This function is used in places that assume strings use char");
1871 return StringRef(getStrDataAsChar(), getByteLength());
1872 }
1873
1874 /// Allow access to clients that need the byte representation, such as
1875 /// ASTWriterStmt::VisitStringLiteral().
1876 StringRef getBytes() const {
1877 // FIXME: StringRef may not be the right type to use as a result for this.
1878 return StringRef(getStrDataAsChar(), getByteLength());
1879 }
1880
1881 void outputString(raw_ostream &OS) const;
1882
1883 uint32_t getCodeUnit(size_t i) const {
1884 assert(i < getLength() && "out of bounds access");
1885 switch (getCharByteWidth()) {
1886 case 1:
1887 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1888 case 2:
1889 return getStrDataAsUInt16()[i];
1890 case 4:
1891 return getStrDataAsUInt32()[i];
1892 }
1893 llvm_unreachable("Unsupported character width!");
1894 }
1895
1896 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1897 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1898 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1899
1901 return static_cast<StringKind>(StringLiteralBits.Kind);
1902 }
1903
1904 bool isOrdinary() const { return getKind() == Ordinary; }
1905 bool isWide() const { return getKind() == Wide; }
1906 bool isUTF8() const { return getKind() == UTF8; }
1907 bool isUTF16() const { return getKind() == UTF16; }
1908 bool isUTF32() const { return getKind() == UTF32; }
1909 bool isPascal() const { return StringLiteralBits.IsPascal; }
1910
1911 bool containsNonAscii() const {
1912 for (auto c : getString())
1913 if (!isASCII(c))
1914 return true;
1915 return false;
1916 }
1917
1919 for (auto c : getString())
1920 if (!isASCII(c) || !c)
1921 return true;
1922 return false;
1923 }
1924
1925 /// getNumConcatenated - Get the number of string literal tokens that were
1926 /// concatenated in translation phase #6 to form this string literal.
1927 unsigned getNumConcatenated() const {
1928 return StringLiteralBits.NumConcatenated;
1929 }
1930
1931 /// Get one of the string literal token.
1932 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1933 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1934 return getTrailingObjects<SourceLocation>()[TokNum];
1935 }
1936
1937 /// getLocationOfByte - Return a source location that points to the specified
1938 /// byte of this string literal.
1939 ///
1940 /// Strings are amazingly complex. They can be formed from multiple tokens
1941 /// and can have escape sequences in them in addition to the usual trigraph
1942 /// and escaped newline business. This routine handles this complexity.
1943 ///
1945 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1946 const LangOptions &Features, const TargetInfo &Target,
1947 unsigned *StartToken = nullptr,
1948 unsigned *StartTokenByteOffset = nullptr) const;
1949
1951
1953 return getTrailingObjects<SourceLocation>();
1954 }
1955
1957 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1958 }
1959
1960 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1961 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1962
1963 static bool classof(const Stmt *T) {
1964 return T->getStmtClass() == StringLiteralClass;
1965 }
1966
1967 // Iterators
1970 }
1973 }
1974};
1975
1976/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1978 : public Expr,
1979 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1980 friend class ASTStmtReader;
1981 friend TrailingObjects;
1982
1983 // PredefinedExpr is optionally followed by a single trailing
1984 // "Stmt *" for the predefined identifier. It is present if and only if
1985 // hasFunctionName() is true and is always a "StringLiteral *".
1986
1987public:
1991 LFunction, // Same as Function, but as wide string.
1994 LFuncSig, // Same as FuncSig, but as wide string
1996 /// The same as PrettyFunction, except that the
1997 /// 'virtual' keyword is omitted for virtual member functions.
2000
2001private:
2003 bool IsTransparent, StringLiteral *SL);
2004
2005 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
2006
2007 /// True if this PredefinedExpr has storage for a function name.
2008 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
2009
2010 void setFunctionName(StringLiteral *SL) {
2011 assert(hasFunctionName() &&
2012 "This PredefinedExpr has no storage for a function name!");
2013 *getTrailingObjects<Stmt *>() = SL;
2014 }
2015
2016public:
2017 /// Create a PredefinedExpr.
2018 ///
2019 /// If IsTransparent, the PredefinedExpr is transparently handled as a
2020 /// StringLiteral.
2021 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
2022 QualType FNTy, IdentKind IK, bool IsTransparent,
2023 StringLiteral *SL);
2024
2025 /// Create an empty PredefinedExpr.
2026 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
2027 bool HasFunctionName);
2028
2030 return static_cast<IdentKind>(PredefinedExprBits.Kind);
2031 }
2032
2033 bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2034
2037
2039 return hasFunctionName()
2040 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2041 : nullptr;
2042 }
2043
2045 return hasFunctionName()
2046 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2047 : nullptr;
2048 }
2049
2050 static StringRef getIdentKindName(IdentKind IK);
2051 StringRef getIdentKindName() const {
2053 }
2054
2055 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
2056
2059
2060 static bool classof(const Stmt *T) {
2061 return T->getStmtClass() == PredefinedExprClass;
2062 }
2063
2064 // Iterators
2066 return child_range(getTrailingObjects<Stmt *>(),
2067 getTrailingObjects<Stmt *>() + hasFunctionName());
2068 }
2069
2071 return const_child_range(getTrailingObjects<Stmt *>(),
2072 getTrailingObjects<Stmt *>() + hasFunctionName());
2073 }
2074};
2075
2076// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2077// type-id, and at CodeGen time emits a unique string representation of the
2078// type in a way that permits us to properly encode information about the SYCL
2079// kernels.
2080class SYCLUniqueStableNameExpr final : public Expr {
2081 friend class ASTStmtReader;
2082 SourceLocation OpLoc, LParen, RParen;
2084
2087 SourceLocation RParen, QualType ResultTy,
2088 TypeSourceInfo *TSI);
2089
2090 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2091
2092 void setLocation(SourceLocation L) { OpLoc = L; }
2093 void setLParenLocation(SourceLocation L) { LParen = L; }
2094 void setRParenLocation(SourceLocation L) { RParen = L; }
2095
2096public:
2098
2099 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2100
2102 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2103 SourceLocation RParen, TypeSourceInfo *TSI);
2104
2106
2108 SourceLocation getEndLoc() const { return RParen; }
2109 SourceLocation getLocation() const { return OpLoc; }
2110 SourceLocation getLParenLocation() const { return LParen; }
2111 SourceLocation getRParenLocation() const { return RParen; }
2112
2113 static bool classof(const Stmt *T) {
2114 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2115 }
2116
2117 // Iterators
2120 }
2121
2124 }
2125
2126 // Convenience function to generate the name of the currently stored type.
2127 std::string ComputeName(ASTContext &Context) const;
2128
2129 // Get the generated name of the type. Note that this only works after all
2130 // kernels have been instantiated.
2131 static std::string ComputeName(ASTContext &Context, QualType Ty);
2132};
2133
2134/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2135/// AST node is only formed if full location information is requested.
2136class ParenExpr : public Expr {
2137 SourceLocation L, R;
2138 Stmt *Val;
2139public:
2141 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2142 val->getObjectKind()),
2143 L(l), R(r), Val(val) {
2145 }
2146
2147 /// Construct an empty parenthesized expression.
2148 explicit ParenExpr(EmptyShell Empty)
2149 : Expr(ParenExprClass, Empty) { }
2150
2151 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2152 Expr *getSubExpr() { return cast<Expr>(Val); }
2153 void setSubExpr(Expr *E) { Val = E; }
2154
2155 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2156 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2157
2158 /// Get the location of the left parentheses '('.
2159 SourceLocation getLParen() const { return L; }
2160 void setLParen(SourceLocation Loc) { L = Loc; }
2161
2162 /// Get the location of the right parentheses ')'.
2163 SourceLocation getRParen() const { return R; }
2164 void setRParen(SourceLocation Loc) { R = Loc; }
2165
2166 static bool classof(const Stmt *T) {
2167 return T->getStmtClass() == ParenExprClass;
2168 }
2169
2170 // Iterators
2171 child_range children() { return child_range(&Val, &Val+1); }
2173 return const_child_range(&Val, &Val + 1);
2174 }
2175};
2176
2177/// UnaryOperator - This represents the unary-expression's (except sizeof and
2178/// alignof), the postinc/postdec operators from postfix-expression, and various
2179/// extensions.
2180///
2181/// Notes on various nodes:
2182///
2183/// Real/Imag - These return the real/imag part of a complex operand. If
2184/// applied to a non-complex value, the former returns its operand and the
2185/// later returns zero in the type of the operand.
2186///
2187class UnaryOperator final
2188 : public Expr,
2189 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2190 Stmt *Val;
2191
2192 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2193 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2194 }
2195
2196 FPOptionsOverride &getTrailingFPFeatures() {
2197 assert(UnaryOperatorBits.HasFPFeatures);
2198 return *getTrailingObjects<FPOptionsOverride>();
2199 }
2200
2201 const FPOptionsOverride &getTrailingFPFeatures() const {
2202 assert(UnaryOperatorBits.HasFPFeatures);
2203 return *getTrailingObjects<FPOptionsOverride>();
2204 }
2205
2206public:
2208
2209protected:
2210 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2212 bool CanOverflow, FPOptionsOverride FPFeatures);
2213
2214 /// Build an empty unary operator.
2215 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2216 : Expr(UnaryOperatorClass, Empty) {
2217 UnaryOperatorBits.Opc = UO_AddrOf;
2218 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2219 }
2220
2221public:
2222 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2223
2224 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2227 bool CanOverflow, FPOptionsOverride FPFeatures);
2228
2230 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2231 }
2232 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2233
2234 Expr *getSubExpr() const { return cast<Expr>(Val); }
2235 void setSubExpr(Expr *E) { Val = E; }
2236
2237 /// getOperatorLoc - Return the location of the operator.
2240
2241 /// Returns true if the unary operator can cause an overflow. For instance,
2242 /// signed int i = INT_MAX; i++;
2243 /// signed char c = CHAR_MAX; c++;
2244 /// Due to integer promotions, c++ is promoted to an int before the postfix
2245 /// increment, and the result is an int that cannot overflow. However, i++
2246 /// can overflow.
2247 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2248 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2249
2250 /// Get the FP contractability status of this operator. Only meaningful for
2251 /// operations on floating point types.
2254 }
2255
2256 /// Get the FENV_ACCESS status of this operator. Only meaningful for
2257 /// operations on floating point types.
2258 bool isFEnvAccessOn(const LangOptions &LO) const {
2259 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2260 }
2261
2262 /// isPostfix - Return true if this is a postfix operation, like x++.
2263 static bool isPostfix(Opcode Op) {
2264 return Op == UO_PostInc || Op == UO_PostDec;
2265 }
2266
2267 /// isPrefix - Return true if this is a prefix operation, like --x.
2268 static bool isPrefix(Opcode Op) {
2269 return Op == UO_PreInc || Op == UO_PreDec;
2270 }
2271
2272 bool isPrefix() const { return isPrefix(getOpcode()); }
2273 bool isPostfix() const { return isPostfix(getOpcode()); }
2274
2275 static bool isIncrementOp(Opcode Op) {
2276 return Op == UO_PreInc || Op == UO_PostInc;
2277 }
2278 bool isIncrementOp() const {
2279 return isIncrementOp(getOpcode());
2280 }
2281
2282 static bool isDecrementOp(Opcode Op) {
2283 return Op == UO_PreDec || Op == UO_PostDec;
2284 }
2285 bool isDecrementOp() const {
2286 return isDecrementOp(getOpcode());
2287 }
2288
2289 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2292 }
2293
2294 static bool isArithmeticOp(Opcode Op) {
2295 return Op >= UO_Plus && Op <= UO_LNot;
2296 }
2297 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2298
2299 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2300 /// corresponds to, e.g. "sizeof" or "[pre]++"
2301 static StringRef getOpcodeStr(Opcode Op);
2302
2303 /// Retrieve the unary opcode that corresponds to the given
2304 /// overloaded operator.
2305 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2306
2307 /// Retrieve the overloaded operator kind that corresponds to
2308 /// the given unary opcode.
2310
2311 SourceLocation getBeginLoc() const LLVM_READONLY {
2312 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2313 }
2314 SourceLocation getEndLoc() const LLVM_READONLY {
2315 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2316 }
2318
2319 static bool classof(const Stmt *T) {
2320 return T->getStmtClass() == UnaryOperatorClass;
2321 }
2322
2323 // Iterators
2324 child_range children() { return child_range(&Val, &Val+1); }
2326 return const_child_range(&Val, &Val + 1);
2327 }
2328
2329 /// Is FPFeatures in Trailing Storage?
2330 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2331
2332 /// Get FPFeatures from trailing storage.
2334 return getTrailingFPFeatures();
2335 }
2336
2337protected:
2338 /// Set FPFeatures in trailing storage, used only by Serialization
2339 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2340
2341public:
2342 /// Get the FP features status of this operator. Only meaningful for
2343 /// operations on floating point types.
2345 if (UnaryOperatorBits.HasFPFeatures)
2348 }
2350 if (UnaryOperatorBits.HasFPFeatures)
2351 return getStoredFPFeatures();
2352 return FPOptionsOverride();
2353 }
2354
2356 friend class ASTReader;
2357 friend class ASTStmtReader;
2358 friend class ASTStmtWriter;
2359};
2360
2361/// Helper class for OffsetOfExpr.
2362
2363// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2365public:
2366 /// The kind of offsetof node we have.
2367 enum Kind {
2368 /// An index into an array.
2369 Array = 0x00,
2370 /// A field.
2371 Field = 0x01,
2372 /// A field in a dependent type, known only by its name.
2374 /// An implicit indirection through a C++ base class, when the
2375 /// field found is in a base class.
2376 Base = 0x03
2378
2379private:
2380 enum { MaskBits = 2, Mask = 0x03 };
2381
2382 /// The source range that covers this part of the designator.
2383 SourceRange Range;
2384
2385 /// The data describing the designator, which comes in three
2386 /// different forms, depending on the lower two bits.
2387 /// - An unsigned index into the array of Expr*'s stored after this node
2388 /// in memory, for [constant-expression] designators.
2389 /// - A FieldDecl*, for references to a known field.
2390 /// - An IdentifierInfo*, for references to a field with a given name
2391 /// when the class type is dependent.
2392 /// - A CXXBaseSpecifier*, for references that look at a field in a
2393 /// base class.
2394 uintptr_t Data;
2395
2396public:
2397 /// Create an offsetof node that refers to an array element.
2398 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2399 SourceLocation RBracketLoc)
2400 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2401
2402 /// Create an offsetof node that refers to a field.
2404 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2405 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2406
2407 /// Create an offsetof node that refers to an identifier.
2409 SourceLocation NameLoc)
2410 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2411 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2412
2413 /// Create an offsetof node that refers into a C++ base class.
2415 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2416
2417 /// Determine what kind of offsetof node this is.
2418 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2419
2420 /// For an array element node, returns the index into the array
2421 /// of expressions.
2422 unsigned getArrayExprIndex() const {
2423 assert(getKind() == Array);
2424 return Data >> 2;
2425 }
2426
2427 /// For a field offsetof node, returns the field.
2429 assert(getKind() == Field);
2430 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2431 }
2432
2433 /// For a field or identifier offsetof node, returns the name of
2434 /// the field.
2436
2437 /// For a base class node, returns the base specifier.
2439 assert(getKind() == Base);
2440 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2441 }
2442
2443 /// Retrieve the source range that covers this offsetof node.
2444 ///
2445 /// For an array element node, the source range contains the locations of
2446 /// the square brackets. For a field or identifier node, the source range
2447 /// contains the location of the period (if there is one) and the
2448 /// identifier.
2449 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2450 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2451 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2452};
2453
2454/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2455/// offsetof(record-type, member-designator). For example, given:
2456/// @code
2457/// struct S {
2458/// float f;
2459/// double d;
2460/// };
2461/// struct T {
2462/// int i;
2463/// struct S s[10];
2464/// };
2465/// @endcode
2466/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2467
2468class OffsetOfExpr final
2469 : public Expr,
2470 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2471 SourceLocation OperatorLoc, RParenLoc;
2472 // Base type;
2473 TypeSourceInfo *TSInfo;
2474 // Number of sub-components (i.e. instances of OffsetOfNode).
2475 unsigned NumComps;
2476 // Number of sub-expressions (i.e. array subscript expressions).
2477 unsigned NumExprs;
2478
2479 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2480 return NumComps;
2481 }
2482
2484 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2486 SourceLocation RParenLoc);
2487
2488 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2489 : Expr(OffsetOfExprClass, EmptyShell()),
2490 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2491
2492public:
2493
2494 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2495 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2497 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2498
2499 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2500 unsigned NumComps, unsigned NumExprs);
2501
2502 /// getOperatorLoc - Return the location of the operator.
2503 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2504 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2505
2506 /// Return the location of the right parentheses.
2507 SourceLocation getRParenLoc() const { return RParenLoc; }
2508 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2509
2511 return TSInfo;
2512 }
2514 TSInfo = tsi;
2515 }
2516
2517 const OffsetOfNode &getComponent(unsigned Idx) const {
2518 assert(Idx < NumComps && "Subscript out of range");
2519 return getTrailingObjects<OffsetOfNode>()[Idx];
2520 }
2521
2522 void setComponent(unsigned Idx, OffsetOfNode ON) {
2523 assert(Idx < NumComps && "Subscript out of range");
2524 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2525 }
2526
2527 unsigned getNumComponents() const {
2528 return NumComps;
2529 }
2530
2531 Expr* getIndexExpr(unsigned Idx) {
2532 assert(Idx < NumExprs && "Subscript out of range");
2533 return getTrailingObjects<Expr *>()[Idx];
2534 }
2535
2536 const Expr *getIndexExpr(unsigned Idx) const {
2537 assert(Idx < NumExprs && "Subscript out of range");
2538 return getTrailingObjects<Expr *>()[Idx];
2539 }
2540
2541 void setIndexExpr(unsigned Idx, Expr* E) {
2542 assert(Idx < NumComps && "Subscript out of range");
2543 getTrailingObjects<Expr *>()[Idx] = E;
2544 }
2545
2546 unsigned getNumExpressions() const {
2547 return NumExprs;
2548 }
2549
2550 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2551 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2552
2553 static bool classof(const Stmt *T) {
2554 return T->getStmtClass() == OffsetOfExprClass;
2555 }
2556
2557 // Iterators
2559 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2560 return child_range(begin, begin + NumExprs);
2561 }
2563 Stmt *const *begin =
2564 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2565 return const_child_range(begin, begin + NumExprs);
2566 }
2568};
2569
2570/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2571/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2572/// vec_step (OpenCL 1.1 6.11.12).
2574 union {
2577 } Argument;
2578 SourceLocation OpLoc, RParenLoc;
2579
2580public:
2582 QualType resultType, SourceLocation op,
2583 SourceLocation rp)
2584 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2585 OK_Ordinary),
2586 OpLoc(op), RParenLoc(rp) {
2587 assert(ExprKind <= UETT_Last && "invalid enum value!");
2588 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2589 assert(static_cast<unsigned>(ExprKind) ==
2591 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2592 UnaryExprOrTypeTraitExprBits.IsType = true;
2593 Argument.Ty = TInfo;
2595 }
2596
2598 QualType resultType, SourceLocation op,
2599 SourceLocation rp);
2600
2601 /// Construct an empty sizeof/alignof expression.
2603 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2604
2606 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2607 }
2609 assert(K <= UETT_Last && "invalid enum value!");
2611 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2612 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2613 }
2614
2615 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2617 return getArgumentTypeInfo()->getType();
2618 }
2620 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2621 return Argument.Ty;
2622 }
2624 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2625 return static_cast<Expr*>(Argument.Ex);
2626 }
2627 const Expr *getArgumentExpr() const {
2628 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2629 }
2630
2632 Argument.Ex = E;
2633 UnaryExprOrTypeTraitExprBits.IsType = false;
2634 }
2636 Argument.Ty = TInfo;
2637 UnaryExprOrTypeTraitExprBits.IsType = true;
2638 }
2639
2640 /// Gets the argument type, or the type of the argument expression, whichever
2641 /// is appropriate.
2644 }
2645
2646 SourceLocation getOperatorLoc() const { return OpLoc; }
2647 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2648
2649 SourceLocation getRParenLoc() const { return RParenLoc; }
2650 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2651
2652 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2653 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2654
2655 static bool classof(const Stmt *T) {
2656 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2657 }
2658
2659 // Iterators
2662};
2663
2664//===----------------------------------------------------------------------===//
2665// Postfix Operators.
2666//===----------------------------------------------------------------------===//
2667
2668/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2669class ArraySubscriptExpr : public Expr {
2670 enum { LHS, RHS, END_EXPR };
2671 Stmt *SubExprs[END_EXPR];
2672
2673 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2674
2675public:
2677 ExprObjectKind OK, SourceLocation rbracketloc)
2678 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2679 SubExprs[LHS] = lhs;
2680 SubExprs[RHS] = rhs;
2681 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2683 }
2684
2685 /// Create an empty array subscript expression.
2687 : Expr(ArraySubscriptExprClass, Shell) { }
2688
2689 /// An array access can be written A[4] or 4[A] (both are equivalent).
2690 /// - getBase() and getIdx() always present the normalized view: A[4].
2691 /// In this case getBase() returns "A" and getIdx() returns "4".
2692 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2693 /// 4[A] getLHS() returns "4".
2694 /// Note: Because vector element access is also written A[4] we must
2695 /// predicate the format conversion in getBase and getIdx only on the
2696 /// the type of the RHS, as it is possible for the LHS to be a vector of
2697 /// integer type
2698 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2699 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2700 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2701
2702 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2703 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2704 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2705
2706 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2707 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2708
2709 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2710 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2711
2712 SourceLocation getBeginLoc() const LLVM_READONLY {
2713 return getLHS()->getBeginLoc();
2714 }
2716
2718 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2719 }
2721 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2722 }
2723
2724 SourceLocation getExprLoc() const LLVM_READONLY {
2725 return getBase()->getExprLoc();
2726 }
2727
2728 static bool classof(const Stmt *T) {
2729 return T->getStmtClass() == ArraySubscriptExprClass;
2730 }
2731
2732 // Iterators
2734 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2735 }
2737 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2738 }
2739};
2740
2741/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2742/// extension.
2743/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2744/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2745/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2746/// exist during the initial construction of the AST.
2748 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2749 Stmt *SubExprs[END_EXPR];
2750
2751public:
2752 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2753 SourceLocation RBracketLoc)
2754 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2756 SubExprs[BASE] = Base;
2757 SubExprs[ROW_IDX] = RowIdx;
2758 SubExprs[COLUMN_IDX] = ColumnIdx;
2759 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2761 }
2762
2763 /// Create an empty matrix subscript expression.
2765 : Expr(MatrixSubscriptExprClass, Shell) {}
2766
2767 bool isIncomplete() const {
2768 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2769 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2770 "expressions without column index must be marked as incomplete");
2771 return IsIncomplete;
2772 }
2773 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
2774 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
2775 void setBase(Expr *E) { SubExprs[BASE] = E; }
2776
2777 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
2778 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
2779 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2780
2781 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
2782 const Expr *getColumnIdx() const {
2783 assert(!isIncomplete() &&
2784 "cannot get the column index of an incomplete expression");
2785 return cast<Expr>(SubExprs[COLUMN_IDX]);
2786 }
2787 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2788
2789 SourceLocation getBeginLoc() const LLVM_READONLY {
2790 return getBase()->getBeginLoc();
2791 }
2792
2794
2795 SourceLocation getExprLoc() const LLVM_READONLY {
2796 return getBase()->getExprLoc();
2797 }
2798
2800 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2801 }
2803 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2804 }
2805
2806 static bool classof(const Stmt *T) {
2807 return T->getStmtClass() == MatrixSubscriptExprClass;
2808 }
2809
2810 // Iterators
2812 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2813 }
2815 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2816 }
2817};
2818
2819/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2820/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2821/// while its subclasses may represent alternative syntax that (semantically)
2822/// results in a function call. For example, CXXOperatorCallExpr is
2823/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2824/// "str1 + str2" to resolve to a function call.
2825class CallExpr : public Expr {
2826 enum { FN = 0, PREARGS_START = 1 };
2827
2828 /// The number of arguments in the call expression.
2829 unsigned NumArgs;
2830
2831 /// The location of the right parentheses. This has a different meaning for
2832 /// the derived classes of CallExpr.
2833 SourceLocation RParenLoc;
2834
2835 // CallExpr store some data in trailing objects. However since CallExpr
2836 // is used a base of other expression classes we cannot use
2837 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2838 // and casts.
2839 //
2840 // The trailing objects are in order:
2841 //
2842 // * A single "Stmt *" for the callee expression.
2843 //
2844 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2845 //
2846 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2847 //
2848 // * An optional of type FPOptionsOverride.
2849 //
2850 // Note that we store the offset in bytes from the this pointer to the start
2851 // of the trailing objects. It would be perfectly possible to compute it
2852 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2853 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2854 // compute this once and then load the offset from the bit-fields of Stmt,
2855 // instead of re-computing the offset each time the trailing objects are
2856 // accessed.
2857
2858 /// Return a pointer to the start of the trailing array of "Stmt *".
2859 Stmt **getTrailingStmts() {
2860 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2861 CallExprBits.OffsetToTrailingObjects);
2862 }
2863 Stmt *const *getTrailingStmts() const {
2864 return const_cast<CallExpr *>(this)->getTrailingStmts();
2865 }
2866
2867 /// Map a statement class to the appropriate offset in bytes from the
2868 /// this pointer to the trailing objects.
2869 static unsigned offsetToTrailingObjects(StmtClass SC);
2870
2871 unsigned getSizeOfTrailingStmts() const {
2872 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2873 }
2874
2875 size_t getOffsetOfTrailingFPFeatures() const {
2876 assert(hasStoredFPFeatures());
2877 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2878 }
2879
2880public:
2881 enum class ADLCallKind : bool { NotADL, UsesADL };
2884
2885protected:
2886 /// Build a call expression, assuming that appropriate storage has been
2887 /// allocated for the trailing objects.
2888 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2890 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2891 unsigned MinNumArgs, ADLCallKind UsesADL);
2892
2893 /// Build an empty call expression, for deserialization.
2894 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2895 bool hasFPFeatures, EmptyShell Empty);
2896
2897 /// Return the size in bytes needed for the trailing objects.
2898 /// Used by the derived classes to allocate the right amount of storage.
2899 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2900 bool HasFPFeatures) {
2901 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2902 HasFPFeatures * sizeof(FPOptionsOverride);
2903 }
2904
2905 Stmt *getPreArg(unsigned I) {
2906 assert(I < getNumPreArgs() && "Prearg access out of range!");
2907 return getTrailingStmts()[PREARGS_START + I];
2908 }
2909 const Stmt *getPreArg(unsigned I) const {
2910 assert(I < getNumPreArgs() && "Prearg access out of range!");
2911 return getTrailingStmts()[PREARGS_START + I];
2912 }
2913 void setPreArg(unsigned I, Stmt *PreArg) {
2914 assert(I < getNumPreArgs() && "Prearg access out of range!");
2915 getTrailingStmts()[PREARGS_START + I] = PreArg;
2916 }
2917
2918 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2919
2920 /// Return a pointer to the trailing FPOptions
2922 assert(hasStoredFPFeatures());
2923 return reinterpret_cast<FPOptionsOverride *>(
2924 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2925 getSizeOfTrailingStmts());
2926 }
2928 assert(hasStoredFPFeatures());
2929 return reinterpret_cast<const FPOptionsOverride *>(
2930 reinterpret_cast<const char *>(this) +
2931 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2932 }
2933
2934public:
2935 /// Create a call expression.
2936 /// \param Fn The callee expression,
2937 /// \param Args The argument array,
2938 /// \param Ty The type of the call expression (which is *not* the return
2939 /// type in general),
2940 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2941 /// \param RParenLoc The location of the right parenthesis in the call
2942 /// expression.
2943 /// \param FPFeatures Floating-point features associated with the call,
2944 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2945 /// number of arguments will be the greater of Args.size()
2946 /// and MinNumArgs. This is used in a few places to allocate
2947 /// enough storage for the default arguments.
2948 /// \param UsesADL Specifies whether the callee was found through
2949 /// argument-dependent lookup.
2950 ///
2951 /// Note that you can use CreateTemporary if you need a temporary call
2952 /// expression on the stack.
2953 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2955 SourceLocation RParenLoc,
2956 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2958
2959 /// Create a temporary call expression with no arguments in the memory
2960 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2961 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2962 ///
2963 /// \code{.cpp}
2964 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2965 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2966 /// \endcode
2967 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2968 ExprValueKind VK, SourceLocation RParenLoc,
2970
2971 /// Create an empty call expression, for deserialization.
2972 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2973 bool HasFPFeatures, EmptyShell Empty);
2974
2975 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2976 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2977 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2978
2980 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2981 }
2983 CallExprBits.UsesADL = static_cast<bool>(V);
2984 }
2985 bool usesADL() const { return getADLCallKind() == UsesADL; }
2986
2987 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2988
2990 const Decl *getCalleeDecl() const {
2992 }
2993
2994 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2996 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2997 }
2999 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
3000 }
3001
3002 /// getNumArgs - Return the number of actual arguments to this call.
3003 unsigned getNumArgs() const { return NumArgs; }
3004
3005 /// Retrieve the call arguments.
3007 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
3008 getNumPreArgs());
3009 }
3010 const Expr *const *getArgs() const {
3011 return reinterpret_cast<const Expr *const *>(
3012 getTrailingStmts() + PREARGS_START + getNumPreArgs());
3013 }
3014
3015 /// getArg - Return the specified argument.
3016 Expr *getArg(unsigned Arg) {
3017 assert(Arg < getNumArgs() && "Arg access out of range!");
3018 return getArgs()[Arg];
3019 }
3020 const Expr *getArg(unsigned Arg) const {
3021 assert(Arg < getNumArgs() && "Arg access out of range!");
3022 return getArgs()[Arg];
3023 }
3024
3025 /// setArg - Set the specified argument.
3026 /// ! the dependence bits might be stale after calling this setter, it is
3027 /// *caller*'s responsibility to recompute them by calling
3028 /// computeDependence().
3029 void setArg(unsigned Arg, Expr *ArgExpr) {
3030 assert(Arg < getNumArgs() && "Arg access out of range!");
3031 getArgs()[Arg] = ArgExpr;
3032 }
3033
3034 /// Compute and set dependence bits.
3037 this, llvm::ArrayRef(
3038 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3039 getNumPreArgs())));
3040 }
3041
3042 /// Reduce the number of arguments in this call expression. This is used for
3043 /// example during error recovery to drop extra arguments. There is no way
3044 /// to perform the opposite because: 1.) We don't track how much storage
3045 /// we have for the argument array 2.) This would potentially require growing
3046 /// the argument array, something we cannot support since the arguments are
3047 /// stored in a trailing array.
3048 void shrinkNumArgs(unsigned NewNumArgs) {
3049 assert((NewNumArgs <= getNumArgs()) &&
3050 "shrinkNumArgs cannot increase the number of arguments!");
3051 NumArgs = NewNumArgs;
3052 }
3053
3054 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3055 /// Only used during construction of a CallExpr in a few places in Sema.
3056 /// FIXME: Find a way to remove it.
3057 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3058
3061 typedef llvm::iterator_range<arg_iterator> arg_range;
3062 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3063
3066 return const_arg_range(arg_begin(), arg_end());
3067 }
3068
3070 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3071 }
3073
3075 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3076 }
3078
3079 /// This method provides fast access to all the subexpressions of
3080 /// a CallExpr without going through the slower virtual child_iterator
3081 /// interface. This provides efficient reverse iteration of the
3082 /// subexpressions. This is currently used for CFG construction.
3084 return llvm::ArrayRef(getTrailingStmts(),
3085 PREARGS_START + getNumPreArgs() + getNumArgs());
3086 }
3087
3088 /// Get FPOptionsOverride from trailing storage.
3090 assert(hasStoredFPFeatures());
3091 return *getTrailingFPFeatures();
3092 }
3093 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3095 assert(hasStoredFPFeatures());
3096 *getTrailingFPFeatures() = F;
3097 }
3098
3099 /// Get the FP features status of this operator. Only meaningful for
3100 /// operations on floating point types.
3102 if (hasStoredFPFeatures())
3105 }
3106
3108 if (hasStoredFPFeatures())
3109 return getStoredFPFeatures();
3110 return FPOptionsOverride();
3111 }
3112
3113 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3114 /// of the callee. If not, return 0.
3115 unsigned getBuiltinCallee() const;
3116
3117 /// Returns \c true if this is a call to a builtin which does not
3118 /// evaluate side-effects within its arguments.
3119 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3120
3121 /// getCallReturnType - Get the return type of the call expr. This is not
3122 /// always the type of the expr itself, if the return type is a reference
3123 /// type.
3124 QualType getCallReturnType(const ASTContext &Ctx) const;
3125
3126 /// Returns the WarnUnusedResultAttr that is either declared on the called
3127 /// function, or its return type declaration.
3128 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3129
3130 /// Returns true if this call expression should warn on unused results.
3131 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3132 return getUnusedResultAttr(Ctx) != nullptr;
3133 }
3134
3135 SourceLocation getRParenLoc() const { return RParenLoc; }
3136 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3137
3138 SourceLocation getBeginLoc() const LLVM_READONLY;
3139 SourceLocation getEndLoc() const LLVM_READONLY;
3140
3141 /// Return true if this is a call to __assume() or __builtin_assume() with
3142 /// a non-value-dependent constant parameter evaluating as false.
3143 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3144
3145 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3146 /// (Usually Exprs themselves should set dependence).
3148 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3149 }
3150
3151 bool isCallToStdMove() const;
3152
3153 static bool classof(const Stmt *T) {
3154 return T->getStmtClass() >= firstCallExprConstant &&
3155 T->getStmtClass() <= lastCallExprConstant;
3156 }
3157
3158 // Iterators
3160 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3162 }
3163
3165 return const_child_range(getTrailingStmts(),
3166 getTrailingStmts() + PREARGS_START +
3168 }
3169};
3170
3171/// Extra data stored in some MemberExpr objects.
3173 /// The nested-name-specifier that qualifies the name, including
3174 /// source-location information.
3176
3177 /// The DeclAccessPair through which the MemberDecl was found due to
3178 /// name qualifiers.
3180};
3181
3182/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3183///
3184class MemberExpr final
3185 : public Expr,
3186 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3187 ASTTemplateKWAndArgsInfo,
3188 TemplateArgumentLoc> {
3189 friend class ASTReader;
3190 friend class ASTStmtReader;
3191 friend class ASTStmtWriter;
3192 friend TrailingObjects;
3193
3194 /// Base - the expression for the base pointer or structure references. In
3195 /// X.F, this is "X".
3196 Stmt *Base;
3197
3198 /// MemberDecl - This is the decl being referenced by the field/member name.
3199 /// In X.F, this is the decl referenced by F.
3200 ValueDecl *MemberDecl;
3201
3202 /// MemberDNLoc - Provides source/type location info for the
3203 /// declaration name embedded in MemberDecl.
3204 DeclarationNameLoc MemberDNLoc;
3205
3206 /// MemberLoc - This is the location of the member name.
3207 SourceLocation MemberLoc;
3208
3209 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3210 return hasQualifierOrFoundDecl();
3211 }
3212
3213 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3214 return hasTemplateKWAndArgsInfo();
3215 }
3216
3217 bool hasQualifierOrFoundDecl() const {
3218 return MemberExprBits.HasQualifierOrFoundDecl;
3219 }
3220
3221 bool hasTemplateKWAndArgsInfo() const {
3222 return MemberExprBits.HasTemplateKWAndArgsInfo;
3223 }
3224
3225 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3226 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3227 QualType T, ExprValueKind VK, ExprObjectKind OK,
3228 NonOdrUseReason NOUR);
3229 MemberExpr(EmptyShell Empty)
3230 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3231
3232public:
3233 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3234 SourceLocation OperatorLoc,
3235 NestedNameSpecifierLoc QualifierLoc,
3236 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3237 DeclAccessPair FoundDecl,
3238 DeclarationNameInfo MemberNameInfo,
3239 const TemplateArgumentListInfo *TemplateArgs,
3240 QualType T, ExprValueKind VK, ExprObjectKind OK,
3241 NonOdrUseReason NOUR);
3242
3243 /// Create an implicit MemberExpr, with no location, qualifier, template
3244 /// arguments, and so on. Suitable only for non-static member access.
3246 bool IsArrow, ValueDecl *MemberDecl,
3247 QualType T, ExprValueKind VK,
3248 ExprObjectKind OK) {
3249 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3250 SourceLocation(), MemberDecl,
3251 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3252 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3253 }
3254
3255 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3256 bool HasFoundDecl,
3257 bool HasTemplateKWAndArgsInfo,
3258 unsigned NumTemplateArgs);
3259
3260 void setBase(Expr *E) { Base = E; }
3261 Expr *getBase() const { return cast<Expr>(Base); }
3262
3263 /// Retrieve the member declaration to which this expression refers.
3264 ///
3265 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3266 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3267 ValueDecl *getMemberDecl() const { return MemberDecl; }
3268 void setMemberDecl(ValueDecl *D);
3269
3270 /// Retrieves the declaration found by lookup.
3272 if (!hasQualifierOrFoundDecl())
3274 getMemberDecl()->getAccess());
3275 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3276 }
3277
3278 /// Determines whether this member expression actually had
3279 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3280 /// x->Base::foo.
3281 bool hasQualifier() const { return getQualifier() != nullptr; }
3282
3283 /// If the member name was qualified, retrieves the
3284 /// nested-name-specifier that precedes the member name, with source-location
3285 /// information.
3287 if (!hasQualifierOrFoundDecl())
3288 return NestedNameSpecifierLoc();
3289 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3290 }
3291
3292 /// If the member name was qualified, retrieves the
3293 /// nested-name-specifier that precedes the member name. Otherwise, returns
3294 /// NULL.
3297 }
3298
3299 /// Retrieve the location of the template keyword preceding
3300 /// the member name, if any.
3302 if (!hasTemplateKWAndArgsInfo())
3303 return SourceLocation();
3304 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3305 }
3306
3307 /// Retrieve the location of the left angle bracket starting the
3308 /// explicit template argument list following the member name, if any.
3310 if (!hasTemplateKWAndArgsInfo())
3311 return SourceLocation();
3312 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3313 }
3314
3315 /// Retrieve the location of the right angle bracket ending the
3316 /// explicit template argument list following the member name, if any.
3318 if (!hasTemplateKWAndArgsInfo())
3319 return SourceLocation();
3320 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3321 }
3322
3323 /// Determines whether the member name was preceded by the template keyword.
3325
3326 /// Determines whether the member name was followed by an
3327 /// explicit template argument list.
3328 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3329
3330 /// Copies the template arguments (if present) into the given
3331 /// structure.
3334 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3335 getTrailingObjects<TemplateArgumentLoc>(), List);
3336 }
3337
3338 /// Retrieve the template arguments provided as part of this
3339 /// template-id.
3342 return nullptr;
3343
3344 return getTrailingObjects<TemplateArgumentLoc>();
3345 }
3346
3347 /// Retrieve the number of template arguments provided as part of this
3348 /// template-id.
3349 unsigned getNumTemplateArgs() const {
3351 return 0;
3352
3353 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3354 }
3355
3357 return {getTemplateArgs(), getNumTemplateArgs()};
3358 }
3359
3360 /// Retrieve the member declaration name info.
3362 return DeclarationNameInfo(MemberDecl->getDeclName(),
3363 MemberLoc, MemberDNLoc);
3364 }
3365
3366 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3367
3368 bool isArrow() const { return MemberExprBits.IsArrow; }
3369 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3370
3371 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3372 /// location of 'F'.
3373 SourceLocation getMemberLoc() const { return MemberLoc; }
3374 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3375
3376 SourceLocation getBeginLoc() const LLVM_READONLY;
3377 SourceLocation getEndLoc() const LLVM_READONLY;
3378
3379 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3380
3381 /// Determine whether the base of this explicit is implicit.
3382 bool isImplicitAccess() const {
3383 return getBase() && getBase()->isImplicitCXXThis();
3384 }
3385
3386 /// Returns true if this member expression refers to a method that
3387 /// was resolved from an overloaded set having size greater than 1.
3389 return MemberExprBits.HadMultipleCandidates;
3390 }
3391 /// Sets the flag telling whether this expression refers to
3392 /// a method that was resolved from an overloaded set having size
3393 /// greater than 1.
3394 void setHadMultipleCandidates(bool V = true) {
3395 MemberExprBits.HadMultipleCandidates = V;
3396 }
3397
3398 /// Returns true if virtual dispatch is performed.
3399 /// If the member access is fully qualified, (i.e. X::f()), virtual
3400 /// dispatching is not performed. In -fapple-kext mode qualified
3401 /// calls to virtual method will still go through the vtable.
3402 bool performsVirtualDispatch(const LangOptions &LO) const {
3403 return LO.AppleKext || !hasQualifier();
3404 }
3405
3406 /// Is this expression a non-odr-use reference, and if so, why?
3407 /// This is only meaningful if the named member is a static member.
3409 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3410 }
3411
3412 static bool classof(const Stmt *T) {
3413 return T->getStmtClass() == MemberExprClass;
3414 }
3415
3416 // Iterators
3419 return const_child_range(&Base, &Base + 1);
3420 }
3421};
3422
3423/// CompoundLiteralExpr - [C99 6.5.2.5]
3424///
3426 /// LParenLoc - If non-null, this is the location of the left paren in a
3427 /// compound literal like "(int){4}". This can be null if this is a
3428 /// synthesized compound expression.
3429 SourceLocation LParenLoc;
3430
3431 /// The type as written. This can be an incomplete array type, in
3432 /// which case the actual expression type will be different.
3433 /// The int part of the pair stores whether this expr is file scope.
3434 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3435 Stmt *Init;
3436public:
3438 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3439 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3440 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3442 }
3443
3444 /// Construct an empty compound literal.
3446 : Expr(CompoundLiteralExprClass, Empty) { }
3447
3448 const Expr *getInitializer() const { return cast<Expr>(Init); }
3449 Expr *getInitializer() { return cast<Expr>(Init); }
3450 void setInitializer(Expr *E) { Init = E; }
3451
3452 bool isFileScope() const { return TInfoAndScope.getInt(); }
3453 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3454
3455 SourceLocation getLParenLoc() const { return LParenLoc; }
3456 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3457
3459 return TInfoAndScope.getPointer();
3460 }
3462 TInfoAndScope.setPointer(tinfo);
3463 }
3464
3465 SourceLocation getBeginLoc() const LLVM_READONLY {
3466 // FIXME: Init should never be null.
3467 if (!Init)
3468 return SourceLocation();
3469 if (LParenLoc.isInvalid())
3470 return Init->getBeginLoc();
3471 return LParenLoc;
3472 }
3473 SourceLocation getEndLoc() const LLVM_READONLY {
3474 // FIXME: Init should never be null.
3475 if (!Init)
3476 return SourceLocation();
3477 return Init->getEndLoc();
3478 }
3479
3480 static bool classof(const Stmt *T) {
3481 return T->getStmtClass() == CompoundLiteralExprClass;
3482 }
3483
3484 // Iterators
3485 child_range children() { return child_range(&Init, &Init+1); }
3487 return const_child_range(&Init, &Init + 1);
3488 }
3489};
3490
3491/// CastExpr - Base class for type casts, including both implicit
3492/// casts (ImplicitCastExpr) and explicit casts that have some
3493/// representation in the source code (ExplicitCastExpr's derived
3494/// classes).
3495class CastExpr : public Expr {
3496 Stmt *Op;
3497
3498 bool CastConsistency() const;
3499
3500 const CXXBaseSpecifier * const *path_buffer() const {
3501 return const_cast<CastExpr*>(this)->path_buffer();
3502 }
3503 CXXBaseSpecifier **path_buffer();
3504
3505 friend class ASTStmtReader;
3506
3507protected:
3509 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3510 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3511 CastExprBits.Kind = kind;
3512 CastExprBits.PartOfExplicitCast = false;
3513 CastExprBits.BasePathSize = BasePathSize;
3514 assert((CastExprBits.BasePathSize == BasePathSize) &&
3515 "BasePathSize overflow!");
3516 assert(CastConsistency());
3517 CastExprBits.HasFPFeatures = HasFPFeatures;
3518 }
3519
3520 /// Construct an empty cast.
3521 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3522 bool HasFPFeatures)
3523 : Expr(SC, Empty) {
3524 CastExprBits.PartOfExplicitCast = false;
3525 CastExprBits.BasePathSize = BasePathSize;
3526 CastExprBits.HasFPFeatures = HasFPFeatures;
3527 assert((CastExprBits.BasePathSize == BasePathSize) &&
3528 "BasePathSize overflow!");
3529 }
3530
3531 /// Return a pointer to the trailing FPOptions.
3532 /// \pre hasStoredFPFeatures() == true
3535 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3536 }
3537
3538public:
3539 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3540 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3541
3542 static const char *getCastKindName(CastKind CK);
3543 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3544
3545 Expr *getSubExpr() { return cast<Expr>(Op); }
3546 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3547 void setSubExpr(Expr *E) { Op = E; }
3548
3549 /// Retrieve the cast subexpression as it was written in the source
3550 /// code, looking through any implicit casts or other intermediate nodes
3551 /// introduced by semantic analysis.
3553 const Expr *getSubExprAsWritten() const {
3554 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3555 }
3556
3557 /// If this cast applies a user-defined conversion, retrieve the conversion
3558 /// function that it invokes.
3560
3563 bool path_empty() const { return path_size() == 0; }
3564 unsigned path_size() const { return CastExprBits.BasePathSize; }
3565 path_iterator path_begin() { return path_buffer(); }
3566 path_iterator path_end() { return path_buffer() + path_size(); }
3567 path_const_iterator path_begin() const { return path_buffer(); }
3568 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3569
3570 llvm::iterator_range<path_iterator> path() {
3571 return llvm::make_range(path_begin(), path_end());
3572 }
3573 llvm::iterator_range<path_const_iterator> path() const {
3574 return llvm::make_range(path_begin(), path_end());
3575 }
3576
3578 assert(getCastKind() == CK_ToUnion);
3580 }
3581
3582 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3583
3584 /// Get FPOptionsOverride from trailing storage.
3586 assert(hasStoredFPFeatures());
3587 return *getTrailingFPFeatures();
3588 }
3589
3590 /// Get the FP features status of this operation. Only meaningful for
3591 /// operations on floating point types.
3593 if (hasStoredFPFeatures())
3596 }
3597
3599 if (hasStoredFPFeatures())
3600 return getStoredFPFeatures();
3601 return FPOptionsOverride();
3602 }
3603
3604 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3605 QualType opType);
3606 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3607 QualType opType);
3608
3609 static bool classof(const Stmt *T) {
3610 return T->getStmtClass() >= firstCastExprConstant &&
3611 T->getStmtClass() <= lastCastExprConstant;
3612 }
3613
3614 // Iterators
3615 child_range children() { return child_range(&Op, &Op+1); }
3616 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3617};
3618
3619/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3620/// conversions, which have no direct representation in the original
3621/// source code. For example: converting T[]->T*, void f()->void
3622/// (*f)(), float->double, short->int, etc.
3623///
3624/// In C, implicit casts always produce rvalues. However, in C++, an
3625/// implicit cast whose result is being bound to a reference will be
3626/// an lvalue or xvalue. For example:
3627///
3628/// @code
3629/// class Base { };
3630/// class Derived : public Base { };
3631/// Derived &&ref();
3632/// void f(Derived d) {
3633/// Base& b = d; // initializer is an ImplicitCastExpr
3634/// // to an lvalue of type Base
3635/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3636/// // to an xvalue of type Base
3637/// }
3638/// @endcode
3640 : public CastExpr,
3641 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3642 FPOptionsOverride> {
3643
3644 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3645 unsigned BasePathLength, FPOptionsOverride FPO,
3646 ExprValueKind VK)
3647 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3650 if (hasStoredFPFeatures())
3651 *getTrailingFPFeatures() = FPO;
3652 }
3653
3654 /// Construct an empty implicit cast.
3655 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3656 bool HasFPFeatures)
3657 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3658
3659 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3660 return path_size();
3661 }
3662
3663public:
3667 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3668 FPO.requiresTrailingStorage()) {
3669 if (hasStoredFPFeatures())
3670 *getTrailingFPFeatures() = FPO;
3671 }
3672
3673 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3674 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3675 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3676 }
3677
3678 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3679 CastKind Kind, Expr *Operand,
3680 const CXXCastPath *BasePath,
3682
3683 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3684 unsigned PathSize, bool HasFPFeatures);
3685
3686 SourceLocation getBeginLoc() const LLVM_READONLY {
3687 return getSubExpr()->getBeginLoc();
3688 }
3689 SourceLocation getEndLoc() const LLVM_READONLY {
3690 return getSubExpr()->getEndLoc();
3691 }
3692
3693 static bool classof(const Stmt *T) {
3694 return T->getStmtClass() == ImplicitCastExprClass;
3695 }
3696
3698 friend class CastExpr;
3699};
3700
3701/// ExplicitCastExpr - An explicit cast written in the source
3702/// code.
3703///
3704/// This class is effectively an abstract class, because it provides
3705/// the basic representation of an explicitly-written cast without
3706/// specifying which kind of cast (C cast, functional cast, static
3707/// cast, etc.) was written; specific derived classes represent the
3708/// particular style of cast and its location information.
3709///
3710/// Unlike implicit casts, explicit cast nodes have two different
3711/// types: the type that was written into the source code, and the
3712/// actual type of the expression as determined by semantic
3713/// analysis. These types may differ slightly. For example, in C++ one
3714/// can cast to a reference type, which indicates that the resulting
3715/// expression will be an lvalue or xvalue. The reference type, however,
3716/// will not be used as the type of the expression.
3718 /// TInfo - Source type info for the (written) type
3719 /// this expression is casting to.
3720 TypeSourceInfo *TInfo;
3721
3722protected:
3724 CastKind kind, Expr *op, unsigned PathSize,
3725 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3726 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3727 TInfo(writtenTy) {
3729 }
3730
3731 /// Construct an empty explicit cast.
3732 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3733 bool HasFPFeatures)
3734 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3735
3736public:
3737 /// getTypeInfoAsWritten - Returns the type source info for the type
3738 /// that this expression is casting to.
3739 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3740 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3741
3742 /// getTypeAsWritten - Returns the type that this expression is
3743 /// casting to, as written in the source code.
3744 QualType getTypeAsWritten() const { return TInfo->getType(); }
3745
3746 static bool classof(const Stmt *T) {
3747 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3748 T->getStmtClass() <= lastExplicitCastExprConstant;
3749 }
3750};
3751
3752/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3753/// cast in C++ (C++ [expr.cast]), which uses the syntax
3754/// (Type)expr. For example: @c (int)f.
3756 : public ExplicitCastExpr,
3757 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3758 FPOptionsOverride> {
3759 SourceLocation LPLoc; // the location of the left paren
3760 SourceLocation RPLoc; // the location of the right paren
3761
3762 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3763 unsigned PathSize, FPOptionsOverride FPO,
3765 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3766 FPO.requiresTrailingStorage(), writtenTy),
3767 LPLoc(l), RPLoc(r) {
3768 if (hasStoredFPFeatures())
3769 *getTrailingFPFeatures() = FPO;
3770 }
3771
3772 /// Construct an empty C-style explicit cast.
3773 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3774 bool HasFPFeatures)
3775 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3776
3777 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3778 return path_size();
3779 }
3780
3781public:
3782 static CStyleCastExpr *
3783 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3784 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3786
3787 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3788 unsigned PathSize, bool HasFPFeatures);
3789
3790 SourceLocation getLParenLoc() const { return LPLoc; }
3791 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3792
3793 SourceLocation getRParenLoc() const { return RPLoc; }
3794 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3795
3796 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3797 SourceLocation getEndLoc() const LLVM_READONLY {
3798 return getSubExpr()->getEndLoc();
3799 }
3800
3801 static bool classof(const Stmt *T) {
3802 return T->getStmtClass() == CStyleCastExprClass;
3803 }
3804
3806 friend class CastExpr;
3807};
3808
3809/// A builtin binary operation expression such as "x + y" or "x <= y".
3810///
3811/// This expression node kind describes a builtin binary operation,
3812/// such as "x + y" for integer values "x" and "y". The operands will
3813/// already have been converted to appropriate types (e.g., by
3814/// performing promotions or conversions).
3815///
3816/// In C++, where operators may be overloaded, a different kind of
3817/// expression node (CXXOperatorCallExpr) is used to express the
3818/// invocation of an overloaded operator with operator syntax. Within
3819/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3820/// used to store an expression "x + y" depends on the subexpressions
3821/// for x and y. If neither x or y is type-dependent, and the "+"
3822/// operator resolves to a built-in operation, BinaryOperator will be
3823/// used to express the computation (x and y may still be
3824/// value-dependent). If either x or y is type-dependent, or if the
3825/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3826/// be used to express the computation.
3827class BinaryOperator : public Expr {
3828 enum { LHS, RHS, END_EXPR };
3829 Stmt *SubExprs[END_EXPR];
3830
3831public:
3833
3834protected:
3835 size_t offsetOfTrailingStorage() const;
3836
3837 /// Return a pointer to the trailing FPOptions
3839 assert(BinaryOperatorBits.HasFPFeatures);
3840 return reinterpret_cast<FPOptionsOverride *>(
3841 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3842 }
3844 assert(BinaryOperatorBits.HasFPFeatures);
3845 return reinterpret_cast<const FPOptionsOverride *>(
3846 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3847 }
3848
3849 /// Build a binary operator, assuming that appropriate storage has been
3850 /// allocated for the trailing objects when needed.
3851 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3853 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3854
3855 /// Construct an empty binary operator.
3856 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3857 BinaryOperatorBits.Opc = BO_Comma;
3858 }
3859
3860public:
3861 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3862
3863 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3864 Opcode opc, QualType ResTy, ExprValueKind VK,
3866 FPOptionsOverride FPFeatures);
3870
3872 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3873 }
3874 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3875
3876 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3877 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3878 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3879 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3880
3881 SourceLocation getBeginLoc() const LLVM_READONLY {
3882 return getLHS()->getBeginLoc();
3883 }
3884 SourceLocation getEndLoc() const LLVM_READONLY {
3885 return getRHS()->getEndLoc();
3886 }
3887
3888 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3889 /// corresponds to, e.g. "<<=".
3890 static StringRef getOpcodeStr(Opcode Op);
3891
3892 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3893
3894 /// Retrieve the binary opcode that corresponds to the given
3895 /// overloaded operator.
3897
3898 /// Retrieve the overloaded operator kind that corresponds to
3899 /// the given binary opcode.
3901
3902 /// predicates to categorize the respective opcodes.
3903 static bool isPtrMemOp(Opcode Opc) {
3904 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3905 }
3906 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3907
3908 static bool isMultiplicativeOp(Opcode Opc) {
3909 return Opc >= BO_Mul && Opc <= BO_Rem;
3910 }
3912 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3913 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3914 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3915 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3916
3917 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3918 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3919
3920 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3921 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3922
3923 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3924 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3925
3926 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3927 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3928
3929 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3930 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3931
3933 switch (Opc) {
3934 default:
3935 llvm_unreachable("Not a comparison operator.");
3936 case BO_LT: return BO_GE;
3937 case BO_GT: return BO_LE;
3938 case BO_LE: return BO_GT;
3939 case BO_GE: return BO_LT;
3940 case BO_EQ: return BO_NE;
3941 case BO_NE: return BO_EQ;
3942 }
3943 }
3944
3946 switch (Opc) {
3947 default:
3948 llvm_unreachable("Not a comparison operator.");
3949 case BO_LT: return BO_GT;
3950 case BO_GT: return BO_LT;
3951 case BO_LE: return BO_GE;
3952 case BO_GE: return BO_LE;
3953 case BO_EQ:
3954 case BO_NE:
3955 return Opc;
3956 }
3957 }
3958
3959 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3960 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3961
3962 static bool isAssignmentOp(Opcode Opc) {
3963 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3964 }
3965 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3966
3968 return Opc > BO_Assign && Opc <= BO_OrAssign;
3969 }
3972 }
3974 assert(isCompoundAssignmentOp(Opc));
3975 if (Opc >= BO_AndAssign)
3976 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3977 else
3978 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3979 }
3980
3981 static bool isShiftAssignOp(Opcode Opc) {
3982 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3983 }
3984 bool isShiftAssignOp() const {
3985 return isShiftAssignOp(getOpcode());
3986 }
3987
3988 /// Return true if a binary operator using the specified opcode and operands
3989 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3990 /// integer to a pointer.
3992 const Expr *LHS,
3993 const Expr *RHS);
3994
3995 static bool classof(const Stmt *S) {
3996 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3997 S->getStmtClass() <= lastBinaryOperatorConstant;
3998 }
3999
4000 // Iterators
4002 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4003 }
4005 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4006 }
4007
4008 /// Set and fetch the bit that shows whether FPFeatures needs to be
4009 /// allocated in Trailing Storage
4010 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
4011 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
4012
4013 /// Get FPFeatures from trailing storage
4015 assert(hasStoredFPFeatures());
4016 return *getTrailingFPFeatures();
4017 }
4018 /// Set FPFeatures in trailing storage, used only by Serialization
4020 assert(BinaryOperatorBits.HasFPFeatures);
4021 *getTrailingFPFeatures() = F;
4022 }
4023
4024 /// Get the FP features status of this operator. Only meaningful for
4025 /// operations on floating point types.
4027 if (BinaryOperatorBits.HasFPFeatures)
4030 }
4031
4032 // This is used in ASTImporter
4034 if (BinaryOperatorBits.HasFPFeatures)
4035 return getStoredFPFeatures();
4036 return FPOptionsOverride();
4037 }
4038
4039 /// Get the FP contractability status of this operator. Only meaningful for
4040 /// operations on floating point types.
4043 }
4044
4045 /// Get the FENV_ACCESS status of this operator. Only meaningful for
4046 /// operations on floating point types.
4047 bool isFEnvAccessOn(const LangOptions &LO) const {
4048 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4049 }
4050
4051protected:
4052 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4054 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4055 bool dead2);
4056
4057 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4058 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4059 BinaryOperatorBits.Opc = BO_MulAssign;
4060 }
4061
4062 /// Return the size in bytes needed for the trailing objects.
4063 /// Used to allocate the right amount of storage.
4064 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4065 return HasFPFeatures * sizeof(FPOptionsOverride);
4066 }
4067};
4068
4069/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4070/// track of the type the operation is performed in. Due to the semantics of
4071/// these operators, the operands are promoted, the arithmetic performed, an
4072/// implicit conversion back to the result type done, then the assignment takes
4073/// place. This captures the intermediate type which the computation is done
4074/// in.
4076 QualType ComputationLHSType;
4077 QualType ComputationResultType;
4078
4079 /// Construct an empty CompoundAssignOperator.
4080 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4081 bool hasFPFeatures)
4082 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4083
4084protected:
4086 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4087 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4088 QualType CompLHSType, QualType CompResultType)
4089 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4090 true),
4091 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4092 assert(isCompoundAssignmentOp() &&
4093 "Only should be used for compound assignments");
4094 }
4095
4096public:
4098 bool hasFPFeatures);
4099
4100 static CompoundAssignOperator *
4101 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4103 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4104 QualType CompResultType = QualType());
4105
4106 // The two computation types are the type the LHS is converted
4107 // to for the computation and the type of the result; the two are
4108 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4109 QualType getComputationLHSType() const { return ComputationLHSType; }
4110 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4111
4112 QualType getComputationResultType() const { return ComputationResultType; }
4113 void setComputationResultType(QualType T) { ComputationResultType = T; }
4114
4115 static bool classof(const Stmt *S) {
4116 return S->getStmtClass() == CompoundAssignOperatorClass;
4117 }
4118};
4119
4121 assert(BinaryOperatorBits.HasFPFeatures);
4122 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4123 : sizeof(BinaryOperator);
4124}
4125
4126/// AbstractConditionalOperator - An abstract base class for
4127/// ConditionalOperator and BinaryConditionalOperator.
4129 SourceLocation QuestionLoc, ColonLoc;
4130 friend class ASTStmtReader;
4131
4132protected:
4135 SourceLocation cloc)
4136 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4137
4139 : Expr(SC, Empty) { }
4140
4141public:
4142 /// getCond - Return the expression representing the condition for
4143 /// the ?: operator.
4144 Expr *getCond() const;
4145
4146 /// getTrueExpr - Return the subexpression representing the value of
4147 /// the expression if the condition evaluates to true.
4148 Expr *getTrueExpr() const;
4149
4150 /// getFalseExpr - Return the subexpression representing the value of
4151 /// the expression if the condition evaluates to false. This is
4152 /// the same as getRHS.
4153 Expr *getFalseExpr() const;
4154
4155 SourceLocation getQuestionLoc() const { return QuestionLoc; }
4156 SourceLocation getColonLoc() const { return ColonLoc; }
4157
4158 static bool classof(const Stmt *T) {
4159 return T->getStmtClass() == ConditionalOperatorClass ||
4160 T->getStmtClass() == BinaryConditionalOperatorClass;
4161 }
4162};
4163
4164/// ConditionalOperator - The ?: ternary operator. The GNU "missing
4165/// middle" extension is a BinaryConditionalOperator.
4167 enum { COND, LHS, RHS, END_EXPR };
4168 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4169
4170 friend class ASTStmtReader;
4171public:
4173 SourceLocation CLoc, Expr *rhs, QualType t,
4175 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4176 CLoc) {
4177 SubExprs[COND] = cond;
4178 SubExprs[LHS] = lhs;
4179 SubExprs[RHS] = rhs;
4181 }
4182
4183 /// Build an empty conditional operator.
4185 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4186
4187 /// getCond - Return the expression representing the condition for
4188 /// the ?: operator.
4189 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4190
4191 /// getTrueExpr - Return the subexpression representing the value of
4192 /// the expression if the condition evaluates to true.
4193 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4194
4195 /// getFalseExpr - Return the subexpression representing the value of
4196 /// the expression if the condition evaluates to false. This is
4197 /// the same as getRHS.
4198 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4199
4200 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4201 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4202
4203 SourceLocation getBeginLoc() const LLVM_READONLY {
4204 return getCond()->getBeginLoc();
4205 }
4206 SourceLocation getEndLoc() const LLVM_READONLY {
4207 return getRHS()->getEndLoc();
4208 }
4209
4210 static bool classof(const Stmt *T) {
4211 return T->getStmtClass() == ConditionalOperatorClass;
4212 }
4213
4214 // Iterators
4216 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4217 }
4219 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4220 }
4221};
4222
4223/// BinaryConditionalOperator - The GNU extension to the conditional
4224/// operator which allows the middle operand to be omitted.
4225///
4226/// This is a different expression kind on the assumption that almost
4227/// every client ends up needing to know that these are different.
4229 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4230
4231 /// - the common condition/left-hand-side expression, which will be
4232 /// evaluated as the opaque value
4233 /// - the condition, expressed in terms of the opaque value
4234 /// - the left-hand-side, expressed in terms of the opaque value
4235 /// - the right-hand-side
4236 Stmt *SubExprs[NUM_SUBEXPRS];
4237 OpaqueValueExpr *OpaqueValue;
4238
4239 friend class ASTStmtReader;
4240public:
4242 Expr *cond, Expr *lhs, Expr *rhs,
4243 SourceLocation qloc, SourceLocation cloc,
4245 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4246 qloc, cloc),
4247 OpaqueValue(opaqueValue) {
4248 SubExprs[COMMON] = common;
4249 SubExprs[COND] = cond;
4250 SubExprs[LHS] = lhs;
4251 SubExprs[RHS] = rhs;
4252 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4254 }
4255
4256 /// Build an empty conditional operator.
4258 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4259
4260 /// getCommon - Return the common expression, written to the
4261 /// left of the condition. The opaque value will be bound to the
4262 /// result of this expression.
4263 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4264
4265 /// getOpaqueValue - Return the opaque value placeholder.
4266 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4267
4268 /// getCond - Return the condition expression; this is defined
4269 /// in terms of the opaque value.
4270 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4271
4272 /// getTrueExpr - Return the subexpression which will be
4273 /// evaluated if the condition evaluates to true; this is defined
4274 /// in terms of the opaque value.
4276 return cast<Expr>(SubExprs[LHS]);
4277 }
4278
4279 /// getFalseExpr - Return the subexpression which will be
4280 /// evaluated if the condnition evaluates to false; this is
4281 /// defined in terms of the opaque value.
4283 return cast<Expr>(SubExprs[RHS]);
4284 }
4285
4286 SourceLocation getBeginLoc() const LLVM_READONLY {
4287 return getCommon()->getBeginLoc();
4288 }
4289 SourceLocation getEndLoc() const LLVM_READONLY {
4290 return getFalseExpr()->getEndLoc();
4291 }
4292
4293 static bool classof(const Stmt *T) {
4294 return T->getStmtClass() == BinaryConditionalOperatorClass;
4295 }
4296
4297 // Iterators
4299 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4300 }
4302 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4303 }
4304};
4305
4307 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4308 return co->getCond();
4309 return cast<BinaryConditionalOperator>(this)->getCond();
4310}
4311
4313