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