1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Expr interface and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CLANG_AST_EXPR_H
14 #define LLVM_CLANG_AST_EXPR_H
15
16 #include "clang/AST/APNumericStorage.h"
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/ComputeDependence.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclAccessPair.h"
22 #include "clang/AST/DependenceFlags.h"
23 #include "clang/AST/OperationKinds.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TemplateBase.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/SyncScope.h"
30 #include "clang/Basic/TypeTraits.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APSInt.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/iterator.h"
36 #include "llvm/ADT/iterator_range.h"
37 #include "llvm/Support/AtomicOrdering.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/TrailingObjects.h"
40 #include <optional>
41
42 namespace clang {
43 class APValue;
44 class ASTContext;
45 class BlockDecl;
46 class CXXBaseSpecifier;
47 class CXXMemberCallExpr;
48 class CXXOperatorCallExpr;
49 class CastExpr;
50 class Decl;
51 class IdentifierInfo;
52 class MaterializeTemporaryExpr;
53 class NamedDecl;
54 class ObjCPropertyRefExpr;
55 class OpaqueValueExpr;
56 class ParmVarDecl;
57 class StringLiteral;
58 class TargetInfo;
59 class ValueDecl;
60
61 /// A simple array of base specifiers.
62 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
63
64 /// An adjustment to be made to the temporary created when emitting a
65 /// reference binding, which accesses a particular subobject of that temporary.
66 struct SubobjectAdjustment {
67 enum {
68 DerivedToBaseAdjustment,
69 FieldAdjustment,
70 MemberPointerAdjustment
71 } Kind;
72
73 struct DTB {
74 const CastExpr *BasePath;
75 const CXXRecordDecl *DerivedClass;
76 };
77
78 struct P {
79 const MemberPointerType *MPT;
80 Expr *RHS;
81 };
82
83 union {
84 struct DTB DerivedToBase;
85 FieldDecl *Field;
86 struct P Ptr;
87 };
88
SubobjectAdjustmentSubobjectAdjustment89 SubobjectAdjustment(const CastExpr *BasePath,
90 const CXXRecordDecl *DerivedClass)
91 : Kind(DerivedToBaseAdjustment) {
92 DerivedToBase.BasePath = BasePath;
93 DerivedToBase.DerivedClass = DerivedClass;
94 }
95
SubobjectAdjustmentSubobjectAdjustment96 SubobjectAdjustment(FieldDecl *Field)
97 : Kind(FieldAdjustment) {
98 this->Field = Field;
99 }
100
SubobjectAdjustmentSubobjectAdjustment101 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
102 : Kind(MemberPointerAdjustment) {
103 this->Ptr.MPT = MPT;
104 this->Ptr.RHS = RHS;
105 }
106 };
107
108 /// This represents one expression. Note that Expr's are subclasses of Stmt.
109 /// This allows an expression to be transparently used any place a Stmt is
110 /// required.
111 class Expr : public ValueStmt {
112 QualType TR;
113
114 public:
115 Expr() = delete;
116 Expr(const Expr&) = delete;
117 Expr(Expr &&) = delete;
118 Expr &operator=(const Expr&) = delete;
119 Expr &operator=(Expr&&) = delete;
120
121 protected:
Expr(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK)122 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
123 : ValueStmt(SC) {
124 ExprBits.Dependent = 0;
125 ExprBits.ValueKind = VK;
126 ExprBits.ObjectKind = OK;
127 assert(ExprBits.ObjectKind == OK && "truncated kind");
128 setType(T);
129 }
130
131 /// Construct an empty expression.
Expr(StmtClass SC,EmptyShell)132 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
133
134 /// Each concrete expr subclass is expected to compute its dependence and call
135 /// this in the constructor.
setDependence(ExprDependence Deps)136 void setDependence(ExprDependence Deps) {
137 ExprBits.Dependent = static_cast<unsigned>(Deps);
138 }
139 friend class ASTImporter; // Sets dependence directly.
140 friend class ASTStmtReader; // Sets dependence directly.
141
142 public:
getType()143 QualType getType() const { return TR; }
setType(QualType t)144 void setType(QualType t) {
145 // In C++, the type of an expression is always adjusted so that it
146 // will not have reference type (C++ [expr]p6). Use
147 // QualType::getNonReferenceType() to retrieve the non-reference
148 // type. Additionally, inspect Expr::isLvalue to determine whether
149 // an expression that is adjusted in this manner should be
150 // considered an lvalue.
151 assert((t.isNull() || !t->isReferenceType()) &&
152 "Expressions can't have reference type");
153
154 TR = t;
155 }
156
getDependence()157 ExprDependence getDependence() const {
158 return static_cast<ExprDependence>(ExprBits.Dependent);
159 }
160
161 /// Determines whether the value of this expression depends on
162 /// - a template parameter (C++ [temp.dep.constexpr])
163 /// - or an error, whose resolution is unknown
164 ///
165 /// For example, the array bound of "Chars" in the following example is
166 /// value-dependent.
167 /// @code
168 /// template<int Size, char (&Chars)[Size]> struct meta_string;
169 /// @endcode
isValueDependent()170 bool isValueDependent() const {
171 return static_cast<bool>(getDependence() & ExprDependence::Value);
172 }
173
174 /// Determines whether the type of this expression depends on
175 /// - a template parameter (C++ [temp.dep.expr], which means that its type
176 /// could change from one template instantiation to the next)
177 /// - or an error
178 ///
179 /// For example, the expressions "x" and "x + y" are type-dependent in
180 /// the following code, but "y" is not type-dependent:
181 /// @code
182 /// template<typename T>
183 /// void add(T x, int y) {
184 /// x + y;
185 /// }
186 /// @endcode
isTypeDependent()187 bool isTypeDependent() const {
188 return static_cast<bool>(getDependence() & ExprDependence::Type);
189 }
190
191 /// Whether this expression is instantiation-dependent, meaning that
192 /// it depends in some way on
193 /// - a template parameter (even if neither its type nor (constant) value
194 /// can change due to the template instantiation)
195 /// - or an error
196 ///
197 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
198 /// instantiation-dependent (since it involves a template parameter \c T), but
199 /// is neither type- nor value-dependent, since the type of the inner
200 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
201 /// \c sizeof is known.
202 ///
203 /// \code
204 /// template<typename T>
205 /// void f(T x, T y) {
206 /// sizeof(sizeof(T() + T());
207 /// }
208 /// \endcode
209 ///
210 /// \code
211 /// void func(int) {
212 /// func(); // the expression is instantiation-dependent, because it depends
213 /// // on an error.
214 /// }
215 /// \endcode
isInstantiationDependent()216 bool isInstantiationDependent() const {
217 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
218 }
219
220 /// Whether this expression contains an unexpanded parameter
221 /// pack (for C++11 variadic templates).
222 ///
223 /// Given the following function template:
224 ///
225 /// \code
226 /// template<typename F, typename ...Types>
227 /// void forward(const F &f, Types &&...args) {
228 /// f(static_cast<Types&&>(args)...);
229 /// }
230 /// \endcode
231 ///
232 /// The expressions \c args and \c static_cast<Types&&>(args) both
233 /// contain parameter packs.
containsUnexpandedParameterPack()234 bool containsUnexpandedParameterPack() const {
235 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
236 }
237
238 /// Whether this expression contains subexpressions which had errors, e.g. a
239 /// TypoExpr.
containsErrors()240 bool containsErrors() const {
241 return static_cast<bool>(getDependence() & ExprDependence::Error);
242 }
243
244 /// getExprLoc - Return the preferred location for the arrow when diagnosing
245 /// a problem with a generic expression.
246 SourceLocation getExprLoc() const LLVM_READONLY;
247
248 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
249 /// applied to this expression if it appears as a discarded-value expression
250 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
251 bool isReadIfDiscardedInCPlusPlus11() const;
252
253 /// isUnusedResultAWarning - Return true if this immediate expression should
254 /// be warned about if the result is unused. If so, fill in expr, location,
255 /// and ranges with expr to warn on and source locations/ranges appropriate
256 /// for a warning.
257 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
258 SourceRange &R1, SourceRange &R2,
259 ASTContext &Ctx) const;
260
261 /// isLValue - True if this expression is an "l-value" according to
262 /// the rules of the current language. C and C++ give somewhat
263 /// different rules for this concept, but in general, the result of
264 /// an l-value expression identifies a specific object whereas the
265 /// result of an r-value expression is a value detached from any
266 /// specific storage.
267 ///
268 /// C++11 divides the concept of "r-value" into pure r-values
269 /// ("pr-values") and so-called expiring values ("x-values"), which
270 /// identify specific objects that can be safely cannibalized for
271 /// their resources.
isLValue()272 bool isLValue() const { return getValueKind() == VK_LValue; }
isPRValue()273 bool isPRValue() const { return getValueKind() == VK_PRValue; }
isXValue()274 bool isXValue() const { return getValueKind() == VK_XValue; }
isGLValue()275 bool isGLValue() const { return getValueKind() != VK_PRValue; }
276
277 enum LValueClassification {
278 LV_Valid,
279 LV_NotObjectType,
280 LV_IncompleteVoidType,
281 LV_DuplicateVectorComponents,
282 LV_InvalidExpression,
283 LV_InvalidMessageExpression,
284 LV_MemberFunction,
285 LV_SubObjCPropertySetting,
286 LV_ClassTemporary,
287 LV_ArrayTemporary
288 };
289 /// Reasons why an expression might not be an l-value.
290 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
291
292 enum isModifiableLvalueResult {
293 MLV_Valid,
294 MLV_NotObjectType,
295 MLV_IncompleteVoidType,
296 MLV_DuplicateVectorComponents,
297 MLV_InvalidExpression,
298 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
299 MLV_IncompleteType,
300 MLV_ConstQualified,
301 MLV_ConstQualifiedField,
302 MLV_ConstAddrSpace,
303 MLV_ArrayType,
304 MLV_NoSetterProperty,
305 MLV_MemberFunction,
306 MLV_SubObjCPropertySetting,
307 MLV_InvalidMessageExpression,
308 MLV_ClassTemporary,
309 MLV_ArrayTemporary
310 };
311 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
312 /// does not have an incomplete type, does not have a const-qualified type,
313 /// and if it is a structure or union, does not have any member (including,
314 /// recursively, any member or element of all contained aggregates or unions)
315 /// with a const-qualified type.
316 ///
317 /// \param Loc [in,out] - A source location which *may* be filled
318 /// in with the location of the expression making this a
319 /// non-modifiable lvalue, if specified.
320 isModifiableLvalueResult
321 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
322
323 /// The return type of classify(). Represents the C++11 expression
324 /// taxonomy.
325 class Classification {
326 public:
327 /// The various classification results. Most of these mean prvalue.
328 enum Kinds {
329 CL_LValue,
330 CL_XValue,
331 CL_Function, // Functions cannot be lvalues in C.
332 CL_Void, // Void cannot be an lvalue in C.
333 CL_AddressableVoid, // Void expression whose address can be taken in C.
334 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
335 CL_MemberFunction, // An expression referring to a member function
336 CL_SubObjCPropertySetting,
337 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
338 CL_ArrayTemporary, // A temporary of array type.
339 CL_ObjCMessageRValue, // ObjC message is an rvalue
340 CL_PRValue // A prvalue for any other reason, of any other type
341 };
342 /// The results of modification testing.
343 enum ModifiableType {
344 CM_Untested, // testModifiable was false.
345 CM_Modifiable,
346 CM_RValue, // Not modifiable because it's an rvalue
347 CM_Function, // Not modifiable because it's a function; C++ only
348 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
349 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
350 CM_ConstQualified,
351 CM_ConstQualifiedField,
352 CM_ConstAddrSpace,
353 CM_ArrayType,
354 CM_IncompleteType
355 };
356
357 private:
358 friend class Expr;
359
360 unsigned short Kind;
361 unsigned short Modifiable;
362
Classification(Kinds k,ModifiableType m)363 explicit Classification(Kinds k, ModifiableType m)
364 : Kind(k), Modifiable(m)
365 {}
366
367 public:
Classification()368 Classification() {}
369
getKind()370 Kinds getKind() const { return static_cast<Kinds>(Kind); }
getModifiable()371 ModifiableType getModifiable() const {
372 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
373 return static_cast<ModifiableType>(Modifiable);
374 }
isLValue()375 bool isLValue() const { return Kind == CL_LValue; }
isXValue()376 bool isXValue() const { return Kind == CL_XValue; }
isGLValue()377 bool isGLValue() const { return Kind <= CL_XValue; }
isPRValue()378 bool isPRValue() const { return Kind >= CL_Function; }
isRValue()379 bool isRValue() const { return Kind >= CL_XValue; }
isModifiable()380 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
381
382 /// Create a simple, modifiably lvalue
makeSimpleLValue()383 static Classification makeSimpleLValue() {
384 return Classification(CL_LValue, CM_Modifiable);
385 }
386
387 };
388 /// Classify - Classify this expression according to the C++11
389 /// expression taxonomy.
390 ///
391 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
392 /// old lvalue vs rvalue. This function determines the type of expression this
393 /// is. There are three expression types:
394 /// - lvalues are classical lvalues as in C++03.
395 /// - prvalues are equivalent to rvalues in C++03.
396 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
397 /// function returning an rvalue reference.
398 /// lvalues and xvalues are collectively referred to as glvalues, while
399 /// prvalues and xvalues together form rvalues.
Classify(ASTContext & Ctx)400 Classification Classify(ASTContext &Ctx) const {
401 return ClassifyImpl(Ctx, nullptr);
402 }
403
404 /// ClassifyModifiable - Classify this expression according to the
405 /// C++11 expression taxonomy, and see if it is valid on the left side
406 /// of an assignment.
407 ///
408 /// This function extends classify in that it also tests whether the
409 /// expression is modifiable (C99 6.3.2.1p1).
410 /// \param Loc A source location that might be filled with a relevant location
411 /// if the expression is not modifiable.
ClassifyModifiable(ASTContext & Ctx,SourceLocation & Loc)412 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
413 return ClassifyImpl(Ctx, &Loc);
414 }
415
416 /// Returns the set of floating point options that apply to this expression.
417 /// Only meaningful for operations on floating point values.
418 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
419
420 /// getValueKindForType - Given a formal return or parameter type,
421 /// give its value kind.
getValueKindForType(QualType T)422 static ExprValueKind getValueKindForType(QualType T) {
423 if (const ReferenceType *RT = T->getAs<ReferenceType>())
424 return (isa<LValueReferenceType>(RT)
425 ? VK_LValue
426 : (RT->getPointeeType()->isFunctionType()
427 ? VK_LValue : VK_XValue));
428 return VK_PRValue;
429 }
430
431 /// getValueKind - The value kind that this expression produces.
getValueKind()432 ExprValueKind getValueKind() const {
433 return static_cast<ExprValueKind>(ExprBits.ValueKind);
434 }
435
436 /// getObjectKind - The object kind that this expression produces.
437 /// Object kinds are meaningful only for expressions that yield an
438 /// l-value or x-value.
getObjectKind()439 ExprObjectKind getObjectKind() const {
440 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
441 }
442
isOrdinaryOrBitFieldObject()443 bool isOrdinaryOrBitFieldObject() const {
444 ExprObjectKind OK = getObjectKind();
445 return (OK == OK_Ordinary || OK == OK_BitField);
446 }
447
448 /// setValueKind - Set the value kind produced by this expression.
setValueKind(ExprValueKind Cat)449 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
450
451 /// setObjectKind - Set the object kind produced by this expression.
setObjectKind(ExprObjectKind Cat)452 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
453
454 private:
455 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
456
457 public:
458
459 /// Returns true if this expression is a gl-value that
460 /// potentially refers to a bit-field.
461 ///
462 /// In C++, whether a gl-value refers to a bitfield is essentially
463 /// an aspect of the value-kind type system.
refersToBitField()464 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
465
466 /// If this expression refers to a bit-field, retrieve the
467 /// declaration of that bit-field.
468 ///
469 /// Note that this returns a non-null pointer in subtly different
470 /// places than refersToBitField returns true. In particular, this can
471 /// return a non-null pointer even for r-values loaded from
472 /// bit-fields, but it will return null for a conditional bit-field.
473 FieldDecl *getSourceBitField();
474
getSourceBitField()475 const FieldDecl *getSourceBitField() const {
476 return const_cast<Expr*>(this)->getSourceBitField();
477 }
478
479 Decl *getReferencedDeclOfCallee();
getReferencedDeclOfCallee()480 const Decl *getReferencedDeclOfCallee() const {
481 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
482 }
483
484 /// If this expression is an l-value for an Objective C
485 /// property, find the underlying property reference expression.
486 const ObjCPropertyRefExpr *getObjCProperty() const;
487
488 /// Check if this expression is the ObjC 'self' implicit parameter.
489 bool isObjCSelfExpr() const;
490
491 /// Returns whether this expression refers to a vector element.
492 bool refersToVectorElement() const;
493
494 /// Returns whether this expression refers to a matrix element.
refersToMatrixElement()495 bool refersToMatrixElement() const {
496 return getObjectKind() == OK_MatrixComponent;
497 }
498
499 /// Returns whether this expression refers to a global register
500 /// variable.
501 bool refersToGlobalRegisterVar() const;
502
503 /// Returns whether this expression has a placeholder type.
hasPlaceholderType()504 bool hasPlaceholderType() const {
505 return getType()->isPlaceholderType();
506 }
507
508 /// Returns whether this expression has a specific placeholder type.
hasPlaceholderType(BuiltinType::Kind K)509 bool hasPlaceholderType(BuiltinType::Kind K) const {
510 assert(BuiltinType::isPlaceholderTypeKind(K));
511 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
512 return BT->getKind() == K;
513 return false;
514 }
515
516 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
517 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
518 /// but also int expressions which are produced by things like comparisons in
519 /// C.
520 ///
521 /// \param Semantic If true, only return true for expressions that are known
522 /// to be semantically boolean, which might not be true even for expressions
523 /// that are known to evaluate to 0/1. For instance, reading an unsigned
524 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
525 /// semantically correspond to a bool.
526 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
527
528 /// Check whether this array fits the idiom of a flexible array member,
529 /// depending on the value of -fstrict-flex-array.
530 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
531 /// resulting from the substitution of a macro or a template as special sizes.
532 bool isFlexibleArrayMemberLike(
533 ASTContext &Context,
534 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
535 bool IgnoreTemplateOrMacroSubstitution = false) const;
536
537 /// isIntegerConstantExpr - Return the value if this expression is a valid
538 /// integer constant expression. If not a valid i-c-e, return std::nullopt
539 /// and fill in Loc (if specified) with the location of the invalid
540 /// expression.
541 ///
542 /// Note: This does not perform the implicit conversions required by C++11
543 /// [expr.const]p5.
544 std::optional<llvm::APSInt>
545 getIntegerConstantExpr(const ASTContext &Ctx,
546 SourceLocation *Loc = nullptr) const;
547 bool isIntegerConstantExpr(const ASTContext &Ctx,
548 SourceLocation *Loc = nullptr) const;
549
550 /// isCXX98IntegralConstantExpr - Return true if this expression is an
551 /// integral constant expression in C++98. Can only be used in C++.
552 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
553
554 /// isCXX11ConstantExpr - Return true if this expression is a constant
555 /// expression in C++11. Can only be used in C++.
556 ///
557 /// Note: This does not perform the implicit conversions required by C++11
558 /// [expr.const]p5.
559 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
560 SourceLocation *Loc = nullptr) const;
561
562 /// isPotentialConstantExpr - Return true if this function's definition
563 /// might be usable in a constant expression in C++11, if it were marked
564 /// constexpr. Return false if the function can never produce a constant
565 /// expression, along with diagnostics describing why not.
566 static bool isPotentialConstantExpr(const FunctionDecl *FD,
567 SmallVectorImpl<
568 PartialDiagnosticAt> &Diags);
569
570 /// isPotentialConstantExprUnevaluated - Return true if this expression might
571 /// be usable in a constant expression in C++11 in an unevaluated context, if
572 /// it were in function FD marked constexpr. Return false if the function can
573 /// never produce a constant expression, along with diagnostics describing
574 /// why not.
575 static bool isPotentialConstantExprUnevaluated(Expr *E,
576 const FunctionDecl *FD,
577 SmallVectorImpl<
578 PartialDiagnosticAt> &Diags);
579
580 /// isConstantInitializer - Returns true if this expression can be emitted to
581 /// IR as a constant, and thus can be used as a constant initializer in C.
582 /// If this expression is not constant and Culprit is non-null,
583 /// it is used to store the address of first non constant expr.
584 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
585 const Expr **Culprit = nullptr) const;
586
587 /// If this expression is an unambiguous reference to a single declaration,
588 /// in the style of __builtin_function_start, return that declaration. Note
589 /// that this may return a non-static member function or field in C++ if this
590 /// expression is a member pointer constant.
591 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
592
593 /// EvalStatus is a struct with detailed info about an evaluation in progress.
594 struct EvalStatus {
595 /// Whether the evaluated expression has side effects.
596 /// For example, (f() && 0) can be folded, but it still has side effects.
597 bool HasSideEffects = false;
598
599 /// Whether the evaluation hit undefined behavior.
600 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
601 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
602 bool HasUndefinedBehavior = false;
603
604 /// Diag - If this is non-null, it will be filled in with a stack of notes
605 /// indicating why evaluation failed (or why it failed to produce a constant
606 /// expression).
607 /// If the expression is unfoldable, the notes will indicate why it's not
608 /// foldable. If the expression is foldable, but not a constant expression,
609 /// the notes will describes why it isn't a constant expression. If the
610 /// expression *is* a constant expression, no notes will be produced.
611 ///
612 /// FIXME: this causes significant performance concerns and should be
613 /// refactored at some point. Not all evaluations of the constant
614 /// expression interpreter will display the given diagnostics, this means
615 /// those kinds of uses are paying the expense of generating a diagnostic
616 /// (which may include expensive operations like converting APValue objects
617 /// to a string representation).
618 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
619
620 EvalStatus() = default;
621
622 // hasSideEffects - Return true if the evaluated expression has
623 // side effects.
hasSideEffectsEvalStatus624 bool hasSideEffects() const {
625 return HasSideEffects;
626 }
627 };
628
629 /// EvalResult is a struct with detailed info about an evaluated expression.
630 struct EvalResult : EvalStatus {
631 /// Val - This is the value the expression can be folded to.
632 APValue Val;
633
634 // isGlobalLValue - Return true if the evaluated lvalue expression
635 // is global.
636 bool isGlobalLValue() const;
637 };
638
639 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
640 /// an rvalue using any crazy technique (that has nothing to do with language
641 /// standards) that we want to, even if the expression has side-effects. If
642 /// this function returns true, it returns the folded constant in Result. If
643 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
644 /// applied.
645 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
646 bool InConstantContext = false) const;
647
648 /// EvaluateAsBooleanCondition - Return true if this is a constant
649 /// which we can fold and convert to a boolean condition using
650 /// any crazy technique that we want to, even if the expression has
651 /// side-effects.
652 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
653 bool InConstantContext = false) const;
654
655 enum SideEffectsKind {
656 SE_NoSideEffects, ///< Strictly evaluate the expression.
657 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
658 ///< arbitrary unmodeled side effects.
659 SE_AllowSideEffects ///< Allow any unmodeled side effect.
660 };
661
662 /// EvaluateAsInt - Return true if this is a constant which we can fold and
663 /// convert to an integer, using any crazy technique that we want to.
664 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
665 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
666 bool InConstantContext = false) const;
667
668 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
669 /// convert to a floating point value, using any crazy technique that we
670 /// want to.
671 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
672 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
673 bool InConstantContext = false) const;
674
675 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
676 /// and convert to a fixed point value.
677 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
678 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
679 bool InConstantContext = false) const;
680
681 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
682 /// constant folded without side-effects, but discard the result.
683 bool isEvaluatable(const ASTContext &Ctx,
684 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
685
686 /// HasSideEffects - This routine returns true for all those expressions
687 /// which have any effect other than producing a value. Example is a function
688 /// call, volatile variable read, or throwing an exception. If
689 /// IncludePossibleEffects is false, this call treats certain expressions with
690 /// potential side effects (such as function call-like expressions,
691 /// instantiation-dependent expressions, or invocations from a macro) as not
692 /// having side effects.
693 bool HasSideEffects(const ASTContext &Ctx,
694 bool IncludePossibleEffects = true) const;
695
696 /// Determine whether this expression involves a call to any function
697 /// that is not trivial.
698 bool hasNonTrivialCall(const ASTContext &Ctx) const;
699
700 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
701 /// integer. This must be called on an expression that constant folds to an
702 /// integer.
703 llvm::APSInt EvaluateKnownConstInt(
704 const ASTContext &Ctx,
705 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
706
707 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
708 const ASTContext &Ctx,
709 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
710
711 void EvaluateForOverflow(const ASTContext &Ctx) const;
712
713 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
714 /// lvalue with link time known address, with no side-effects.
715 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
716 bool InConstantContext = false) const;
717
718 /// EvaluateAsInitializer - Evaluate an expression as if it were the
719 /// initializer of the given declaration. Returns true if the initializer
720 /// can be folded to a constant, and produces any relevant notes. In C++11,
721 /// notes will be produced if the expression is not a constant expression.
722 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
723 const VarDecl *VD,
724 SmallVectorImpl<PartialDiagnosticAt> &Notes,
725 bool IsConstantInitializer) const;
726
727 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
728 /// of a call to the given function with the given arguments, inside an
729 /// unevaluated context. Returns true if the expression could be folded to a
730 /// constant.
731 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
732 const FunctionDecl *Callee,
733 ArrayRef<const Expr*> Args,
734 const Expr *This = nullptr) const;
735
736 enum class ConstantExprKind {
737 /// An integer constant expression (an array bound, enumerator, case value,
738 /// bit-field width, or similar) or similar.
739 Normal,
740 /// A non-class template argument. Such a value is only used for mangling,
741 /// not for code generation, so can refer to dllimported functions.
742 NonClassTemplateArgument,
743 /// A class template argument. Such a value is used for code generation.
744 ClassTemplateArgument,
745 /// An immediate invocation. The destruction of the end result of this
746 /// evaluation is not part of the evaluation, but all other temporaries
747 /// are destroyed.
748 ImmediateInvocation,
749 };
750
751 /// Evaluate an expression that is required to be a constant expression. Does
752 /// not check the syntactic constraints for C and C++98 constant expressions.
753 bool EvaluateAsConstantExpr(
754 EvalResult &Result, const ASTContext &Ctx,
755 ConstantExprKind Kind = ConstantExprKind::Normal) const;
756
757 /// If the current Expr is a pointer, this will try to statically
758 /// determine the number of bytes available where the pointer is pointing.
759 /// Returns true if all of the above holds and we were able to figure out the
760 /// size, false otherwise.
761 ///
762 /// \param Type - How to evaluate the size of the Expr, as defined by the
763 /// "type" parameter of __builtin_object_size
764 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
765 unsigned Type) const;
766
767 /// If the current Expr is a pointer, this will try to statically
768 /// determine the strlen of the string pointed to.
769 /// Returns true if all of the above holds and we were able to figure out the
770 /// strlen, false otherwise.
771 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
772
773 bool EvaluateCharRangeAsString(std::string &Result,
774 const Expr *SizeExpression,
775 const Expr *PtrExpression, ASTContext &Ctx,
776 EvalResult &Status) const;
777
778 /// Enumeration used to describe the kind of Null pointer constant
779 /// returned from \c isNullPointerConstant().
780 enum NullPointerConstantKind {
781 /// Expression is not a Null pointer constant.
782 NPCK_NotNull = 0,
783
784 /// Expression is a Null pointer constant built from a zero integer
785 /// expression that is not a simple, possibly parenthesized, zero literal.
786 /// C++ Core Issue 903 will classify these expressions as "not pointers"
787 /// once it is adopted.
788 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
789 NPCK_ZeroExpression,
790
791 /// Expression is a Null pointer constant built from a literal zero.
792 NPCK_ZeroLiteral,
793
794 /// Expression is a C++11 nullptr.
795 NPCK_CXX11_nullptr,
796
797 /// Expression is a GNU-style __null constant.
798 NPCK_GNUNull
799 };
800
801 /// Enumeration used to describe how \c isNullPointerConstant()
802 /// should cope with value-dependent expressions.
803 enum NullPointerConstantValueDependence {
804 /// Specifies that the expression should never be value-dependent.
805 NPC_NeverValueDependent = 0,
806
807 /// Specifies that a value-dependent expression of integral or
808 /// dependent type should be considered a null pointer constant.
809 NPC_ValueDependentIsNull,
810
811 /// Specifies that a value-dependent expression should be considered
812 /// to never be a null pointer constant.
813 NPC_ValueDependentIsNotNull
814 };
815
816 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
817 /// a Null pointer constant. The return value can further distinguish the
818 /// kind of NULL pointer constant that was detected.
819 NullPointerConstantKind isNullPointerConstant(
820 ASTContext &Ctx,
821 NullPointerConstantValueDependence NPC) const;
822
823 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
824 /// write barrier.
825 bool isOBJCGCCandidate(ASTContext &Ctx) const;
826
827 /// Returns true if this expression is a bound member function.
828 bool isBoundMemberFunction(ASTContext &Ctx) const;
829
830 /// Given an expression of bound-member type, find the type
831 /// of the member. Returns null if this is an *overloaded* bound
832 /// member expression.
833 static QualType findBoundMemberType(const Expr *expr);
834
835 /// Skip past any invisible AST nodes which might surround this
836 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
837 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
838 /// implicit conversions.
839 Expr *IgnoreUnlessSpelledInSource();
IgnoreUnlessSpelledInSource()840 const Expr *IgnoreUnlessSpelledInSource() const {
841 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
842 }
843
844 /// Skip past any implicit casts which might surround this expression until
845 /// reaching a fixed point. Skips:
846 /// * ImplicitCastExpr
847 /// * FullExpr
848 Expr *IgnoreImpCasts() LLVM_READONLY;
IgnoreImpCasts()849 const Expr *IgnoreImpCasts() const {
850 return const_cast<Expr *>(this)->IgnoreImpCasts();
851 }
852
853 /// Skip past any casts which might surround this expression until reaching
854 /// a fixed point. Skips:
855 /// * CastExpr
856 /// * FullExpr
857 /// * MaterializeTemporaryExpr
858 /// * SubstNonTypeTemplateParmExpr
859 Expr *IgnoreCasts() LLVM_READONLY;
IgnoreCasts()860 const Expr *IgnoreCasts() const {
861 return const_cast<Expr *>(this)->IgnoreCasts();
862 }
863
864 /// Skip past any implicit AST nodes which might surround this expression
865 /// until reaching a fixed point. Skips:
866 /// * What IgnoreImpCasts() skips
867 /// * MaterializeTemporaryExpr
868 /// * CXXBindTemporaryExpr
869 Expr *IgnoreImplicit() LLVM_READONLY;
IgnoreImplicit()870 const Expr *IgnoreImplicit() const {
871 return const_cast<Expr *>(this)->IgnoreImplicit();
872 }
873
874 /// Skip past any implicit AST nodes which might surround this expression
875 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
876 /// also skips over implicit calls to constructors and conversion functions.
877 ///
878 /// FIXME: Should IgnoreImplicit do this?
879 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
IgnoreImplicitAsWritten()880 const Expr *IgnoreImplicitAsWritten() const {
881 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
882 }
883
884 /// Skip past any parentheses which might surround this expression until
885 /// reaching a fixed point. Skips:
886 /// * ParenExpr
887 /// * UnaryOperator if `UO_Extension`
888 /// * GenericSelectionExpr if `!isResultDependent()`
889 /// * ChooseExpr if `!isConditionDependent()`
890 /// * ConstantExpr
891 Expr *IgnoreParens() LLVM_READONLY;
IgnoreParens()892 const Expr *IgnoreParens() const {
893 return const_cast<Expr *>(this)->IgnoreParens();
894 }
895
896 /// Skip past any parentheses and implicit casts which might surround this
897 /// expression until reaching a fixed point.
898 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
899 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
900 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
901 /// * What IgnoreParens() skips
902 /// * What IgnoreImpCasts() skips
903 /// * MaterializeTemporaryExpr
904 /// * SubstNonTypeTemplateParmExpr
905 Expr *IgnoreParenImpCasts() LLVM_READONLY;
IgnoreParenImpCasts()906 const Expr *IgnoreParenImpCasts() const {
907 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
908 }
909
910 /// Skip past any parentheses and casts which might surround this expression
911 /// until reaching a fixed point. Skips:
912 /// * What IgnoreParens() skips
913 /// * What IgnoreCasts() skips
914 Expr *IgnoreParenCasts() LLVM_READONLY;
IgnoreParenCasts()915 const Expr *IgnoreParenCasts() const {
916 return const_cast<Expr *>(this)->IgnoreParenCasts();
917 }
918
919 /// Skip conversion operators. If this Expr is a call to a conversion
920 /// operator, return the argument.
921 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
IgnoreConversionOperatorSingleStep()922 const Expr *IgnoreConversionOperatorSingleStep() const {
923 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
924 }
925
926 /// Skip past any parentheses and lvalue casts which might surround this
927 /// expression until reaching a fixed point. Skips:
928 /// * What IgnoreParens() skips
929 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
930 /// casts are skipped
931 /// FIXME: This is intended purely as a temporary workaround for code
932 /// that hasn't yet been rewritten to do the right thing about those
933 /// casts, and may disappear along with the last internal use.
934 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
IgnoreParenLValueCasts()935 const Expr *IgnoreParenLValueCasts() const {
936 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
937 }
938
939 /// Skip past any parentheses and casts which do not change the value
940 /// (including ptr->int casts of the same size) until reaching a fixed point.
941 /// Skips:
942 /// * What IgnoreParens() skips
943 /// * CastExpr which do not change the value
944 /// * SubstNonTypeTemplateParmExpr
945 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
IgnoreParenNoopCasts(const ASTContext & Ctx)946 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
947 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
948 }
949
950 /// Skip past any parentheses and derived-to-base casts until reaching a
951 /// fixed point. Skips:
952 /// * What IgnoreParens() skips
953 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
954 /// CK_UncheckedDerivedToBase and CK_NoOp)
955 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
IgnoreParenBaseCasts()956 const Expr *IgnoreParenBaseCasts() const {
957 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
958 }
959
960 /// Determine whether this expression is a default function argument.
961 ///
962 /// Default arguments are implicitly generated in the abstract syntax tree
963 /// by semantic analysis for function calls, object constructions, etc. in
964 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
965 /// this routine also looks through any implicit casts to determine whether
966 /// the expression is a default argument.
967 bool isDefaultArgument() const;
968
969 /// Determine whether the result of this expression is a
970 /// temporary object of the given class type.
971 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
972
973 /// Whether this expression is an implicit reference to 'this' in C++.
974 bool isImplicitCXXThis() const;
975
976 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
977
978 /// For an expression of class type or pointer to class type,
979 /// return the most derived class decl the expression is known to refer to.
980 ///
981 /// If this expression is a cast, this method looks through it to find the
982 /// most derived decl that can be inferred from the expression.
983 /// This is valid because derived-to-base conversions have undefined
984 /// behavior if the object isn't dynamically of the derived type.
985 const CXXRecordDecl *getBestDynamicClassType() const;
986
987 /// Get the inner expression that determines the best dynamic class.
988 /// If this is a prvalue, we guarantee that it is of the most-derived type
989 /// for the object itself.
990 const Expr *getBestDynamicClassTypeExpr() const;
991
992 /// Walk outwards from an expression we want to bind a reference to and
993 /// find the expression whose lifetime needs to be extended. Record
994 /// the LHSs of comma expressions and adjustments needed along the path.
995 const Expr *skipRValueSubobjectAdjustments(
996 SmallVectorImpl<const Expr *> &CommaLHS,
997 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
skipRValueSubobjectAdjustments()998 const Expr *skipRValueSubobjectAdjustments() const {
999 SmallVector<const Expr *, 8> CommaLHSs;
1000 SmallVector<SubobjectAdjustment, 8> Adjustments;
1001 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1002 }
1003
1004 /// Checks that the two Expr's will refer to the same value as a comparison
1005 /// operand. The caller must ensure that the values referenced by the Expr's
1006 /// are not modified between E1 and E2 or the result my be invalid.
1007 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
1008
classof(const Stmt * T)1009 static bool classof(const Stmt *T) {
1010 return T->getStmtClass() >= firstExprConstant &&
1011 T->getStmtClass() <= lastExprConstant;
1012 }
1013 };
1014 // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1015 // Expr. Verify that we got it right.
1016 static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
1017 llvm::detail::ConstantLog2<alignof(Expr)>::value,
1018 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1019
1020 using ConstantExprKind = Expr::ConstantExprKind;
1021
1022 //===----------------------------------------------------------------------===//
1023 // Wrapper Expressions.
1024 //===----------------------------------------------------------------------===//
1025
1026 /// FullExpr - Represents a "full-expression" node.
1027 class FullExpr : public Expr {
1028 protected:
1029 Stmt *SubExpr;
1030
FullExpr(StmtClass SC,Expr * subexpr)1031 FullExpr(StmtClass SC, Expr *subexpr)
1032 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1033 subexpr->getObjectKind()),
1034 SubExpr(subexpr) {
1035 setDependence(computeDependence(this));
1036 }
FullExpr(StmtClass SC,EmptyShell Empty)1037 FullExpr(StmtClass SC, EmptyShell Empty)
1038 : Expr(SC, Empty) {}
1039 public:
getSubExpr()1040 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
getSubExpr()1041 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1042
1043 /// As with any mutator of the AST, be very careful when modifying an
1044 /// existing AST to preserve its invariants.
setSubExpr(Expr * E)1045 void setSubExpr(Expr *E) { SubExpr = E; }
1046
classof(const Stmt * T)1047 static bool classof(const Stmt *T) {
1048 return T->getStmtClass() >= firstFullExprConstant &&
1049 T->getStmtClass() <= lastFullExprConstant;
1050 }
1051 };
1052
1053 /// Describes the kind of result that can be tail-allocated.
1054 enum class ConstantResultStorageKind { None, Int64, APValue };
1055
1056 /// ConstantExpr - An expression that occurs in a constant context and
1057 /// optionally the result of evaluating the expression.
1058 class ConstantExpr final
1059 : public FullExpr,
1060 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1061 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1062 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1063 "for tail-allocated storage");
1064 friend TrailingObjects;
1065 friend class ASTStmtReader;
1066 friend class ASTStmtWriter;
1067
numTrailingObjects(OverloadToken<APValue>)1068 size_t numTrailingObjects(OverloadToken<APValue>) const {
1069 return getResultStorageKind() == ConstantResultStorageKind::APValue;
1070 }
numTrailingObjects(OverloadToken<uint64_t>)1071 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1072 return getResultStorageKind() == ConstantResultStorageKind::Int64;
1073 }
1074
Int64Result()1075 uint64_t &Int64Result() {
1076 assert(getResultStorageKind() == ConstantResultStorageKind::Int64 &&
1077 "invalid accessor");
1078 return *getTrailingObjects<uint64_t>();
1079 }
Int64Result()1080 const uint64_t &Int64Result() const {
1081 return const_cast<ConstantExpr *>(this)->Int64Result();
1082 }
APValueResult()1083 APValue &APValueResult() {
1084 assert(getResultStorageKind() == ConstantResultStorageKind::APValue &&
1085 "invalid accessor");
1086 return *getTrailingObjects<APValue>();
1087 }
APValueResult()1088 APValue &APValueResult() const {
1089 return const_cast<ConstantExpr *>(this)->APValueResult();
1090 }
1091
1092 ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
1093 bool IsImmediateInvocation);
1094 ConstantExpr(EmptyShell Empty, ConstantResultStorageKind StorageKind);
1095
1096 public:
1097 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1098 const APValue &Result);
1099 static ConstantExpr *
1100 Create(const ASTContext &Context, Expr *E,
1101 ConstantResultStorageKind Storage = ConstantResultStorageKind::None,
1102 bool IsImmediateInvocation = false);
1103 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1104 ConstantResultStorageKind StorageKind);
1105
1106 static ConstantResultStorageKind getStorageKind(const APValue &Value);
1107 static ConstantResultStorageKind getStorageKind(const Type *T,
1108 const ASTContext &Context);
1109
getBeginLoc()1110 SourceLocation getBeginLoc() const LLVM_READONLY {
1111 return SubExpr->getBeginLoc();
1112 }
getEndLoc()1113 SourceLocation getEndLoc() const LLVM_READONLY {
1114 return SubExpr->getEndLoc();
1115 }
1116
classof(const Stmt * T)1117 static bool classof(const Stmt *T) {
1118 return T->getStmtClass() == ConstantExprClass;
1119 }
1120
SetResult(APValue Value,const ASTContext & Context)1121 void SetResult(APValue Value, const ASTContext &Context) {
1122 MoveIntoResult(Value, Context);
1123 }
1124 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1125
getResultAPValueKind()1126 APValue::ValueKind getResultAPValueKind() const {
1127 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1128 }
getResultStorageKind()1129 ConstantResultStorageKind getResultStorageKind() const {
1130 return static_cast<ConstantResultStorageKind>(ConstantExprBits.ResultKind);
1131 }
isImmediateInvocation()1132 bool isImmediateInvocation() const {
1133 return ConstantExprBits.IsImmediateInvocation;
1134 }
hasAPValueResult()1135 bool hasAPValueResult() const {
1136 return ConstantExprBits.APValueKind != APValue::None;
1137 }
1138 APValue getAPValueResult() const;
1139 llvm::APSInt getResultAsAPSInt() const;
1140 // Iterators
children()1141 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
children()1142 const_child_range children() const {
1143 return const_child_range(&SubExpr, &SubExpr + 1);
1144 }
1145 };
1146
1147 //===----------------------------------------------------------------------===//
1148 // Primary Expressions.
1149 //===----------------------------------------------------------------------===//
1150
1151 /// OpaqueValueExpr - An expression referring to an opaque object of a
1152 /// fixed type and value class. These don't correspond to concrete
1153 /// syntax; instead they're used to express operations (usually copy
1154 /// operations) on values whose source is generally obvious from
1155 /// context.
1156 class OpaqueValueExpr : public Expr {
1157 friend class ASTStmtReader;
1158 Expr *SourceExpr;
1159
1160 public:
1161 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1162 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
Expr(OpaqueValueExprClass,T,VK,OK)1163 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1164 setIsUnique(false);
1165 OpaqueValueExprBits.Loc = Loc;
1166 setDependence(computeDependence(this));
1167 }
1168
1169 /// Given an expression which invokes a copy constructor --- i.e. a
1170 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1171 /// find the OpaqueValueExpr that's the source of the construction.
1172 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1173
OpaqueValueExpr(EmptyShell Empty)1174 explicit OpaqueValueExpr(EmptyShell Empty)
1175 : Expr(OpaqueValueExprClass, Empty) {}
1176
1177 /// Retrieve the location of this expression.
getLocation()1178 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1179
getBeginLoc()1180 SourceLocation getBeginLoc() const LLVM_READONLY {
1181 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1182 }
getEndLoc()1183 SourceLocation getEndLoc() const LLVM_READONLY {
1184 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1185 }
getExprLoc()1186 SourceLocation getExprLoc() const LLVM_READONLY {
1187 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1188 }
1189
children()1190 child_range children() {
1191 return child_range(child_iterator(), child_iterator());
1192 }
1193
children()1194 const_child_range children() const {
1195 return const_child_range(const_child_iterator(), const_child_iterator());
1196 }
1197
1198 /// The source expression of an opaque value expression is the
1199 /// expression which originally generated the value. This is
1200 /// provided as a convenience for analyses that don't wish to
1201 /// precisely model the execution behavior of the program.
1202 ///
1203 /// The source expression is typically set when building the
1204 /// expression which binds the opaque value expression in the first
1205 /// place.
getSourceExpr()1206 Expr *getSourceExpr() const { return SourceExpr; }
1207
setIsUnique(bool V)1208 void setIsUnique(bool V) {
1209 assert((!V || SourceExpr) &&
1210 "unique OVEs are expected to have source expressions");
1211 OpaqueValueExprBits.IsUnique = V;
1212 }
1213
isUnique()1214 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1215
classof(const Stmt * T)1216 static bool classof(const Stmt *T) {
1217 return T->getStmtClass() == OpaqueValueExprClass;
1218 }
1219 };
1220
1221 /// A reference to a declared variable, function, enum, etc.
1222 /// [C99 6.5.1p2]
1223 ///
1224 /// This encodes all the information about how a declaration is referenced
1225 /// within an expression.
1226 ///
1227 /// There are several optional constructs attached to DeclRefExprs only when
1228 /// they apply in order to conserve memory. These are laid out past the end of
1229 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
1230 ///
1231 /// DeclRefExprBits.HasQualifier:
1232 /// Specifies when this declaration reference expression has a C++
1233 /// nested-name-specifier.
1234 /// DeclRefExprBits.HasFoundDecl:
1235 /// Specifies when this declaration reference expression has a record of
1236 /// a NamedDecl (different from the referenced ValueDecl) which was found
1237 /// during name lookup and/or overload resolution.
1238 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1239 /// Specifies when this declaration reference expression has an explicit
1240 /// C++ template keyword and/or template argument list.
1241 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1242 /// Specifies when this declaration reference expression (validly)
1243 /// refers to an enclosed local or a captured variable.
1244 class DeclRefExpr final
1245 : public Expr,
1246 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1247 NamedDecl *, ASTTemplateKWAndArgsInfo,
1248 TemplateArgumentLoc> {
1249 friend class ASTStmtReader;
1250 friend class ASTStmtWriter;
1251 friend TrailingObjects;
1252
1253 /// The declaration that we are referencing.
1254 ValueDecl *D;
1255
1256 /// Provides source/type location info for the declaration name
1257 /// embedded in D.
1258 DeclarationNameLoc DNLoc;
1259
numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>)1260 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1261 return hasQualifier();
1262 }
1263
numTrailingObjects(OverloadToken<NamedDecl * >)1264 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1265 return hasFoundDecl();
1266 }
1267
numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>)1268 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1269 return hasTemplateKWAndArgsInfo();
1270 }
1271
1272 /// Test whether there is a distinct FoundDecl attached to the end of
1273 /// this DRE.
hasFoundDecl()1274 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1275
1276 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1277 SourceLocation TemplateKWLoc, ValueDecl *D,
1278 bool RefersToEnlosingVariableOrCapture,
1279 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1280 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1281 ExprValueKind VK, NonOdrUseReason NOUR);
1282
1283 /// Construct an empty declaration reference expression.
DeclRefExpr(EmptyShell Empty)1284 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1285
1286 public:
1287 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1288 bool RefersToEnclosingVariableOrCapture, QualType T,
1289 ExprValueKind VK, SourceLocation L,
1290 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1291 NonOdrUseReason NOUR = NOUR_None);
1292
1293 static DeclRefExpr *
1294 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1295 SourceLocation TemplateKWLoc, ValueDecl *D,
1296 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1297 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1298 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1299 NonOdrUseReason NOUR = NOUR_None);
1300
1301 static DeclRefExpr *
1302 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1303 SourceLocation TemplateKWLoc, ValueDecl *D,
1304 bool RefersToEnclosingVariableOrCapture,
1305 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1306 NamedDecl *FoundD = nullptr,
1307 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1308 NonOdrUseReason NOUR = NOUR_None);
1309
1310 /// Construct an empty declaration reference expression.
1311 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1312 bool HasFoundDecl,
1313 bool HasTemplateKWAndArgsInfo,
1314 unsigned NumTemplateArgs);
1315
getDecl()1316 ValueDecl *getDecl() { return D; }
getDecl()1317 const ValueDecl *getDecl() const { return D; }
1318 void setDecl(ValueDecl *NewD);
1319
getNameInfo()1320 DeclarationNameInfo getNameInfo() const {
1321 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1322 }
1323
getLocation()1324 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
setLocation(SourceLocation L)1325 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1326 SourceLocation getBeginLoc() const LLVM_READONLY;
1327 SourceLocation getEndLoc() const LLVM_READONLY;
1328
1329 /// Determine whether this declaration reference was preceded by a
1330 /// C++ nested-name-specifier, e.g., \c N::foo.
hasQualifier()1331 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1332
1333 /// If the name was qualified, retrieves the nested-name-specifier
1334 /// that precedes the name, with source-location information.
getQualifierLoc()1335 NestedNameSpecifierLoc getQualifierLoc() const {
1336 if (!hasQualifier())
1337 return NestedNameSpecifierLoc();
1338 return *getTrailingObjects<NestedNameSpecifierLoc>();
1339 }
1340
1341 /// If the name was qualified, retrieves the nested-name-specifier
1342 /// that precedes the name. Otherwise, returns NULL.
getQualifier()1343 NestedNameSpecifier *getQualifier() const {
1344 return getQualifierLoc().getNestedNameSpecifier();
1345 }
1346
1347 /// Get the NamedDecl through which this reference occurred.
1348 ///
1349 /// This Decl may be different from the ValueDecl actually referred to in the
1350 /// presence of using declarations, etc. It always returns non-NULL, and may
1351 /// simple return the ValueDecl when appropriate.
1352
getFoundDecl()1353 NamedDecl *getFoundDecl() {
1354 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1355 }
1356
1357 /// Get the NamedDecl through which this reference occurred.
1358 /// See non-const variant.
getFoundDecl()1359 const NamedDecl *getFoundDecl() const {
1360 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1361 }
1362
hasTemplateKWAndArgsInfo()1363 bool hasTemplateKWAndArgsInfo() const {
1364 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1365 }
1366
1367 /// Retrieve the location of the template keyword preceding
1368 /// this name, if any.
getTemplateKeywordLoc()1369 SourceLocation getTemplateKeywordLoc() const {
1370 if (!hasTemplateKWAndArgsInfo())
1371 return SourceLocation();
1372 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1373 }
1374
1375 /// Retrieve the location of the left angle bracket starting the
1376 /// explicit template argument list following the name, if any.
getLAngleLoc()1377 SourceLocation getLAngleLoc() const {
1378 if (!hasTemplateKWAndArgsInfo())
1379 return SourceLocation();
1380 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1381 }
1382
1383 /// Retrieve the location of the right angle bracket ending the
1384 /// explicit template argument list following the name, if any.
getRAngleLoc()1385 SourceLocation getRAngleLoc() const {
1386 if (!hasTemplateKWAndArgsInfo())
1387 return SourceLocation();
1388 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1389 }
1390
1391 /// Determines whether the name in this declaration reference
1392 /// was preceded by the template keyword.
hasTemplateKeyword()1393 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1394
1395 /// Determines whether this declaration reference was followed by an
1396 /// explicit template argument list.
hasExplicitTemplateArgs()1397 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1398
1399 /// Copies the template arguments (if present) into the given
1400 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)1401 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1402 if (hasExplicitTemplateArgs())
1403 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1404 getTrailingObjects<TemplateArgumentLoc>(), List);
1405 }
1406
1407 /// Retrieve the template arguments provided as part of this
1408 /// template-id.
getTemplateArgs()1409 const TemplateArgumentLoc *getTemplateArgs() const {
1410 if (!hasExplicitTemplateArgs())
1411 return nullptr;
1412 return getTrailingObjects<TemplateArgumentLoc>();
1413 }
1414
1415 /// Retrieve the number of template arguments provided as part of this
1416 /// template-id.
getNumTemplateArgs()1417 unsigned getNumTemplateArgs() const {
1418 if (!hasExplicitTemplateArgs())
1419 return 0;
1420 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1421 }
1422
template_arguments()1423 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1424 return {getTemplateArgs(), getNumTemplateArgs()};
1425 }
1426
1427 /// Returns true if this expression refers to a function that
1428 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()1429 bool hadMultipleCandidates() const {
1430 return DeclRefExprBits.HadMultipleCandidates;
1431 }
1432 /// Sets the flag telling whether this expression refers to
1433 /// a function that was resolved from an overloaded set having size
1434 /// greater than 1.
1435 void setHadMultipleCandidates(bool V = true) {
1436 DeclRefExprBits.HadMultipleCandidates = V;
1437 }
1438
1439 /// Is this expression a non-odr-use reference, and if so, why?
isNonOdrUse()1440 NonOdrUseReason isNonOdrUse() const {
1441 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1442 }
1443
1444 /// Does this DeclRefExpr refer to an enclosing local or a captured
1445 /// variable?
refersToEnclosingVariableOrCapture()1446 bool refersToEnclosingVariableOrCapture() const {
1447 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1448 }
1449
isImmediateEscalating()1450 bool isImmediateEscalating() const {
1451 return DeclRefExprBits.IsImmediateEscalating;
1452 }
1453
setIsImmediateEscalating(bool Set)1454 void setIsImmediateEscalating(bool Set) {
1455 DeclRefExprBits.IsImmediateEscalating = Set;
1456 }
1457
isCapturedByCopyInLambdaWithExplicitObjectParameter()1458 bool isCapturedByCopyInLambdaWithExplicitObjectParameter() const {
1459 return DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1460 }
1461
setCapturedByCopyInLambdaWithExplicitObjectParameter(bool Set,const ASTContext & Context)1462 void setCapturedByCopyInLambdaWithExplicitObjectParameter(
1463 bool Set, const ASTContext &Context) {
1464 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1465 setDependence(computeDependence(this, Context));
1466 }
1467
classof(const Stmt * T)1468 static bool classof(const Stmt *T) {
1469 return T->getStmtClass() == DeclRefExprClass;
1470 }
1471
1472 // Iterators
children()1473 child_range children() {
1474 return child_range(child_iterator(), child_iterator());
1475 }
1476
children()1477 const_child_range children() const {
1478 return const_child_range(const_child_iterator(), const_child_iterator());
1479 }
1480 };
1481
1482 class IntegerLiteral : public Expr, public APIntStorage {
1483 SourceLocation Loc;
1484
1485 /// Construct an empty integer literal.
IntegerLiteral(EmptyShell Empty)1486 explicit IntegerLiteral(EmptyShell Empty)
1487 : Expr(IntegerLiteralClass, Empty) { }
1488
1489 public:
1490 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1491 // or UnsignedLongLongTy
1492 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1493 SourceLocation l);
1494
1495 /// Returns a new integer literal with value 'V' and type 'type'.
1496 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1497 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1498 /// \param V - the value that the returned integer literal contains.
1499 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1500 QualType type, SourceLocation l);
1501 /// Returns a new empty integer literal.
1502 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1503
getBeginLoc()1504 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1505 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1506
1507 /// Retrieve the location of the literal.
getLocation()1508 SourceLocation getLocation() const { return Loc; }
1509
setLocation(SourceLocation Location)1510 void setLocation(SourceLocation Location) { Loc = Location; }
1511
classof(const Stmt * T)1512 static bool classof(const Stmt *T) {
1513 return T->getStmtClass() == IntegerLiteralClass;
1514 }
1515
1516 // Iterators
children()1517 child_range children() {
1518 return child_range(child_iterator(), child_iterator());
1519 }
children()1520 const_child_range children() const {
1521 return const_child_range(const_child_iterator(), const_child_iterator());
1522 }
1523 };
1524
1525 class FixedPointLiteral : public Expr, public APIntStorage {
1526 SourceLocation Loc;
1527 unsigned Scale;
1528
1529 /// \brief Construct an empty fixed-point literal.
FixedPointLiteral(EmptyShell Empty)1530 explicit FixedPointLiteral(EmptyShell Empty)
1531 : Expr(FixedPointLiteralClass, Empty) {}
1532
1533 public:
1534 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1535 SourceLocation l, unsigned Scale);
1536
1537 // Store the int as is without any bit shifting.
1538 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1539 const llvm::APInt &V,
1540 QualType type, SourceLocation l,
1541 unsigned Scale);
1542
1543 /// Returns an empty fixed-point literal.
1544 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1545
getBeginLoc()1546 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1547 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1548
1549 /// \brief Retrieve the location of the literal.
getLocation()1550 SourceLocation getLocation() const { return Loc; }
1551
setLocation(SourceLocation Location)1552 void setLocation(SourceLocation Location) { Loc = Location; }
1553
getScale()1554 unsigned getScale() const { return Scale; }
setScale(unsigned S)1555 void setScale(unsigned S) { Scale = S; }
1556
classof(const Stmt * T)1557 static bool classof(const Stmt *T) {
1558 return T->getStmtClass() == FixedPointLiteralClass;
1559 }
1560
1561 std::string getValueAsString(unsigned Radix) const;
1562
1563 // Iterators
children()1564 child_range children() {
1565 return child_range(child_iterator(), child_iterator());
1566 }
children()1567 const_child_range children() const {
1568 return const_child_range(const_child_iterator(), const_child_iterator());
1569 }
1570 };
1571
1572 enum class CharacterLiteralKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1573
1574 class CharacterLiteral : public Expr {
1575 unsigned Value;
1576 SourceLocation Loc;
1577 public:
1578 // type should be IntTy
CharacterLiteral(unsigned value,CharacterLiteralKind kind,QualType type,SourceLocation l)1579 CharacterLiteral(unsigned value, CharacterLiteralKind kind, QualType type,
1580 SourceLocation l)
1581 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1582 Value(value), Loc(l) {
1583 CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1584 setDependence(ExprDependence::None);
1585 }
1586
1587 /// Construct an empty character literal.
CharacterLiteral(EmptyShell Empty)1588 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1589
getLocation()1590 SourceLocation getLocation() const { return Loc; }
getKind()1591 CharacterLiteralKind getKind() const {
1592 return static_cast<CharacterLiteralKind>(CharacterLiteralBits.Kind);
1593 }
1594
getBeginLoc()1595 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1596 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1597
getValue()1598 unsigned getValue() const { return Value; }
1599
setLocation(SourceLocation Location)1600 void setLocation(SourceLocation Location) { Loc = Location; }
setKind(CharacterLiteralKind kind)1601 void setKind(CharacterLiteralKind kind) {
1602 CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1603 }
setValue(unsigned Val)1604 void setValue(unsigned Val) { Value = Val; }
1605
classof(const Stmt * T)1606 static bool classof(const Stmt *T) {
1607 return T->getStmtClass() == CharacterLiteralClass;
1608 }
1609
1610 static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS);
1611
1612 // Iterators
children()1613 child_range children() {
1614 return child_range(child_iterator(), child_iterator());
1615 }
children()1616 const_child_range children() const {
1617 return const_child_range(const_child_iterator(), const_child_iterator());
1618 }
1619 };
1620
1621 class FloatingLiteral : public Expr, private APFloatStorage {
1622 SourceLocation Loc;
1623
1624 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1625 QualType Type, SourceLocation L);
1626
1627 /// Construct an empty floating-point literal.
1628 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1629
1630 public:
1631 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1632 bool isexact, QualType Type, SourceLocation L);
1633 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1634
getValue()1635 llvm::APFloat getValue() const {
1636 return APFloatStorage::getValue(getSemantics());
1637 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1638 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1639 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1640 APFloatStorage::setValue(C, Val);
1641 }
1642
1643 /// Get a raw enumeration value representing the floating-point semantics of
1644 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
getRawSemantics()1645 llvm::APFloatBase::Semantics getRawSemantics() const {
1646 return static_cast<llvm::APFloatBase::Semantics>(
1647 FloatingLiteralBits.Semantics);
1648 }
1649
1650 /// Set the raw enumeration value representing the floating-point semantics of
1651 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
setRawSemantics(llvm::APFloatBase::Semantics Sem)1652 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1653 FloatingLiteralBits.Semantics = Sem;
1654 }
1655
1656 /// Return the APFloat semantics this literal uses.
getSemantics()1657 const llvm::fltSemantics &getSemantics() const {
1658 return llvm::APFloatBase::EnumToSemantics(
1659 static_cast<llvm::APFloatBase::Semantics>(
1660 FloatingLiteralBits.Semantics));
1661 }
1662
1663 /// Set the APFloat semantics this literal uses.
setSemantics(const llvm::fltSemantics & Sem)1664 void setSemantics(const llvm::fltSemantics &Sem) {
1665 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1666 }
1667
isExact()1668 bool isExact() const { return FloatingLiteralBits.IsExact; }
setExact(bool E)1669 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1670
1671 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1672 /// double. Note that this may cause loss of precision, but is useful for
1673 /// debugging dumps, etc.
1674 double getValueAsApproximateDouble() const;
1675
getLocation()1676 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1677 void setLocation(SourceLocation L) { Loc = L; }
1678
getBeginLoc()1679 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1680 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1681
classof(const Stmt * T)1682 static bool classof(const Stmt *T) {
1683 return T->getStmtClass() == FloatingLiteralClass;
1684 }
1685
1686 // Iterators
children()1687 child_range children() {
1688 return child_range(child_iterator(), child_iterator());
1689 }
children()1690 const_child_range children() const {
1691 return const_child_range(const_child_iterator(), const_child_iterator());
1692 }
1693 };
1694
1695 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1696 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1697 /// IntegerLiteral classes. Instances of this class always have a Complex type
1698 /// whose element type matches the subexpression.
1699 ///
1700 class ImaginaryLiteral : public Expr {
1701 Stmt *Val;
1702 public:
ImaginaryLiteral(Expr * val,QualType Ty)1703 ImaginaryLiteral(Expr *val, QualType Ty)
1704 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1705 setDependence(ExprDependence::None);
1706 }
1707
1708 /// Build an empty imaginary literal.
ImaginaryLiteral(EmptyShell Empty)1709 explicit ImaginaryLiteral(EmptyShell Empty)
1710 : Expr(ImaginaryLiteralClass, Empty) { }
1711
getSubExpr()1712 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()1713 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)1714 void setSubExpr(Expr *E) { Val = E; }
1715
getBeginLoc()1716 SourceLocation getBeginLoc() const LLVM_READONLY {
1717 return Val->getBeginLoc();
1718 }
getEndLoc()1719 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1720
classof(const Stmt * T)1721 static bool classof(const Stmt *T) {
1722 return T->getStmtClass() == ImaginaryLiteralClass;
1723 }
1724
1725 // Iterators
children()1726 child_range children() { return child_range(&Val, &Val+1); }
children()1727 const_child_range children() const {
1728 return const_child_range(&Val, &Val + 1);
1729 }
1730 };
1731
1732 enum class StringLiteralKind {
1733 Ordinary,
1734 Wide,
1735 UTF8,
1736 UTF16,
1737 UTF32,
1738 Unevaluated
1739 };
1740
1741 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1742 /// or L"bar" (wide strings). The actual string data can be obtained with
1743 /// getBytes() and is NOT null-terminated. The length of the string data is
1744 /// determined by calling getByteLength().
1745 ///
1746 /// The C type for a string is always a ConstantArrayType. In C++, the char
1747 /// type is const qualified, in C it is not.
1748 ///
1749 /// Note that strings in C can be formed by concatenation of multiple string
1750 /// literal pptokens in translation phase #6. This keeps track of the locations
1751 /// of each of these pieces.
1752 ///
1753 /// Strings in C can also be truncated and extended by assigning into arrays,
1754 /// e.g. with constructs like:
1755 /// char X[2] = "foobar";
1756 /// In this case, getByteLength() will return 6, but the string literal will
1757 /// have type "char[2]".
1758 class StringLiteral final
1759 : public Expr,
1760 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1761 char> {
1762 friend class ASTStmtReader;
1763 friend TrailingObjects;
1764
1765 /// StringLiteral is followed by several trailing objects. They are in order:
1766 ///
1767 /// * A single unsigned storing the length in characters of this string. The
1768 /// length in bytes is this length times the width of a single character.
1769 /// Always present and stored as a trailing objects because storing it in
1770 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1771 /// due to alignment requirements. If you add some data to StringLiteral,
1772 /// consider moving it inside StringLiteral.
1773 ///
1774 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1775 /// token this string is made of.
1776 ///
1777 /// * An array of getByteLength() char used to store the string data.
1778
numTrailingObjects(OverloadToken<unsigned>)1779 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
numTrailingObjects(OverloadToken<SourceLocation>)1780 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1781 return getNumConcatenated();
1782 }
1783
numTrailingObjects(OverloadToken<char>)1784 unsigned numTrailingObjects(OverloadToken<char>) const {
1785 return getByteLength();
1786 }
1787
getStrDataAsChar()1788 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
getStrDataAsChar()1789 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1790
getStrDataAsUInt16()1791 const uint16_t *getStrDataAsUInt16() const {
1792 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1793 }
1794
getStrDataAsUInt32()1795 const uint32_t *getStrDataAsUInt32() const {
1796 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1797 }
1798
1799 /// Build a string literal.
1800 StringLiteral(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind,
1801 bool Pascal, QualType Ty, const SourceLocation *Loc,
1802 unsigned NumConcatenated);
1803
1804 /// Build an empty string literal.
1805 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1806 unsigned CharByteWidth);
1807
1808 /// Map a target and string kind to the appropriate character width.
1809 static unsigned mapCharByteWidth(TargetInfo const &Target,
1810 StringLiteralKind SK);
1811
1812 /// Set one of the string literal token.
setStrTokenLoc(unsigned TokNum,SourceLocation L)1813 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1814 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1815 getTrailingObjects<SourceLocation>()[TokNum] = L;
1816 }
1817
1818 public:
1819 /// This is the "fully general" constructor that allows representation of
1820 /// strings formed from multiple concatenated tokens.
1821 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1822 StringLiteralKind Kind, bool Pascal, QualType Ty,
1823 const SourceLocation *Loc,
1824 unsigned NumConcatenated);
1825
1826 /// Simple constructor for string literals made from one token.
Create(const ASTContext & Ctx,StringRef Str,StringLiteralKind Kind,bool Pascal,QualType Ty,SourceLocation Loc)1827 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1828 StringLiteralKind Kind, bool Pascal, QualType Ty,
1829 SourceLocation Loc) {
1830 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1831 }
1832
1833 /// Construct an empty string literal.
1834 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1835 unsigned NumConcatenated, unsigned Length,
1836 unsigned CharByteWidth);
1837
getString()1838 StringRef getString() const {
1839 assert((isUnevaluated() || getCharByteWidth() == 1) &&
1840 "This function is used in places that assume strings use char");
1841 return StringRef(getStrDataAsChar(), getByteLength());
1842 }
1843
1844 /// Allow access to clients that need the byte representation, such as
1845 /// ASTWriterStmt::VisitStringLiteral().
getBytes()1846 StringRef getBytes() const {
1847 // FIXME: StringRef may not be the right type to use as a result for this.
1848 return StringRef(getStrDataAsChar(), getByteLength());
1849 }
1850
1851 void outputString(raw_ostream &OS) const;
1852
getCodeUnit(size_t i)1853 uint32_t getCodeUnit(size_t i) const {
1854 assert(i < getLength() && "out of bounds access");
1855 switch (getCharByteWidth()) {
1856 case 1:
1857 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1858 case 2:
1859 return getStrDataAsUInt16()[i];
1860 case 4:
1861 return getStrDataAsUInt32()[i];
1862 }
1863 llvm_unreachable("Unsupported character width!");
1864 }
1865
getByteLength()1866 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
getLength()1867 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
getCharByteWidth()1868 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1869
getKind()1870 StringLiteralKind getKind() const {
1871 return static_cast<StringLiteralKind>(StringLiteralBits.Kind);
1872 }
1873
isOrdinary()1874 bool isOrdinary() const { return getKind() == StringLiteralKind::Ordinary; }
isWide()1875 bool isWide() const { return getKind() == StringLiteralKind::Wide; }
isUTF8()1876 bool isUTF8() const { return getKind() == StringLiteralKind::UTF8; }
isUTF16()1877 bool isUTF16() const { return getKind() == StringLiteralKind::UTF16; }
isUTF32()1878 bool isUTF32() const { return getKind() == StringLiteralKind::UTF32; }
isUnevaluated()1879 bool isUnevaluated() const { return getKind() == StringLiteralKind::Unevaluated; }
isPascal()1880 bool isPascal() const { return StringLiteralBits.IsPascal; }
1881
containsNonAscii()1882 bool containsNonAscii() const {
1883 for (auto c : getString())
1884 if (!isASCII(c))
1885 return true;
1886 return false;
1887 }
1888
containsNonAsciiOrNull()1889 bool containsNonAsciiOrNull() const {
1890 for (auto c : getString())
1891 if (!isASCII(c) || !c)
1892 return true;
1893 return false;
1894 }
1895
1896 /// getNumConcatenated - Get the number of string literal tokens that were
1897 /// concatenated in translation phase #6 to form this string literal.
getNumConcatenated()1898 unsigned getNumConcatenated() const {
1899 return StringLiteralBits.NumConcatenated;
1900 }
1901
1902 /// Get one of the string literal token.
getStrTokenLoc(unsigned TokNum)1903 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1904 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1905 return getTrailingObjects<SourceLocation>()[TokNum];
1906 }
1907
1908 /// getLocationOfByte - Return a source location that points to the specified
1909 /// byte of this string literal.
1910 ///
1911 /// Strings are amazingly complex. They can be formed from multiple tokens
1912 /// and can have escape sequences in them in addition to the usual trigraph
1913 /// and escaped newline business. This routine handles this complexity.
1914 ///
1915 SourceLocation
1916 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1917 const LangOptions &Features, const TargetInfo &Target,
1918 unsigned *StartToken = nullptr,
1919 unsigned *StartTokenByteOffset = nullptr) const;
1920
1921 typedef const SourceLocation *tokloc_iterator;
1922
tokloc_begin()1923 tokloc_iterator tokloc_begin() const {
1924 return getTrailingObjects<SourceLocation>();
1925 }
1926
tokloc_end()1927 tokloc_iterator tokloc_end() const {
1928 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1929 }
1930
getBeginLoc()1931 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
getEndLoc()1932 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1933
classof(const Stmt * T)1934 static bool classof(const Stmt *T) {
1935 return T->getStmtClass() == StringLiteralClass;
1936 }
1937
1938 // Iterators
children()1939 child_range children() {
1940 return child_range(child_iterator(), child_iterator());
1941 }
children()1942 const_child_range children() const {
1943 return const_child_range(const_child_iterator(), const_child_iterator());
1944 }
1945 };
1946
1947 enum class PredefinedIdentKind {
1948 Func,
1949 Function,
1950 LFunction, // Same as Function, but as wide string.
1951 FuncDName,
1952 FuncSig,
1953 LFuncSig, // Same as FuncSig, but as wide string
1954 PrettyFunction,
1955 /// The same as PrettyFunction, except that the
1956 /// 'virtual' keyword is omitted for virtual member functions.
1957 PrettyFunctionNoVirtual
1958 };
1959
1960 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1961 class PredefinedExpr final
1962 : public Expr,
1963 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1964 friend class ASTStmtReader;
1965 friend TrailingObjects;
1966
1967 // PredefinedExpr is optionally followed by a single trailing
1968 // "Stmt *" for the predefined identifier. It is present if and only if
1969 // hasFunctionName() is true and is always a "StringLiteral *".
1970
1971 PredefinedExpr(SourceLocation L, QualType FNTy, PredefinedIdentKind IK,
1972 bool IsTransparent, StringLiteral *SL);
1973
1974 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1975
1976 /// True if this PredefinedExpr has storage for a function name.
hasFunctionName()1977 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1978
setFunctionName(StringLiteral * SL)1979 void setFunctionName(StringLiteral *SL) {
1980 assert(hasFunctionName() &&
1981 "This PredefinedExpr has no storage for a function name!");
1982 *getTrailingObjects<Stmt *>() = SL;
1983 }
1984
1985 public:
1986 /// Create a PredefinedExpr.
1987 ///
1988 /// If IsTransparent, the PredefinedExpr is transparently handled as a
1989 /// StringLiteral.
1990 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1991 QualType FNTy, PredefinedIdentKind IK,
1992 bool IsTransparent, StringLiteral *SL);
1993
1994 /// Create an empty PredefinedExpr.
1995 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1996 bool HasFunctionName);
1997
getIdentKind()1998 PredefinedIdentKind getIdentKind() const {
1999 return static_cast<PredefinedIdentKind>(PredefinedExprBits.Kind);
2000 }
2001
isTransparent()2002 bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2003
getLocation()2004 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
setLocation(SourceLocation L)2005 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2006
getFunctionName()2007 StringLiteral *getFunctionName() {
2008 return hasFunctionName()
2009 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2010 : nullptr;
2011 }
2012
getFunctionName()2013 const StringLiteral *getFunctionName() const {
2014 return hasFunctionName()
2015 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2016 : nullptr;
2017 }
2018
2019 static StringRef getIdentKindName(PredefinedIdentKind IK);
getIdentKindName()2020 StringRef getIdentKindName() const {
2021 return getIdentKindName(getIdentKind());
2022 }
2023
2024 static std::string ComputeName(PredefinedIdentKind IK,
2025 const Decl *CurrentDecl);
2026
getBeginLoc()2027 SourceLocation getBeginLoc() const { return getLocation(); }
getEndLoc()2028 SourceLocation getEndLoc() const { return getLocation(); }
2029
classof(const Stmt * T)2030 static bool classof(const Stmt *T) {
2031 return T->getStmtClass() == PredefinedExprClass;
2032 }
2033
2034 // Iterators
children()2035 child_range children() {
2036 return child_range(getTrailingObjects<Stmt *>(),
2037 getTrailingObjects<Stmt *>() + hasFunctionName());
2038 }
2039
children()2040 const_child_range children() const {
2041 return const_child_range(getTrailingObjects<Stmt *>(),
2042 getTrailingObjects<Stmt *>() + hasFunctionName());
2043 }
2044 };
2045
2046 // This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2047 // type-id, and at CodeGen time emits a unique string representation of the
2048 // type in a way that permits us to properly encode information about the SYCL
2049 // kernels.
2050 class SYCLUniqueStableNameExpr final : public Expr {
2051 friend class ASTStmtReader;
2052 SourceLocation OpLoc, LParen, RParen;
2053 TypeSourceInfo *TypeInfo;
2054
2055 SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2056 SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2057 SourceLocation RParen, QualType ResultTy,
2058 TypeSourceInfo *TSI);
2059
setTypeSourceInfo(TypeSourceInfo * Ty)2060 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2061
setLocation(SourceLocation L)2062 void setLocation(SourceLocation L) { OpLoc = L; }
setLParenLocation(SourceLocation L)2063 void setLParenLocation(SourceLocation L) { LParen = L; }
setRParenLocation(SourceLocation L)2064 void setRParenLocation(SourceLocation L) { RParen = L; }
2065
2066 public:
getTypeSourceInfo()2067 TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2068
getTypeSourceInfo()2069 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2070
2071 static SYCLUniqueStableNameExpr *
2072 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2073 SourceLocation RParen, TypeSourceInfo *TSI);
2074
2075 static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2076
getBeginLoc()2077 SourceLocation getBeginLoc() const { return getLocation(); }
getEndLoc()2078 SourceLocation getEndLoc() const { return RParen; }
getLocation()2079 SourceLocation getLocation() const { return OpLoc; }
getLParenLocation()2080 SourceLocation getLParenLocation() const { return LParen; }
getRParenLocation()2081 SourceLocation getRParenLocation() const { return RParen; }
2082
classof(const Stmt * T)2083 static bool classof(const Stmt *T) {
2084 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2085 }
2086
2087 // Iterators
children()2088 child_range children() {
2089 return child_range(child_iterator(), child_iterator());
2090 }
2091
children()2092 const_child_range children() const {
2093 return const_child_range(const_child_iterator(), const_child_iterator());
2094 }
2095
2096 // Convenience function to generate the name of the currently stored type.
2097 std::string ComputeName(ASTContext &Context) const;
2098
2099 // Get the generated name of the type. Note that this only works after all
2100 // kernels have been instantiated.
2101 static std::string ComputeName(ASTContext &Context, QualType Ty);
2102 };
2103
2104 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2105 /// AST node is only formed if full location information is requested.
2106 class ParenExpr : public Expr {
2107 SourceLocation L, R;
2108 Stmt *Val;
2109 public:
ParenExpr(SourceLocation l,SourceLocation r,Expr * val)2110 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2111 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2112 val->getObjectKind()),
2113 L(l), R(r), Val(val) {
2114 setDependence(computeDependence(this));
2115 }
2116
2117 /// Construct an empty parenthesized expression.
ParenExpr(EmptyShell Empty)2118 explicit ParenExpr(EmptyShell Empty)
2119 : Expr(ParenExprClass, Empty) { }
2120
getSubExpr()2121 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()2122 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)2123 void setSubExpr(Expr *E) { Val = E; }
2124
getBeginLoc()2125 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
getEndLoc()2126 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2127
2128 /// Get the location of the left parentheses '('.
getLParen()2129 SourceLocation getLParen() const { return L; }
setLParen(SourceLocation Loc)2130 void setLParen(SourceLocation Loc) { L = Loc; }
2131
2132 /// Get the location of the right parentheses ')'.
getRParen()2133 SourceLocation getRParen() const { return R; }
setRParen(SourceLocation Loc)2134 void setRParen(SourceLocation Loc) { R = Loc; }
2135
classof(const Stmt * T)2136 static bool classof(const Stmt *T) {
2137 return T->getStmtClass() == ParenExprClass;
2138 }
2139
2140 // Iterators
children()2141 child_range children() { return child_range(&Val, &Val+1); }
children()2142 const_child_range children() const {
2143 return const_child_range(&Val, &Val + 1);
2144 }
2145 };
2146
2147 /// UnaryOperator - This represents the unary-expression's (except sizeof and
2148 /// alignof), the postinc/postdec operators from postfix-expression, and various
2149 /// extensions.
2150 ///
2151 /// Notes on various nodes:
2152 ///
2153 /// Real/Imag - These return the real/imag part of a complex operand. If
2154 /// applied to a non-complex value, the former returns its operand and the
2155 /// later returns zero in the type of the operand.
2156 ///
2157 class UnaryOperator final
2158 : public Expr,
2159 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2160 Stmt *Val;
2161
numTrailingObjects(OverloadToken<FPOptionsOverride>)2162 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2163 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2164 }
2165
getTrailingFPFeatures()2166 FPOptionsOverride &getTrailingFPFeatures() {
2167 assert(UnaryOperatorBits.HasFPFeatures);
2168 return *getTrailingObjects<FPOptionsOverride>();
2169 }
2170
getTrailingFPFeatures()2171 const FPOptionsOverride &getTrailingFPFeatures() const {
2172 assert(UnaryOperatorBits.HasFPFeatures);
2173 return *getTrailingObjects<FPOptionsOverride>();
2174 }
2175
2176 public:
2177 typedef UnaryOperatorKind Opcode;
2178
2179 protected:
2180 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2181 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2182 bool CanOverflow, FPOptionsOverride FPFeatures);
2183
2184 /// Build an empty unary operator.
UnaryOperator(bool HasFPFeatures,EmptyShell Empty)2185 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2186 : Expr(UnaryOperatorClass, Empty) {
2187 UnaryOperatorBits.Opc = UO_AddrOf;
2188 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2189 }
2190
2191 public:
2192 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2193
2194 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2195 QualType type, ExprValueKind VK,
2196 ExprObjectKind OK, SourceLocation l,
2197 bool CanOverflow, FPOptionsOverride FPFeatures);
2198
getOpcode()2199 Opcode getOpcode() const {
2200 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2201 }
setOpcode(Opcode Opc)2202 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2203
getSubExpr()2204 Expr *getSubExpr() const { return cast<Expr>(Val); }
setSubExpr(Expr * E)2205 void setSubExpr(Expr *E) { Val = E; }
2206
2207 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2208 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
setOperatorLoc(SourceLocation L)2209 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2210
2211 /// Returns true if the unary operator can cause an overflow. For instance,
2212 /// signed int i = INT_MAX; i++;
2213 /// signed char c = CHAR_MAX; c++;
2214 /// Due to integer promotions, c++ is promoted to an int before the postfix
2215 /// increment, and the result is an int that cannot overflow. However, i++
2216 /// can overflow.
canOverflow()2217 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
setCanOverflow(bool C)2218 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2219
2220 /// Get the FP contractability status of this operator. Only meaningful for
2221 /// operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)2222 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2223 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2224 }
2225
2226 /// Get the FENV_ACCESS status of this operator. Only meaningful for
2227 /// operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)2228 bool isFEnvAccessOn(const LangOptions &LO) const {
2229 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2230 }
2231
2232 /// isPostfix - Return true if this is a postfix operation, like x++.
isPostfix(Opcode Op)2233 static bool isPostfix(Opcode Op) {
2234 return Op == UO_PostInc || Op == UO_PostDec;
2235 }
2236
2237 /// isPrefix - Return true if this is a prefix operation, like --x.
isPrefix(Opcode Op)2238 static bool isPrefix(Opcode Op) {
2239 return Op == UO_PreInc || Op == UO_PreDec;
2240 }
2241
isPrefix()2242 bool isPrefix() const { return isPrefix(getOpcode()); }
isPostfix()2243 bool isPostfix() const { return isPostfix(getOpcode()); }
2244
isIncrementOp(Opcode Op)2245 static bool isIncrementOp(Opcode Op) {
2246 return Op == UO_PreInc || Op == UO_PostInc;
2247 }
isIncrementOp()2248 bool isIncrementOp() const {
2249 return isIncrementOp(getOpcode());
2250 }
2251
isDecrementOp(Opcode Op)2252 static bool isDecrementOp(Opcode Op) {
2253 return Op == UO_PreDec || Op == UO_PostDec;
2254 }
isDecrementOp()2255 bool isDecrementOp() const {
2256 return isDecrementOp(getOpcode());
2257 }
2258
isIncrementDecrementOp(Opcode Op)2259 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
isIncrementDecrementOp()2260 bool isIncrementDecrementOp() const {
2261 return isIncrementDecrementOp(getOpcode());
2262 }
2263
isArithmeticOp(Opcode Op)2264 static bool isArithmeticOp(Opcode Op) {
2265 return Op >= UO_Plus && Op <= UO_LNot;
2266 }
isArithmeticOp()2267 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2268
2269 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2270 /// corresponds to, e.g. "sizeof" or "[pre]++"
2271 static StringRef getOpcodeStr(Opcode Op);
2272
2273 /// Retrieve the unary opcode that corresponds to the given
2274 /// overloaded operator.
2275 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2276
2277 /// Retrieve the overloaded operator kind that corresponds to
2278 /// the given unary opcode.
2279 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2280
getBeginLoc()2281 SourceLocation getBeginLoc() const LLVM_READONLY {
2282 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2283 }
getEndLoc()2284 SourceLocation getEndLoc() const LLVM_READONLY {
2285 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2286 }
getExprLoc()2287 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2288
classof(const Stmt * T)2289 static bool classof(const Stmt *T) {
2290 return T->getStmtClass() == UnaryOperatorClass;
2291 }
2292
2293 // Iterators
children()2294 child_range children() { return child_range(&Val, &Val+1); }
children()2295 const_child_range children() const {
2296 return const_child_range(&Val, &Val + 1);
2297 }
2298
2299 /// Is FPFeatures in Trailing Storage?
hasStoredFPFeatures()2300 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2301
2302 /// Get FPFeatures from trailing storage.
getStoredFPFeatures()2303 FPOptionsOverride getStoredFPFeatures() const {
2304 return getTrailingFPFeatures();
2305 }
2306
2307 protected:
2308 /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
setStoredFPFeatures(FPOptionsOverride F)2309 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2310
2311 public:
2312 /// Get the FP features status of this operator. Only meaningful for
2313 /// operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)2314 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2315 if (UnaryOperatorBits.HasFPFeatures)
2316 return getStoredFPFeatures().applyOverrides(LO);
2317 return FPOptions::defaultWithoutTrailingStorage(LO);
2318 }
getFPOptionsOverride()2319 FPOptionsOverride getFPOptionsOverride() const {
2320 if (UnaryOperatorBits.HasFPFeatures)
2321 return getStoredFPFeatures();
2322 return FPOptionsOverride();
2323 }
2324
2325 friend TrailingObjects;
2326 friend class ASTNodeImporter;
2327 friend class ASTReader;
2328 friend class ASTStmtReader;
2329 friend class ASTStmtWriter;
2330 };
2331
2332 /// Helper class for OffsetOfExpr.
2333
2334 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2335 class OffsetOfNode {
2336 public:
2337 /// The kind of offsetof node we have.
2338 enum Kind {
2339 /// An index into an array.
2340 Array = 0x00,
2341 /// A field.
2342 Field = 0x01,
2343 /// A field in a dependent type, known only by its name.
2344 Identifier = 0x02,
2345 /// An implicit indirection through a C++ base class, when the
2346 /// field found is in a base class.
2347 Base = 0x03
2348 };
2349
2350 private:
2351 enum { MaskBits = 2, Mask = 0x03 };
2352
2353 /// The source range that covers this part of the designator.
2354 SourceRange Range;
2355
2356 /// The data describing the designator, which comes in three
2357 /// different forms, depending on the lower two bits.
2358 /// - An unsigned index into the array of Expr*'s stored after this node
2359 /// in memory, for [constant-expression] designators.
2360 /// - A FieldDecl*, for references to a known field.
2361 /// - An IdentifierInfo*, for references to a field with a given name
2362 /// when the class type is dependent.
2363 /// - A CXXBaseSpecifier*, for references that look at a field in a
2364 /// base class.
2365 uintptr_t Data;
2366
2367 public:
2368 /// Create an offsetof node that refers to an array element.
OffsetOfNode(SourceLocation LBracketLoc,unsigned Index,SourceLocation RBracketLoc)2369 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2370 SourceLocation RBracketLoc)
2371 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2372
2373 /// Create an offsetof node that refers to a field.
OffsetOfNode(SourceLocation DotLoc,FieldDecl * Field,SourceLocation NameLoc)2374 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2375 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2376 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2377
2378 /// Create an offsetof node that refers to an identifier.
OffsetOfNode(SourceLocation DotLoc,IdentifierInfo * Name,SourceLocation NameLoc)2379 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2380 SourceLocation NameLoc)
2381 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2382 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2383
2384 /// Create an offsetof node that refers into a C++ base class.
OffsetOfNode(const CXXBaseSpecifier * Base)2385 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2386 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2387
2388 /// Determine what kind of offsetof node this is.
getKind()2389 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2390
2391 /// For an array element node, returns the index into the array
2392 /// of expressions.
getArrayExprIndex()2393 unsigned getArrayExprIndex() const {
2394 assert(getKind() == Array);
2395 return Data >> 2;
2396 }
2397
2398 /// For a field offsetof node, returns the field.
getField()2399 FieldDecl *getField() const {
2400 assert(getKind() == Field);
2401 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2402 }
2403
2404 /// For a field or identifier offsetof node, returns the name of
2405 /// the field.
2406 IdentifierInfo *getFieldName() const;
2407
2408 /// For a base class node, returns the base specifier.
getBase()2409 CXXBaseSpecifier *getBase() const {
2410 assert(getKind() == Base);
2411 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2412 }
2413
2414 /// Retrieve the source range that covers this offsetof node.
2415 ///
2416 /// For an array element node, the source range contains the locations of
2417 /// the square brackets. For a field or identifier node, the source range
2418 /// contains the location of the period (if there is one) and the
2419 /// identifier.
getSourceRange()2420 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getBeginLoc()2421 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
getEndLoc()2422 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2423 };
2424
2425 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2426 /// offsetof(record-type, member-designator). For example, given:
2427 /// @code
2428 /// struct S {
2429 /// float f;
2430 /// double d;
2431 /// };
2432 /// struct T {
2433 /// int i;
2434 /// struct S s[10];
2435 /// };
2436 /// @endcode
2437 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2438
2439 class OffsetOfExpr final
2440 : public Expr,
2441 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2442 SourceLocation OperatorLoc, RParenLoc;
2443 // Base type;
2444 TypeSourceInfo *TSInfo;
2445 // Number of sub-components (i.e. instances of OffsetOfNode).
2446 unsigned NumComps;
2447 // Number of sub-expressions (i.e. array subscript expressions).
2448 unsigned NumExprs;
2449
numTrailingObjects(OverloadToken<OffsetOfNode>)2450 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2451 return NumComps;
2452 }
2453
2454 OffsetOfExpr(const ASTContext &C, QualType type,
2455 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2456 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2457 SourceLocation RParenLoc);
2458
OffsetOfExpr(unsigned numComps,unsigned numExprs)2459 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2460 : Expr(OffsetOfExprClass, EmptyShell()),
2461 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2462
2463 public:
2464
2465 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2466 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2467 ArrayRef<OffsetOfNode> comps,
2468 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2469
2470 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2471 unsigned NumComps, unsigned NumExprs);
2472
2473 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2474 SourceLocation getOperatorLoc() const { return OperatorLoc; }
setOperatorLoc(SourceLocation L)2475 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2476
2477 /// Return the location of the right parentheses.
getRParenLoc()2478 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation R)2479 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2480
getTypeSourceInfo()2481 TypeSourceInfo *getTypeSourceInfo() const {
2482 return TSInfo;
2483 }
setTypeSourceInfo(TypeSourceInfo * tsi)2484 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2485 TSInfo = tsi;
2486 }
2487
getComponent(unsigned Idx)2488 const OffsetOfNode &getComponent(unsigned Idx) const {
2489 assert(Idx < NumComps && "Subscript out of range");
2490 return getTrailingObjects<OffsetOfNode>()[Idx];
2491 }
2492
setComponent(unsigned Idx,OffsetOfNode ON)2493 void setComponent(unsigned Idx, OffsetOfNode ON) {
2494 assert(Idx < NumComps && "Subscript out of range");
2495 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2496 }
2497
getNumComponents()2498 unsigned getNumComponents() const {
2499 return NumComps;
2500 }
2501
getIndexExpr(unsigned Idx)2502 Expr* getIndexExpr(unsigned Idx) {
2503 assert(Idx < NumExprs && "Subscript out of range");
2504 return getTrailingObjects<Expr *>()[Idx];
2505 }
2506
getIndexExpr(unsigned Idx)2507 const Expr *getIndexExpr(unsigned Idx) const {
2508 assert(Idx < NumExprs && "Subscript out of range");
2509 return getTrailingObjects<Expr *>()[Idx];
2510 }
2511
setIndexExpr(unsigned Idx,Expr * E)2512 void setIndexExpr(unsigned Idx, Expr* E) {
2513 assert(Idx < NumComps && "Subscript out of range");
2514 getTrailingObjects<Expr *>()[Idx] = E;
2515 }
2516
getNumExpressions()2517 unsigned getNumExpressions() const {
2518 return NumExprs;
2519 }
2520
getBeginLoc()2521 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
getEndLoc()2522 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2523
classof(const Stmt * T)2524 static bool classof(const Stmt *T) {
2525 return T->getStmtClass() == OffsetOfExprClass;
2526 }
2527
2528 // Iterators
children()2529 child_range children() {
2530 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2531 return child_range(begin, begin + NumExprs);
2532 }
children()2533 const_child_range children() const {
2534 Stmt *const *begin =
2535 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2536 return const_child_range(begin, begin + NumExprs);
2537 }
2538 friend TrailingObjects;
2539 };
2540
2541 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2542 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2543 /// vec_step (OpenCL 1.1 6.11.12).
2544 class UnaryExprOrTypeTraitExpr : public Expr {
2545 union {
2546 TypeSourceInfo *Ty;
2547 Stmt *Ex;
2548 } Argument;
2549 SourceLocation OpLoc, RParenLoc;
2550
2551 public:
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,TypeSourceInfo * TInfo,QualType resultType,SourceLocation op,SourceLocation rp)2552 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2553 QualType resultType, SourceLocation op,
2554 SourceLocation rp)
2555 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2556 OK_Ordinary),
2557 OpLoc(op), RParenLoc(rp) {
2558 assert(ExprKind <= UETT_Last && "invalid enum value!");
2559 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2560 assert(static_cast<unsigned>(ExprKind) ==
2561 UnaryExprOrTypeTraitExprBits.Kind &&
2562 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2563 UnaryExprOrTypeTraitExprBits.IsType = true;
2564 Argument.Ty = TInfo;
2565 setDependence(computeDependence(this));
2566 }
2567
2568 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2569 QualType resultType, SourceLocation op,
2570 SourceLocation rp);
2571
2572 /// Construct an empty sizeof/alignof expression.
UnaryExprOrTypeTraitExpr(EmptyShell Empty)2573 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2574 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2575
getKind()2576 UnaryExprOrTypeTrait getKind() const {
2577 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2578 }
setKind(UnaryExprOrTypeTrait K)2579 void setKind(UnaryExprOrTypeTrait K) {
2580 assert(K <= UETT_Last && "invalid enum value!");
2581 UnaryExprOrTypeTraitExprBits.Kind = K;
2582 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2583 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2584 }
2585
isArgumentType()2586 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
getArgumentType()2587 QualType getArgumentType() const {
2588 return getArgumentTypeInfo()->getType();
2589 }
getArgumentTypeInfo()2590 TypeSourceInfo *getArgumentTypeInfo() const {
2591 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2592 return Argument.Ty;
2593 }
getArgumentExpr()2594 Expr *getArgumentExpr() {
2595 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2596 return static_cast<Expr*>(Argument.Ex);
2597 }
getArgumentExpr()2598 const Expr *getArgumentExpr() const {
2599 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2600 }
2601
setArgument(Expr * E)2602 void setArgument(Expr *E) {
2603 Argument.Ex = E;
2604 UnaryExprOrTypeTraitExprBits.IsType = false;
2605 }
setArgument(TypeSourceInfo * TInfo)2606 void setArgument(TypeSourceInfo *TInfo) {
2607 Argument.Ty = TInfo;
2608 UnaryExprOrTypeTraitExprBits.IsType = true;
2609 }
2610
2611 /// Gets the argument type, or the type of the argument expression, whichever
2612 /// is appropriate.
getTypeOfArgument()2613 QualType getTypeOfArgument() const {
2614 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2615 }
2616
getOperatorLoc()2617 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2618 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2619
getRParenLoc()2620 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2621 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2622
getBeginLoc()2623 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
getEndLoc()2624 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2625
classof(const Stmt * T)2626 static bool classof(const Stmt *T) {
2627 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2628 }
2629
2630 // Iterators
2631 child_range children();
2632 const_child_range children() const;
2633 };
2634
2635 //===----------------------------------------------------------------------===//
2636 // Postfix Operators.
2637 //===----------------------------------------------------------------------===//
2638
2639 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2640 class ArraySubscriptExpr : public Expr {
2641 enum { LHS, RHS, END_EXPR };
2642 Stmt *SubExprs[END_EXPR];
2643
lhsIsBase()2644 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2645
2646 public:
ArraySubscriptExpr(Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation rbracketloc)2647 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2648 ExprObjectKind OK, SourceLocation rbracketloc)
2649 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2650 SubExprs[LHS] = lhs;
2651 SubExprs[RHS] = rhs;
2652 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2653 setDependence(computeDependence(this));
2654 }
2655
2656 /// Create an empty array subscript expression.
ArraySubscriptExpr(EmptyShell Shell)2657 explicit ArraySubscriptExpr(EmptyShell Shell)
2658 : Expr(ArraySubscriptExprClass, Shell) { }
2659
2660 /// An array access can be written A[4] or 4[A] (both are equivalent).
2661 /// - getBase() and getIdx() always present the normalized view: A[4].
2662 /// In this case getBase() returns "A" and getIdx() returns "4".
2663 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2664 /// 4[A] getLHS() returns "4".
2665 /// Note: Because vector element access is also written A[4] we must
2666 /// predicate the format conversion in getBase and getIdx only on the
2667 /// the type of the RHS, as it is possible for the LHS to be a vector of
2668 /// integer type
getLHS()2669 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
getLHS()2670 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2671 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2672
getRHS()2673 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
getRHS()2674 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2675 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2676
getBase()2677 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
getBase()2678 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2679
getIdx()2680 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
getIdx()2681 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2682
getBeginLoc()2683 SourceLocation getBeginLoc() const LLVM_READONLY {
2684 return getLHS()->getBeginLoc();
2685 }
getEndLoc()2686 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2687
getRBracketLoc()2688 SourceLocation getRBracketLoc() const {
2689 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2690 }
setRBracketLoc(SourceLocation L)2691 void setRBracketLoc(SourceLocation L) {
2692 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2693 }
2694
getExprLoc()2695 SourceLocation getExprLoc() const LLVM_READONLY {
2696 return getBase()->getExprLoc();
2697 }
2698
classof(const Stmt * T)2699 static bool classof(const Stmt *T) {
2700 return T->getStmtClass() == ArraySubscriptExprClass;
2701 }
2702
2703 // Iterators
children()2704 child_range children() {
2705 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2706 }
children()2707 const_child_range children() const {
2708 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2709 }
2710 };
2711
2712 /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2713 /// extension.
2714 /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2715 /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2716 /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2717 /// exist during the initial construction of the AST.
2718 class MatrixSubscriptExpr : public Expr {
2719 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2720 Stmt *SubExprs[END_EXPR];
2721
2722 public:
MatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,QualType T,SourceLocation RBracketLoc)2723 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2724 SourceLocation RBracketLoc)
2725 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2726 OK_MatrixComponent) {
2727 SubExprs[BASE] = Base;
2728 SubExprs[ROW_IDX] = RowIdx;
2729 SubExprs[COLUMN_IDX] = ColumnIdx;
2730 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2731 setDependence(computeDependence(this));
2732 }
2733
2734 /// Create an empty matrix subscript expression.
MatrixSubscriptExpr(EmptyShell Shell)2735 explicit MatrixSubscriptExpr(EmptyShell Shell)
2736 : Expr(MatrixSubscriptExprClass, Shell) {}
2737
isIncomplete()2738 bool isIncomplete() const {
2739 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2740 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2741 "expressions without column index must be marked as incomplete");
2742 return IsIncomplete;
2743 }
getBase()2744 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
getBase()2745 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
setBase(Expr * E)2746 void setBase(Expr *E) { SubExprs[BASE] = E; }
2747
getRowIdx()2748 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
getRowIdx()2749 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
setRowIdx(Expr * E)2750 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2751
getColumnIdx()2752 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
getColumnIdx()2753 const Expr *getColumnIdx() const {
2754 assert(!isIncomplete() &&
2755 "cannot get the column index of an incomplete expression");
2756 return cast<Expr>(SubExprs[COLUMN_IDX]);
2757 }
setColumnIdx(Expr * E)2758 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2759
getBeginLoc()2760 SourceLocation getBeginLoc() const LLVM_READONLY {
2761 return getBase()->getBeginLoc();
2762 }
2763
getEndLoc()2764 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2765
getExprLoc()2766 SourceLocation getExprLoc() const LLVM_READONLY {
2767 return getBase()->getExprLoc();
2768 }
2769
getRBracketLoc()2770 SourceLocation getRBracketLoc() const {
2771 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2772 }
setRBracketLoc(SourceLocation L)2773 void setRBracketLoc(SourceLocation L) {
2774 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2775 }
2776
classof(const Stmt * T)2777 static bool classof(const Stmt *T) {
2778 return T->getStmtClass() == MatrixSubscriptExprClass;
2779 }
2780
2781 // Iterators
children()2782 child_range children() {
2783 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2784 }
children()2785 const_child_range children() const {
2786 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2787 }
2788 };
2789
2790 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2791 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2792 /// while its subclasses may represent alternative syntax that (semantically)
2793 /// results in a function call. For example, CXXOperatorCallExpr is
2794 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2795 /// "str1 + str2" to resolve to a function call.
2796 class CallExpr : public Expr {
2797 enum { FN = 0, PREARGS_START = 1 };
2798
2799 /// The number of arguments in the call expression.
2800 unsigned NumArgs;
2801
2802 /// The location of the right parentheses. This has a different meaning for
2803 /// the derived classes of CallExpr.
2804 SourceLocation RParenLoc;
2805
2806 // CallExpr store some data in trailing objects. However since CallExpr
2807 // is used a base of other expression classes we cannot use
2808 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2809 // and casts.
2810 //
2811 // The trailing objects are in order:
2812 //
2813 // * A single "Stmt *" for the callee expression.
2814 //
2815 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2816 //
2817 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2818 //
2819 // * An optional of type FPOptionsOverride.
2820 //
2821 // Note that we store the offset in bytes from the this pointer to the start
2822 // of the trailing objects. It would be perfectly possible to compute it
2823 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2824 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2825 // compute this once and then load the offset from the bit-fields of Stmt,
2826 // instead of re-computing the offset each time the trailing objects are
2827 // accessed.
2828
2829 /// Return a pointer to the start of the trailing array of "Stmt *".
getTrailingStmts()2830 Stmt **getTrailingStmts() {
2831 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2832 CallExprBits.OffsetToTrailingObjects);
2833 }
getTrailingStmts()2834 Stmt *const *getTrailingStmts() const {
2835 return const_cast<CallExpr *>(this)->getTrailingStmts();
2836 }
2837
2838 /// Map a statement class to the appropriate offset in bytes from the
2839 /// this pointer to the trailing objects.
2840 static unsigned offsetToTrailingObjects(StmtClass SC);
2841
getSizeOfTrailingStmts()2842 unsigned getSizeOfTrailingStmts() const {
2843 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2844 }
2845
getOffsetOfTrailingFPFeatures()2846 size_t getOffsetOfTrailingFPFeatures() const {
2847 assert(hasStoredFPFeatures());
2848 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2849 }
2850
2851 public:
2852 enum class ADLCallKind : bool { NotADL, UsesADL };
2853 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2854 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2855
2856 protected:
2857 /// Build a call expression, assuming that appropriate storage has been
2858 /// allocated for the trailing objects.
2859 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2860 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2861 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2862 unsigned MinNumArgs, ADLCallKind UsesADL);
2863
2864 /// Build an empty call expression, for deserialization.
2865 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2866 bool hasFPFeatures, EmptyShell Empty);
2867
2868 /// Return the size in bytes needed for the trailing objects.
2869 /// Used by the derived classes to allocate the right amount of storage.
sizeOfTrailingObjects(unsigned NumPreArgs,unsigned NumArgs,bool HasFPFeatures)2870 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2871 bool HasFPFeatures) {
2872 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2873 HasFPFeatures * sizeof(FPOptionsOverride);
2874 }
2875
getPreArg(unsigned I)2876 Stmt *getPreArg(unsigned I) {
2877 assert(I < getNumPreArgs() && "Prearg access out of range!");
2878 return getTrailingStmts()[PREARGS_START + I];
2879 }
getPreArg(unsigned I)2880 const Stmt *getPreArg(unsigned I) const {
2881 assert(I < getNumPreArgs() && "Prearg access out of range!");
2882 return getTrailingStmts()[PREARGS_START + I];
2883 }
setPreArg(unsigned I,Stmt * PreArg)2884 void setPreArg(unsigned I, Stmt *PreArg) {
2885 assert(I < getNumPreArgs() && "Prearg access out of range!");
2886 getTrailingStmts()[PREARGS_START + I] = PreArg;
2887 }
2888
getNumPreArgs()2889 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2890
2891 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()2892 FPOptionsOverride *getTrailingFPFeatures() {
2893 assert(hasStoredFPFeatures());
2894 return reinterpret_cast<FPOptionsOverride *>(
2895 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2896 getSizeOfTrailingStmts());
2897 }
getTrailingFPFeatures()2898 const FPOptionsOverride *getTrailingFPFeatures() const {
2899 assert(hasStoredFPFeatures());
2900 return reinterpret_cast<const FPOptionsOverride *>(
2901 reinterpret_cast<const char *>(this) +
2902 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2903 }
2904
2905 public:
2906 /// Create a call expression.
2907 /// \param Fn The callee expression,
2908 /// \param Args The argument array,
2909 /// \param Ty The type of the call expression (which is *not* the return
2910 /// type in general),
2911 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2912 /// \param RParenLoc The location of the right parenthesis in the call
2913 /// expression.
2914 /// \param FPFeatures Floating-point features associated with the call,
2915 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2916 /// number of arguments will be the greater of Args.size()
2917 /// and MinNumArgs. This is used in a few places to allocate
2918 /// enough storage for the default arguments.
2919 /// \param UsesADL Specifies whether the callee was found through
2920 /// argument-dependent lookup.
2921 ///
2922 /// Note that you can use CreateTemporary if you need a temporary call
2923 /// expression on the stack.
2924 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2925 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2926 SourceLocation RParenLoc,
2927 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2928 ADLCallKind UsesADL = NotADL);
2929
2930 /// Create a temporary call expression with no arguments in the memory
2931 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2932 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2933 ///
2934 /// \code{.cpp}
2935 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2936 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2937 /// \endcode
2938 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2939 ExprValueKind VK, SourceLocation RParenLoc,
2940 ADLCallKind UsesADL = NotADL);
2941
2942 /// Create an empty call expression, for deserialization.
2943 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2944 bool HasFPFeatures, EmptyShell Empty);
2945
getCallee()2946 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
getCallee()2947 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
setCallee(Expr * F)2948 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2949
getADLCallKind()2950 ADLCallKind getADLCallKind() const {
2951 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2952 }
2953 void setADLCallKind(ADLCallKind V = UsesADL) {
2954 CallExprBits.UsesADL = static_cast<bool>(V);
2955 }
usesADL()2956 bool usesADL() const { return getADLCallKind() == UsesADL; }
2957
hasStoredFPFeatures()2958 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2959
getCalleeDecl()2960 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
getCalleeDecl()2961 const Decl *getCalleeDecl() const {
2962 return getCallee()->getReferencedDeclOfCallee();
2963 }
2964
2965 /// If the callee is a FunctionDecl, return it. Otherwise return null.
getDirectCallee()2966 FunctionDecl *getDirectCallee() {
2967 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2968 }
getDirectCallee()2969 const FunctionDecl *getDirectCallee() const {
2970 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2971 }
2972
2973 /// getNumArgs - Return the number of actual arguments to this call.
getNumArgs()2974 unsigned getNumArgs() const { return NumArgs; }
2975
2976 /// Retrieve the call arguments.
getArgs()2977 Expr **getArgs() {
2978 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2979 getNumPreArgs());
2980 }
getArgs()2981 const Expr *const *getArgs() const {
2982 return reinterpret_cast<const Expr *const *>(
2983 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2984 }
2985
2986 /// getArg - Return the specified argument.
getArg(unsigned Arg)2987 Expr *getArg(unsigned Arg) {
2988 assert(Arg < getNumArgs() && "Arg access out of range!");
2989 return getArgs()[Arg];
2990 }
getArg(unsigned Arg)2991 const Expr *getArg(unsigned Arg) const {
2992 assert(Arg < getNumArgs() && "Arg access out of range!");
2993 return getArgs()[Arg];
2994 }
2995
2996 /// setArg - Set the specified argument.
2997 /// ! the dependence bits might be stale after calling this setter, it is
2998 /// *caller*'s responsibility to recompute them by calling
2999 /// computeDependence().
setArg(unsigned Arg,Expr * ArgExpr)3000 void setArg(unsigned Arg, Expr *ArgExpr) {
3001 assert(Arg < getNumArgs() && "Arg access out of range!");
3002 getArgs()[Arg] = ArgExpr;
3003 }
3004
3005 /// Compute and set dependence bits.
computeDependence()3006 void computeDependence() {
3007 setDependence(clang::computeDependence(
3008 this, llvm::ArrayRef(
3009 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3010 getNumPreArgs())));
3011 }
3012
3013 /// Reduce the number of arguments in this call expression. This is used for
3014 /// example during error recovery to drop extra arguments. There is no way
3015 /// to perform the opposite because: 1.) We don't track how much storage
3016 /// we have for the argument array 2.) This would potentially require growing
3017 /// the argument array, something we cannot support since the arguments are
3018 /// stored in a trailing array.
shrinkNumArgs(unsigned NewNumArgs)3019 void shrinkNumArgs(unsigned NewNumArgs) {
3020 assert((NewNumArgs <= getNumArgs()) &&
3021 "shrinkNumArgs cannot increase the number of arguments!");
3022 NumArgs = NewNumArgs;
3023 }
3024
3025 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3026 /// Only used during construction of a CallExpr in a few places in Sema.
3027 /// FIXME: Find a way to remove it.
setNumArgsUnsafe(unsigned NewNumArgs)3028 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3029
3030 typedef ExprIterator arg_iterator;
3031 typedef ConstExprIterator const_arg_iterator;
3032 typedef llvm::iterator_range<arg_iterator> arg_range;
3033 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3034
arguments()3035 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arguments()3036 const_arg_range arguments() const {
3037 return const_arg_range(arg_begin(), arg_end());
3038 }
3039
arg_begin()3040 arg_iterator arg_begin() {
3041 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3042 }
arg_end()3043 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3044
arg_begin()3045 const_arg_iterator arg_begin() const {
3046 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3047 }
arg_end()3048 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3049
3050 /// This method provides fast access to all the subexpressions of
3051 /// a CallExpr without going through the slower virtual child_iterator
3052 /// interface. This provides efficient reverse iteration of the
3053 /// subexpressions. This is currently used for CFG construction.
getRawSubExprs()3054 ArrayRef<Stmt *> getRawSubExprs() {
3055 return llvm::ArrayRef(getTrailingStmts(),
3056 PREARGS_START + getNumPreArgs() + getNumArgs());
3057 }
3058
3059 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()3060 FPOptionsOverride getStoredFPFeatures() const {
3061 assert(hasStoredFPFeatures());
3062 return *getTrailingFPFeatures();
3063 }
3064 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
setStoredFPFeatures(FPOptionsOverride F)3065 void setStoredFPFeatures(FPOptionsOverride F) {
3066 assert(hasStoredFPFeatures());
3067 *getTrailingFPFeatures() = F;
3068 }
3069
3070 /// Get the FP features status of this operator. Only meaningful for
3071 /// operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3072 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3073 if (hasStoredFPFeatures())
3074 return getStoredFPFeatures().applyOverrides(LO);
3075 return FPOptions::defaultWithoutTrailingStorage(LO);
3076 }
3077
getFPFeatures()3078 FPOptionsOverride getFPFeatures() const {
3079 if (hasStoredFPFeatures())
3080 return getStoredFPFeatures();
3081 return FPOptionsOverride();
3082 }
3083
3084 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3085 /// of the callee. If not, return 0.
3086 unsigned getBuiltinCallee() const;
3087
3088 /// Returns \c true if this is a call to a builtin which does not
3089 /// evaluate side-effects within its arguments.
3090 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3091
3092 /// getCallReturnType - Get the return type of the call expr. This is not
3093 /// always the type of the expr itself, if the return type is a reference
3094 /// type.
3095 QualType getCallReturnType(const ASTContext &Ctx) const;
3096
3097 /// Returns the WarnUnusedResultAttr that is either declared on the called
3098 /// function, or its return type declaration.
3099 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3100
3101 /// Returns true if this call expression should warn on unused results.
hasUnusedResultAttr(const ASTContext & Ctx)3102 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3103 return getUnusedResultAttr(Ctx) != nullptr;
3104 }
3105
getRParenLoc()3106 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3107 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3108
3109 SourceLocation getBeginLoc() const LLVM_READONLY;
3110 SourceLocation getEndLoc() const LLVM_READONLY;
3111
3112 /// Return true if this is a call to __assume() or __builtin_assume() with
3113 /// a non-value-dependent constant parameter evaluating as false.
3114 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3115
3116 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3117 /// (Usually Exprs themselves should set dependence).
markDependentForPostponedNameLookup()3118 void markDependentForPostponedNameLookup() {
3119 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3120 }
3121
3122 bool isCallToStdMove() const;
3123
classof(const Stmt * T)3124 static bool classof(const Stmt *T) {
3125 return T->getStmtClass() >= firstCallExprConstant &&
3126 T->getStmtClass() <= lastCallExprConstant;
3127 }
3128
3129 // Iterators
children()3130 child_range children() {
3131 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3132 getNumPreArgs() + getNumArgs());
3133 }
3134
children()3135 const_child_range children() const {
3136 return const_child_range(getTrailingStmts(),
3137 getTrailingStmts() + PREARGS_START +
3138 getNumPreArgs() + getNumArgs());
3139 }
3140 };
3141
3142 /// Extra data stored in some MemberExpr objects.
3143 struct MemberExprNameQualifier {
3144 /// The nested-name-specifier that qualifies the name, including
3145 /// source-location information.
3146 NestedNameSpecifierLoc QualifierLoc;
3147
3148 /// The DeclAccessPair through which the MemberDecl was found due to
3149 /// name qualifiers.
3150 DeclAccessPair FoundDecl;
3151 };
3152
3153 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3154 ///
3155 class MemberExpr final
3156 : public Expr,
3157 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3158 ASTTemplateKWAndArgsInfo,
3159 TemplateArgumentLoc> {
3160 friend class ASTReader;
3161 friend class ASTStmtReader;
3162 friend class ASTStmtWriter;
3163 friend TrailingObjects;
3164
3165 /// Base - the expression for the base pointer or structure references. In
3166 /// X.F, this is "X".
3167 Stmt *Base;
3168
3169 /// MemberDecl - This is the decl being referenced by the field/member name.
3170 /// In X.F, this is the decl referenced by F.
3171 ValueDecl *MemberDecl;
3172
3173 /// MemberDNLoc - Provides source/type location info for the
3174 /// declaration name embedded in MemberDecl.
3175 DeclarationNameLoc MemberDNLoc;
3176
3177 /// MemberLoc - This is the location of the member name.
3178 SourceLocation MemberLoc;
3179
numTrailingObjects(OverloadToken<MemberExprNameQualifier>)3180 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3181 return hasQualifierOrFoundDecl();
3182 }
3183
numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>)3184 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3185 return hasTemplateKWAndArgsInfo();
3186 }
3187
hasQualifierOrFoundDecl()3188 bool hasQualifierOrFoundDecl() const {
3189 return MemberExprBits.HasQualifierOrFoundDecl;
3190 }
3191
hasTemplateKWAndArgsInfo()3192 bool hasTemplateKWAndArgsInfo() const {
3193 return MemberExprBits.HasTemplateKWAndArgsInfo;
3194 }
3195
3196 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3197 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3198 QualType T, ExprValueKind VK, ExprObjectKind OK,
3199 NonOdrUseReason NOUR);
MemberExpr(EmptyShell Empty)3200 MemberExpr(EmptyShell Empty)
3201 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3202
3203 public:
3204 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3205 SourceLocation OperatorLoc,
3206 NestedNameSpecifierLoc QualifierLoc,
3207 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3208 DeclAccessPair FoundDecl,
3209 DeclarationNameInfo MemberNameInfo,
3210 const TemplateArgumentListInfo *TemplateArgs,
3211 QualType T, ExprValueKind VK, ExprObjectKind OK,
3212 NonOdrUseReason NOUR);
3213
3214 /// Create an implicit MemberExpr, with no location, qualifier, template
3215 /// arguments, and so on. Suitable only for non-static member access.
CreateImplicit(const ASTContext & C,Expr * Base,bool IsArrow,ValueDecl * MemberDecl,QualType T,ExprValueKind VK,ExprObjectKind OK)3216 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3217 bool IsArrow, ValueDecl *MemberDecl,
3218 QualType T, ExprValueKind VK,
3219 ExprObjectKind OK) {
3220 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3221 SourceLocation(), MemberDecl,
3222 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3223 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3224 }
3225
3226 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3227 bool HasFoundDecl,
3228 bool HasTemplateKWAndArgsInfo,
3229 unsigned NumTemplateArgs);
3230
setBase(Expr * E)3231 void setBase(Expr *E) { Base = E; }
getBase()3232 Expr *getBase() const { return cast<Expr>(Base); }
3233
3234 /// Retrieve the member declaration to which this expression refers.
3235 ///
3236 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3237 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
getMemberDecl()3238 ValueDecl *getMemberDecl() const { return MemberDecl; }
3239 void setMemberDecl(ValueDecl *D);
3240
3241 /// Retrieves the declaration found by lookup.
getFoundDecl()3242 DeclAccessPair getFoundDecl() const {
3243 if (!hasQualifierOrFoundDecl())
3244 return DeclAccessPair::make(getMemberDecl(),
3245 getMemberDecl()->getAccess());
3246 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3247 }
3248
3249 /// Determines whether this member expression actually had
3250 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3251 /// x->Base::foo.
hasQualifier()3252 bool hasQualifier() const { return getQualifier() != nullptr; }
3253
3254 /// If the member name was qualified, retrieves the
3255 /// nested-name-specifier that precedes the member name, with source-location
3256 /// information.
getQualifierLoc()3257 NestedNameSpecifierLoc getQualifierLoc() const {
3258 if (!hasQualifierOrFoundDecl())
3259 return NestedNameSpecifierLoc();
3260 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3261 }
3262
3263 /// If the member name was qualified, retrieves the
3264 /// nested-name-specifier that precedes the member name. Otherwise, returns
3265 /// NULL.
getQualifier()3266 NestedNameSpecifier *getQualifier() const {
3267 return getQualifierLoc().getNestedNameSpecifier();
3268 }
3269
3270 /// Retrieve the location of the template keyword preceding
3271 /// the member name, if any.
getTemplateKeywordLoc()3272 SourceLocation getTemplateKeywordLoc() const {
3273 if (!hasTemplateKWAndArgsInfo())
3274 return SourceLocation();
3275 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3276 }
3277
3278 /// Retrieve the location of the left angle bracket starting the
3279 /// explicit template argument list following the member name, if any.
getLAngleLoc()3280 SourceLocation getLAngleLoc() const {
3281 if (!hasTemplateKWAndArgsInfo())
3282 return SourceLocation();
3283 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3284 }
3285
3286 /// Retrieve the location of the right angle bracket ending the
3287 /// explicit template argument list following the member name, if any.
getRAngleLoc()3288 SourceLocation getRAngleLoc() const {
3289 if (!hasTemplateKWAndArgsInfo())
3290 return SourceLocation();
3291 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3292 }
3293
3294 /// Determines whether the member name was preceded by the template keyword.
hasTemplateKeyword()3295 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3296
3297 /// Determines whether the member name was followed by an
3298 /// explicit template argument list.
hasExplicitTemplateArgs()3299 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3300
3301 /// Copies the template arguments (if present) into the given
3302 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)3303 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3304 if (hasExplicitTemplateArgs())
3305 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3306 getTrailingObjects<TemplateArgumentLoc>(), List);
3307 }
3308
3309 /// Retrieve the template arguments provided as part of this
3310 /// template-id.
getTemplateArgs()3311 const TemplateArgumentLoc *getTemplateArgs() const {
3312 if (!hasExplicitTemplateArgs())
3313 return nullptr;
3314
3315 return getTrailingObjects<TemplateArgumentLoc>();
3316 }
3317
3318 /// Retrieve the number of template arguments provided as part of this
3319 /// template-id.
getNumTemplateArgs()3320 unsigned getNumTemplateArgs() const {
3321 if (!hasExplicitTemplateArgs())
3322 return 0;
3323
3324 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3325 }
3326
template_arguments()3327 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3328 return {getTemplateArgs(), getNumTemplateArgs()};
3329 }
3330
3331 /// Retrieve the member declaration name info.
getMemberNameInfo()3332 DeclarationNameInfo getMemberNameInfo() const {
3333 return DeclarationNameInfo(MemberDecl->getDeclName(),
3334 MemberLoc, MemberDNLoc);
3335 }
3336
getOperatorLoc()3337 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3338
isArrow()3339 bool isArrow() const { return MemberExprBits.IsArrow; }
setArrow(bool A)3340 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3341
3342 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3343 /// location of 'F'.
getMemberLoc()3344 SourceLocation getMemberLoc() const { return MemberLoc; }
setMemberLoc(SourceLocation L)3345 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3346
3347 SourceLocation getBeginLoc() const LLVM_READONLY;
3348 SourceLocation getEndLoc() const LLVM_READONLY;
3349
getExprLoc()3350 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3351
3352 /// Determine whether the base of this explicit is implicit.
isImplicitAccess()3353 bool isImplicitAccess() const {
3354 return getBase() && getBase()->isImplicitCXXThis();
3355 }
3356
3357 /// Returns true if this member expression refers to a method that
3358 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()3359 bool hadMultipleCandidates() const {
3360 return MemberExprBits.HadMultipleCandidates;
3361 }
3362 /// Sets the flag telling whether this expression refers to
3363 /// a method that was resolved from an overloaded set having size
3364 /// greater than 1.
3365 void setHadMultipleCandidates(bool V = true) {
3366 MemberExprBits.HadMultipleCandidates = V;
3367 }
3368
3369 /// Returns true if virtual dispatch is performed.
3370 /// If the member access is fully qualified, (i.e. X::f()), virtual
3371 /// dispatching is not performed. In -fapple-kext mode qualified
3372 /// calls to virtual method will still go through the vtable.
performsVirtualDispatch(const LangOptions & LO)3373 bool performsVirtualDispatch(const LangOptions &LO) const {
3374 return LO.AppleKext || !hasQualifier();
3375 }
3376
3377 /// Is this expression a non-odr-use reference, and if so, why?
3378 /// This is only meaningful if the named member is a static member.
isNonOdrUse()3379 NonOdrUseReason isNonOdrUse() const {
3380 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3381 }
3382
classof(const Stmt * T)3383 static bool classof(const Stmt *T) {
3384 return T->getStmtClass() == MemberExprClass;
3385 }
3386
3387 // Iterators
children()3388 child_range children() { return child_range(&Base, &Base+1); }
children()3389 const_child_range children() const {
3390 return const_child_range(&Base, &Base + 1);
3391 }
3392 };
3393
3394 /// CompoundLiteralExpr - [C99 6.5.2.5]
3395 ///
3396 class CompoundLiteralExpr : public Expr {
3397 /// LParenLoc - If non-null, this is the location of the left paren in a
3398 /// compound literal like "(int){4}". This can be null if this is a
3399 /// synthesized compound expression.
3400 SourceLocation LParenLoc;
3401
3402 /// The type as written. This can be an incomplete array type, in
3403 /// which case the actual expression type will be different.
3404 /// The int part of the pair stores whether this expr is file scope.
3405 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3406 Stmt *Init;
3407 public:
CompoundLiteralExpr(SourceLocation lparenloc,TypeSourceInfo * tinfo,QualType T,ExprValueKind VK,Expr * init,bool fileScope)3408 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3409 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3410 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3411 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3412 setDependence(computeDependence(this));
3413 }
3414
3415 /// Construct an empty compound literal.
CompoundLiteralExpr(EmptyShell Empty)3416 explicit CompoundLiteralExpr(EmptyShell Empty)
3417 : Expr(CompoundLiteralExprClass, Empty) { }
3418
getInitializer()3419 const Expr *getInitializer() const { return cast<Expr>(Init); }
getInitializer()3420 Expr *getInitializer() { return cast<Expr>(Init); }
setInitializer(Expr * E)3421 void setInitializer(Expr *E) { Init = E; }
3422
isFileScope()3423 bool isFileScope() const { return TInfoAndScope.getInt(); }
setFileScope(bool FS)3424 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3425
getLParenLoc()3426 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)3427 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3428
getTypeSourceInfo()3429 TypeSourceInfo *getTypeSourceInfo() const {
3430 return TInfoAndScope.getPointer();
3431 }
setTypeSourceInfo(TypeSourceInfo * tinfo)3432 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3433 TInfoAndScope.setPointer(tinfo);
3434 }
3435
getBeginLoc()3436 SourceLocation getBeginLoc() const LLVM_READONLY {
3437 // FIXME: Init should never be null.
3438 if (!Init)
3439 return SourceLocation();
3440 if (LParenLoc.isInvalid())
3441 return Init->getBeginLoc();
3442 return LParenLoc;
3443 }
getEndLoc()3444 SourceLocation getEndLoc() const LLVM_READONLY {
3445 // FIXME: Init should never be null.
3446 if (!Init)
3447 return SourceLocation();
3448 return Init->getEndLoc();
3449 }
3450
classof(const Stmt * T)3451 static bool classof(const Stmt *T) {
3452 return T->getStmtClass() == CompoundLiteralExprClass;
3453 }
3454
3455 // Iterators
children()3456 child_range children() { return child_range(&Init, &Init+1); }
children()3457 const_child_range children() const {
3458 return const_child_range(&Init, &Init + 1);
3459 }
3460 };
3461
3462 /// CastExpr - Base class for type casts, including both implicit
3463 /// casts (ImplicitCastExpr) and explicit casts that have some
3464 /// representation in the source code (ExplicitCastExpr's derived
3465 /// classes).
3466 class CastExpr : public Expr {
3467 Stmt *Op;
3468
3469 bool CastConsistency() const;
3470
path_buffer()3471 const CXXBaseSpecifier * const *path_buffer() const {
3472 return const_cast<CastExpr*>(this)->path_buffer();
3473 }
3474 CXXBaseSpecifier **path_buffer();
3475
3476 friend class ASTStmtReader;
3477
3478 protected:
CastExpr(StmtClass SC,QualType ty,ExprValueKind VK,const CastKind kind,Expr * op,unsigned BasePathSize,bool HasFPFeatures)3479 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3480 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3481 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3482 CastExprBits.Kind = kind;
3483 CastExprBits.PartOfExplicitCast = false;
3484 CastExprBits.BasePathSize = BasePathSize;
3485 assert((CastExprBits.BasePathSize == BasePathSize) &&
3486 "BasePathSize overflow!");
3487 assert(CastConsistency());
3488 CastExprBits.HasFPFeatures = HasFPFeatures;
3489 }
3490
3491 /// Construct an empty cast.
CastExpr(StmtClass SC,EmptyShell Empty,unsigned BasePathSize,bool HasFPFeatures)3492 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3493 bool HasFPFeatures)
3494 : Expr(SC, Empty) {
3495 CastExprBits.PartOfExplicitCast = false;
3496 CastExprBits.BasePathSize = BasePathSize;
3497 CastExprBits.HasFPFeatures = HasFPFeatures;
3498 assert((CastExprBits.BasePathSize == BasePathSize) &&
3499 "BasePathSize overflow!");
3500 }
3501
3502 /// Return a pointer to the trailing FPOptions.
3503 /// \pre hasStoredFPFeatures() == true
3504 FPOptionsOverride *getTrailingFPFeatures();
getTrailingFPFeatures()3505 const FPOptionsOverride *getTrailingFPFeatures() const {
3506 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3507 }
3508
3509 public:
getCastKind()3510 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
setCastKind(CastKind K)3511 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3512
3513 static const char *getCastKindName(CastKind CK);
getCastKindName()3514 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3515
getSubExpr()3516 Expr *getSubExpr() { return cast<Expr>(Op); }
getSubExpr()3517 const Expr *getSubExpr() const { return cast<Expr>(Op); }
setSubExpr(Expr * E)3518 void setSubExpr(Expr *E) { Op = E; }
3519
3520 /// Retrieve the cast subexpression as it was written in the source
3521 /// code, looking through any implicit casts or other intermediate nodes
3522 /// introduced by semantic analysis.
3523 Expr *getSubExprAsWritten();
getSubExprAsWritten()3524 const Expr *getSubExprAsWritten() const {
3525 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3526 }
3527
3528 /// If this cast applies a user-defined conversion, retrieve the conversion
3529 /// function that it invokes.
3530 NamedDecl *getConversionFunction() const;
3531
3532 typedef CXXBaseSpecifier **path_iterator;
3533 typedef const CXXBaseSpecifier *const *path_const_iterator;
path_empty()3534 bool path_empty() const { return path_size() == 0; }
path_size()3535 unsigned path_size() const { return CastExprBits.BasePathSize; }
path_begin()3536 path_iterator path_begin() { return path_buffer(); }
path_end()3537 path_iterator path_end() { return path_buffer() + path_size(); }
path_begin()3538 path_const_iterator path_begin() const { return path_buffer(); }
path_end()3539 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3540
path()3541 llvm::iterator_range<path_iterator> path() {
3542 return llvm::make_range(path_begin(), path_end());
3543 }
path()3544 llvm::iterator_range<path_const_iterator> path() const {
3545 return llvm::make_range(path_begin(), path_end());
3546 }
3547
getTargetUnionField()3548 const FieldDecl *getTargetUnionField() const {
3549 assert(getCastKind() == CK_ToUnion);
3550 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3551 }
3552
hasStoredFPFeatures()3553 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3554
3555 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()3556 FPOptionsOverride getStoredFPFeatures() const {
3557 assert(hasStoredFPFeatures());
3558 return *getTrailingFPFeatures();
3559 }
3560
3561 /// Get the FP features status of this operation. Only meaningful for
3562 /// operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3563 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3564 if (hasStoredFPFeatures())
3565 return getStoredFPFeatures().applyOverrides(LO);
3566 return FPOptions::defaultWithoutTrailingStorage(LO);
3567 }
3568
getFPFeatures()3569 FPOptionsOverride getFPFeatures() const {
3570 if (hasStoredFPFeatures())
3571 return getStoredFPFeatures();
3572 return FPOptionsOverride();
3573 }
3574
3575 /// Return
3576 // True : if this conversion changes the volatile-ness of a gl-value.
3577 // Qualification conversions on gl-values currently use CK_NoOp, but
3578 // it's important to recognize volatile-changing conversions in
3579 // clients code generation that normally eagerly peephole loads. Note
3580 // that the query is answering for this specific node; Sema may
3581 // produce multiple cast nodes for any particular conversion sequence.
3582 // False : Otherwise.
changesVolatileQualification()3583 bool changesVolatileQualification() const {
3584 return (isGLValue() && (getType().isVolatileQualified() !=
3585 getSubExpr()->getType().isVolatileQualified()));
3586 }
3587
3588 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3589 QualType opType);
3590 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3591 QualType opType);
3592
classof(const Stmt * T)3593 static bool classof(const Stmt *T) {
3594 return T->getStmtClass() >= firstCastExprConstant &&
3595 T->getStmtClass() <= lastCastExprConstant;
3596 }
3597
3598 // Iterators
children()3599 child_range children() { return child_range(&Op, &Op+1); }
children()3600 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3601 };
3602
3603 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
3604 /// conversions, which have no direct representation in the original
3605 /// source code. For example: converting T[]->T*, void f()->void
3606 /// (*f)(), float->double, short->int, etc.
3607 ///
3608 /// In C, implicit casts always produce rvalues. However, in C++, an
3609 /// implicit cast whose result is being bound to a reference will be
3610 /// an lvalue or xvalue. For example:
3611 ///
3612 /// @code
3613 /// class Base { };
3614 /// class Derived : public Base { };
3615 /// Derived &&ref();
3616 /// void f(Derived d) {
3617 /// Base& b = d; // initializer is an ImplicitCastExpr
3618 /// // to an lvalue of type Base
3619 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
3620 /// // to an xvalue of type Base
3621 /// }
3622 /// @endcode
3623 class ImplicitCastExpr final
3624 : public CastExpr,
3625 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3626 FPOptionsOverride> {
3627
ImplicitCastExpr(QualType ty,CastKind kind,Expr * op,unsigned BasePathLength,FPOptionsOverride FPO,ExprValueKind VK)3628 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3629 unsigned BasePathLength, FPOptionsOverride FPO,
3630 ExprValueKind VK)
3631 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3632 FPO.requiresTrailingStorage()) {
3633 setDependence(computeDependence(this));
3634 if (hasStoredFPFeatures())
3635 *getTrailingFPFeatures() = FPO;
3636 }
3637
3638 /// Construct an empty implicit cast.
ImplicitCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3639 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3640 bool HasFPFeatures)
3641 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3642
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3643 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3644 return path_size();
3645 }
3646
3647 public:
3648 enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _,QualType ty,CastKind kind,Expr * op,ExprValueKind VK,FPOptionsOverride FPO)3649 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3650 ExprValueKind VK, FPOptionsOverride FPO)
3651 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3652 FPO.requiresTrailingStorage()) {
3653 if (hasStoredFPFeatures())
3654 *getTrailingFPFeatures() = FPO;
3655 }
3656
isPartOfExplicitCast()3657 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
setIsPartOfExplicitCast(bool PartOfExplicitCast)3658 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3659 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3660 }
3661
3662 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3663 CastKind Kind, Expr *Operand,
3664 const CXXCastPath *BasePath,
3665 ExprValueKind Cat, FPOptionsOverride FPO);
3666
3667 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3668 unsigned PathSize, bool HasFPFeatures);
3669
getBeginLoc()3670 SourceLocation getBeginLoc() const LLVM_READONLY {
3671 return getSubExpr()->getBeginLoc();
3672 }
getEndLoc()3673 SourceLocation getEndLoc() const LLVM_READONLY {
3674 return getSubExpr()->getEndLoc();
3675 }
3676
classof(const Stmt * T)3677 static bool classof(const Stmt *T) {
3678 return T->getStmtClass() == ImplicitCastExprClass;
3679 }
3680
3681 friend TrailingObjects;
3682 friend class CastExpr;
3683 };
3684
3685 /// ExplicitCastExpr - An explicit cast written in the source
3686 /// code.
3687 ///
3688 /// This class is effectively an abstract class, because it provides
3689 /// the basic representation of an explicitly-written cast without
3690 /// specifying which kind of cast (C cast, functional cast, static
3691 /// cast, etc.) was written; specific derived classes represent the
3692 /// particular style of cast and its location information.
3693 ///
3694 /// Unlike implicit casts, explicit cast nodes have two different
3695 /// types: the type that was written into the source code, and the
3696 /// actual type of the expression as determined by semantic
3697 /// analysis. These types may differ slightly. For example, in C++ one
3698 /// can cast to a reference type, which indicates that the resulting
3699 /// expression will be an lvalue or xvalue. The reference type, however,
3700 /// will not be used as the type of the expression.
3701 class ExplicitCastExpr : public CastExpr {
3702 /// TInfo - Source type info for the (written) type
3703 /// this expression is casting to.
3704 TypeSourceInfo *TInfo;
3705
3706 protected:
ExplicitCastExpr(StmtClass SC,QualType exprTy,ExprValueKind VK,CastKind kind,Expr * op,unsigned PathSize,bool HasFPFeatures,TypeSourceInfo * writtenTy)3707 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3708 CastKind kind, Expr *op, unsigned PathSize,
3709 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3710 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3711 TInfo(writtenTy) {
3712 setDependence(computeDependence(this));
3713 }
3714
3715 /// Construct an empty explicit cast.
ExplicitCastExpr(StmtClass SC,EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3716 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3717 bool HasFPFeatures)
3718 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3719
3720 public:
3721 /// getTypeInfoAsWritten - Returns the type source info for the type
3722 /// that this expression is casting to.
getTypeInfoAsWritten()3723 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
setTypeInfoAsWritten(TypeSourceInfo * writtenTy)3724 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3725
3726 /// getTypeAsWritten - Returns the type that this expression is
3727 /// casting to, as written in the source code.
getTypeAsWritten()3728 QualType getTypeAsWritten() const { return TInfo->getType(); }
3729
classof(const Stmt * T)3730 static bool classof(const Stmt *T) {
3731 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3732 T->getStmtClass() <= lastExplicitCastExprConstant;
3733 }
3734 };
3735
3736 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3737 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3738 /// (Type)expr. For example: @c (int)f.
3739 class CStyleCastExpr final
3740 : public ExplicitCastExpr,
3741 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3742 FPOptionsOverride> {
3743 SourceLocation LPLoc; // the location of the left paren
3744 SourceLocation RPLoc; // the location of the right paren
3745
CStyleCastExpr(QualType exprTy,ExprValueKind vk,CastKind kind,Expr * op,unsigned PathSize,FPOptionsOverride FPO,TypeSourceInfo * writtenTy,SourceLocation l,SourceLocation r)3746 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3747 unsigned PathSize, FPOptionsOverride FPO,
3748 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3749 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3750 FPO.requiresTrailingStorage(), writtenTy),
3751 LPLoc(l), RPLoc(r) {
3752 if (hasStoredFPFeatures())
3753 *getTrailingFPFeatures() = FPO;
3754 }
3755
3756 /// Construct an empty C-style explicit cast.
CStyleCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3757 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3758 bool HasFPFeatures)
3759 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3760
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3761 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3762 return path_size();
3763 }
3764
3765 public:
3766 static CStyleCastExpr *
3767 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3768 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3769 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3770
3771 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3772 unsigned PathSize, bool HasFPFeatures);
3773
getLParenLoc()3774 SourceLocation getLParenLoc() const { return LPLoc; }
setLParenLoc(SourceLocation L)3775 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3776
getRParenLoc()3777 SourceLocation getRParenLoc() const { return RPLoc; }
setRParenLoc(SourceLocation L)3778 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3779
getBeginLoc()3780 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
getEndLoc()3781 SourceLocation getEndLoc() const LLVM_READONLY {
3782 return getSubExpr()->getEndLoc();
3783 }
3784
classof(const Stmt * T)3785 static bool classof(const Stmt *T) {
3786 return T->getStmtClass() == CStyleCastExprClass;
3787 }
3788
3789 friend TrailingObjects;
3790 friend class CastExpr;
3791 };
3792
3793 /// A builtin binary operation expression such as "x + y" or "x <= y".
3794 ///
3795 /// This expression node kind describes a builtin binary operation,
3796 /// such as "x + y" for integer values "x" and "y". The operands will
3797 /// already have been converted to appropriate types (e.g., by
3798 /// performing promotions or conversions).
3799 ///
3800 /// In C++, where operators may be overloaded, a different kind of
3801 /// expression node (CXXOperatorCallExpr) is used to express the
3802 /// invocation of an overloaded operator with operator syntax. Within
3803 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3804 /// used to store an expression "x + y" depends on the subexpressions
3805 /// for x and y. If neither x or y is type-dependent, and the "+"
3806 /// operator resolves to a built-in operation, BinaryOperator will be
3807 /// used to express the computation (x and y may still be
3808 /// value-dependent). If either x or y is type-dependent, or if the
3809 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3810 /// be used to express the computation.
3811 class BinaryOperator : public Expr {
3812 enum { LHS, RHS, END_EXPR };
3813 Stmt *SubExprs[END_EXPR];
3814
3815 public:
3816 typedef BinaryOperatorKind Opcode;
3817
3818 protected:
3819 size_t offsetOfTrailingStorage() const;
3820
3821 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()3822 FPOptionsOverride *getTrailingFPFeatures() {
3823 assert(BinaryOperatorBits.HasFPFeatures);
3824 return reinterpret_cast<FPOptionsOverride *>(
3825 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3826 }
getTrailingFPFeatures()3827 const FPOptionsOverride *getTrailingFPFeatures() const {
3828 assert(BinaryOperatorBits.HasFPFeatures);
3829 return reinterpret_cast<const FPOptionsOverride *>(
3830 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3831 }
3832
3833 /// Build a binary operator, assuming that appropriate storage has been
3834 /// allocated for the trailing objects when needed.
3835 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3836 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3837 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3838
3839 /// Construct an empty binary operator.
BinaryOperator(EmptyShell Empty)3840 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3841 BinaryOperatorBits.Opc = BO_Comma;
3842 }
3843
3844 public:
3845 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3846
3847 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3848 Opcode opc, QualType ResTy, ExprValueKind VK,
3849 ExprObjectKind OK, SourceLocation opLoc,
3850 FPOptionsOverride FPFeatures);
getExprLoc()3851 SourceLocation getExprLoc() const { return getOperatorLoc(); }
getOperatorLoc()3852 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
setOperatorLoc(SourceLocation L)3853 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3854
getOpcode()3855 Opcode getOpcode() const {
3856 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3857 }
setOpcode(Opcode Opc)3858 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3859
getLHS()3860 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)3861 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()3862 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)3863 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3864
getBeginLoc()3865 SourceLocation getBeginLoc() const LLVM_READONLY {
3866 return getLHS()->getBeginLoc();
3867 }
getEndLoc()3868 SourceLocation getEndLoc() const LLVM_READONLY {
3869 return getRHS()->getEndLoc();
3870 }
3871
3872 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3873 /// corresponds to, e.g. "<<=".
3874 static StringRef getOpcodeStr(Opcode Op);
3875
getOpcodeStr()3876 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3877
3878 /// Retrieve the binary opcode that corresponds to the given
3879 /// overloaded operator.
3880 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3881
3882 /// Retrieve the overloaded operator kind that corresponds to
3883 /// the given binary opcode.
3884 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3885
3886 /// predicates to categorize the respective opcodes.
isPtrMemOp(Opcode Opc)3887 static bool isPtrMemOp(Opcode Opc) {
3888 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3889 }
isPtrMemOp()3890 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3891
isMultiplicativeOp(Opcode Opc)3892 static bool isMultiplicativeOp(Opcode Opc) {
3893 return Opc >= BO_Mul && Opc <= BO_Rem;
3894 }
isMultiplicativeOp()3895 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
isAdditiveOp(Opcode Opc)3896 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
isAdditiveOp()3897 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
isShiftOp(Opcode Opc)3898 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
isShiftOp()3899 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3900
isBitwiseOp(Opcode Opc)3901 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
isBitwiseOp()3902 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3903
isRelationalOp(Opcode Opc)3904 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
isRelationalOp()3905 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3906
isEqualityOp(Opcode Opc)3907 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
isEqualityOp()3908 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3909
isComparisonOp(Opcode Opc)3910 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
isComparisonOp()3911 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3912
isCommaOp(Opcode Opc)3913 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
isCommaOp()3914 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3915
negateComparisonOp(Opcode Opc)3916 static Opcode negateComparisonOp(Opcode Opc) {
3917 switch (Opc) {
3918 default:
3919 llvm_unreachable("Not a comparison operator.");
3920 case BO_LT: return BO_GE;
3921 case BO_GT: return BO_LE;
3922 case BO_LE: return BO_GT;
3923 case BO_GE: return BO_LT;
3924 case BO_EQ: return BO_NE;
3925 case BO_NE: return BO_EQ;
3926 }
3927 }
3928
reverseComparisonOp(Opcode Opc)3929 static Opcode reverseComparisonOp(Opcode Opc) {
3930 switch (Opc) {
3931 default:
3932 llvm_unreachable("Not a comparison operator.");
3933 case BO_LT: return BO_GT;
3934 case BO_GT: return BO_LT;
3935 case BO_LE: return BO_GE;
3936 case BO_GE: return BO_LE;
3937 case BO_EQ:
3938 case BO_NE:
3939 return Opc;
3940 }
3941 }
3942
isLogicalOp(Opcode Opc)3943 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
isLogicalOp()3944 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3945
isAssignmentOp(Opcode Opc)3946 static bool isAssignmentOp(Opcode Opc) {
3947 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3948 }
isAssignmentOp()3949 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3950
isCompoundAssignmentOp(Opcode Opc)3951 static bool isCompoundAssignmentOp(Opcode Opc) {
3952 return Opc > BO_Assign && Opc <= BO_OrAssign;
3953 }
isCompoundAssignmentOp()3954 bool isCompoundAssignmentOp() const {
3955 return isCompoundAssignmentOp(getOpcode());
3956 }
getOpForCompoundAssignment(Opcode Opc)3957 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3958 assert(isCompoundAssignmentOp(Opc));
3959 if (Opc >= BO_AndAssign)
3960 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3961 else
3962 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3963 }
3964
isShiftAssignOp(Opcode Opc)3965 static bool isShiftAssignOp(Opcode Opc) {
3966 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3967 }
isShiftAssignOp()3968 bool isShiftAssignOp() const {
3969 return isShiftAssignOp(getOpcode());
3970 }
3971
3972 /// Return true if a binary operator using the specified opcode and operands
3973 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3974 /// integer to a pointer.
3975 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3976 const Expr *LHS,
3977 const Expr *RHS);
3978
classof(const Stmt * S)3979 static bool classof(const Stmt *S) {
3980 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3981 S->getStmtClass() <= lastBinaryOperatorConstant;
3982 }
3983
3984 // Iterators
children()3985 child_range children() {
3986 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3987 }
children()3988 const_child_range children() const {
3989 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3990 }
3991
3992 /// Set and fetch the bit that shows whether FPFeatures needs to be
3993 /// allocated in Trailing Storage
setHasStoredFPFeatures(bool B)3994 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
hasStoredFPFeatures()3995 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3996
3997 /// Get FPFeatures from trailing storage
getStoredFPFeatures()3998 FPOptionsOverride getStoredFPFeatures() const {
3999 assert(hasStoredFPFeatures());
4000 return *getTrailingFPFeatures();
4001 }
4002 /// Set FPFeatures in trailing storage, used only by Serialization
setStoredFPFeatures(FPOptionsOverride F)4003 void setStoredFPFeatures(FPOptionsOverride F) {
4004 assert(BinaryOperatorBits.HasFPFeatures);
4005 *getTrailingFPFeatures() = F;
4006 }
4007
4008 /// Get the FP features status of this operator. Only meaningful for
4009 /// operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)4010 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4011 if (BinaryOperatorBits.HasFPFeatures)
4012 return getStoredFPFeatures().applyOverrides(LO);
4013 return FPOptions::defaultWithoutTrailingStorage(LO);
4014 }
4015
4016 // This is used in ASTImporter
getFPFeatures()4017 FPOptionsOverride getFPFeatures() const {
4018 if (BinaryOperatorBits.HasFPFeatures)
4019 return getStoredFPFeatures();
4020 return FPOptionsOverride();
4021 }
4022
4023 /// Get the FP contractability status of this operator. Only meaningful for
4024 /// operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)4025 bool isFPContractableWithinStatement(const LangOptions &LO) const {
4026 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4027 }
4028
4029 /// Get the FENV_ACCESS status of this operator. Only meaningful for
4030 /// operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)4031 bool isFEnvAccessOn(const LangOptions &LO) const {
4032 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4033 }
4034
4035 protected:
4036 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4037 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4038 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4039 bool dead2);
4040
4041 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
BinaryOperator(StmtClass SC,EmptyShell Empty)4042 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4043 BinaryOperatorBits.Opc = BO_MulAssign;
4044 }
4045
4046 /// Return the size in bytes needed for the trailing objects.
4047 /// Used to allocate the right amount of storage.
sizeOfTrailingObjects(bool HasFPFeatures)4048 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4049 return HasFPFeatures * sizeof(FPOptionsOverride);
4050 }
4051 };
4052
4053 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4054 /// track of the type the operation is performed in. Due to the semantics of
4055 /// these operators, the operands are promoted, the arithmetic performed, an
4056 /// implicit conversion back to the result type done, then the assignment takes
4057 /// place. This captures the intermediate type which the computation is done
4058 /// in.
4059 class CompoundAssignOperator : public BinaryOperator {
4060 QualType ComputationLHSType;
4061 QualType ComputationResultType;
4062
4063 /// Construct an empty CompoundAssignOperator.
CompoundAssignOperator(const ASTContext & C,EmptyShell Empty,bool hasFPFeatures)4064 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4065 bool hasFPFeatures)
4066 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4067
4068 protected:
CompoundAssignOperator(const ASTContext & C,Expr * lhs,Expr * rhs,Opcode opc,QualType ResType,ExprValueKind VK,ExprObjectKind OK,SourceLocation OpLoc,FPOptionsOverride FPFeatures,QualType CompLHSType,QualType CompResultType)4069 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4070 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4071 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4072 QualType CompLHSType, QualType CompResultType)
4073 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4074 true),
4075 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4076 assert(isCompoundAssignmentOp() &&
4077 "Only should be used for compound assignments");
4078 }
4079
4080 public:
4081 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4082 bool hasFPFeatures);
4083
4084 static CompoundAssignOperator *
4085 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4086 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4087 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4088 QualType CompResultType = QualType());
4089
4090 // The two computation types are the type the LHS is converted
4091 // to for the computation and the type of the result; the two are
4092 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
getComputationLHSType()4093 QualType getComputationLHSType() const { return ComputationLHSType; }
setComputationLHSType(QualType T)4094 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4095
getComputationResultType()4096 QualType getComputationResultType() const { return ComputationResultType; }
setComputationResultType(QualType T)4097 void setComputationResultType(QualType T) { ComputationResultType = T; }
4098
classof(const Stmt * S)4099 static bool classof(const Stmt *S) {
4100 return S->getStmtClass() == CompoundAssignOperatorClass;
4101 }
4102 };
4103
offsetOfTrailingStorage()4104 inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4105 assert(BinaryOperatorBits.HasFPFeatures);
4106 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4107 : sizeof(BinaryOperator);
4108 }
4109
4110 /// AbstractConditionalOperator - An abstract base class for
4111 /// ConditionalOperator and BinaryConditionalOperator.
4112 class AbstractConditionalOperator : public Expr {
4113 SourceLocation QuestionLoc, ColonLoc;
4114 friend class ASTStmtReader;
4115
4116 protected:
AbstractConditionalOperator(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,SourceLocation qloc,SourceLocation cloc)4117 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4118 ExprObjectKind OK, SourceLocation qloc,
4119 SourceLocation cloc)
4120 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4121
AbstractConditionalOperator(StmtClass SC,EmptyShell Empty)4122 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4123 : Expr(SC, Empty) { }
4124
4125 public:
4126 /// getCond - Return the expression representing the condition for
4127 /// the ?: operator.
4128 Expr *getCond() const;
4129
4130 /// getTrueExpr - Return the subexpression representing the value of
4131 /// the expression if the condition evaluates to true.
4132 Expr *getTrueExpr() const;
4133
4134 /// getFalseExpr - Return the subexpression representing the value of
4135 /// the expression if the condition evaluates to false. This is
4136 /// the same as getRHS.
4137 Expr *getFalseExpr() const;
4138
getQuestionLoc()4139 SourceLocation getQuestionLoc() const { return QuestionLoc; }
getColonLoc()4140 SourceLocation getColonLoc() const { return ColonLoc; }
4141
classof(const Stmt * T)4142 static bool classof(const Stmt *T) {
4143 return T->getStmtClass() == ConditionalOperatorClass ||
4144 T->getStmtClass() == BinaryConditionalOperatorClass;
4145 }
4146 };
4147
4148 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
4149 /// middle" extension is a BinaryConditionalOperator.
4150 class ConditionalOperator : public AbstractConditionalOperator {
4151 enum { COND, LHS, RHS, END_EXPR };
4152 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4153
4154 friend class ASTStmtReader;
4155 public:
ConditionalOperator(Expr * cond,SourceLocation QLoc,Expr * lhs,SourceLocation CLoc,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK)4156 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4157 SourceLocation CLoc, Expr *rhs, QualType t,
4158 ExprValueKind VK, ExprObjectKind OK)
4159 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4160 CLoc) {
4161 SubExprs[COND] = cond;
4162 SubExprs[LHS] = lhs;
4163 SubExprs[RHS] = rhs;
4164 setDependence(computeDependence(this));
4165 }
4166
4167 /// Build an empty conditional operator.
ConditionalOperator(EmptyShell Empty)4168 explicit ConditionalOperator(EmptyShell Empty)
4169 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4170
4171 /// getCond - Return the expression representing the condition for
4172 /// the ?: operator.
getCond()4173 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4174
4175 /// getTrueExpr - Return the subexpression representing the value of
4176 /// the expression if the condition evaluates to true.
getTrueExpr()4177 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4178
4179 /// getFalseExpr - Return the subexpression representing the value of
4180 /// the expression if the condition evaluates to false. This is
4181 /// the same as getRHS.
getFalseExpr()4182 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4183
getLHS()4184 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
getRHS()4185 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4186
getBeginLoc()4187 SourceLocation getBeginLoc() const LLVM_READONLY {
4188 return getCond()->getBeginLoc();
4189 }
getEndLoc()4190 SourceLocation getEndLoc() const LLVM_READONLY {
4191 return getRHS()->getEndLoc();
4192 }
4193
classof(const Stmt * T)4194 static bool classof(const Stmt *T) {
4195 return T->getStmtClass() == ConditionalOperatorClass;
4196 }
4197
4198 // Iterators
children()4199 child_range children() {
4200 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4201 }
children()4202 const_child_range children() const {
4203 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4204 }
4205 };
4206
4207 /// BinaryConditionalOperator - The GNU extension to the conditional
4208 /// operator which allows the middle operand to be omitted.
4209 ///
4210 /// This is a different expression kind on the assumption that almost
4211 /// every client ends up needing to know that these are different.
4212 class BinaryConditionalOperator : public AbstractConditionalOperator {
4213 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4214
4215 /// - the common condition/left-hand-side expression, which will be
4216 /// evaluated as the opaque value
4217 /// - the condition, expressed in terms of the opaque value
4218 /// - the left-hand-side, expressed in terms of the opaque value
4219 /// - the right-hand-side
4220 Stmt *SubExprs[NUM_SUBEXPRS];
4221 OpaqueValueExpr *OpaqueValue;
4222
4223 friend class ASTStmtReader;
4224 public:
BinaryConditionalOperator(Expr * common,OpaqueValueExpr * opaqueValue,Expr * cond,Expr * lhs,Expr * rhs,SourceLocation qloc,SourceLocation cloc,QualType t,ExprValueKind VK,ExprObjectKind OK)4225 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4226 Expr *cond, Expr *lhs, Expr *rhs,
4227 SourceLocation qloc, SourceLocation cloc,
4228 QualType t, ExprValueKind VK, ExprObjectKind OK)
4229 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4230 qloc, cloc),
4231 OpaqueValue(opaqueValue) {
4232 SubExprs[COMMON] = common;
4233 SubExprs[COND] = cond;
4234 SubExprs[LHS] = lhs;
4235 SubExprs[RHS] = rhs;
4236 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4237 setDependence(computeDependence(this));
4238 }
4239
4240 /// Build an empty conditional operator.
BinaryConditionalOperator(EmptyShell Empty)4241 explicit BinaryConditionalOperator(EmptyShell Empty)
4242 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4243
4244 /// getCommon - Return the common expression, written to the
4245 /// left of the condition. The opaque value will be bound to the
4246 /// result of this expression.
getCommon()4247 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4248
4249 /// getOpaqueValue - Return the opaque value placeholder.
getOpaqueValue()4250 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4251
4252 /// getCond - Return the condition expression; this is defined
4253 /// in terms of the opaque value.
getCond()4254 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4255
4256 /// getTrueExpr - Return the subexpression which will be
4257 /// evaluated if the condition evaluates to true; this is defined
4258 /// in terms of the opaque value.
getTrueExpr()4259 Expr *getTrueExpr() const {
4260 return cast<Expr>(SubExprs[LHS]);
4261 }
4262
4263 /// getFalseExpr - Return the subexpression which will be
4264 /// evaluated if the condnition evaluates to false; this is
4265 /// defined in terms of the opaque value.
getFalseExpr()4266 Expr *getFalseExpr() const {
4267 return cast<Expr>(SubExprs[RHS]);
4268 }
4269
getBeginLoc()4270 SourceLocation getBeginLoc() const LLVM_READONLY {
4271 return getCommon()->getBeginLoc();
4272 }
getEndLoc()4273 SourceLocation getEndLoc() const LLVM_READONLY {
4274 return getFalseExpr()->getEndLoc();
4275 }
4276
classof(const Stmt * T)4277 static bool classof(const Stmt *T) {
4278 return T->getStmtClass() == BinaryConditionalOperatorClass;
4279 }
4280
4281 // Iterators
children()4282 child_range children() {
4283 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4284 }
children()4285 const_child_range children() const {
4286 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4287 }
4288 };
4289
getCond()4290 inline Expr *AbstractConditionalOperator::getCond() const {
4291 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4292 return co->getCond();
4293 return cast<BinaryConditionalOperator>(this)->getCond();
4294 }
4295
getTrueExpr()4296 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4297 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4298 return co->getTrueExpr();
4299 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4300 }
4301
getFalseExpr()4302 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4303 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4304 return co->getFalseExpr();
4305 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4306 }
4307
4308 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
4309 class AddrLabelExpr : public Expr {
4310 SourceLocation AmpAmpLoc, LabelLoc;
4311 LabelDecl *Label;
4312 public:
AddrLabelExpr(SourceLocation AALoc,SourceLocation LLoc,LabelDecl * L,QualType t)4313 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4314 QualType t)
4315 : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4316 LabelLoc(LLoc), Label(L) {
4317 setDependence(ExprDependence::None);
4318 }
4319
4320 /// Build an empty address of a label expression.
AddrLabelExpr(EmptyShell Empty)4321 explicit AddrLabelExpr(EmptyShell Empty)
4322 : Expr(AddrLabelExprClass, Empty) { }
4323
getAmpAmpLoc()4324 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
setAmpAmpLoc(SourceLocation L)4325 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
getLabelLoc()4326 SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)4327 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4328
getBeginLoc()4329 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
getEndLoc()4330 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4331
getLabel()4332 LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * L)4333 void setLabel(LabelDecl *L) { Label = L; }
4334
classof(const Stmt * T)4335 static bool classof(const Stmt *T) {
4336 return T->getStmtClass() == AddrLabelExprClass;
4337 }
4338
4339 // Iterators
children()4340 child_range children() {
4341 return child_range(child_iterator(), child_iterator());
4342 }
children()4343 const_child_range children() const {
4344 return const_child_range(const_child_iterator(), const_child_iterator());
4345 }
4346 };
4347
4348 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4349 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4350 /// takes the value of the last subexpression.
4351 ///
4352 /// A StmtExpr is always an r-value; values "returned" out of a
4353 /// StmtExpr will be copied.
4354 class StmtExpr : public Expr {
4355 Stmt *SubStmt;
4356 SourceLocation LParenLoc, RParenLoc;
4357 public:
StmtExpr(CompoundStmt * SubStmt,QualType T,SourceLocation LParenLoc,SourceLocation RParenLoc,unsigned TemplateDepth)4358 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4359 SourceLocation RParenLoc, unsigned TemplateDepth)
4360 : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4361 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4362 setDependence(computeDependence(this, TemplateDepth));
4363 // FIXME: A templated statement expression should have an associated
4364 // DeclContext so that nested declarations always have a dependent context.
4365 StmtExprBits.TemplateDepth = TemplateDepth;
4366 }
4367
4368 /// Build an empty statement expression.
StmtExpr(EmptyShell Empty)4369 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4370
getSubStmt()4371 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
getSubStmt()4372 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
setSubStmt(CompoundStmt * S)4373 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4374
getBeginLoc()4375 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
getEndLoc()4376 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4377
getLParenLoc()4378 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)4379 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()4380 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4381 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4382
getTemplateDepth()4383 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4384
classof(const Stmt * T)4385 static bool classof(const Stmt *T) {
4386 return T->getStmtClass() == StmtExprClass;
4387 }
4388
4389 // Iterators
children()4390 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
children()4391 const_child_range children() const {
4392 return const_child_range(&SubStmt, &SubStmt + 1);
4393 }
4394 };
4395
4396 /// ShuffleVectorExpr - clang-specific builtin-in function
4397 /// __builtin_shufflevector.
4398 /// This AST node represents a operator that does a constant
4399 /// shuffle, similar to LLVM's shufflevector instruction. It takes
4400 /// two vectors and a variable number of constant indices,
4401 /// and returns the appropriately shuffled vector.
4402 class ShuffleVectorExpr : public Expr {
4403 SourceLocation BuiltinLoc, RParenLoc;
4404
4405 // SubExprs - the list of values passed to the __builtin_shufflevector
4406 // function. The first two are vectors, and the rest are constant
4407 // indices. The number of values in this list is always
4408 // 2+the number of indices in the vector type.
4409 Stmt **SubExprs;
4410 unsigned NumExprs;
4411
4412 public:
4413 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4414 SourceLocation BLoc, SourceLocation RP);
4415
4416 /// Build an empty vector-shuffle expression.
ShuffleVectorExpr(EmptyShell Empty)4417 explicit ShuffleVectorExpr(EmptyShell Empty)
4418 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4419
getBuiltinLoc()4420 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4421 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4422
getRParenLoc()4423 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4424 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4425
getBeginLoc()4426 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4427 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4428
classof(const Stmt * T)4429 static bool classof(const Stmt *T) {
4430 return T->getStmtClass() == ShuffleVectorExprClass;
4431 }
4432
4433 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4434 /// constant expression, the actual arguments passed in, and the function
4435 /// pointers.
getNumSubExprs()4436 unsigned getNumSubExprs() const { return NumExprs; }
4437
4438 /// Retrieve the array of expressions.
getSubExprs()4439 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4440
4441 /// getExpr - Return the Expr at the specified index.
getExpr(unsigned Index)4442 Expr *getExpr(unsigned Index) {
4443 assert((Index < NumExprs) && "Arg access out of range!");
4444 return cast<Expr>(SubExprs[Index]);
4445 }
getExpr(unsigned Index)4446 const Expr *getExpr(unsigned Index) const {
4447 assert((Index < NumExprs) && "Arg access out of range!");
4448 return cast<Expr>(SubExprs[Index]);
4449 }
4450
4451 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4452
getShuffleMaskIdx(const ASTContext & Ctx,unsigned N)4453 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4454 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4455 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4456 }
4457
4458 // Iterators
children()4459 child_range children() {
4460 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4461 }
children()4462 const_child_range children() const {
4463 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4464 }
4465 };
4466
4467 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4468 /// This AST node provides support for converting a vector type to another
4469 /// vector type of the same arity.
4470 class ConvertVectorExpr : public Expr {
4471 private:
4472 Stmt *SrcExpr;
4473 TypeSourceInfo *TInfo;
4474 SourceLocation BuiltinLoc, RParenLoc;
4475
4476 friend class ASTReader;
4477 friend class ASTStmtReader;
ConvertVectorExpr(EmptyShell Empty)4478 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4479
4480 public:
ConvertVectorExpr(Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4481 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4482 ExprValueKind VK, ExprObjectKind OK,
4483 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4484 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4485 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4486 setDependence(computeDependence(this));
4487 }
4488
4489 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()4490 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4491
4492 /// getTypeSourceInfo - Return the destination type.
getTypeSourceInfo()4493 TypeSourceInfo *getTypeSourceInfo() const {
4494 return TInfo;
4495 }
setTypeSourceInfo(TypeSourceInfo * ti)4496 void setTypeSourceInfo(TypeSourceInfo *ti) {
4497 TInfo = ti;
4498 }
4499
4500 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
getBuiltinLoc()4501 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4502
4503 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()4504 SourceLocation getRParenLoc() const { return RParenLoc; }
4505
getBeginLoc()4506 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4507 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4508
classof(const Stmt * T)4509 static bool classof(const Stmt *T) {
4510 return T->getStmtClass() == ConvertVectorExprClass;
4511 }
4512
4513 // Iterators
children()4514 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
children()4515 const_child_range children() const {
4516 return const_child_range(&SrcExpr, &SrcExpr + 1);
4517 }
4518 };
4519
4520 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4521 /// This AST node is similar to the conditional operator (?:) in C, with
4522 /// the following exceptions:
4523 /// - the test expression must be a integer constant expression.
4524 /// - the expression returned acts like the chosen subexpression in every
4525 /// visible way: the type is the same as that of the chosen subexpression,
4526 /// and all predicates (whether it's an l-value, whether it's an integer
4527 /// constant expression, etc.) return the same result as for the chosen
4528 /// sub-expression.
4529 class ChooseExpr : public Expr {
4530 enum { COND, LHS, RHS, END_EXPR };
4531 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4532 SourceLocation BuiltinLoc, RParenLoc;
4533 bool CondIsTrue;
4534 public:
ChooseExpr(SourceLocation BLoc,Expr * cond,Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation RP,bool condIsTrue)4535 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4536 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4537 bool condIsTrue)
4538 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4539 CondIsTrue(condIsTrue) {
4540 SubExprs[COND] = cond;
4541 SubExprs[LHS] = lhs;
4542 SubExprs[RHS] = rhs;
4543
4544 setDependence(computeDependence(this));
4545 }
4546
4547 /// Build an empty __builtin_choose_expr.
ChooseExpr(EmptyShell Empty)4548 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4549
4550 /// isConditionTrue - Return whether the condition is true (i.e. not
4551 /// equal to zero).
isConditionTrue()4552 bool isConditionTrue() const {
4553 assert(!isConditionDependent() &&
4554 "Dependent condition isn't true or false");
4555 return CondIsTrue;
4556 }
setIsConditionTrue(bool isTrue)4557 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4558
isConditionDependent()4559 bool isConditionDependent() const {
4560 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4561 }
4562
4563 /// getChosenSubExpr - Return the subexpression chosen according to the
4564 /// condition.
getChosenSubExpr()4565 Expr *getChosenSubExpr() const {
4566 return isConditionTrue() ? getLHS() : getRHS();
4567 }
4568
getCond()4569 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
setCond(Expr * E)4570 void setCond(Expr *E) { SubExprs[COND] = E; }
getLHS()4571 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)4572 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()4573 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)4574 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4575
getBuiltinLoc()4576 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4577 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4578
getRParenLoc()4579 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4580 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4581
getBeginLoc()4582 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4583 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4584
classof(const Stmt * T)4585 static bool classof(const Stmt *T) {
4586 return T->getStmtClass() == ChooseExprClass;
4587 }
4588
4589 // Iterators
children()4590 child_range children() {
4591 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4592 }
children()4593 const_child_range children() const {
4594 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4595 }
4596 };
4597
4598 /// GNUNullExpr - Implements the GNU __null extension, which is a name
4599 /// for a null pointer constant that has integral type (e.g., int or
4600 /// long) and is the same size and alignment as a pointer. The __null
4601 /// extension is typically only used by system headers, which define
4602 /// NULL as __null in C++ rather than using 0 (which is an integer
4603 /// that may not match the size of a pointer).
4604 class GNUNullExpr : public Expr {
4605 /// TokenLoc - The location of the __null keyword.
4606 SourceLocation TokenLoc;
4607
4608 public:
GNUNullExpr(QualType Ty,SourceLocation Loc)4609 GNUNullExpr(QualType Ty, SourceLocation Loc)
4610 : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4611 setDependence(ExprDependence::None);
4612 }
4613
4614 /// Build an empty GNU __null expression.
GNUNullExpr(EmptyShell Empty)4615 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4616
4617 /// getTokenLocation - The location of the __null token.
getTokenLocation()4618 SourceLocation getTokenLocation() const { return TokenLoc; }
setTokenLocation(SourceLocation L)4619 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4620
getBeginLoc()4621 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
getEndLoc()4622 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4623
classof(const Stmt * T)4624 static bool classof(const Stmt *T) {
4625 return T->getStmtClass() == GNUNullExprClass;
4626 }
4627
4628 // Iterators
children()4629 child_range children() {
4630 return child_range(child_iterator(), child_iterator());
4631 }
children()4632 const_child_range children() const {
4633 return const_child_range(const_child_iterator(), const_child_iterator());
4634 }
4635 };
4636
4637 /// Represents a call to the builtin function \c __builtin_va_arg.
4638 class VAArgExpr : public Expr {
4639 Stmt *Val;
4640 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4641 SourceLocation BuiltinLoc, RParenLoc;
4642 public:
VAArgExpr(SourceLocation BLoc,Expr * e,TypeSourceInfo * TInfo,SourceLocation RPLoc,QualType t,bool IsMS)4643 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4644 SourceLocation RPLoc, QualType t, bool IsMS)
4645 : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4646 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4647 setDependence(computeDependence(this));
4648 }
4649
4650 /// Create an empty __builtin_va_arg expression.
VAArgExpr(EmptyShell Empty)4651 explicit VAArgExpr(EmptyShell Empty)
4652 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4653
getSubExpr()4654 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()4655 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)4656 void setSubExpr(Expr *E) { Val = E; }
4657
4658 /// Returns whether this is really a Win64 ABI va_arg expression.
isMicrosoftABI()4659 bool isMicrosoftABI() const { return TInfo.getInt(); }
setIsMicrosoftABI(bool IsMS)4660 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4661
getWrittenTypeInfo()4662 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
setWrittenTypeInfo(TypeSourceInfo * TI)4663 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4664
getBuiltinLoc()4665 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4666 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4667
getRParenLoc()4668 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4669 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4670
getBeginLoc()4671 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4672 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4673
classof(const Stmt * T)4674 static bool classof(const Stmt *T) {
4675 return T->getStmtClass() == VAArgExprClass;
4676 }
4677
4678 // Iterators
children()4679 child_range children() { return child_range(&Val, &Val+1); }
children()4680 const_child_range children() const {
4681 return const_child_range(&Val, &Val + 1);
4682 }
4683 };
4684
4685 enum class SourceLocIdentKind {
4686 Function,
4687 FuncSig,
4688 File,
4689 FileName,
4690 Line,
4691 Column,
4692 SourceLocStruct
4693 };
4694
4695 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4696 /// __builtin_FUNCTION(), __builtin_FUNCSIG(), __builtin_FILE(),
4697 /// __builtin_FILE_NAME() or __builtin_source_location().
4698 class SourceLocExpr final : public Expr {
4699 SourceLocation BuiltinLoc, RParenLoc;
4700 DeclContext *ParentContext;
4701
4702 public:
4703 SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Type,
4704 QualType ResultTy, SourceLocation BLoc,
4705 SourceLocation RParenLoc, DeclContext *Context);
4706
4707 /// Build an empty call expression.
SourceLocExpr(EmptyShell Empty)4708 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4709
4710 /// Return the result of evaluating this SourceLocExpr in the specified
4711 /// (and possibly null) default argument or initialization context.
4712 APValue EvaluateInContext(const ASTContext &Ctx,
4713 const Expr *DefaultExpr) const;
4714
4715 /// Return a string representing the name of the specific builtin function.
4716 StringRef getBuiltinStr() const;
4717
getIdentKind()4718 SourceLocIdentKind getIdentKind() const {
4719 return static_cast<SourceLocIdentKind>(SourceLocExprBits.Kind);
4720 }
4721
isIntType()4722 bool isIntType() const {
4723 switch (getIdentKind()) {
4724 case SourceLocIdentKind::File:
4725 case SourceLocIdentKind::FileName:
4726 case SourceLocIdentKind::Function:
4727 case SourceLocIdentKind::FuncSig:
4728 case SourceLocIdentKind::SourceLocStruct:
4729 return false;
4730 case SourceLocIdentKind::Line:
4731 case SourceLocIdentKind::Column:
4732 return true;
4733 }
4734 llvm_unreachable("unknown source location expression kind");
4735 }
4736
4737 /// If the SourceLocExpr has been resolved return the subexpression
4738 /// representing the resolved value. Otherwise return null.
getParentContext()4739 const DeclContext *getParentContext() const { return ParentContext; }
getParentContext()4740 DeclContext *getParentContext() { return ParentContext; }
4741
getLocation()4742 SourceLocation getLocation() const { return BuiltinLoc; }
getBeginLoc()4743 SourceLocation getBeginLoc() const { return BuiltinLoc; }
getEndLoc()4744 SourceLocation getEndLoc() const { return RParenLoc; }
4745
children()4746 child_range children() {
4747 return child_range(child_iterator(), child_iterator());
4748 }
4749
children()4750 const_child_range children() const {
4751 return const_child_range(child_iterator(), child_iterator());
4752 }
4753
classof(const Stmt * T)4754 static bool classof(const Stmt *T) {
4755 return T->getStmtClass() == SourceLocExprClass;
4756 }
4757
MayBeDependent(SourceLocIdentKind Kind)4758 static bool MayBeDependent(SourceLocIdentKind Kind) {
4759 switch (Kind) {
4760 case SourceLocIdentKind::Function:
4761 case SourceLocIdentKind::FuncSig:
4762 case SourceLocIdentKind::SourceLocStruct:
4763 return true;
4764 default:
4765 return false;
4766 }
4767 }
4768
4769 private:
4770 friend class ASTStmtReader;
4771 };
4772
4773 /// Describes an C or C++ initializer list.
4774 ///
4775 /// InitListExpr describes an initializer list, which can be used to
4776 /// initialize objects of different types, including
4777 /// struct/class/union types, arrays, and vectors. For example:
4778 ///
4779 /// @code
4780 /// struct foo x = { 1, { 2, 3 } };
4781 /// @endcode
4782 ///
4783 /// Prior to semantic analysis, an initializer list will represent the
4784 /// initializer list as written by the user, but will have the
4785 /// placeholder type "void". This initializer list is called the
4786 /// syntactic form of the initializer, and may contain C99 designated
4787 /// initializers (represented as DesignatedInitExprs), initializations
4788 /// of subobject members without explicit braces, and so on. Clients
4789 /// interested in the original syntax of the initializer list should
4790 /// use the syntactic form of the initializer list.
4791 ///
4792 /// After semantic analysis, the initializer list will represent the
4793 /// semantic form of the initializer, where the initializations of all
4794 /// subobjects are made explicit with nested InitListExpr nodes and
4795 /// C99 designators have been eliminated by placing the designated
4796 /// initializations into the subobject they initialize. Additionally,
4797 /// any "holes" in the initialization, where no initializer has been
4798 /// specified for a particular subobject, will be replaced with
4799 /// implicitly-generated ImplicitValueInitExpr expressions that
4800 /// value-initialize the subobjects. Note, however, that the
4801 /// initializer lists may still have fewer initializers than there are
4802 /// elements to initialize within the object.
4803 ///
4804 /// After semantic analysis has completed, given an initializer list,
4805 /// method isSemanticForm() returns true if and only if this is the
4806 /// semantic form of the initializer list (note: the same AST node
4807 /// may at the same time be the syntactic form).
4808 /// Given the semantic form of the initializer list, one can retrieve
4809 /// the syntactic form of that initializer list (when different)
4810 /// using method getSyntacticForm(); the method returns null if applied
4811 /// to a initializer list which is already in syntactic form.
4812 /// Similarly, given the syntactic form (i.e., an initializer list such
4813 /// that isSemanticForm() returns false), one can retrieve the semantic
4814 /// form using method getSemanticForm().
4815 /// Since many initializer lists have the same syntactic and semantic forms,
4816 /// getSyntacticForm() may return NULL, indicating that the current
4817 /// semantic initializer list also serves as its syntactic form.
4818 class InitListExpr : public Expr {
4819 // FIXME: Eliminate this vector in favor of ASTContext allocation
4820 typedef ASTVector<Stmt *> InitExprsTy;
4821 InitExprsTy InitExprs;
4822 SourceLocation LBraceLoc, RBraceLoc;
4823
4824 /// The alternative form of the initializer list (if it exists).
4825 /// The int part of the pair stores whether this initializer list is
4826 /// in semantic form. If not null, the pointer points to:
4827 /// - the syntactic form, if this is in semantic form;
4828 /// - the semantic form, if this is in syntactic form.
4829 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4830
4831 /// Either:
4832 /// If this initializer list initializes an array with more elements than
4833 /// there are initializers in the list, specifies an expression to be used
4834 /// for value initialization of the rest of the elements.
4835 /// Or
4836 /// If this initializer list initializes a union, specifies which
4837 /// field within the union will be initialized.
4838 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4839
4840 public:
4841 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4842 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4843
4844 /// Build an empty initializer list.
InitListExpr(EmptyShell Empty)4845 explicit InitListExpr(EmptyShell Empty)
4846 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4847
getNumInits()4848 unsigned getNumInits() const { return InitExprs.size(); }
4849
4850 /// Retrieve the set of initializers.
getInits()4851 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4852
4853 /// Retrieve the set of initializers.
getInits()4854 Expr * const *getInits() const {
4855 return reinterpret_cast<Expr * const *>(InitExprs.data());
4856 }
4857
inits()4858 ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); }
4859
inits()4860 ArrayRef<Expr *> inits() const {
4861 return llvm::ArrayRef(getInits(), getNumInits());
4862 }
4863
getInit(unsigned Init)4864 const Expr *getInit(unsigned Init) const {
4865 assert(Init < getNumInits() && "Initializer access out of range!");
4866 return cast_or_null<Expr>(InitExprs[Init]);
4867 }
4868
getInit(unsigned Init)4869 Expr *getInit(unsigned Init) {
4870 assert(Init < getNumInits() && "Initializer access out of range!");
4871 return cast_or_null<Expr>(InitExprs[Init]);
4872 }
4873
setInit(unsigned Init,Expr * expr)4874 void setInit(unsigned Init, Expr *expr) {
4875 assert(Init < getNumInits() && "Initializer access out of range!");
4876 InitExprs[Init] = expr;
4877
4878 if (expr)
4879 setDependence(getDependence() | expr->getDependence());
4880 }
4881
4882 /// Mark the semantic form of the InitListExpr as error when the semantic
4883 /// analysis fails.
markError()4884 void markError() {
4885 assert(isSemanticForm());
4886 setDependence(getDependence() | ExprDependence::ErrorDependent);
4887 }
4888
4889 /// Reserve space for some number of initializers.
4890 void reserveInits(const ASTContext &C, unsigned NumInits);
4891
4892 /// Specify the number of initializers
4893 ///
4894 /// If there are more than @p NumInits initializers, the remaining
4895 /// initializers will be destroyed. If there are fewer than @p
4896 /// NumInits initializers, NULL expressions will be added for the
4897 /// unknown initializers.
4898 void resizeInits(const ASTContext &Context, unsigned NumInits);
4899
4900 /// Updates the initializer at index @p Init with the new
4901 /// expression @p expr, and returns the old expression at that
4902 /// location.
4903 ///
4904 /// When @p Init is out of range for this initializer list, the
4905 /// initializer list will be extended with NULL expressions to
4906 /// accommodate the new entry.
4907 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4908
4909 /// If this initializer list initializes an array with more elements
4910 /// than there are initializers in the list, specifies an expression to be
4911 /// used for value initialization of the rest of the elements.
getArrayFiller()4912 Expr *getArrayFiller() {
4913 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4914 }
getArrayFiller()4915 const Expr *getArrayFiller() const {
4916 return const_cast<InitListExpr *>(this)->getArrayFiller();
4917 }
4918 void setArrayFiller(Expr *filler);
4919
4920 /// Return true if this is an array initializer and its array "filler"
4921 /// has been set.
hasArrayFiller()4922 bool hasArrayFiller() const { return getArrayFiller(); }
4923
4924 /// Determine whether this initializer list contains a designated initializer.
hasDesignatedInit()4925 bool hasDesignatedInit() const {
4926 return std::any_of(begin(), end(), [](const Stmt *S) {
4927 return isa<DesignatedInitExpr>(S);
4928 });
4929 }
4930
4931 /// If this initializes a union, specifies which field in the
4932 /// union to initialize.
4933 ///
4934 /// Typically, this field is the first named field within the
4935 /// union. However, a designated initializer can specify the
4936 /// initialization of a different field within the union.
getInitializedFieldInUnion()4937 FieldDecl *getInitializedFieldInUnion() {
4938 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4939 }
getInitializedFieldInUnion()4940 const FieldDecl *getInitializedFieldInUnion() const {
4941 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4942 }
setInitializedFieldInUnion(FieldDecl * FD)4943 void setInitializedFieldInUnion(FieldDecl *FD) {
4944 assert((FD == nullptr
4945 || getInitializedFieldInUnion() == nullptr
4946 || getInitializedFieldInUnion() == FD)
4947 && "Only one field of a union may be initialized at a time!");
4948 ArrayFillerOrUnionFieldInit = FD;
4949 }
4950
4951 // Explicit InitListExpr's originate from source code (and have valid source
4952 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4953 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4954 // valid source locations too!
isExplicit()4955 bool isExplicit() const {
4956 return LBraceLoc.isValid() && RBraceLoc.isValid();
4957 }
4958
4959 /// Is this an initializer for an array of characters, initialized by a string
4960 /// literal or an @encode?
4961 bool isStringLiteralInit() const;
4962
4963 /// Is this a transparent initializer list (that is, an InitListExpr that is
4964 /// purely syntactic, and whose semantics are that of the sole contained
4965 /// initializer)?
4966 bool isTransparent() const;
4967
4968 /// Is this the zero initializer {0} in a language which considers it
4969 /// idiomatic?
4970 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4971
getLBraceLoc()4972 SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation Loc)4973 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
getRBraceLoc()4974 SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation Loc)4975 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4976
isSemanticForm()4977 bool isSemanticForm() const { return AltForm.getInt(); }
getSemanticForm()4978 InitListExpr *getSemanticForm() const {
4979 return isSemanticForm() ? nullptr : AltForm.getPointer();
4980 }
isSyntacticForm()4981 bool isSyntacticForm() const {
4982 return !AltForm.getInt() || !AltForm.getPointer();
4983 }
getSyntacticForm()4984 InitListExpr *getSyntacticForm() const {
4985 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4986 }
4987
setSyntacticForm(InitListExpr * Init)4988 void setSyntacticForm(InitListExpr *Init) {
4989 AltForm.setPointer(Init);
4990 AltForm.setInt(true);
4991 Init->AltForm.setPointer(this);
4992 Init->AltForm.setInt(false);
4993 }
4994
hadArrayRangeDesignator()4995 bool hadArrayRangeDesignator() const {
4996 return InitListExprBits.HadArrayRangeDesignator != 0;
4997 }
4998 void sawArrayRangeDesignator(bool ARD = true) {
4999 InitListExprBits.HadArrayRangeDesignator = ARD;
5000 }
5001
5002 SourceLocation getBeginLoc() const LLVM_READONLY;
5003 SourceLocation getEndLoc() const LLVM_READONLY;
5004
classof(const Stmt * T)5005 static bool classof(const Stmt *T) {
5006 return T->getStmtClass() == InitListExprClass;
5007 }
5008
5009 // Iterators
children()5010 child_range children() {
5011 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
5012 return child_range(cast_away_const(CCR.begin()),
5013 cast_away_const(CCR.end()));
5014 }
5015
children()5016 const_child_range children() const {
5017 // FIXME: This does not include the array filler expression.
5018 if (InitExprs.empty())
5019 return const_child_range(const_child_iterator(), const_child_iterator());
5020 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
5021 }
5022
5023 typedef InitExprsTy::iterator iterator;
5024 typedef InitExprsTy::const_iterator const_iterator;
5025 typedef InitExprsTy::reverse_iterator reverse_iterator;
5026 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
5027
begin()5028 iterator begin() { return InitExprs.begin(); }
begin()5029 const_iterator begin() const { return InitExprs.begin(); }
end()5030