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
42namespace 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.
62typedef 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.
66struct 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
89 SubobjectAdjustment(const CastExpr *BasePath,
90 const CXXRecordDecl *DerivedClass)
91 : Kind(DerivedToBaseAdjustment) {
92 DerivedToBase.BasePath = BasePath;
93 DerivedToBase.DerivedClass = DerivedClass;
94 }
95
96 SubobjectAdjustment(const FieldDecl *Field) : Kind(FieldAdjustment) {
97 this->Field = Field;
98 }
99
100 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.
110class Expr : public ValueStmt {
111 QualType TR;
112
113public:
114 Expr() = delete;
115 Expr(const Expr&) = delete;
116 Expr(Expr &&) = delete;
117 Expr &operator=(const Expr&) = delete;
118 Expr &operator=(Expr&&) = delete;
119
120protected:
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.
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.
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
141public:
142 QualType getType() const { return TR; }
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
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
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
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
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.
239 bool containsUnexpandedParameterPack() const {
240 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
241 }
242
243 /// Whether this expression contains subexpressions which had errors.
244 bool containsErrors() const {
245 return static_cast<bool>(getDependence() & ExprDependence::Error);
246 }
247
248 /// getExprLoc - Return the preferred location for the arrow when diagnosing
249 /// a problem with a generic expression.
250 SourceLocation getExprLoc() const LLVM_READONLY;
251
252 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
253 /// applied to this expression if it appears as a discarded-value expression
254 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
255 bool isReadIfDiscardedInCPlusPlus11() const;
256
257 /// isUnusedResultAWarning - Return true if this immediate expression should
258 /// be warned about if the result is unused. If so, fill in expr, location,
259 /// and ranges with expr to warn on and source locations/ranges appropriate
260 /// for a warning.
261 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
262 SourceRange &R1, SourceRange &R2,
263 ASTContext &Ctx) const;
264
265 /// isLValue - True if this expression is an "l-value" according to
266 /// the rules of the current language. C and C++ give somewhat
267 /// different rules for this concept, but in general, the result of
268 /// an l-value expression identifies a specific object whereas the
269 /// result of an r-value expression is a value detached from any
270 /// specific storage.
271 ///
272 /// C++11 divides the concept of "r-value" into pure r-values
273 /// ("pr-values") and so-called expiring values ("x-values"), which
274 /// identify specific objects that can be safely cannibalized for
275 /// their resources.
276 bool isLValue() const { return getValueKind() == VK_LValue; }
277 bool isPRValue() const { return getValueKind() == VK_PRValue; }
278 bool isXValue() const { return getValueKind() == VK_XValue; }
279 bool isGLValue() const { return getValueKind() != VK_PRValue; }
280
281 enum LValueClassification {
282 LV_Valid,
283 LV_NotObjectType,
284 LV_IncompleteVoidType,
285 LV_DuplicateVectorComponents,
286 LV_InvalidExpression,
287 LV_InvalidMessageExpression,
288 LV_MemberFunction,
289 LV_SubObjCPropertySetting,
290 LV_ClassTemporary,
291 LV_ArrayTemporary
292 };
293 /// Reasons why an expression might not be an l-value.
294 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
295
296 enum isModifiableLvalueResult {
297 MLV_Valid,
298 MLV_NotObjectType,
299 MLV_IncompleteVoidType,
300 MLV_DuplicateVectorComponents,
301 MLV_InvalidExpression,
302 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
303 MLV_IncompleteType,
304 MLV_ConstQualified,
305 MLV_ConstQualifiedField,
306 MLV_ConstAddrSpace,
307 MLV_ArrayType,
308 MLV_NoSetterProperty,
309 MLV_MemberFunction,
310 MLV_SubObjCPropertySetting,
311 MLV_InvalidMessageExpression,
312 MLV_ClassTemporary,
313 MLV_ArrayTemporary
314 };
315 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
316 /// does not have an incomplete type, does not have a const-qualified type,
317 /// and if it is a structure or union, does not have any member (including,
318 /// recursively, any member or element of all contained aggregates or unions)
319 /// with a const-qualified type.
320 ///
321 /// \param Loc [in,out] - A source location which *may* be filled
322 /// in with the location of the expression making this a
323 /// non-modifiable lvalue, if specified.
324 isModifiableLvalueResult
325 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
326
327 /// The return type of classify(). Represents the C++11 expression
328 /// taxonomy.
329 class Classification {
330 public:
331 /// The various classification results. Most of these mean prvalue.
332 enum Kinds {
333 CL_LValue,
334 CL_XValue,
335 CL_Function, // Functions cannot be lvalues in C.
336 CL_Void, // Void cannot be an lvalue in C.
337 CL_AddressableVoid, // Void expression whose address can be taken in C.
338 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
339 CL_MemberFunction, // An expression referring to a member function
340 CL_SubObjCPropertySetting,
341 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
342 CL_ArrayTemporary, // A temporary of array type.
343 CL_ObjCMessageRValue, // ObjC message is an rvalue
344 CL_PRValue // A prvalue for any other reason, of any other type
345 };
346 /// The results of modification testing.
347 enum ModifiableType {
348 CM_Untested, // testModifiable was false.
349 CM_Modifiable,
350 CM_RValue, // Not modifiable because it's an rvalue
351 CM_Function, // Not modifiable because it's a function; C++ only
352 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
353 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
354 CM_ConstQualified,
355 CM_ConstQualifiedField,
356 CM_ConstAddrSpace,
357 CM_ArrayType,
358 CM_IncompleteType
359 };
360
361 private:
362 friend class Expr;
363
364 unsigned short Kind;
365 unsigned short Modifiable;
366
367 explicit Classification(Kinds k, ModifiableType m)
368 : Kind(k), Modifiable(m)
369 {}
370
371 public:
372 Classification() {}
373
374 Kinds getKind() const { return static_cast<Kinds>(Kind); }
375 ModifiableType getModifiable() const {
376 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
377 return static_cast<ModifiableType>(Modifiable);
378 }
379 bool isLValue() const { return Kind == CL_LValue; }
380 bool isXValue() const { return Kind == CL_XValue; }
381 bool isGLValue() const { return Kind <= CL_XValue; }
382 bool isPRValue() const { return Kind >= CL_Function; }
383 bool isRValue() const { return Kind >= CL_XValue; }
384 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
385
386 /// Create a simple, modifiable lvalue
387 static Classification makeSimpleLValue() {
388 return Classification(CL_LValue, CM_Modifiable);
389 }
390
391 };
392 /// Classify - Classify this expression according to the C++11
393 /// expression taxonomy.
394 ///
395 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
396 /// old lvalue vs rvalue. This function determines the type of expression this
397 /// is. There are three expression types:
398 /// - lvalues are classical lvalues as in C++03.
399 /// - prvalues are equivalent to rvalues in C++03.
400 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
401 /// function returning an rvalue reference.
402 /// lvalues and xvalues are collectively referred to as glvalues, while
403 /// prvalues and xvalues together form rvalues.
404 Classification Classify(ASTContext &Ctx) const {
405 return ClassifyImpl(Ctx, Loc: nullptr);
406 }
407
408 /// ClassifyModifiable - Classify this expression according to the
409 /// C++11 expression taxonomy, and see if it is valid on the left side
410 /// of an assignment.
411 ///
412 /// This function extends classify in that it also tests whether the
413 /// expression is modifiable (C99 6.3.2.1p1).
414 /// \param Loc A source location that might be filled with a relevant location
415 /// if the expression is not modifiable.
416 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
417 return ClassifyImpl(Ctx, Loc: &Loc);
418 }
419
420 /// Returns the set of floating point options that apply to this expression.
421 /// Only meaningful for operations on floating point values.
422 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
423
424 /// getValueKindForType - Given a formal return or parameter type,
425 /// give its value kind.
426 static ExprValueKind getValueKindForType(QualType T) {
427 if (const ReferenceType *RT = T->getAs<ReferenceType>())
428 return (isa<LValueReferenceType>(Val: RT)
429 ? VK_LValue
430 : (RT->getPointeeType()->isFunctionType()
431 ? VK_LValue : VK_XValue));
432 return VK_PRValue;
433 }
434
435 /// getValueKind - The value kind that this expression produces.
436 ExprValueKind getValueKind() const {
437 return static_cast<ExprValueKind>(ExprBits.ValueKind);
438 }
439
440 /// getObjectKind - The object kind that this expression produces.
441 /// Object kinds are meaningful only for expressions that yield an
442 /// l-value or x-value.
443 ExprObjectKind getObjectKind() const {
444 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
445 }
446
447 bool isOrdinaryOrBitFieldObject() const {
448 ExprObjectKind OK = getObjectKind();
449 return (OK == OK_Ordinary || OK == OK_BitField);
450 }
451
452 /// setValueKind - Set the value kind produced by this expression.
453 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
454
455 /// setObjectKind - Set the object kind produced by this expression.
456 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
457
458private:
459 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
460
461public:
462
463 /// Returns true if this expression is a gl-value that
464 /// potentially refers to a bit-field.
465 ///
466 /// In C++, whether a gl-value refers to a bitfield is essentially
467 /// an aspect of the value-kind type system.
468 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
469
470 /// If this expression refers to a bit-field, retrieve the
471 /// declaration of that bit-field.
472 ///
473 /// Note that this returns a non-null pointer in subtly different
474 /// places than refersToBitField returns true. In particular, this can
475 /// return a non-null pointer even for r-values loaded from
476 /// bit-fields, but it will return null for a conditional bit-field.
477 FieldDecl *getSourceBitField();
478
479 /// If this expression refers to an enum constant, retrieve its declaration
480 EnumConstantDecl *getEnumConstantDecl();
481
482 const EnumConstantDecl *getEnumConstantDecl() const {
483 return const_cast<Expr *>(this)->getEnumConstantDecl();
484 }
485
486 const FieldDecl *getSourceBitField() const {
487 return const_cast<Expr*>(this)->getSourceBitField();
488 }
489
490 Decl *getReferencedDeclOfCallee();
491 const Decl *getReferencedDeclOfCallee() const {
492 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
493 }
494
495 /// If this expression is an l-value for an Objective C
496 /// property, find the underlying property reference expression.
497 const ObjCPropertyRefExpr *getObjCProperty() const;
498
499 /// Check if this expression is the ObjC 'self' implicit parameter.
500 bool isObjCSelfExpr() const;
501
502 /// Returns whether this expression refers to a vector element.
503 bool refersToVectorElement() const;
504
505 /// Returns whether this expression refers to a matrix element.
506 bool refersToMatrixElement() const {
507 return getObjectKind() == OK_MatrixComponent;
508 }
509
510 /// Returns whether this expression refers to a global register
511 /// variable.
512 bool refersToGlobalRegisterVar() const;
513
514 /// Returns whether this expression has a placeholder type.
515 bool hasPlaceholderType() const {
516 return getType()->isPlaceholderType();
517 }
518
519 /// Returns whether this expression has a specific placeholder type.
520 bool hasPlaceholderType(BuiltinType::Kind K) const {
521 assert(BuiltinType::isPlaceholderTypeKind(K));
522 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val: getType()))
523 return BT->getKind() == K;
524 return false;
525 }
526
527 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
528 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
529 /// but also int expressions which are produced by things like comparisons in
530 /// C.
531 ///
532 /// \param Semantic If true, only return true for expressions that are known
533 /// to be semantically boolean, which might not be true even for expressions
534 /// that are known to evaluate to 0/1. For instance, reading an unsigned
535 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
536 /// semantically correspond to a bool.
537 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
538
539 /// Check whether this array fits the idiom of a flexible array member,
540 /// depending on the value of -fstrict-flex-array.
541 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
542 /// resulting from the substitution of a macro or a template as special sizes.
543 bool isFlexibleArrayMemberLike(
544 const ASTContext &Context,
545 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
546 bool IgnoreTemplateOrMacroSubstitution = false) const;
547
548 /// isIntegerConstantExpr - Return the value if this expression is a valid
549 /// integer constant expression. If not a valid i-c-e, return std::nullopt
550 /// and fill in Loc (if specified) with the location of the invalid
551 /// expression.
552 ///
553 /// Note: This does not perform the implicit conversions required by C++11
554 /// [expr.const]p5.
555 std::optional<llvm::APSInt>
556 getIntegerConstantExpr(const ASTContext &Ctx,
557 SourceLocation *Loc = nullptr) const;
558 bool isIntegerConstantExpr(const ASTContext &Ctx,
559 SourceLocation *Loc = nullptr) const;
560
561 /// isCXX98IntegralConstantExpr - Return true if this expression is an
562 /// integral constant expression in C++98. Can only be used in C++.
563 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
564
565 /// isCXX11ConstantExpr - Return true if this expression is a constant
566 /// expression in C++11. Can only be used in C++.
567 ///
568 /// Note: This does not perform the implicit conversions required by C++11
569 /// [expr.const]p5.
570 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
571 SourceLocation *Loc = nullptr) const;
572
573 /// isPotentialConstantExpr - Return true if this function's definition
574 /// might be usable in a constant expression in C++11, if it were marked
575 /// constexpr. Return false if the function can never produce a constant
576 /// expression, along with diagnostics describing why not.
577 static bool isPotentialConstantExpr(const FunctionDecl *FD,
578 SmallVectorImpl<
579 PartialDiagnosticAt> &Diags);
580
581 /// isPotentialConstantExprUnevaluated - Return true if this expression might
582 /// be usable in a constant expression in C++11 in an unevaluated context, if
583 /// it were in function FD marked constexpr. Return false if the function can
584 /// never produce a constant expression, along with diagnostics describing
585 /// why not.
586 static bool isPotentialConstantExprUnevaluated(Expr *E,
587 const FunctionDecl *FD,
588 SmallVectorImpl<
589 PartialDiagnosticAt> &Diags);
590
591 /// isConstantInitializer - Returns true if this expression can be emitted to
592 /// IR as a constant, and thus can be used as a constant initializer in C.
593 /// If this expression is not constant and Culprit is non-null,
594 /// it is used to store the address of first non constant expr.
595 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
596 const Expr **Culprit = nullptr) const;
597
598 /// If this expression is an unambiguous reference to a single declaration,
599 /// in the style of __builtin_function_start, return that declaration. Note
600 /// that this may return a non-static member function or field in C++ if this
601 /// expression is a member pointer constant.
602 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
603
604 /// EvalStatus is a struct with detailed info about an evaluation in progress.
605 struct EvalStatus {
606 /// Whether the evaluated expression has side effects.
607 /// For example, (f() && 0) can be folded, but it still has side effects.
608 bool HasSideEffects = false;
609
610 /// Whether the evaluation hit undefined behavior.
611 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
612 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
613 bool HasUndefinedBehavior = false;
614
615 /// Diag - If this is non-null, it will be filled in with a stack of notes
616 /// indicating why evaluation failed (or why it failed to produce a constant
617 /// expression).
618 /// If the expression is unfoldable, the notes will indicate why it's not
619 /// foldable. If the expression is foldable, but not a constant expression,
620 /// the notes will describes why it isn't a constant expression. If the
621 /// expression *is* a constant expression, no notes will be produced.
622 ///
623 /// FIXME: this causes significant performance concerns and should be
624 /// refactored at some point. Not all evaluations of the constant
625 /// expression interpreter will display the given diagnostics, this means
626 /// those kinds of uses are paying the expense of generating a diagnostic
627 /// (which may include expensive operations like converting APValue objects
628 /// to a string representation).
629 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
630
631 EvalStatus() = default;
632
633 // hasSideEffects - Return true if the evaluated expression has
634 // side effects.
635 bool hasSideEffects() const {
636 return HasSideEffects;
637 }
638 };
639
640 /// EvalResult is a struct with detailed info about an evaluated expression.
641 struct EvalResult : EvalStatus {
642 /// Val - This is the value the expression can be folded to.
643 APValue Val;
644
645 // isGlobalLValue - Return true if the evaluated lvalue expression
646 // is global.
647 bool isGlobalLValue() const;
648 };
649
650 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
651 /// an rvalue using any crazy technique (that has nothing to do with language
652 /// standards) that we want to, even if the expression has side-effects. If
653 /// this function returns true, it returns the folded constant in Result. If
654 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
655 /// applied.
656 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
657 bool InConstantContext = false) const;
658
659 /// EvaluateAsBooleanCondition - Return true if this is a constant
660 /// which we can fold and convert to a boolean condition using
661 /// any crazy technique that we want to, even if the expression has
662 /// side-effects.
663 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
664 bool InConstantContext = false) const;
665
666 enum SideEffectsKind {
667 SE_NoSideEffects, ///< Strictly evaluate the expression.
668 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
669 ///< arbitrary unmodeled side effects.
670 SE_AllowSideEffects ///< Allow any unmodeled side effect.
671 };
672
673 /// EvaluateAsInt - Return true if this is a constant which we can fold and
674 /// convert to an integer, using any crazy technique that we want to.
675 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
676 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
677 bool InConstantContext = false) const;
678
679 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
680 /// convert to a floating point value, using any crazy technique that we
681 /// want to.
682 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
683 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
684 bool InConstantContext = false) const;
685
686 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
687 /// and convert to a fixed point value.
688 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
689 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
690 bool InConstantContext = false) const;
691
692 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
693 /// constant folded without side-effects, but discard the result.
694 bool isEvaluatable(const ASTContext &Ctx,
695 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
696
697 /// HasSideEffects - This routine returns true for all those expressions
698 /// which have any effect other than producing a value. Example is a function
699 /// call, volatile variable read, or throwing an exception. If
700 /// IncludePossibleEffects is false, this call treats certain expressions with
701 /// potential side effects (such as function call-like expressions,
702 /// instantiation-dependent expressions, or invocations from a macro) as not
703 /// having side effects.
704 bool HasSideEffects(const ASTContext &Ctx,
705 bool IncludePossibleEffects = true) const;
706
707 /// Determine whether this expression involves a call to any function
708 /// that is not trivial.
709 bool hasNonTrivialCall(const ASTContext &Ctx) const;
710
711 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
712 /// integer. This must be called on an expression that constant folds to an
713 /// integer.
714 llvm::APSInt EvaluateKnownConstInt(
715 const ASTContext &Ctx,
716 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
717
718 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
719 const ASTContext &Ctx,
720 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
721
722 void EvaluateForOverflow(const ASTContext &Ctx) const;
723
724 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
725 /// lvalue with link time known address, with no side-effects.
726 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
727 bool InConstantContext = false) const;
728
729 /// EvaluateAsInitializer - Evaluate an expression as if it were the
730 /// initializer of the given declaration. Returns true if the initializer
731 /// can be folded to a constant, and produces any relevant notes. In C++11,
732 /// notes will be produced if the expression is not a constant expression.
733 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
734 const VarDecl *VD,
735 SmallVectorImpl<PartialDiagnosticAt> &Notes,
736 bool IsConstantInitializer) const;
737
738 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
739 /// of a call to the given function with the given arguments, inside an
740 /// unevaluated context. Returns true if the expression could be folded to a
741 /// constant.
742 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
743 const FunctionDecl *Callee,
744 ArrayRef<const Expr*> Args,
745 const Expr *This = nullptr) const;
746
747 enum class ConstantExprKind {
748 /// An integer constant expression (an array bound, enumerator, case value,
749 /// bit-field width, or similar) or similar.
750 Normal,
751 /// A non-class template argument. Such a value is only used for mangling,
752 /// not for code generation, so can refer to dllimported functions.
753 NonClassTemplateArgument,
754 /// A class template argument. Such a value is used for code generation.
755 ClassTemplateArgument,
756 /// An immediate invocation. The destruction of the end result of this
757 /// evaluation is not part of the evaluation, but all other temporaries
758 /// are destroyed.
759 ImmediateInvocation,
760 };
761
762 /// Evaluate an expression that is required to be a constant expression. Does
763 /// not check the syntactic constraints for C and C++98 constant expressions.
764 bool EvaluateAsConstantExpr(
765 EvalResult &Result, const ASTContext &Ctx,
766 ConstantExprKind Kind = ConstantExprKind::Normal) const;
767
768 /// If the current Expr is a pointer, this will try to statically
769 /// determine the number of bytes available where the pointer is pointing.
770 /// Returns true if all of the above holds and we were able to figure out the
771 /// size, false otherwise.
772 ///
773 /// \param Type - How to evaluate the size of the Expr, as defined by the
774 /// "type" parameter of __builtin_object_size
775 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
776 unsigned Type) const;
777
778 /// If the current Expr is a pointer, this will try to statically
779 /// determine the strlen of the string pointed to.
780 /// Returns true if all of the above holds and we were able to figure out the
781 /// strlen, false otherwise.
782 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
783
784 bool EvaluateCharRangeAsString(std::string &Result,
785 const Expr *SizeExpression,
786 const Expr *PtrExpression, ASTContext &Ctx,
787 EvalResult &Status) const;
788
789 bool EvaluateCharRangeAsString(APValue &Result, const Expr *SizeExpression,
790 const Expr *PtrExpression, ASTContext &Ctx,
791 EvalResult &Status) const;
792
793 /// If the current Expr can be evaluated to a pointer to a null-terminated
794 /// constant string, return the constant string (without the terminating
795 /// null).
796 std::optional<std::string> tryEvaluateString(ASTContext &Ctx) const;
797
798 /// Enumeration used to describe the kind of Null pointer constant
799 /// returned from \c isNullPointerConstant().
800 enum NullPointerConstantKind {
801 /// Expression is not a Null pointer constant.
802 NPCK_NotNull = 0,
803
804 /// Expression is a Null pointer constant built from a zero integer
805 /// expression that is not a simple, possibly parenthesized, zero literal.
806 /// C++ Core Issue 903 will classify these expressions as "not pointers"
807 /// once it is adopted.
808 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
809 NPCK_ZeroExpression,
810
811 /// Expression is a Null pointer constant built from a literal zero.
812 NPCK_ZeroLiteral,
813
814 /// Expression is a C++11 nullptr.
815 NPCK_CXX11_nullptr,
816
817 /// Expression is a GNU-style __null constant.
818 NPCK_GNUNull
819 };
820
821 /// Enumeration used to describe how \c isNullPointerConstant()
822 /// should cope with value-dependent expressions.
823 enum NullPointerConstantValueDependence {
824 /// Specifies that the expression should never be value-dependent.
825 NPC_NeverValueDependent = 0,
826
827 /// Specifies that a value-dependent expression of integral or
828 /// dependent type should be considered a null pointer constant.
829 NPC_ValueDependentIsNull,
830
831 /// Specifies that a value-dependent expression should be considered
832 /// to never be a null pointer constant.
833 NPC_ValueDependentIsNotNull
834 };
835
836 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
837 /// a Null pointer constant. The return value can further distinguish the
838 /// kind of NULL pointer constant that was detected.
839 NullPointerConstantKind isNullPointerConstant(
840 ASTContext &Ctx,
841 NullPointerConstantValueDependence NPC) const;
842
843 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
844 /// write barrier.
845 bool isOBJCGCCandidate(ASTContext &Ctx) const;
846
847 /// Returns true if this expression is a bound member function.
848 bool isBoundMemberFunction(ASTContext &Ctx) const;
849
850 /// Given an expression of bound-member type, find the type
851 /// of the member. Returns null if this is an *overloaded* bound
852 /// member expression.
853 static QualType findBoundMemberType(const Expr *expr);
854
855 /// Skip past any invisible AST nodes which might surround this
856 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
857 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
858 /// implicit conversions.
859 Expr *IgnoreUnlessSpelledInSource();
860 const Expr *IgnoreUnlessSpelledInSource() const {
861 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
862 }
863
864 /// Skip past any implicit casts which might surround this expression until
865 /// reaching a fixed point. Skips:
866 /// * ImplicitCastExpr
867 /// * FullExpr
868 Expr *IgnoreImpCasts() LLVM_READONLY;
869 const Expr *IgnoreImpCasts() const {
870 return const_cast<Expr *>(this)->IgnoreImpCasts();
871 }
872
873 /// Skip past any casts which might surround this expression until reaching
874 /// a fixed point. Skips:
875 /// * CastExpr
876 /// * FullExpr
877 /// * MaterializeTemporaryExpr
878 /// * SubstNonTypeTemplateParmExpr
879 Expr *IgnoreCasts() LLVM_READONLY;
880 const Expr *IgnoreCasts() const {
881 return const_cast<Expr *>(this)->IgnoreCasts();
882 }
883
884 /// Skip past any implicit AST nodes which might surround this expression
885 /// until reaching a fixed point. Skips:
886 /// * What IgnoreImpCasts() skips
887 /// * MaterializeTemporaryExpr
888 /// * CXXBindTemporaryExpr
889 Expr *IgnoreImplicit() LLVM_READONLY;
890 const Expr *IgnoreImplicit() const {
891 return const_cast<Expr *>(this)->IgnoreImplicit();
892 }
893
894 /// Skip past any implicit AST nodes which might surround this expression
895 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
896 /// also skips over implicit calls to constructors and conversion functions.
897 ///
898 /// FIXME: Should IgnoreImplicit do this?
899 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
900 const Expr *IgnoreImplicitAsWritten() const {
901 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
902 }
903
904 /// Skip past any parentheses which might surround this expression until
905 /// reaching a fixed point. Skips:
906 /// * ParenExpr
907 /// * UnaryOperator if `UO_Extension`
908 /// * GenericSelectionExpr if `!isResultDependent()`
909 /// * ChooseExpr if `!isConditionDependent()`
910 /// * ConstantExpr
911 Expr *IgnoreParens() LLVM_READONLY;
912 const Expr *IgnoreParens() const {
913 return const_cast<Expr *>(this)->IgnoreParens();
914 }
915
916 /// Skip past any parentheses and implicit casts which might surround this
917 /// expression until reaching a fixed point.
918 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
919 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
920 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
921 /// * What IgnoreParens() skips
922 /// * What IgnoreImpCasts() skips
923 /// * MaterializeTemporaryExpr
924 /// * SubstNonTypeTemplateParmExpr
925 Expr *IgnoreParenImpCasts() LLVM_READONLY;
926 const Expr *IgnoreParenImpCasts() const {
927 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
928 }
929
930 /// Skip past any parentheses and casts which might surround this expression
931 /// until reaching a fixed point. Skips:
932 /// * What IgnoreParens() skips
933 /// * What IgnoreCasts() skips
934 Expr *IgnoreParenCasts() LLVM_READONLY;
935 const Expr *IgnoreParenCasts() const {
936 return const_cast<Expr *>(this)->IgnoreParenCasts();
937 }
938
939 /// Skip conversion operators. If this Expr is a call to a conversion
940 /// operator, return the argument.
941 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
942 const Expr *IgnoreConversionOperatorSingleStep() const {
943 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
944 }
945
946 /// Skip past any parentheses and lvalue casts which might surround this
947 /// expression until reaching a fixed point. Skips:
948 /// * What IgnoreParens() skips
949 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
950 /// casts are skipped
951 /// FIXME: This is intended purely as a temporary workaround for code
952 /// that hasn't yet been rewritten to do the right thing about those
953 /// casts, and may disappear along with the last internal use.
954 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
955 const Expr *IgnoreParenLValueCasts() const {
956 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
957 }
958
959 /// Skip past any parentheses and casts which do not change the value
960 /// (including ptr->int casts of the same size) until reaching a fixed point.
961 /// Skips:
962 /// * What IgnoreParens() skips
963 /// * CastExpr which do not change the value
964 /// * SubstNonTypeTemplateParmExpr
965 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
966 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
967 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
968 }
969
970 /// Skip past any parentheses and derived-to-base casts until reaching a
971 /// fixed point. Skips:
972 /// * What IgnoreParens() skips
973 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
974 /// CK_UncheckedDerivedToBase and CK_NoOp)
975 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
976 const Expr *IgnoreParenBaseCasts() const {
977 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
978 }
979
980 /// Determine whether this expression is a default function argument.
981 ///
982 /// Default arguments are implicitly generated in the abstract syntax tree
983 /// by semantic analysis for function calls, object constructions, etc. in
984 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
985 /// this routine also looks through any implicit casts to determine whether
986 /// the expression is a default argument.
987 bool isDefaultArgument() const;
988
989 /// Determine whether the result of this expression is a
990 /// temporary object of the given class type.
991 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
992
993 /// Whether this expression is an implicit reference to 'this' in C++.
994 bool isImplicitCXXThis() const;
995
996 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
997
998 /// For an expression of class type or pointer to class type,
999 /// return the most derived class decl the expression is known to refer to.
1000 ///
1001 /// If this expression is a cast, this method looks through it to find the
1002 /// most derived decl that can be inferred from the expression.
1003 /// This is valid because derived-to-base conversions have undefined
1004 /// behavior if the object isn't dynamically of the derived type.
1005 const CXXRecordDecl *getBestDynamicClassType() const;
1006
1007 /// Get the inner expression that determines the best dynamic class.
1008 /// If this is a prvalue, we guarantee that it is of the most-derived type
1009 /// for the object itself.
1010 const Expr *getBestDynamicClassTypeExpr() const;
1011
1012 /// Walk outwards from an expression we want to bind a reference to and
1013 /// find the expression whose lifetime needs to be extended. Record
1014 /// the LHSs of comma expressions and adjustments needed along the path.
1015 const Expr *skipRValueSubobjectAdjustments(
1016 SmallVectorImpl<const Expr *> &CommaLHS,
1017 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
1018 const Expr *skipRValueSubobjectAdjustments() const {
1019 SmallVector<const Expr *, 8> CommaLHSs;
1020 SmallVector<SubobjectAdjustment, 8> Adjustments;
1021 return skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments);
1022 }
1023
1024 /// Checks that the two Expr's will refer to the same value as a comparison
1025 /// operand. The caller must ensure that the values referenced by the Expr's
1026 /// are not modified between E1 and E2 or the result my be invalid.
1027 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
1028
1029 static bool classof(const Stmt *T) {
1030 return T->getStmtClass() >= firstExprConstant &&
1031 T->getStmtClass() <= lastExprConstant;
1032 }
1033};
1034// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1035// Expr. Verify that we got it right.
1036static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
1037 llvm::detail::ConstantLog2<alignof(Expr)>::value,
1038 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1039
1040using ConstantExprKind = Expr::ConstantExprKind;
1041
1042//===----------------------------------------------------------------------===//
1043// Wrapper Expressions.
1044//===----------------------------------------------------------------------===//
1045
1046/// FullExpr - Represents a "full-expression" node.
1047class FullExpr : public Expr {
1048protected:
1049 Stmt *SubExpr;
1050
1051 FullExpr(StmtClass SC, Expr *subexpr)
1052 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1053 subexpr->getObjectKind()),
1054 SubExpr(subexpr) {
1055 setDependence(computeDependence(E: this));
1056 }
1057 FullExpr(StmtClass SC, EmptyShell Empty)
1058 : Expr(SC, Empty) {}
1059public:
1060 const Expr *getSubExpr() const { return cast<Expr>(Val: SubExpr); }
1061 Expr *getSubExpr() { return cast<Expr>(Val: SubExpr); }
1062
1063 /// As with any mutator of the AST, be very careful when modifying an
1064 /// existing AST to preserve its invariants.
1065 void setSubExpr(Expr *E) { SubExpr = E; }
1066
1067 static bool classof(const Stmt *T) {
1068 return T->getStmtClass() >= firstFullExprConstant &&
1069 T->getStmtClass() <= lastFullExprConstant;
1070 }
1071};
1072
1073/// Describes the kind of result that can be tail-allocated.
1074enum class ConstantResultStorageKind { None, Int64, APValue };
1075
1076/// ConstantExpr - An expression that occurs in a constant context and
1077/// optionally the result of evaluating the expression.
1078class ConstantExpr final
1079 : public FullExpr,
1080 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1081 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1082 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1083 "for tail-allocated storage");
1084 friend TrailingObjects;
1085 friend class ASTStmtReader;
1086 friend class ASTStmtWriter;
1087
1088 size_t numTrailingObjects(OverloadToken<APValue>) const {
1089 return getResultStorageKind() == ConstantResultStorageKind::APValue;
1090 }
1091 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1092 return getResultStorageKind() == ConstantResultStorageKind::Int64;
1093 }
1094
1095 uint64_t &Int64Result() {
1096 assert(getResultStorageKind() == ConstantResultStorageKind::Int64 &&
1097 "invalid accessor");
1098 return *getTrailingObjects<uint64_t>();
1099 }
1100 const uint64_t &Int64Result() const {
1101 return const_cast<ConstantExpr *>(this)->Int64Result();
1102 }
1103 APValue &APValueResult() {
1104 assert(getResultStorageKind() == ConstantResultStorageKind::APValue &&
1105 "invalid accessor");
1106 return *getTrailingObjects<APValue>();
1107 }
1108 APValue &APValueResult() const {
1109 return const_cast<ConstantExpr *>(this)->APValueResult();
1110 }
1111
1112 ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
1113 bool IsImmediateInvocation);
1114 ConstantExpr(EmptyShell Empty, ConstantResultStorageKind StorageKind);
1115
1116public:
1117 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1118 const APValue &Result);
1119 static ConstantExpr *
1120 Create(const ASTContext &Context, Expr *E,
1121 ConstantResultStorageKind Storage = ConstantResultStorageKind::None,
1122 bool IsImmediateInvocation = false);
1123 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1124 ConstantResultStorageKind StorageKind);
1125
1126 static ConstantResultStorageKind getStorageKind(const APValue &Value);
1127 static ConstantResultStorageKind getStorageKind(const Type *T,
1128 const ASTContext &Context);
1129
1130 SourceLocation getBeginLoc() const LLVM_READONLY {
1131 return SubExpr->getBeginLoc();
1132 }
1133 SourceLocation getEndLoc() const LLVM_READONLY {
1134 return SubExpr->getEndLoc();
1135 }
1136
1137 static bool classof(const Stmt *T) {
1138 return T->getStmtClass() == ConstantExprClass;
1139 }
1140
1141 void SetResult(APValue Value, const ASTContext &Context) {
1142 MoveIntoResult(Value, Context);
1143 }
1144 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1145
1146 APValue::ValueKind getResultAPValueKind() const {
1147 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1148 }
1149 ConstantResultStorageKind getResultStorageKind() const {
1150 return static_cast<ConstantResultStorageKind>(ConstantExprBits.ResultKind);
1151 }
1152 bool isImmediateInvocation() const {
1153 return ConstantExprBits.IsImmediateInvocation;
1154 }
1155 bool hasAPValueResult() const {
1156 return ConstantExprBits.APValueKind != APValue::None;
1157 }
1158 APValue getAPValueResult() const;
1159 llvm::APSInt getResultAsAPSInt() const;
1160 // Iterators
1161 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1162 const_child_range children() const {
1163 return const_child_range(&SubExpr, &SubExpr + 1);
1164 }
1165};
1166
1167//===----------------------------------------------------------------------===//
1168// Primary Expressions.
1169//===----------------------------------------------------------------------===//
1170
1171/// OpaqueValueExpr - An expression referring to an opaque object of a
1172/// fixed type and value class. These don't correspond to concrete
1173/// syntax; instead they're used to express operations (usually copy
1174/// operations) on values whose source is generally obvious from
1175/// context.
1176class OpaqueValueExpr : public Expr {
1177 friend class ASTStmtReader;
1178 Expr *SourceExpr;
1179
1180public:
1181 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1182 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1183 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1184 setIsUnique(false);
1185 OpaqueValueExprBits.Loc = Loc;
1186 setDependence(computeDependence(E: this));
1187 }
1188
1189 /// Given an expression which invokes a copy constructor --- i.e. a
1190 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1191 /// find the OpaqueValueExpr that's the source of the construction.
1192 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1193
1194 explicit OpaqueValueExpr(EmptyShell Empty)
1195 : Expr(OpaqueValueExprClass, Empty) {}
1196
1197 /// Retrieve the location of this expression.
1198 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1199
1200 SourceLocation getBeginLoc() const LLVM_READONLY {
1201 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1202 }
1203 SourceLocation getEndLoc() const LLVM_READONLY {
1204 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1205 }
1206 SourceLocation getExprLoc() const LLVM_READONLY {
1207 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1208 }
1209
1210 child_range children() {
1211 return child_range(child_iterator(), child_iterator());
1212 }
1213
1214 const_child_range children() const {
1215 return const_child_range(const_child_iterator(), const_child_iterator());
1216 }
1217
1218 /// The source expression of an opaque value expression is the
1219 /// expression which originally generated the value. This is
1220 /// provided as a convenience for analyses that don't wish to
1221 /// precisely model the execution behavior of the program.
1222 ///
1223 /// The source expression is typically set when building the
1224 /// expression which binds the opaque value expression in the first
1225 /// place.
1226 Expr *getSourceExpr() const { return SourceExpr; }
1227
1228 void setIsUnique(bool V) {
1229 assert((!V || SourceExpr) &&
1230 "unique OVEs are expected to have source expressions");
1231 OpaqueValueExprBits.IsUnique = V;
1232 }
1233
1234 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1235
1236 static bool classof(const Stmt *T) {
1237 return T->getStmtClass() == OpaqueValueExprClass;
1238 }
1239};
1240
1241/// A reference to a declared variable, function, enum, etc.
1242/// [C99 6.5.1p2]
1243///
1244/// This encodes all the information about how a declaration is referenced
1245/// within an expression.
1246///
1247/// There are several optional constructs attached to DeclRefExprs only when
1248/// they apply in order to conserve memory. These are laid out past the end of
1249/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1250///
1251/// DeclRefExprBits.HasQualifier:
1252/// Specifies when this declaration reference expression has a C++
1253/// nested-name-specifier.
1254/// DeclRefExprBits.HasFoundDecl:
1255/// Specifies when this declaration reference expression has a record of
1256/// a NamedDecl (different from the referenced ValueDecl) which was found
1257/// during name lookup and/or overload resolution.
1258/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1259/// Specifies when this declaration reference expression has an explicit
1260/// C++ template keyword and/or template argument list.
1261/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1262/// Specifies when this declaration reference expression (validly)
1263/// refers to an enclosed local or a captured variable.
1264class DeclRefExpr final
1265 : public Expr,
1266 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1267 NamedDecl *, ASTTemplateKWAndArgsInfo,
1268 TemplateArgumentLoc> {
1269 friend class ASTStmtReader;
1270 friend class ASTStmtWriter;
1271 friend TrailingObjects;
1272
1273 /// The declaration that we are referencing.
1274 ValueDecl *D;
1275
1276 /// Provides source/type location info for the declaration name
1277 /// embedded in D.
1278 DeclarationNameLoc DNLoc;
1279
1280 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1281 return hasQualifier();
1282 }
1283
1284 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1285 return hasFoundDecl();
1286 }
1287
1288 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1289 return hasTemplateKWAndArgsInfo();
1290 }
1291
1292 /// Test whether there is a distinct FoundDecl attached to the end of
1293 /// this DRE.
1294 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1295
1296 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1297 SourceLocation TemplateKWLoc, ValueDecl *D,
1298 bool RefersToEnclosingVariableOrCapture,
1299 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1300 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1301 ExprValueKind VK, NonOdrUseReason NOUR);
1302
1303 /// Construct an empty declaration reference expression.
1304 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1305
1306public:
1307 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1308 bool RefersToEnclosingVariableOrCapture, QualType T,
1309 ExprValueKind VK, SourceLocation L,
1310 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1311 NonOdrUseReason NOUR = NOUR_None);
1312
1313 static DeclRefExpr *
1314 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1315 SourceLocation TemplateKWLoc, ValueDecl *D,
1316 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1317 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1318 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1319 NonOdrUseReason NOUR = NOUR_None);
1320
1321 static DeclRefExpr *
1322 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1323 SourceLocation TemplateKWLoc, ValueDecl *D,
1324 bool RefersToEnclosingVariableOrCapture,
1325 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1326 NamedDecl *FoundD = nullptr,
1327 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1328 NonOdrUseReason NOUR = NOUR_None);
1329
1330 /// Construct an empty declaration reference expression.
1331 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1332 bool HasFoundDecl,
1333 bool HasTemplateKWAndArgsInfo,
1334 unsigned NumTemplateArgs);
1335
1336 ValueDecl *getDecl() { return D; }
1337 const ValueDecl *getDecl() const { return D; }
1338 void setDecl(ValueDecl *NewD);
1339
1340 DeclarationNameInfo getNameInfo() const {
1341 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1342 }
1343
1344 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1345 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1346
1347 SourceLocation getBeginLoc() const {
1348 if (hasQualifier())
1349 return getQualifierLoc().getBeginLoc();
1350 return DeclRefExprBits.Loc;
1351 }
1352
1353 SourceLocation getEndLoc() const LLVM_READONLY;
1354
1355 /// Determine whether this declaration reference was preceded by a
1356 /// C++ nested-name-specifier, e.g., \c N::foo.
1357 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1358
1359 /// If the name was qualified, retrieves the nested-name-specifier
1360 /// that precedes the name, with source-location information.
1361 NestedNameSpecifierLoc getQualifierLoc() const {
1362 if (!hasQualifier())
1363 return NestedNameSpecifierLoc();
1364 return *getTrailingObjects<NestedNameSpecifierLoc>();
1365 }
1366
1367 /// If the name was qualified, retrieves the nested-name-specifier
1368 /// that precedes the name. Otherwise, returns NULL.
1369 NestedNameSpecifier *getQualifier() const {
1370 return getQualifierLoc().getNestedNameSpecifier();
1371 }
1372
1373 /// Get the NamedDecl through which this reference occurred.
1374 ///
1375 /// This Decl may be different from the ValueDecl actually referred to in the
1376 /// presence of using declarations, etc. It always returns non-NULL, and may
1377 /// simple return the ValueDecl when appropriate.
1378
1379 NamedDecl *getFoundDecl() {
1380 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1381 }
1382
1383 /// Get the NamedDecl through which this reference occurred.
1384 /// See non-const variant.
1385 const NamedDecl *getFoundDecl() const {
1386 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1387 }
1388
1389 bool hasTemplateKWAndArgsInfo() const {
1390 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1391 }
1392
1393 /// Retrieve the location of the template keyword preceding
1394 /// this name, if any.
1395 SourceLocation getTemplateKeywordLoc() const {
1396 if (!hasTemplateKWAndArgsInfo())
1397 return SourceLocation();
1398 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1399 }
1400
1401 /// Retrieve the location of the left angle bracket starting the
1402 /// explicit template argument list following the name, if any.
1403 SourceLocation getLAngleLoc() const {
1404 if (!hasTemplateKWAndArgsInfo())
1405 return SourceLocation();
1406 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1407 }
1408
1409 /// Retrieve the location of the right angle bracket ending the
1410 /// explicit template argument list following the name, if any.
1411 SourceLocation getRAngleLoc() const {
1412 if (!hasTemplateKWAndArgsInfo())
1413 return SourceLocation();
1414 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1415 }
1416
1417 /// Determines whether the name in this declaration reference
1418 /// was preceded by the template keyword.
1419 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1420
1421 /// Determines whether this declaration reference was followed by an
1422 /// explicit template argument list.
1423 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1424
1425 /// Copies the template arguments (if present) into the given
1426 /// structure.
1427 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1428 if (hasExplicitTemplateArgs())
1429 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1430 ArgArray: getTrailingObjects<TemplateArgumentLoc>(), List);
1431 }
1432
1433 /// Retrieve the template arguments provided as part of this
1434 /// template-id.
1435 const TemplateArgumentLoc *getTemplateArgs() const {
1436 if (!hasExplicitTemplateArgs())
1437 return nullptr;
1438 return getTrailingObjects<TemplateArgumentLoc>();
1439 }
1440
1441 /// Retrieve the number of template arguments provided as part of this
1442 /// template-id.
1443 unsigned getNumTemplateArgs() const {
1444 if (!hasExplicitTemplateArgs())
1445 return 0;
1446 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1447 }
1448
1449 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1450 return {getTemplateArgs(), getNumTemplateArgs()};
1451 }
1452
1453 /// Returns true if this expression refers to a function that
1454 /// was resolved from an overloaded set having size greater than 1.
1455 bool hadMultipleCandidates() const {
1456 return DeclRefExprBits.HadMultipleCandidates;
1457 }
1458 /// Sets the flag telling whether this expression refers to
1459 /// a function that was resolved from an overloaded set having size
1460 /// greater than 1.
1461 void setHadMultipleCandidates(bool V = true) {
1462 DeclRefExprBits.HadMultipleCandidates = V;
1463 }
1464
1465 /// Is this expression a non-odr-use reference, and if so, why?
1466 NonOdrUseReason isNonOdrUse() const {
1467 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1468 }
1469
1470 /// Does this DeclRefExpr refer to an enclosing local or a captured
1471 /// variable?
1472 bool refersToEnclosingVariableOrCapture() const {
1473 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1474 }
1475
1476 bool isImmediateEscalating() const {
1477 return DeclRefExprBits.IsImmediateEscalating;
1478 }
1479
1480 void setIsImmediateEscalating(bool Set) {
1481 DeclRefExprBits.IsImmediateEscalating = Set;
1482 }
1483
1484 bool isCapturedByCopyInLambdaWithExplicitObjectParameter() const {
1485 return DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1486 }
1487
1488 void setCapturedByCopyInLambdaWithExplicitObjectParameter(
1489 bool Set, const ASTContext &Context) {
1490 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1491 setDependence(computeDependence(E: this, Ctx: Context));
1492 }
1493
1494 static bool classof(const Stmt *T) {
1495 return T->getStmtClass() == DeclRefExprClass;
1496 }
1497
1498 // Iterators
1499 child_range children() {
1500 return child_range(child_iterator(), child_iterator());
1501 }
1502
1503 const_child_range children() const {
1504 return const_child_range(const_child_iterator(), const_child_iterator());
1505 }
1506};
1507
1508class IntegerLiteral : public Expr, public APIntStorage {
1509 SourceLocation Loc;
1510
1511 /// Construct an empty integer literal.
1512 explicit IntegerLiteral(EmptyShell Empty)
1513 : Expr(IntegerLiteralClass, Empty) { }
1514
1515public:
1516 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1517 // or UnsignedLongLongTy
1518 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1519 SourceLocation l);
1520
1521 /// Returns a new integer literal with value 'V' and type 'type'.
1522 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1523 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1524 /// \param V - the value that the returned integer literal contains.
1525 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1526 QualType type, SourceLocation l);
1527 /// Returns a new empty integer literal.
1528 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1529
1530 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1531 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1532
1533 /// Retrieve the location of the literal.
1534 SourceLocation getLocation() const { return Loc; }
1535
1536 void setLocation(SourceLocation Location) { Loc = Location; }
1537
1538 static bool classof(const Stmt *T) {
1539 return T->getStmtClass() == IntegerLiteralClass;
1540 }
1541
1542 // Iterators
1543 child_range children() {
1544 return child_range(child_iterator(), child_iterator());
1545 }
1546 const_child_range children() const {
1547 return const_child_range(const_child_iterator(), const_child_iterator());
1548 }
1549};
1550
1551class FixedPointLiteral : public Expr, public APIntStorage {
1552 SourceLocation Loc;
1553 unsigned Scale;
1554
1555 /// \brief Construct an empty fixed-point literal.
1556 explicit FixedPointLiteral(EmptyShell Empty)
1557 : Expr(FixedPointLiteralClass, Empty) {}
1558
1559 public:
1560 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1561 SourceLocation l, unsigned Scale);
1562
1563 // Store the int as is without any bit shifting.
1564 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1565 const llvm::APInt &V,
1566 QualType type, SourceLocation l,
1567 unsigned Scale);
1568
1569 /// Returns an empty fixed-point literal.
1570 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1571
1572 /// Returns an internal integer representation of the literal.
1573 llvm::APInt getValue() const { return APIntStorage::getValue(); }
1574
1575 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1576 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1577
1578 /// \brief Retrieve the location of the literal.
1579 SourceLocation getLocation() const { return Loc; }
1580
1581 void setLocation(SourceLocation Location) { Loc = Location; }
1582
1583 unsigned getScale() const { return Scale; }
1584 void setScale(unsigned S) { Scale = S; }
1585
1586 static bool classof(const Stmt *T) {
1587 return T->getStmtClass() == FixedPointLiteralClass;
1588 }
1589
1590 std::string getValueAsString(unsigned Radix) const;
1591
1592 // Iterators
1593 child_range children() {
1594 return child_range(child_iterator(), child_iterator());
1595 }
1596 const_child_range children() const {
1597 return const_child_range(const_child_iterator(), const_child_iterator());
1598 }
1599};
1600
1601enum class CharacterLiteralKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1602
1603class CharacterLiteral : public Expr {
1604 unsigned Value;
1605 SourceLocation Loc;
1606public:
1607 // type should be IntTy
1608 CharacterLiteral(unsigned value, CharacterLiteralKind kind, QualType type,
1609 SourceLocation l)
1610 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1611 Value(value), Loc(l) {
1612 CharacterLiteralBits.Kind = llvm::to_underlying(E: kind);
1613 setDependence(ExprDependence::None);
1614 }
1615
1616 /// Construct an empty character literal.
1617 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1618
1619 SourceLocation getLocation() const { return Loc; }
1620 CharacterLiteralKind getKind() const {
1621 return static_cast<CharacterLiteralKind>(CharacterLiteralBits.Kind);
1622 }
1623
1624 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1625 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1626
1627 unsigned getValue() const { return Value; }
1628
1629 void setLocation(SourceLocation Location) { Loc = Location; }
1630 void setKind(CharacterLiteralKind kind) {
1631 CharacterLiteralBits.Kind = llvm::to_underlying(E: kind);
1632 }
1633 void setValue(unsigned Val) { Value = Val; }
1634
1635 static bool classof(const Stmt *T) {
1636 return T->getStmtClass() == CharacterLiteralClass;
1637 }
1638
1639 static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS);
1640
1641 // Iterators
1642 child_range children() {
1643 return child_range(child_iterator(), child_iterator());
1644 }
1645 const_child_range children() const {
1646 return const_child_range(const_child_iterator(), const_child_iterator());
1647 }
1648};
1649
1650class FloatingLiteral : public Expr, private APFloatStorage {
1651 SourceLocation Loc;
1652
1653 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1654 QualType Type, SourceLocation L);
1655
1656 /// Construct an empty floating-point literal.
1657 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1658
1659public:
1660 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1661 bool isexact, QualType Type, SourceLocation L);
1662 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1663
1664 llvm::APFloat getValue() const {
1665 return APFloatStorage::getValue(Semantics: getSemantics());
1666 }
1667 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1668 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1669 APFloatStorage::setValue(C, Val);
1670 }
1671
1672 /// Get a raw enumeration value representing the floating-point semantics of
1673 /// this literal (32-bit IEEE, x87, ...), suitable for serialization.
1674 llvm::APFloatBase::Semantics getRawSemantics() const {
1675 return static_cast<llvm::APFloatBase::Semantics>(
1676 FloatingLiteralBits.Semantics);
1677 }
1678
1679 /// Set the raw enumeration value representing the floating-point semantics of
1680 /// this literal (32-bit IEEE, x87, ...), suitable for serialization.
1681 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1682 FloatingLiteralBits.Semantics = Sem;
1683 }
1684
1685 /// Return the APFloat semantics this literal uses.
1686 const llvm::fltSemantics &getSemantics() const {
1687 return llvm::APFloatBase::EnumToSemantics(
1688 S: static_cast<llvm::APFloatBase::Semantics>(
1689 FloatingLiteralBits.Semantics));
1690 }
1691
1692 /// Set the APFloat semantics this literal uses.
1693 void setSemantics(const llvm::fltSemantics &Sem) {
1694 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1695 }
1696
1697 bool isExact() const { return FloatingLiteralBits.IsExact; }
1698 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1699
1700 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1701 /// double. Note that this may cause loss of precision, but is useful for
1702 /// debugging dumps, etc.
1703 double getValueAsApproximateDouble() const;
1704
1705 SourceLocation getLocation() const { return Loc; }
1706 void setLocation(SourceLocation L) { Loc = L; }
1707
1708 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1709 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1710
1711 static bool classof(const Stmt *T) {
1712 return T->getStmtClass() == FloatingLiteralClass;
1713 }
1714
1715 // Iterators
1716 child_range children() {
1717 return child_range(child_iterator(), child_iterator());
1718 }
1719 const_child_range children() const {
1720 return const_child_range(const_child_iterator(), const_child_iterator());
1721 }
1722};
1723
1724/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1725/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1726/// IntegerLiteral classes. Instances of this class always have a Complex type
1727/// whose element type matches the subexpression.
1728///
1729class ImaginaryLiteral : public Expr {
1730 Stmt *Val;
1731public:
1732 ImaginaryLiteral(Expr *val, QualType Ty)
1733 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1734 setDependence(ExprDependence::None);
1735 }
1736
1737 /// Build an empty imaginary literal.
1738 explicit ImaginaryLiteral(EmptyShell Empty)
1739 : Expr(ImaginaryLiteralClass, Empty) { }
1740
1741 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1742 Expr *getSubExpr() { return cast<Expr>(Val); }
1743 void setSubExpr(Expr *E) { Val = E; }
1744
1745 SourceLocation getBeginLoc() const LLVM_READONLY {
1746 return Val->getBeginLoc();
1747 }
1748 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1749
1750 static bool classof(const Stmt *T) {
1751 return T->getStmtClass() == ImaginaryLiteralClass;
1752 }
1753
1754 // Iterators
1755 child_range children() { return child_range(&Val, &Val+1); }
1756 const_child_range children() const {
1757 return const_child_range(&Val, &Val + 1);
1758 }
1759};
1760
1761enum class StringLiteralKind {
1762 Ordinary,
1763 Wide,
1764 UTF8,
1765 UTF16,
1766 UTF32,
1767 Unevaluated,
1768 // Binary kind of string literal is used for the data coming via #embed
1769 // directive. File's binary contents is transformed to a special kind of
1770 // string literal that in some cases may be used directly as an initializer
1771 // and some features of classic string literals are not applicable to this
1772 // kind of a string literal, for example finding a particular byte's source
1773 // location for better diagnosing.
1774 Binary
1775};
1776
1777/// StringLiteral - This represents a string literal expression, e.g. "foo"
1778/// or L"bar" (wide strings). The actual string data can be obtained with
1779/// getBytes() and is NOT null-terminated. The length of the string data is
1780/// determined by calling getByteLength().
1781///
1782/// The C type for a string is always a ConstantArrayType. In C++, the char
1783/// type is const qualified, in C it is not.
1784///
1785/// Note that strings in C can be formed by concatenation of multiple string
1786/// literal pptokens in translation phase #6. This keeps track of the locations
1787/// of each of these pieces.
1788///
1789/// Strings in C can also be truncated and extended by assigning into arrays,
1790/// e.g. with constructs like:
1791/// char X[2] = "foobar";
1792/// In this case, getByteLength() will return 6, but the string literal will
1793/// have type "char[2]".
1794class StringLiteral final
1795 : public Expr,
1796 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1797 char> {
1798 friend class ASTStmtReader;
1799 friend TrailingObjects;
1800
1801 /// StringLiteral is followed by several trailing objects. They are in order:
1802 ///
1803 /// * A single unsigned storing the length in characters of this string. The
1804 /// length in bytes is this length times the width of a single character.
1805 /// Always present and stored as a trailing objects because storing it in
1806 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1807 /// due to alignment requirements. If you add some data to StringLiteral,
1808 /// consider moving it inside StringLiteral.
1809 ///
1810 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1811 /// token this string is made of.
1812 ///
1813 /// * An array of getByteLength() char used to store the string data.
1814
1815 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1816 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1817 return getNumConcatenated();
1818 }
1819
1820 unsigned numTrailingObjects(OverloadToken<char>) const {
1821 return getByteLength();
1822 }
1823
1824 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1825 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1826
1827 const uint16_t *getStrDataAsUInt16() const {
1828 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1829 }
1830
1831 const uint32_t *getStrDataAsUInt32() const {
1832 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1833 }
1834
1835 /// Build a string literal.
1836 StringLiteral(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind,
1837 bool Pascal, QualType Ty, ArrayRef<SourceLocation> Locs);
1838
1839 /// Build an empty string literal.
1840 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1841 unsigned CharByteWidth);
1842
1843 /// Map a target and string kind to the appropriate character width.
1844 static unsigned mapCharByteWidth(TargetInfo const &Target,
1845 StringLiteralKind SK);
1846
1847 /// Set one of the string literal token.
1848 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1849 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1850 getTrailingObjects<SourceLocation>()[TokNum] = L;
1851 }
1852
1853public:
1854 /// This is the "fully general" constructor that allows representation of
1855 /// strings formed from one or more concatenated tokens.
1856 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1857 StringLiteralKind Kind, bool Pascal, QualType Ty,
1858 ArrayRef<SourceLocation> Locs);
1859
1860 /// Construct an empty string literal.
1861 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1862 unsigned NumConcatenated, unsigned Length,
1863 unsigned CharByteWidth);
1864
1865 StringRef getString() const {
1866 assert((isUnevaluated() || getCharByteWidth() == 1) &&
1867 "This function is used in places that assume strings use char");
1868 return StringRef(getStrDataAsChar(), getByteLength());
1869 }
1870
1871 /// Allow access to clients that need the byte representation, such as
1872 /// ASTWriterStmt::VisitStringLiteral().
1873 StringRef getBytes() const {
1874 // FIXME: StringRef may not be the right type to use as a result for this.
1875 return StringRef(getStrDataAsChar(), getByteLength());
1876 }
1877
1878 void outputString(raw_ostream &OS) const;
1879
1880 uint32_t getCodeUnit(size_t i) const {
1881 assert(i < getLength() && "out of bounds access");
1882 switch (getCharByteWidth()) {
1883 case 1:
1884 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1885 case 2:
1886 return getStrDataAsUInt16()[i];
1887 case 4:
1888 return getStrDataAsUInt32()[i];
1889 }
1890 llvm_unreachable("Unsupported character width!");
1891 }
1892
1893 // Get code unit but preserve sign info.
1894 int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const {
1895 int64_t V = getCodeUnit(i: I);
1896 if (isOrdinary() || isWide()) {
1897 // Ordinary and wide string literals have types that can be signed.
1898 // It is important for checking C23 constexpr initializers.
1899 unsigned Width = getCharByteWidth() * BitWidth;
1900 llvm::APInt AInt(Width, (uint64_t)V);
1901 V = AInt.getSExtValue();
1902 }
1903 return V;
1904 }
1905
1906 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1907 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1908 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1909
1910 StringLiteralKind getKind() const {
1911 return static_cast<StringLiteralKind>(StringLiteralBits.Kind);
1912 }
1913
1914 bool isOrdinary() const { return getKind() == StringLiteralKind::Ordinary; }
1915 bool isWide() const { return getKind() == StringLiteralKind::Wide; }
1916 bool isUTF8() const { return getKind() == StringLiteralKind::UTF8; }
1917 bool isUTF16() const { return getKind() == StringLiteralKind::UTF16; }
1918 bool isUTF32() const { return getKind() == StringLiteralKind::UTF32; }
1919 bool isUnevaluated() const { return getKind() == StringLiteralKind::Unevaluated; }
1920 bool isPascal() const { return StringLiteralBits.IsPascal; }
1921
1922 bool containsNonAscii() const {
1923 for (auto c : getString())
1924 if (!isASCII(c))
1925 return true;
1926 return false;
1927 }
1928
1929 bool containsNonAsciiOrNull() const {
1930 for (auto c : getString())
1931 if (!isASCII(c) || !c)
1932 return true;
1933 return false;
1934 }
1935
1936 /// getNumConcatenated - Get the number of string literal tokens that were
1937 /// concatenated in translation phase #6 to form this string literal.
1938 unsigned getNumConcatenated() const {
1939 return StringLiteralBits.NumConcatenated;
1940 }
1941
1942 /// Get one of the string literal token.
1943 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1944 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1945 return getTrailingObjects<SourceLocation>()[TokNum];
1946 }
1947
1948 /// getLocationOfByte - Return a source location that points to the specified
1949 /// byte of this string literal.
1950 ///
1951 /// Strings are amazingly complex. They can be formed from multiple tokens
1952 /// and can have escape sequences in them in addition to the usual trigraph
1953 /// and escaped newline business. This routine handles this complexity.
1954 ///
1955 SourceLocation
1956 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1957 const LangOptions &Features, const TargetInfo &Target,
1958 unsigned *StartToken = nullptr,
1959 unsigned *StartTokenByteOffset = nullptr) const;
1960
1961 typedef const SourceLocation *tokloc_iterator;
1962
1963 tokloc_iterator tokloc_begin() const {
1964 return getTrailingObjects<SourceLocation>();
1965 }
1966
1967 tokloc_iterator tokloc_end() const {
1968 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1969 }
1970
1971 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1972 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1973
1974 static bool classof(const Stmt *T) {
1975 return T->getStmtClass() == StringLiteralClass;
1976 }
1977
1978 // Iterators
1979 child_range children() {
1980 return child_range(child_iterator(), child_iterator());
1981 }
1982 const_child_range children() const {
1983 return const_child_range(const_child_iterator(), const_child_iterator());
1984 }
1985};
1986
1987enum class PredefinedIdentKind {
1988 Func,
1989 Function,
1990 LFunction, // Same as Function, but as wide string.
1991 FuncDName,
1992 FuncSig,
1993 LFuncSig, // Same as FuncSig, but as wide string
1994 PrettyFunction,
1995 /// The same as PrettyFunction, except that the
1996 /// 'virtual' keyword is omitted for virtual member functions.
1997 PrettyFunctionNoVirtual
1998};
1999
2000/// [C99 6.4.2.2] - A predefined identifier such as __func__.
2001class PredefinedExpr final
2002 : public Expr,
2003 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
2004 friend class ASTStmtReader;
2005 friend TrailingObjects;
2006
2007 // PredefinedExpr is optionally followed by a single trailing
2008 // "Stmt *" for the predefined identifier. It is present if and only if
2009 // hasFunctionName() is true and is always a "StringLiteral *".
2010
2011 PredefinedExpr(SourceLocation L, QualType FNTy, PredefinedIdentKind IK,
2012 bool IsTransparent, StringLiteral *SL);
2013
2014 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
2015
2016 /// True if this PredefinedExpr has storage for a function name.
2017 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
2018
2019 void setFunctionName(StringLiteral *SL) {
2020 assert(hasFunctionName() &&
2021 "This PredefinedExpr has no storage for a function name!");
2022 *getTrailingObjects() = SL;
2023 }
2024
2025public:
2026 /// Create a PredefinedExpr.
2027 ///
2028 /// If IsTransparent, the PredefinedExpr is transparently handled as a
2029 /// StringLiteral.
2030 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
2031 QualType FNTy, PredefinedIdentKind IK,
2032 bool IsTransparent, StringLiteral *SL);
2033
2034 /// Create an empty PredefinedExpr.
2035 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
2036 bool HasFunctionName);
2037
2038 PredefinedIdentKind getIdentKind() const {
2039 return static_cast<PredefinedIdentKind>(PredefinedExprBits.Kind);
2040 }
2041
2042 bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2043
2044 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
2045 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2046
2047 StringLiteral *getFunctionName() {
2048 return hasFunctionName()
2049 ? static_cast<StringLiteral *>(*getTrailingObjects())
2050 : nullptr;
2051 }
2052
2053 const StringLiteral *getFunctionName() const {
2054 return hasFunctionName()
2055 ? static_cast<StringLiteral *>(*getTrailingObjects())
2056 : nullptr;
2057 }
2058
2059 static StringRef getIdentKindName(PredefinedIdentKind IK);
2060 StringRef getIdentKindName() const {
2061 return getIdentKindName(IK: getIdentKind());
2062 }
2063
2064 static std::string ComputeName(PredefinedIdentKind IK,
2065 const Decl *CurrentDecl,
2066 bool ForceElaboratedPrinting = false);
2067
2068 SourceLocation getBeginLoc() const { return getLocation(); }
2069 SourceLocation getEndLoc() const { return getLocation(); }
2070
2071 static bool classof(const Stmt *T) {
2072 return T->getStmtClass() == PredefinedExprClass;
2073 }
2074
2075 // Iterators
2076 child_range children() {
2077 return child_range(getTrailingObjects(N: hasFunctionName()));
2078 }
2079
2080 const_child_range children() const {
2081 return const_child_range(getTrailingObjects(N: hasFunctionName()));
2082 }
2083};
2084
2085/// This expression type represents an asterisk in an OpenACC Size-Expr, used in
2086/// the 'tile' and 'gang' clauses. It is of 'int' type, but should not be
2087/// evaluated.
2088class OpenACCAsteriskSizeExpr final : public Expr {
2089 friend class ASTStmtReader;
2090 SourceLocation AsteriskLoc;
2091
2092 OpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc, QualType IntTy)
2093 : Expr(OpenACCAsteriskSizeExprClass, IntTy, VK_PRValue, OK_Ordinary),
2094 AsteriskLoc(AsteriskLoc) {}
2095
2096 void setAsteriskLocation(SourceLocation Loc) { AsteriskLoc = Loc; }
2097
2098public:
2099 static OpenACCAsteriskSizeExpr *Create(const ASTContext &C,
2100 SourceLocation Loc);
2101 static OpenACCAsteriskSizeExpr *CreateEmpty(const ASTContext &C);
2102
2103 SourceLocation getBeginLoc() const { return AsteriskLoc; }
2104 SourceLocation getEndLoc() const { return AsteriskLoc; }
2105 SourceLocation getLocation() const { return AsteriskLoc; }
2106
2107 static bool classof(const Stmt *T) {
2108 return T->getStmtClass() == OpenACCAsteriskSizeExprClass;
2109 }
2110 // Iterators
2111 child_range children() {
2112 return child_range(child_iterator(), child_iterator());
2113 }
2114
2115 const_child_range children() const {
2116 return const_child_range(const_child_iterator(), const_child_iterator());
2117 }
2118};
2119
2120// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2121// type-id, and at CodeGen time emits a unique string representation of the
2122// type in a way that permits us to properly encode information about the SYCL
2123// kernels.
2124class SYCLUniqueStableNameExpr final : public Expr {
2125 friend class ASTStmtReader;
2126 SourceLocation OpLoc, LParen, RParen;
2127 TypeSourceInfo *TypeInfo;
2128
2129 SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2130 SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2131 SourceLocation RParen, QualType ResultTy,
2132 TypeSourceInfo *TSI);
2133
2134 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2135
2136 void setLocation(SourceLocation L) { OpLoc = L; }
2137 void setLParenLocation(SourceLocation L) { LParen = L; }
2138 void setRParenLocation(SourceLocation L) { RParen = L; }
2139
2140public:
2141 TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2142
2143 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2144
2145 static SYCLUniqueStableNameExpr *
2146 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2147 SourceLocation RParen, TypeSourceInfo *TSI);
2148
2149 static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2150
2151 SourceLocation getBeginLoc() const { return getLocation(); }
2152 SourceLocation getEndLoc() const { return RParen; }
2153 SourceLocation getLocation() const { return OpLoc; }
2154 SourceLocation getLParenLocation() const { return LParen; }
2155 SourceLocation getRParenLocation() const { return RParen; }
2156
2157 static bool classof(const Stmt *T) {
2158 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2159 }
2160
2161 // Iterators
2162 child_range children() {
2163 return child_range(child_iterator(), child_iterator());
2164 }
2165
2166 const_child_range children() const {
2167 return const_child_range(const_child_iterator(), const_child_iterator());
2168 }
2169
2170 // Convenience function to generate the name of the currently stored type.
2171 std::string ComputeName(ASTContext &Context) const;
2172
2173 // Get the generated name of the type. Note that this only works after all
2174 // kernels have been instantiated.
2175 static std::string ComputeName(ASTContext &Context, QualType Ty);
2176};
2177
2178/// ParenExpr - This represents a parenthesized expression, e.g. "(1)". This
2179/// AST node is only formed if full location information is requested.
2180class ParenExpr : public Expr {
2181 SourceLocation L, R;
2182 Stmt *Val;
2183
2184public:
2185 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2186 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2187 val->getObjectKind()),
2188 L(l), R(r), Val(val) {
2189 ParenExprBits.ProducedByFoldExpansion = false;
2190 setDependence(computeDependence(E: this));
2191 }
2192
2193 /// Construct an empty parenthesized expression.
2194 explicit ParenExpr(EmptyShell Empty)
2195 : Expr(ParenExprClass, Empty) { }
2196
2197 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2198 Expr *getSubExpr() { return cast<Expr>(Val); }
2199 void setSubExpr(Expr *E) { Val = E; }
2200
2201 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2202 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2203
2204 /// Get the location of the left parentheses '('.
2205 SourceLocation getLParen() const { return L; }
2206 void setLParen(SourceLocation Loc) { L = Loc; }
2207
2208 /// Get the location of the right parentheses ')'.
2209 SourceLocation getRParen() const { return R; }
2210 void setRParen(SourceLocation Loc) { R = Loc; }
2211
2212 static bool classof(const Stmt *T) {
2213 return T->getStmtClass() == ParenExprClass;
2214 }
2215
2216 // Iterators
2217 child_range children() { return child_range(&Val, &Val+1); }
2218 const_child_range children() const {
2219 return const_child_range(&Val, &Val + 1);
2220 }
2221
2222 bool isProducedByFoldExpansion() const {
2223 return ParenExprBits.ProducedByFoldExpansion != 0;
2224 }
2225 void setIsProducedByFoldExpansion(bool ProducedByFoldExpansion = true) {
2226 ParenExprBits.ProducedByFoldExpansion = ProducedByFoldExpansion;
2227 }
2228};
2229
2230/// UnaryOperator - This represents the unary-expression's (except sizeof and
2231/// alignof), the postinc/postdec operators from postfix-expression, and various
2232/// extensions.
2233///
2234/// Notes on various nodes:
2235///
2236/// Real/Imag - These return the real/imag part of a complex operand. If
2237/// applied to a non-complex value, the former returns its operand and the
2238/// later returns zero in the type of the operand.
2239///
2240class UnaryOperator final
2241 : public Expr,
2242 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2243 Stmt *Val;
2244
2245 FPOptionsOverride &getTrailingFPFeatures() {
2246 assert(UnaryOperatorBits.HasFPFeatures);
2247 return *getTrailingObjects();
2248 }
2249
2250 const FPOptionsOverride &getTrailingFPFeatures() const {
2251 assert(UnaryOperatorBits.HasFPFeatures);
2252 return *getTrailingObjects();
2253 }
2254
2255public:
2256 typedef UnaryOperatorKind Opcode;
2257
2258protected:
2259 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2260 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2261 bool CanOverflow, FPOptionsOverride FPFeatures);
2262
2263 /// Build an empty unary operator.
2264 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2265 : Expr(UnaryOperatorClass, Empty) {
2266 UnaryOperatorBits.Opc = UO_AddrOf;
2267 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2268 }
2269
2270public:
2271 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2272
2273 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2274 QualType type, ExprValueKind VK,
2275 ExprObjectKind OK, SourceLocation l,
2276 bool CanOverflow, FPOptionsOverride FPFeatures);
2277
2278 Opcode getOpcode() const {
2279 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2280 }
2281 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2282
2283 Expr *getSubExpr() const { return cast<Expr>(Val); }
2284 void setSubExpr(Expr *E) { Val = E; }
2285
2286 /// getOperatorLoc - Return the location of the operator.
2287 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2288 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2289
2290 /// Returns true if the unary operator can cause an overflow. For instance,
2291 /// signed int i = INT_MAX; i++;
2292 /// signed char c = CHAR_MAX; c++;
2293 /// Due to integer promotions, c++ is promoted to an int before the postfix
2294 /// increment, and the result is an int that cannot overflow. However, i++
2295 /// can overflow.
2296 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2297 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2298
2299 /// Get the FP contractibility status of this operator. Only meaningful for
2300 /// operations on floating point types.
2301 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2302 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2303 }
2304
2305 /// Get the FENV_ACCESS status of this operator. Only meaningful for
2306 /// operations on floating point types.
2307 bool isFEnvAccessOn(const LangOptions &LO) const {
2308 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2309 }
2310
2311 /// isPostfix - Return true if this is a postfix operation, like x++.
2312 static bool isPostfix(Opcode Op) {
2313 return Op == UO_PostInc || Op == UO_PostDec;
2314 }
2315
2316 /// isPrefix - Return true if this is a prefix operation, like --x.
2317 static bool isPrefix(Opcode Op) {
2318 return Op == UO_PreInc || Op == UO_PreDec;
2319 }
2320
2321 bool isPrefix() const { return isPrefix(Op: getOpcode()); }
2322 bool isPostfix() const { return isPostfix(Op: getOpcode()); }
2323
2324 static bool isIncrementOp(Opcode Op) {
2325 return Op == UO_PreInc || Op == UO_PostInc;
2326 }
2327 bool isIncrementOp() const {
2328 return isIncrementOp(Op: getOpcode());
2329 }
2330
2331 static bool isDecrementOp(Opcode Op) {
2332 return Op == UO_PreDec || Op == UO_PostDec;
2333 }
2334 bool isDecrementOp() const {
2335 return isDecrementOp(Op: getOpcode());
2336 }
2337
2338 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2339 bool isIncrementDecrementOp() const {
2340 return isIncrementDecrementOp(Op: getOpcode());
2341 }
2342
2343 static bool isArithmeticOp(Opcode Op) {
2344 return Op >= UO_Plus && Op <= UO_LNot;
2345 }
2346 bool isArithmeticOp() const { return isArithmeticOp(Op: getOpcode()); }
2347
2348 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2349 /// corresponds to, e.g. "sizeof" or "[pre]++"
2350 static StringRef getOpcodeStr(Opcode Op);
2351
2352 /// Retrieve the unary opcode that corresponds to the given
2353 /// overloaded operator.
2354 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2355
2356 /// Retrieve the overloaded operator kind that corresponds to
2357 /// the given unary opcode.
2358 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2359
2360 SourceLocation getBeginLoc() const LLVM_READONLY {
2361 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2362 }
2363 SourceLocation getEndLoc() const LLVM_READONLY {
2364 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2365 }
2366 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2367
2368 static bool classof(const Stmt *T) {
2369 return T->getStmtClass() == UnaryOperatorClass;
2370 }
2371
2372 // Iterators
2373 child_range children() { return child_range(&Val, &Val+1); }
2374 const_child_range children() const {
2375 return const_child_range(&Val, &Val + 1);
2376 }
2377
2378 /// Is FPFeatures in Trailing Storage?
2379 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2380
2381 /// Get FPFeatures from trailing storage.
2382 FPOptionsOverride getStoredFPFeatures() const {
2383 return getTrailingFPFeatures();
2384 }
2385
2386 /// Get the store FPOptionsOverride or default if not stored.
2387 FPOptionsOverride getStoredFPFeaturesOrDefault() const {
2388 return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
2389 }
2390
2391protected:
2392 /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
2393 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2394
2395public:
2396 /// Get the FP features status of this operator. Only meaningful for
2397 /// operations on floating point types.
2398 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2399 if (UnaryOperatorBits.HasFPFeatures)
2400 return getStoredFPFeatures().applyOverrides(LO);
2401 return FPOptions::defaultWithoutTrailingStorage(LO);
2402 }
2403 FPOptionsOverride getFPOptionsOverride() const {
2404 if (UnaryOperatorBits.HasFPFeatures)
2405 return getStoredFPFeatures();
2406 return FPOptionsOverride();
2407 }
2408
2409 friend TrailingObjects;
2410 friend class ASTNodeImporter;
2411 friend class ASTReader;
2412 friend class ASTStmtReader;
2413 friend class ASTStmtWriter;
2414};
2415
2416/// Helper class for OffsetOfExpr.
2417
2418// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2419class OffsetOfNode {
2420public:
2421 /// The kind of offsetof node we have.
2422 enum Kind {
2423 /// An index into an array.
2424 Array = 0x00,
2425 /// A field.
2426 Field = 0x01,
2427 /// A field in a dependent type, known only by its name.
2428 Identifier = 0x02,
2429 /// An implicit indirection through a C++ base class, when the
2430 /// field found is in a base class.
2431 Base = 0x03
2432 };
2433
2434private:
2435 enum { MaskBits = 2, Mask = 0x03 };
2436
2437 /// The source range that covers this part of the designator.
2438 SourceRange Range;
2439
2440 /// The data describing the designator, which comes in three
2441 /// different forms, depending on the lower two bits.
2442 /// - An unsigned index into the array of Expr*'s stored after this node
2443 /// in memory, for [constant-expression] designators.
2444 /// - A FieldDecl*, for references to a known field.
2445 /// - An IdentifierInfo*, for references to a field with a given name
2446 /// when the class type is dependent.
2447 /// - A CXXBaseSpecifier*, for references that look at a field in a
2448 /// base class.
2449 uintptr_t Data;
2450
2451public:
2452 /// Create an offsetof node that refers to an array element.
2453 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2454 SourceLocation RBracketLoc)
2455 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2456
2457 /// Create an offsetof node that refers to a field.
2458 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2459 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2460 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2461
2462 /// Create an offsetof node that refers to an identifier.
2463 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2464 SourceLocation NameLoc)
2465 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2466 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2467
2468 /// Create an offsetof node that refers into a C++ base class.
2469 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2470 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2471
2472 /// Determine what kind of offsetof node this is.
2473 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2474
2475 /// For an array element node, returns the index into the array
2476 /// of expressions.
2477 unsigned getArrayExprIndex() const {
2478 assert(getKind() == Array);
2479 return Data >> 2;
2480 }
2481
2482 /// For a field offsetof node, returns the field.
2483 FieldDecl *getField() const {
2484 assert(getKind() == Field);
2485 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2486 }
2487
2488 /// For a field or identifier offsetof node, returns the name of
2489 /// the field.
2490 IdentifierInfo *getFieldName() const;
2491
2492 /// For a base class node, returns the base specifier.
2493 CXXBaseSpecifier *getBase() const {
2494 assert(getKind() == Base);
2495 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2496 }
2497
2498 /// Retrieve the source range that covers this offsetof node.
2499 ///
2500 /// For an array element node, the source range contains the locations of
2501 /// the square brackets. For a field or identifier node, the source range
2502 /// contains the location of the period (if there is one) and the
2503 /// identifier.
2504 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2505 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2506 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2507};
2508
2509/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2510/// offsetof(record-type, member-designator). For example, given:
2511/// @code
2512/// struct S {
2513/// float f;
2514/// double d;
2515/// };
2516/// struct T {
2517/// int i;
2518/// struct S s[10];
2519/// };
2520/// @endcode
2521/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2522
2523class OffsetOfExpr final
2524 : public Expr,
2525 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2526 SourceLocation OperatorLoc, RParenLoc;
2527 // Base type;
2528 TypeSourceInfo *TSInfo;
2529 // Number of sub-components (i.e. instances of OffsetOfNode).
2530 unsigned NumComps;
2531 // Number of sub-expressions (i.e. array subscript expressions).
2532 unsigned NumExprs;
2533
2534 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2535 return NumComps;
2536 }
2537
2538 OffsetOfExpr(const ASTContext &C, QualType type,
2539 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2540 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2541 SourceLocation RParenLoc);
2542
2543 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2544 : Expr(OffsetOfExprClass, EmptyShell()),
2545 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2546
2547public:
2548
2549 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2550 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2551 ArrayRef<OffsetOfNode> comps,
2552 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2553
2554 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2555 unsigned NumComps, unsigned NumExprs);
2556
2557 /// getOperatorLoc - Return the location of the operator.
2558 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2559 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2560
2561 /// Return the location of the right parentheses.
2562 SourceLocation getRParenLoc() const { return RParenLoc; }
2563 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2564
2565 TypeSourceInfo *getTypeSourceInfo() const {
2566 return TSInfo;
2567 }
2568 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2569 TSInfo = tsi;
2570 }
2571
2572 const OffsetOfNode &getComponent(unsigned Idx) const {
2573 return getTrailingObjects<OffsetOfNode>(N: NumComps)[Idx];
2574 }
2575
2576 void setComponent(unsigned Idx, OffsetOfNode ON) {
2577 getTrailingObjects<OffsetOfNode>(N: NumComps)[Idx] = ON;
2578 }
2579
2580 unsigned getNumComponents() const {
2581 return NumComps;
2582 }
2583
2584 Expr* getIndexExpr(unsigned Idx) {
2585 return getTrailingObjects<Expr *>(N: NumExprs)[Idx];
2586 }
2587
2588 const Expr *getIndexExpr(unsigned Idx) const {
2589 return getTrailingObjects<Expr *>(N: NumExprs)[Idx];
2590 }
2591
2592 void setIndexExpr(unsigned Idx, Expr* E) {
2593 getTrailingObjects<Expr *>(N: NumComps)[Idx] = E;
2594 }
2595
2596 unsigned getNumExpressions() const {
2597 return NumExprs;
2598 }
2599
2600 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2601 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2602
2603 static bool classof(const Stmt *T) {
2604 return T->getStmtClass() == OffsetOfExprClass;
2605 }
2606
2607 // Iterators
2608 child_range children() {
2609 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2610 return child_range(begin, begin + NumExprs);
2611 }
2612 const_child_range children() const {
2613 Stmt *const *begin =
2614 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2615 return const_child_range(begin, begin + NumExprs);
2616 }
2617 friend TrailingObjects;
2618};
2619
2620/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2621/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2622/// vec_step (OpenCL 1.1 6.11.12).
2623class UnaryExprOrTypeTraitExpr : public Expr {
2624 union {
2625 TypeSourceInfo *Ty;
2626 Stmt *Ex;
2627 } Argument;
2628 SourceLocation OpLoc, RParenLoc;
2629
2630public:
2631 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2632 QualType resultType, SourceLocation op,
2633 SourceLocation rp)
2634 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2635 OK_Ordinary),
2636 OpLoc(op), RParenLoc(rp) {
2637 assert(ExprKind <= UETT_Last && "invalid enum value!");
2638 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2639 assert(static_cast<unsigned>(ExprKind) ==
2640 UnaryExprOrTypeTraitExprBits.Kind &&
2641 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2642 UnaryExprOrTypeTraitExprBits.IsType = true;
2643 Argument.Ty = TInfo;
2644 setDependence(computeDependence(E: this));
2645 }
2646
2647 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2648 QualType resultType, SourceLocation op,
2649 SourceLocation rp);
2650
2651 /// Construct an empty sizeof/alignof expression.
2652 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2653 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2654
2655 UnaryExprOrTypeTrait getKind() const {
2656 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2657 }
2658 void setKind(UnaryExprOrTypeTrait K) {
2659 assert(K <= UETT_Last && "invalid enum value!");
2660 UnaryExprOrTypeTraitExprBits.Kind = K;
2661 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2662 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2663 }
2664
2665 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2666 QualType getArgumentType() const {
2667 return getArgumentTypeInfo()->getType();
2668 }
2669 TypeSourceInfo *getArgumentTypeInfo() const {
2670 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2671 return Argument.Ty;
2672 }
2673 Expr *getArgumentExpr() {
2674 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2675 return static_cast<Expr*>(Argument.Ex);
2676 }
2677 const Expr *getArgumentExpr() const {
2678 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2679 }
2680
2681 void setArgument(Expr *E) {
2682 Argument.Ex = E;
2683 UnaryExprOrTypeTraitExprBits.IsType = false;
2684 }
2685 void setArgument(TypeSourceInfo *TInfo) {
2686 Argument.Ty = TInfo;
2687 UnaryExprOrTypeTraitExprBits.IsType = true;
2688 }
2689
2690 /// Gets the argument type, or the type of the argument expression, whichever
2691 /// is appropriate.
2692 QualType getTypeOfArgument() const {
2693 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2694 }
2695
2696 SourceLocation getOperatorLoc() const { return OpLoc; }
2697 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2698
2699 SourceLocation getRParenLoc() const { return RParenLoc; }
2700 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2701
2702 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2703 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2704
2705 static bool classof(const Stmt *T) {
2706 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2707 }
2708
2709 // Iterators
2710 child_range children();
2711 const_child_range children() const;
2712};
2713
2714//===----------------------------------------------------------------------===//
2715// Postfix Operators.
2716//===----------------------------------------------------------------------===//
2717
2718/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2719class ArraySubscriptExpr : public Expr {
2720 enum { LHS, RHS, END_EXPR };
2721 Stmt *SubExprs[END_EXPR];
2722
2723 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2724
2725public:
2726 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2727 ExprObjectKind OK, SourceLocation rbracketloc)
2728 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2729 SubExprs[LHS] = lhs;
2730 SubExprs[RHS] = rhs;
2731 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2732 setDependence(computeDependence(E: this));
2733 }
2734
2735 /// Create an empty array subscript expression.
2736 explicit ArraySubscriptExpr(EmptyShell Shell)
2737 : Expr(ArraySubscriptExprClass, Shell) { }
2738
2739 /// An array access can be written A[4] or 4[A] (both are equivalent).
2740 /// - getBase() and getIdx() always present the normalized view: A[4].
2741 /// In this case getBase() returns "A" and getIdx() returns "4".
2742 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2743 /// 4[A] getLHS() returns "4".
2744 /// Note: Because vector element access is also written A[4] we must
2745 /// predicate the format conversion in getBase and getIdx only on the
2746 /// the type of the RHS, as it is possible for the LHS to be a vector of
2747 /// integer type
2748 Expr *getLHS() { return cast<Expr>(Val: SubExprs[LHS]); }
2749 const Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
2750 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2751
2752 Expr *getRHS() { return cast<Expr>(Val: SubExprs[RHS]); }
2753 const Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
2754 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2755
2756 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2757 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2758
2759 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2760 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2761
2762 SourceLocation getBeginLoc() const LLVM_READONLY {
2763 return getLHS()->getBeginLoc();
2764 }
2765 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2766
2767 SourceLocation getRBracketLoc() const {
2768 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2769 }
2770 void setRBracketLoc(SourceLocation L) {
2771 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2772 }
2773
2774 SourceLocation getExprLoc() const LLVM_READONLY {
2775 return getBase()->getExprLoc();
2776 }
2777
2778 static bool classof(const Stmt *T) {
2779 return T->getStmtClass() == ArraySubscriptExprClass;
2780 }
2781
2782 // Iterators
2783 child_range children() {
2784 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2785 }
2786 const_child_range children() const {
2787 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2788 }
2789};
2790
2791/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2792/// extension.
2793/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2794/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2795/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2796/// exist during the initial construction of the AST.
2797class MatrixSubscriptExpr : public Expr {
2798 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2799 Stmt *SubExprs[END_EXPR];
2800
2801public:
2802 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2803 SourceLocation RBracketLoc)
2804 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2805 OK_MatrixComponent) {
2806 SubExprs[BASE] = Base;
2807 SubExprs[ROW_IDX] = RowIdx;
2808 SubExprs[COLUMN_IDX] = ColumnIdx;
2809 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2810 setDependence(computeDependence(E: this));
2811 }
2812
2813 /// Create an empty matrix subscript expression.
2814 explicit MatrixSubscriptExpr(EmptyShell Shell)
2815 : Expr(MatrixSubscriptExprClass, Shell) {}
2816
2817 bool isIncomplete() const {
2818 bool IsIncomplete = hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx);
2819 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2820 "expressions without column index must be marked as incomplete");
2821 return IsIncomplete;
2822 }
2823 Expr *getBase() { return cast<Expr>(Val: SubExprs[BASE]); }
2824 const Expr *getBase() const { return cast<Expr>(Val: SubExprs[BASE]); }
2825 void setBase(Expr *E) { SubExprs[BASE] = E; }
2826
2827 Expr *getRowIdx() { return cast<Expr>(Val: SubExprs[ROW_IDX]); }
2828 const Expr *getRowIdx() const { return cast<Expr>(Val: SubExprs[ROW_IDX]); }
2829 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2830
2831 Expr *getColumnIdx() { return cast_or_null<Expr>(Val: SubExprs[COLUMN_IDX]); }
2832 const Expr *getColumnIdx() const {
2833 assert(!isIncomplete() &&
2834 "cannot get the column index of an incomplete expression");
2835 return cast<Expr>(Val: SubExprs[COLUMN_IDX]);
2836 }
2837 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2838
2839 SourceLocation getBeginLoc() const LLVM_READONLY {
2840 return getBase()->getBeginLoc();
2841 }
2842
2843 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2844
2845 SourceLocation getExprLoc() const LLVM_READONLY {
2846 return getBase()->getExprLoc();
2847 }
2848
2849 SourceLocation getRBracketLoc() const {
2850 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2851 }
2852 void setRBracketLoc(SourceLocation L) {
2853 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2854 }
2855
2856 static bool classof(const Stmt *T) {
2857 return T->getStmtClass() == MatrixSubscriptExprClass;
2858 }
2859
2860 // Iterators
2861 child_range children() {
2862 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2863 }
2864 const_child_range children() const {
2865 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2866 }
2867};
2868
2869/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2870/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2871/// while its subclasses may represent alternative syntax that (semantically)
2872/// results in a function call. For example, CXXOperatorCallExpr is
2873/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2874/// "str1 + str2" to resolve to a function call.
2875class CallExpr : public Expr {
2876 enum { FN = 0, PREARGS_START = 1 };
2877
2878 /// The number of arguments in the call expression.
2879 unsigned NumArgs;
2880
2881 /// The location of the right parentheses. This has a different meaning for
2882 /// the derived classes of CallExpr.
2883 SourceLocation RParenLoc;
2884
2885 // CallExpr store some data in trailing objects. However since CallExpr
2886 // is used a base of other expression classes we cannot use
2887 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2888 // and casts.
2889 //
2890 // The trailing objects are in order:
2891 //
2892 // * A single "Stmt *" for the callee expression.
2893 //
2894 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2895 //
2896 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2897 //
2898 // * An optional of type FPOptionsOverride.
2899 //
2900 // CallExpr subclasses are asssumed to be 32 bytes or less, and CallExpr
2901 // itself is 24 bytes. To avoid having to recompute or store the offset of the
2902 // trailing objects, we put it at 32 bytes (such that it is suitable for all
2903 // subclasses) We use the 8 bytes gap left for instances of CallExpr to store
2904 // the begin source location, which has a significant impact on perf as
2905 // getBeginLoc is assumed to be cheap.
2906 // The layourt is as follow:
2907 // CallExpr | Begin | 4 bytes left | Trailing Objects
2908 // CXXMemberCallExpr | Trailing Objects
2909 // A bit in CallExprBitfields indicates if source locations are present.
2910
2911protected:
2912 static constexpr unsigned OffsetToTrailingObjects = 32;
2913 template <typename T>
2914 static constexpr unsigned
2915 sizeToAllocateForCallExprSubclass(unsigned SizeOfTrailingObjects) {
2916 static_assert(sizeof(T) <= CallExpr::OffsetToTrailingObjects);
2917 return SizeOfTrailingObjects + CallExpr::OffsetToTrailingObjects;
2918 }
2919
2920private:
2921 /// Return a pointer to the start of the trailing array of "Stmt *".
2922 Stmt **getTrailingStmts() {
2923 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2924 OffsetToTrailingObjects);
2925 }
2926 Stmt *const *getTrailingStmts() const {
2927 return const_cast<CallExpr *>(this)->getTrailingStmts();
2928 }
2929
2930 unsigned getSizeOfTrailingStmts() const {
2931 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2932 }
2933
2934 size_t getOffsetOfTrailingFPFeatures() const {
2935 assert(hasStoredFPFeatures());
2936 return OffsetToTrailingObjects + getSizeOfTrailingStmts();
2937 }
2938
2939public:
2940 enum class ADLCallKind : bool { NotADL, UsesADL };
2941 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2942 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2943
2944protected:
2945 /// Build a call expression, assuming that appropriate storage has been
2946 /// allocated for the trailing objects.
2947 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2948 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2949 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2950 unsigned MinNumArgs, ADLCallKind UsesADL);
2951
2952 /// Build an empty call expression, for deserialization.
2953 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2954 bool hasFPFeatures, EmptyShell Empty);
2955
2956 /// Return the size in bytes needed for the trailing objects.
2957 /// Used by the derived classes to allocate the right amount of storage.
2958 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2959 bool HasFPFeatures) {
2960 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2961 HasFPFeatures * sizeof(FPOptionsOverride);
2962 }
2963
2964 Stmt *getPreArg(unsigned I) {
2965 assert(I < getNumPreArgs() && "Prearg access out of range!");
2966 return getTrailingStmts()[PREARGS_START + I];
2967 }
2968 const Stmt *getPreArg(unsigned I) const {
2969 assert(I < getNumPreArgs() && "Prearg access out of range!");
2970 return getTrailingStmts()[PREARGS_START + I];
2971 }
2972 void setPreArg(unsigned I, Stmt *PreArg) {
2973 assert(I < getNumPreArgs() && "Prearg access out of range!");
2974 getTrailingStmts()[PREARGS_START + I] = PreArg;
2975 }
2976
2977 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2978
2979 /// Return a pointer to the trailing FPOptions
2980 FPOptionsOverride *getTrailingFPFeatures() {
2981 assert(hasStoredFPFeatures());
2982 return reinterpret_cast<FPOptionsOverride *>(
2983 reinterpret_cast<char *>(this) + OffsetToTrailingObjects +
2984 getSizeOfTrailingStmts());
2985 }
2986 const FPOptionsOverride *getTrailingFPFeatures() const {
2987 assert(hasStoredFPFeatures());
2988 return reinterpret_cast<const FPOptionsOverride *>(
2989 reinterpret_cast<const char *>(this) + OffsetToTrailingObjects +
2990 getSizeOfTrailingStmts());
2991 }
2992
2993public:
2994 /// Create a call expression.
2995 /// \param Fn The callee expression,
2996 /// \param Args The argument array,
2997 /// \param Ty The type of the call expression (which is *not* the return
2998 /// type in general),
2999 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
3000 /// \param RParenLoc The location of the right parenthesis in the call
3001 /// expression.
3002 /// \param FPFeatures Floating-point features associated with the call,
3003 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
3004 /// number of arguments will be the greater of Args.size()
3005 /// and MinNumArgs. This is used in a few places to allocate
3006 /// enough storage for the default arguments.
3007 /// \param UsesADL Specifies whether the callee was found through
3008 /// argument-dependent lookup.
3009 ///
3010 /// Note that you can use CreateTemporary if you need a temporary call
3011 /// expression on the stack.
3012 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
3013 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
3014 SourceLocation RParenLoc,
3015 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
3016 ADLCallKind UsesADL = NotADL);
3017
3018 /// Create an empty call expression, for deserialization.
3019 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
3020 bool HasFPFeatures, EmptyShell Empty);
3021
3022 Expr *getCallee() { return cast<Expr>(Val: getTrailingStmts()[FN]); }
3023 const Expr *getCallee() const { return cast<Expr>(Val: getTrailingStmts()[FN]); }
3024 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
3025
3026 ADLCallKind getADLCallKind() const {
3027 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
3028 }
3029 void setADLCallKind(ADLCallKind V = UsesADL) {
3030 CallExprBits.UsesADL = static_cast<bool>(V);
3031 }
3032 bool usesADL() const { return getADLCallKind() == UsesADL; }
3033
3034 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
3035
3036 bool usesMemberSyntax() const {
3037 return CallExprBits.ExplicitObjectMemFunUsingMemberSyntax;
3038 }
3039 void setUsesMemberSyntax(bool V = true) {
3040 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = V;
3041 // Because the source location may be different for explicit
3042 // member, we reset the cached values.
3043 if (CallExprBits.HasTrailingSourceLoc) {
3044 CallExprBits.HasTrailingSourceLoc = false;
3045 updateTrailingSourceLoc();
3046 }
3047 }
3048
3049 bool isCoroElideSafe() const { return CallExprBits.IsCoroElideSafe; }
3050 void setCoroElideSafe(bool V = true) { CallExprBits.IsCoroElideSafe = V; }
3051
3052 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
3053 const Decl *getCalleeDecl() const {
3054 return getCallee()->getReferencedDeclOfCallee();
3055 }
3056
3057 /// If the callee is a FunctionDecl, return it. Otherwise return null.
3058 FunctionDecl *getDirectCallee() {
3059 return dyn_cast_or_null<FunctionDecl>(Val: getCalleeDecl());
3060 }
3061 const FunctionDecl *getDirectCallee() const {
3062 return dyn_cast_or_null<FunctionDecl>(Val: getCalleeDecl());
3063 }
3064
3065 /// getNumArgs - Return the number of actual arguments to this call.
3066 unsigned getNumArgs() const { return NumArgs; }
3067
3068 /// Retrieve the call arguments.
3069 Expr **getArgs() {
3070 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
3071 getNumPreArgs());
3072 }
3073 const Expr *const *getArgs() const {
3074 return reinterpret_cast<const Expr *const *>(
3075 getTrailingStmts() + PREARGS_START + getNumPreArgs());
3076 }
3077
3078 /// getArg - Return the specified argument.
3079 Expr *getArg(unsigned Arg) {
3080 assert(Arg < getNumArgs() && "Arg access out of range!");
3081 return getArgs()[Arg];
3082 }
3083 const Expr *getArg(unsigned Arg) const {
3084 assert(Arg < getNumArgs() && "Arg access out of range!");
3085 return getArgs()[Arg];
3086 }
3087
3088 /// setArg - Set the specified argument.
3089 /// ! the dependence bits might be stale after calling this setter, it is
3090 /// *caller*'s responsibility to recompute them by calling
3091 /// computeDependence().
3092 void setArg(unsigned Arg, Expr *ArgExpr) {
3093 assert(Arg < getNumArgs() && "Arg access out of range!");
3094 getArgs()[Arg] = ArgExpr;
3095 }
3096
3097 /// Compute and set dependence bits.
3098 void computeDependence() {
3099 setDependence(clang::computeDependence(
3100 E: this,
3101 PreArgs: ArrayRef(reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3102 getNumPreArgs())));
3103 }
3104
3105 /// Reduce the number of arguments in this call expression. This is used for
3106 /// example during error recovery to drop extra arguments. There is no way
3107 /// to perform the opposite because: 1.) We don't track how much storage
3108 /// we have for the argument array 2.) This would potentially require growing
3109 /// the argument array, something we cannot support since the arguments are
3110 /// stored in a trailing array.
3111 void shrinkNumArgs(unsigned NewNumArgs) {
3112 assert((NewNumArgs <= getNumArgs()) &&
3113 "shrinkNumArgs cannot increase the number of arguments!");
3114 NumArgs = NewNumArgs;
3115 }
3116
3117 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3118 /// Only used during construction of a CallExpr in a few places in Sema.
3119 /// FIXME: Find a way to remove it.
3120 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3121
3122 typedef ExprIterator arg_iterator;
3123 typedef ConstExprIterator const_arg_iterator;
3124 typedef llvm::iterator_range<arg_iterator> arg_range;
3125 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3126
3127 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3128 const_arg_range arguments() const {
3129 return const_arg_range(arg_begin(), arg_end());
3130 }
3131
3132 arg_iterator arg_begin() {
3133 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3134 }
3135 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3136
3137 const_arg_iterator arg_begin() const {
3138 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3139 }
3140 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3141
3142 /// This method provides fast access to all the subexpressions of
3143 /// a CallExpr without going through the slower virtual child_iterator
3144 /// interface. This provides efficient reverse iteration of the
3145 /// subexpressions. This is currently used for CFG construction.
3146 ArrayRef<Stmt *> getRawSubExprs() {
3147 return {getTrailingStmts(), PREARGS_START + getNumPreArgs() + getNumArgs()};
3148 }
3149
3150 /// Get FPOptionsOverride from trailing storage.
3151 FPOptionsOverride getStoredFPFeatures() const {
3152 assert(hasStoredFPFeatures());
3153 return *getTrailingFPFeatures();
3154 }
3155 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3156 void setStoredFPFeatures(FPOptionsOverride F) {
3157 assert(hasStoredFPFeatures());
3158 *getTrailingFPFeatures() = F;
3159 }
3160
3161 /// Get the store FPOptionsOverride or default if not stored.
3162 FPOptionsOverride getStoredFPFeaturesOrDefault() const {
3163 return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
3164 }
3165
3166 /// Get the FP features status of this operator. Only meaningful for
3167 /// operations on floating point types.
3168 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3169 if (hasStoredFPFeatures())
3170 return getStoredFPFeatures().applyOverrides(LO);
3171 return FPOptions::defaultWithoutTrailingStorage(LO);
3172 }
3173
3174 FPOptionsOverride getFPFeatures() const {
3175 if (hasStoredFPFeatures())
3176 return getStoredFPFeatures();
3177 return FPOptionsOverride();
3178 }
3179
3180 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3181 /// of the callee. If not, return 0.
3182 unsigned getBuiltinCallee() const;
3183
3184 /// Returns \c true if this is a call to a builtin which does not
3185 /// evaluate side-effects within its arguments.
3186 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3187
3188 /// getCallReturnType - Get the return type of the call expr. This is not
3189 /// always the type of the expr itself, if the return type is a reference
3190 /// type.
3191 QualType getCallReturnType(const ASTContext &Ctx) const;
3192
3193 /// Returns the WarnUnusedResultAttr that is either declared on the called
3194 /// function, or its return type declaration, together with a NamedDecl that
3195 /// refers to the declaration the attribute is attached onto.
3196 std::pair<const NamedDecl *, const Attr *>
3197 getUnusedResultAttr(const ASTContext &Ctx) const;
3198
3199 /// Returns true if this call expression should warn on unused results.
3200 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3201 return getUnusedResultAttr(Ctx).second != nullptr;
3202 }
3203
3204 SourceLocation getRParenLoc() const { return RParenLoc; }
3205 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3206
3207 SourceLocation getBeginLoc() const {
3208 if (CallExprBits.HasTrailingSourceLoc) {
3209 static_assert(sizeof(CallExpr) <=
3210 OffsetToTrailingObjects + sizeof(SourceLocation));
3211 return *reinterpret_cast<const SourceLocation *>(
3212 reinterpret_cast<const char *>(this + 1));
3213 }
3214
3215 if (usesMemberSyntax())
3216 if (auto FirstArgLoc = getArg(Arg: 0)->getBeginLoc(); FirstArgLoc.isValid())
3217 return FirstArgLoc;
3218
3219 // FIXME: Some builtins have no callee begin location
3220 SourceLocation begin = getCallee()->getBeginLoc();
3221 if (begin.isInvalid() && getNumArgs() > 0 && getArg(Arg: 0))
3222 begin = getArg(Arg: 0)->getBeginLoc();
3223 return begin;
3224 }
3225
3226 SourceLocation getEndLoc() const { return getRParenLoc(); }
3227
3228private:
3229 friend class ASTStmtReader;
3230 bool hasTrailingSourceLoc() const {
3231 return CallExprBits.HasTrailingSourceLoc;
3232 }
3233
3234 void updateTrailingSourceLoc() {
3235 assert(!CallExprBits.HasTrailingSourceLoc &&
3236 "Trailing source loc already set?");
3237 assert(getStmtClass() == CallExprClass &&
3238 "Calling setTrailingSourceLocs on a subclass of CallExpr");
3239 static_assert(sizeof(CallExpr) <=
3240 OffsetToTrailingObjects + sizeof(SourceLocation));
3241
3242 SourceLocation *Locs =
3243 reinterpret_cast<SourceLocation *>(reinterpret_cast<char *>(this + 1));
3244 new (Locs) SourceLocation(getBeginLoc());
3245 CallExprBits.HasTrailingSourceLoc = true;
3246 }
3247
3248public:
3249 /// Return true if this is a call to __assume() or __builtin_assume() with
3250 /// a non-value-dependent constant parameter evaluating as false.
3251 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3252
3253 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3254 /// (Usually Exprs themselves should set dependence).
3255 void markDependentForPostponedNameLookup() {
3256 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3257 }
3258
3259 bool isCallToStdMove() const;
3260
3261 static bool classof(const Stmt *T) {
3262 return T->getStmtClass() >= firstCallExprConstant &&
3263 T->getStmtClass() <= lastCallExprConstant;
3264 }
3265
3266 // Iterators
3267 child_range children() {
3268 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3269 getNumPreArgs() + getNumArgs());
3270 }
3271
3272 const_child_range children() const {
3273 return const_child_range(getTrailingStmts(),
3274 getTrailingStmts() + PREARGS_START +
3275 getNumPreArgs() + getNumArgs());
3276 }
3277};
3278
3279/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3280///
3281class MemberExpr final
3282 : public Expr,
3283 private llvm::TrailingObjects<MemberExpr, NestedNameSpecifierLoc,
3284 DeclAccessPair, ASTTemplateKWAndArgsInfo,
3285 TemplateArgumentLoc> {
3286 friend class ASTReader;
3287 friend class ASTStmtReader;
3288 friend class ASTStmtWriter;
3289 friend TrailingObjects;
3290
3291 /// Base - the expression for the base pointer or structure references. In
3292 /// X.F, this is "X".
3293 Stmt *Base;
3294
3295 /// MemberDecl - This is the decl being referenced by the field/member name.
3296 /// In X.F, this is the decl referenced by F.
3297 ValueDecl *MemberDecl;
3298
3299 /// MemberDNLoc - Provides source/type location info for the
3300 /// declaration name embedded in MemberDecl.
3301 DeclarationNameLoc MemberDNLoc;
3302
3303 /// MemberLoc - This is the location of the member name.
3304 SourceLocation MemberLoc;
3305
3306 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
3307 return hasQualifier();
3308 }
3309
3310 size_t numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3311 return hasFoundDecl();
3312 }
3313
3314 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3315 return hasTemplateKWAndArgsInfo();
3316 }
3317
3318 bool hasFoundDecl() const { return MemberExprBits.HasFoundDecl; }
3319
3320 bool hasTemplateKWAndArgsInfo() const {
3321 return MemberExprBits.HasTemplateKWAndArgsInfo;
3322 }
3323
3324 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3325 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3326 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
3327 const DeclarationNameInfo &NameInfo,
3328 const TemplateArgumentListInfo *TemplateArgs, QualType T,
3329 ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR);
3330 MemberExpr(EmptyShell Empty)
3331 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3332
3333public:
3334 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3335 SourceLocation OperatorLoc,
3336 NestedNameSpecifierLoc QualifierLoc,
3337 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3338 DeclAccessPair FoundDecl,
3339 DeclarationNameInfo MemberNameInfo,
3340 const TemplateArgumentListInfo *TemplateArgs,
3341 QualType T, ExprValueKind VK, ExprObjectKind OK,
3342 NonOdrUseReason NOUR);
3343
3344 /// Create an implicit MemberExpr, with no location, qualifier, template
3345 /// arguments, and so on. Suitable only for non-static member access.
3346 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3347 bool IsArrow, ValueDecl *MemberDecl,
3348 QualType T, ExprValueKind VK,
3349 ExprObjectKind OK) {
3350 return Create(C, Base, IsArrow, OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(),
3351 TemplateKWLoc: SourceLocation(), MemberDecl,
3352 FoundDecl: DeclAccessPair::make(D: MemberDecl, AS: MemberDecl->getAccess()),
3353 MemberNameInfo: DeclarationNameInfo(), TemplateArgs: nullptr, T, VK, OK, NOUR: NOUR_None);
3354 }
3355
3356 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3357 bool HasFoundDecl,
3358 bool HasTemplateKWAndArgsInfo,
3359 unsigned NumTemplateArgs);
3360
3361 void setBase(Expr *E) { Base = E; }
3362 Expr *getBase() const { return cast<Expr>(Val: Base); }
3363
3364 /// Retrieve the member declaration to which this expression refers.
3365 ///
3366 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3367 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3368 ValueDecl *getMemberDecl() const { return MemberDecl; }
3369 void setMemberDecl(ValueDecl *D);
3370
3371 /// Retrieves the declaration found by lookup.
3372 DeclAccessPair getFoundDecl() const {
3373 if (!hasFoundDecl())
3374 return DeclAccessPair::make(D: getMemberDecl(),
3375 AS: getMemberDecl()->getAccess());
3376 return *getTrailingObjects<DeclAccessPair>();
3377 }
3378
3379 /// Determines whether this member expression actually had
3380 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3381 /// x->Base::foo.
3382 bool hasQualifier() const { return MemberExprBits.HasQualifier; }
3383
3384 /// If the member name was qualified, retrieves the
3385 /// nested-name-specifier that precedes the member name, with source-location
3386 /// information.
3387 NestedNameSpecifierLoc getQualifierLoc() const {
3388 if (!hasQualifier())
3389 return NestedNameSpecifierLoc();
3390 return *getTrailingObjects<NestedNameSpecifierLoc>();
3391 }
3392
3393 /// If the member name was qualified, retrieves the
3394 /// nested-name-specifier that precedes the member name. Otherwise, returns
3395 /// NULL.
3396 NestedNameSpecifier *getQualifier() const {
3397 return getQualifierLoc().getNestedNameSpecifier();
3398 }
3399
3400 /// Retrieve the location of the template keyword preceding
3401 /// the member name, if any.
3402 SourceLocation getTemplateKeywordLoc() const {
3403 if (!hasTemplateKWAndArgsInfo())
3404 return SourceLocation();
3405 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3406 }
3407
3408 /// Retrieve the location of the left angle bracket starting the
3409 /// explicit template argument list following the member name, if any.
3410 SourceLocation getLAngleLoc() const {
3411 if (!hasTemplateKWAndArgsInfo())
3412 return SourceLocation();
3413 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3414 }
3415
3416 /// Retrieve the location of the right angle bracket ending the
3417 /// explicit template argument list following the member name, if any.
3418 SourceLocation getRAngleLoc() const {
3419 if (!hasTemplateKWAndArgsInfo())
3420 return SourceLocation();
3421 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3422 }
3423
3424 /// Determines whether the member name was preceded by the template keyword.
3425 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3426
3427 /// Determines whether the member name was followed by an
3428 /// explicit template argument list.
3429 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3430
3431 /// Copies the template arguments (if present) into the given
3432 /// structure.
3433 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3434 if (hasExplicitTemplateArgs())
3435 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3436 ArgArray: getTrailingObjects<TemplateArgumentLoc>(), List);
3437 }
3438
3439 /// Retrieve the template arguments provided as part of this
3440 /// template-id.
3441 const TemplateArgumentLoc *getTemplateArgs() const {
3442 if (!hasExplicitTemplateArgs())
3443 return nullptr;
3444
3445 return getTrailingObjects<TemplateArgumentLoc>();
3446 }
3447
3448 /// Retrieve the number of template arguments provided as part of this
3449 /// template-id.
3450 unsigned getNumTemplateArgs() const {
3451 if (!hasExplicitTemplateArgs())
3452 return 0;
3453
3454 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3455 }
3456
3457 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3458 return {getTemplateArgs(), getNumTemplateArgs()};
3459 }
3460
3461 /// Retrieve the member declaration name info.
3462 DeclarationNameInfo getMemberNameInfo() const {
3463 return DeclarationNameInfo(MemberDecl->getDeclName(),
3464 MemberLoc, MemberDNLoc);
3465 }
3466
3467 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3468
3469 bool isArrow() const { return MemberExprBits.IsArrow; }
3470 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3471
3472 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3473 /// location of 'F'.
3474 SourceLocation getMemberLoc() const { return MemberLoc; }
3475 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3476
3477 SourceLocation getBeginLoc() const LLVM_READONLY;
3478 SourceLocation getEndLoc() const LLVM_READONLY;
3479
3480 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3481
3482 /// Determine whether the base of this explicit is implicit.
3483 bool isImplicitAccess() const {
3484 return getBase() && getBase()->isImplicitCXXThis();
3485 }
3486
3487 /// Returns true if this member expression refers to a method that
3488 /// was resolved from an overloaded set having size greater than 1.
3489 bool hadMultipleCandidates() const {
3490 return MemberExprBits.HadMultipleCandidates;
3491 }
3492 /// Sets the flag telling whether this expression refers to
3493 /// a method that was resolved from an overloaded set having size
3494 /// greater than 1.
3495 void setHadMultipleCandidates(bool V = true) {
3496 MemberExprBits.HadMultipleCandidates = V;
3497 }
3498
3499 /// Returns true if virtual dispatch is performed.
3500 /// If the member access is fully qualified, (i.e. X::f()), virtual
3501 /// dispatching is not performed. In -fapple-kext mode qualified
3502 /// calls to virtual method will still go through the vtable.
3503 bool performsVirtualDispatch(const LangOptions &LO) const {
3504 return LO.AppleKext || !hasQualifier();
3505 }
3506
3507 /// Is this expression a non-odr-use reference, and if so, why?
3508 /// This is only meaningful if the named member is a static member.
3509 NonOdrUseReason isNonOdrUse() const {
3510 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3511 }
3512
3513 static bool classof(const Stmt *T) {
3514 return T->getStmtClass() == MemberExprClass;
3515 }
3516
3517 // Iterators
3518 child_range children() { return child_range(&Base, &Base+1); }
3519 const_child_range children() const {
3520 return const_child_range(&Base, &Base + 1);
3521 }
3522};
3523
3524/// CompoundLiteralExpr - [C99 6.5.2.5]
3525///
3526class CompoundLiteralExpr : public Expr {
3527 /// LParenLoc - If non-null, this is the location of the left paren in a
3528 /// compound literal like "(int){4}". This can be null if this is a
3529 /// synthesized compound expression.
3530 SourceLocation LParenLoc;
3531
3532 /// The type as written. This can be an incomplete array type, in
3533 /// which case the actual expression type will be different.
3534 /// The int part of the pair stores whether this expr is file scope.
3535 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3536 Stmt *Init;
3537
3538 /// Value of constant literals with static storage duration.
3539 mutable APValue *StaticValue = nullptr;
3540
3541public:
3542 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3543 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3544 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3545 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3546 setDependence(computeDependence(E: this));
3547 }
3548
3549 /// Construct an empty compound literal.
3550 explicit CompoundLiteralExpr(EmptyShell Empty)
3551 : Expr(CompoundLiteralExprClass, Empty) { }
3552
3553 const Expr *getInitializer() const { return cast<Expr>(Val: Init); }
3554 Expr *getInitializer() { return cast<Expr>(Val: Init); }
3555 void setInitializer(Expr *E) { Init = E; }
3556
3557 bool isFileScope() const { return TInfoAndScope.getInt(); }
3558 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3559
3560 SourceLocation getLParenLoc() const { return LParenLoc; }
3561 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3562
3563 TypeSourceInfo *getTypeSourceInfo() const {
3564 return TInfoAndScope.getPointer();
3565 }
3566 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3567 TInfoAndScope.setPointer(tinfo);
3568 }
3569
3570 bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
3571 APValue &getOrCreateStaticValue(ASTContext &Ctx) const;
3572 APValue &getStaticValue() const;
3573
3574 SourceLocation getBeginLoc() const LLVM_READONLY {
3575 // FIXME: Init should never be null.
3576 if (!Init)
3577 return SourceLocation();
3578 if (LParenLoc.isInvalid())
3579 return Init->getBeginLoc();
3580 return LParenLoc;
3581 }
3582 SourceLocation getEndLoc() const LLVM_READONLY {
3583 // FIXME: Init should never be null.
3584 if (!Init)
3585 return SourceLocation();
3586 return Init->getEndLoc();
3587 }
3588
3589 static bool classof(const Stmt *T) {
3590 return T->getStmtClass() == CompoundLiteralExprClass;
3591 }
3592
3593 // Iterators
3594 child_range children() { return child_range(&Init, &Init+1); }
3595 const_child_range children() const {
3596 return const_child_range(&Init, &Init + 1);
3597 }
3598};
3599
3600/// CastExpr - Base class for type casts, including both implicit
3601/// casts (ImplicitCastExpr) and explicit casts that have some
3602/// representation in the source code (ExplicitCastExpr's derived
3603/// classes).
3604class CastExpr : public Expr {
3605 Stmt *Op;
3606
3607 bool CastConsistency() const;
3608
3609 const CXXBaseSpecifier * const *path_buffer() const {
3610 return const_cast<CastExpr*>(this)->path_buffer();
3611 }
3612 CXXBaseSpecifier **path_buffer();
3613
3614 friend class ASTStmtReader;
3615
3616protected:
3617 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3618 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3619 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3620 CastExprBits.Kind = kind;
3621 CastExprBits.PartOfExplicitCast = false;
3622 CastExprBits.BasePathSize = BasePathSize;
3623 assert((CastExprBits.BasePathSize == BasePathSize) &&
3624 "BasePathSize overflow!");
3625 assert(CastConsistency());
3626 CastExprBits.HasFPFeatures = HasFPFeatures;
3627 }
3628
3629 /// Construct an empty cast.
3630 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3631 bool HasFPFeatures)
3632 : Expr(SC, Empty) {
3633 CastExprBits.PartOfExplicitCast = false;
3634 CastExprBits.BasePathSize = BasePathSize;
3635 CastExprBits.HasFPFeatures = HasFPFeatures;
3636 assert((CastExprBits.BasePathSize == BasePathSize) &&
3637 "BasePathSize overflow!");
3638 }
3639
3640 /// Return a pointer to the trailing FPOptions.
3641 /// \pre hasStoredFPFeatures() == true
3642 FPOptionsOverride *getTrailingFPFeatures();
3643 const FPOptionsOverride *getTrailingFPFeatures() const {
3644 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3645 }
3646
3647public:
3648 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3649 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3650
3651 static const char *getCastKindName(CastKind CK);
3652 const char *getCastKindName() const { return getCastKindName(CK: getCastKind()); }
3653
3654 Expr *getSubExpr() { return cast<Expr>(Val: Op); }
3655 const Expr *getSubExpr() const { return cast<Expr>(Val: Op); }
3656 void setSubExpr(Expr *E) { Op = E; }
3657
3658 /// Retrieve the cast subexpression as it was written in the source
3659 /// code, looking through any implicit casts or other intermediate nodes
3660 /// introduced by semantic analysis.
3661 Expr *getSubExprAsWritten();
3662 const Expr *getSubExprAsWritten() const {
3663 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3664 }
3665
3666 /// If this cast applies a user-defined conversion, retrieve the conversion
3667 /// function that it invokes.
3668 NamedDecl *getConversionFunction() const;
3669
3670 typedef CXXBaseSpecifier **path_iterator;
3671 typedef const CXXBaseSpecifier *const *path_const_iterator;
3672 bool path_empty() const { return path_size() == 0; }
3673 unsigned path_size() const { return CastExprBits.BasePathSize; }
3674 path_iterator path_begin() { return path_buffer(); }
3675 path_iterator path_end() { return path_buffer() + path_size(); }
3676 path_const_iterator path_begin() const { return path_buffer(); }
3677 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3678
3679 /// Path through the class hierarchy taken by casts between base and derived
3680 /// classes (see implementation of `CastConsistency()` for a full list of
3681 /// cast kinds that have a path).
3682 ///
3683 /// For each derived-to-base edge in the path, the path contains a
3684 /// `CXXBaseSpecifier` for the base class of that edge; the entries are
3685 /// ordered from derived class to base class.
3686 ///
3687 /// For example, given classes `Base`, `Intermediate : public Base` and
3688 /// `Derived : public Intermediate`, the path for a cast from `Derived *` to
3689 /// `Base *` contains two entries: One for `Intermediate`, and one for `Base`,
3690 /// in that order.
3691 llvm::iterator_range<path_iterator> path() {
3692 return llvm::make_range(x: path_begin(), y: path_end());
3693 }
3694 llvm::iterator_range<path_const_iterator> path() const {
3695 return llvm::make_range(x: path_begin(), y: path_end());
3696 }
3697
3698 const FieldDecl *getTargetUnionField() const {
3699 assert(getCastKind() == CK_ToUnion);
3700 return getTargetFieldForToUnionCast(unionType: getType(), opType: getSubExpr()->getType());
3701 }
3702
3703 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3704
3705 /// Get FPOptionsOverride from trailing storage.
3706 FPOptionsOverride getStoredFPFeatures() const {
3707 assert(hasStoredFPFeatures());
3708 return *getTrailingFPFeatures();
3709 }
3710
3711 /// Get the store FPOptionsOverride or default if not stored.
3712 FPOptionsOverride getStoredFPFeaturesOrDefault() const {
3713 return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
3714 }
3715
3716 /// Get the FP features status of this operation. Only meaningful for
3717 /// operations on floating point types.
3718 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3719 if (hasStoredFPFeatures())
3720 return getStoredFPFeatures().applyOverrides(LO);
3721 return FPOptions::defaultWithoutTrailingStorage(LO);
3722 }
3723
3724 FPOptionsOverride getFPFeatures() const {
3725 if (hasStoredFPFeatures())
3726 return getStoredFPFeatures();
3727 return FPOptionsOverride();
3728 }
3729
3730 /// Return
3731 // True : if this conversion changes the volatile-ness of a gl-value.
3732 // Qualification conversions on gl-values currently use CK_NoOp, but
3733 // it's important to recognize volatile-changing conversions in
3734 // clients code generation that normally eagerly peephole loads. Note
3735 // that the query is answering for this specific node; Sema may
3736 // produce multiple cast nodes for any particular conversion sequence.
3737 // False : Otherwise.
3738 bool changesVolatileQualification() const {
3739 return (isGLValue() && (getType().isVolatileQualified() !=
3740 getSubExpr()->getType().isVolatileQualified()));
3741 }
3742
3743 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3744 QualType opType);
3745 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3746 QualType opType);
3747
3748 static bool classof(const Stmt *T) {
3749 return T->getStmtClass() >= firstCastExprConstant &&
3750 T->getStmtClass() <= lastCastExprConstant;
3751 }
3752
3753 // Iterators
3754 child_range children() { return child_range(&Op, &Op+1); }
3755 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3756};
3757
3758/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3759/// conversions, which have no direct representation in the original
3760/// source code. For example: converting T[]->T*, void f()->void
3761/// (*f)(), float->double, short->int, etc.
3762///
3763/// In C, implicit casts always produce rvalues. However, in C++, an
3764/// implicit cast whose result is being bound to a reference will be
3765/// an lvalue or xvalue. For example:
3766///
3767/// @code
3768/// class Base { };
3769/// class Derived : public Base { };
3770/// Derived &&ref();
3771/// void f(Derived d) {
3772/// Base& b = d; // initializer is an ImplicitCastExpr
3773/// // to an lvalue of type Base
3774/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3775/// // to an xvalue of type Base
3776/// }
3777/// @endcode
3778class ImplicitCastExpr final
3779 : public CastExpr,
3780 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3781 FPOptionsOverride> {
3782
3783 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3784 unsigned BasePathLength, FPOptionsOverride FPO,
3785 ExprValueKind VK)
3786 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3787 FPO.requiresTrailingStorage()) {
3788 setDependence(computeDependence(E: this));
3789 if (hasStoredFPFeatures())
3790 *getTrailingFPFeatures() = FPO;
3791 }
3792
3793 /// Construct an empty implicit cast.
3794 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3795 bool HasFPFeatures)
3796 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3797
3798 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3799 return path_size();
3800 }
3801
3802public:
3803 enum OnStack_t { OnStack };
3804 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3805 ExprValueKind VK, FPOptionsOverride FPO)
3806 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3807 FPO.requiresTrailingStorage()) {
3808 if (hasStoredFPFeatures())
3809 *getTrailingFPFeatures() = FPO;
3810 }
3811
3812 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3813 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3814 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3815 }
3816
3817 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3818 CastKind Kind, Expr *Operand,
3819 const CXXCastPath *BasePath,
3820 ExprValueKind Cat, FPOptionsOverride FPO);
3821
3822 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3823 unsigned PathSize, bool HasFPFeatures);
3824
3825 SourceLocation getBeginLoc() const LLVM_READONLY {
3826 return getSubExpr()->getBeginLoc();
3827 }
3828 SourceLocation getEndLoc() const LLVM_READONLY {
3829 return getSubExpr()->getEndLoc();
3830 }
3831
3832 static bool classof(const Stmt *T) {
3833 return T->getStmtClass() == ImplicitCastExprClass;
3834 }
3835
3836 friend TrailingObjects;
3837 friend class CastExpr;
3838};
3839
3840/// ExplicitCastExpr - An explicit cast written in the source
3841/// code.
3842///
3843/// This class is effectively an abstract class, because it provides
3844/// the basic representation of an explicitly-written cast without
3845/// specifying which kind of cast (C cast, functional cast, static
3846/// cast, etc.) was written; specific derived classes represent the
3847/// particular style of cast and its location information.
3848///
3849/// Unlike implicit casts, explicit cast nodes have two different
3850/// types: the type that was written into the source code, and the
3851/// actual type of the expression as determined by semantic
3852/// analysis. These types may differ slightly. For example, in C++ one
3853/// can cast to a reference type, which indicates that the resulting
3854/// expression will be an lvalue or xvalue. The reference type, however,
3855/// will not be used as the type of the expression.
3856class ExplicitCastExpr : public CastExpr {
3857 /// TInfo - Source type info for the (written) type
3858 /// this expression is casting to.
3859 TypeSourceInfo *TInfo;
3860
3861protected:
3862 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3863 CastKind kind, Expr *op, unsigned PathSize,
3864 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3865 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3866 TInfo(writtenTy) {
3867 setDependence(computeDependence(E: this));
3868 }
3869
3870 /// Construct an empty explicit cast.
3871 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3872 bool HasFPFeatures)
3873 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3874
3875public:
3876 /// getTypeInfoAsWritten - Returns the type source info for the type
3877 /// that this expression is casting to.
3878 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3879 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3880
3881 /// getTypeAsWritten - Returns the type that this expression is
3882 /// casting to, as written in the source code.
3883 QualType getTypeAsWritten() const { return TInfo->getType(); }
3884
3885 static bool classof(const Stmt *T) {
3886 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3887 T->getStmtClass() <= lastExplicitCastExprConstant;
3888 }
3889};
3890
3891/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3892/// cast in C++ (C++ [expr.cast]), which uses the syntax
3893/// (Type)expr. For example: @c (int)f.
3894class CStyleCastExpr final
3895 : public ExplicitCastExpr,
3896 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3897 FPOptionsOverride> {
3898 SourceLocation LPLoc; // the location of the left paren
3899 SourceLocation RPLoc; // the location of the right paren
3900
3901 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3902 unsigned PathSize, FPOptionsOverride FPO,
3903 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3904 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3905 FPO.requiresTrailingStorage(), writtenTy),
3906 LPLoc(l), RPLoc(r) {
3907 if (hasStoredFPFeatures())
3908 *getTrailingFPFeatures() = FPO;
3909 }
3910
3911 /// Construct an empty C-style explicit cast.
3912 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3913 bool HasFPFeatures)
3914 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3915
3916 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3917 return path_size();
3918 }
3919
3920public:
3921 static CStyleCastExpr *
3922 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3923 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3924 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3925
3926 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3927 unsigned PathSize, bool HasFPFeatures);
3928
3929 SourceLocation getLParenLoc() const { return LPLoc; }
3930 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3931
3932 SourceLocation getRParenLoc() const { return RPLoc; }
3933 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3934
3935 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3936 SourceLocation getEndLoc() const LLVM_READONLY {
3937 return getSubExpr()->getEndLoc();
3938 }
3939
3940 static bool classof(const Stmt *T) {
3941 return T->getStmtClass() == CStyleCastExprClass;
3942 }
3943
3944 friend TrailingObjects;
3945 friend class CastExpr;
3946};
3947
3948/// A builtin binary operation expression such as "x + y" or "x <= y".
3949///
3950/// This expression node kind describes a builtin binary operation,
3951/// such as "x + y" for integer values "x" and "y". The operands will
3952/// already have been converted to appropriate types (e.g., by
3953/// performing promotions or conversions).
3954///
3955/// In C++, where operators may be overloaded, a different kind of
3956/// expression node (CXXOperatorCallExpr) is used to express the
3957/// invocation of an overloaded operator with operator syntax. Within
3958/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3959/// used to store an expression "x + y" depends on the subexpressions
3960/// for x and y. If neither x or y is type-dependent, and the "+"
3961/// operator resolves to a built-in operation, BinaryOperator will be
3962/// used to express the computation (x and y may still be
3963/// value-dependent). If either x or y is type-dependent, or if the
3964/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3965/// be used to express the computation.
3966class BinaryOperator : public Expr {
3967 enum { LHS, RHS, END_EXPR };
3968 Stmt *SubExprs[END_EXPR];
3969
3970public:
3971 typedef BinaryOperatorKind Opcode;
3972
3973protected:
3974 size_t offsetOfTrailingStorage() const;
3975
3976 /// Return a pointer to the trailing FPOptions
3977 FPOptionsOverride *getTrailingFPFeatures() {
3978 assert(BinaryOperatorBits.HasFPFeatures);
3979 return reinterpret_cast<FPOptionsOverride *>(
3980 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3981 }
3982 const FPOptionsOverride *getTrailingFPFeatures() const {
3983 assert(BinaryOperatorBits.HasFPFeatures);
3984 return reinterpret_cast<const FPOptionsOverride *>(
3985 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3986 }
3987
3988 /// Build a binary operator, assuming that appropriate storage has been
3989 /// allocated for the trailing objects when needed.
3990 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3991 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3992 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3993
3994 /// Construct an empty binary operator.
3995 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3996 BinaryOperatorBits.Opc = BO_Comma;
3997 BinaryOperatorBits.ExcludedOverflowPattern = false;
3998 }
3999
4000public:
4001 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
4002
4003 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4004 Opcode opc, QualType ResTy, ExprValueKind VK,
4005 ExprObjectKind OK, SourceLocation opLoc,
4006 FPOptionsOverride FPFeatures);
4007 SourceLocation getExprLoc() const { return getOperatorLoc(); }
4008 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
4009 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
4010
4011 Opcode getOpcode() const {
4012 return static_cast<Opcode>(BinaryOperatorBits.Opc);
4013 }
4014 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
4015
4016 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
4017 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4018 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
4019 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4020
4021 SourceLocation getBeginLoc() const LLVM_READONLY {
4022 return getLHS()->getBeginLoc();
4023 }
4024 SourceLocation getEndLoc() const LLVM_READONLY {
4025 return getRHS()->getEndLoc();
4026 }
4027
4028 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
4029 /// corresponds to, e.g. "<<=".
4030 static StringRef getOpcodeStr(Opcode Op);
4031
4032 StringRef getOpcodeStr() const { return getOpcodeStr(Op: getOpcode()); }
4033
4034 /// Retrieve the binary opcode that corresponds to the given
4035 /// overloaded operator.
4036 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
4037
4038 /// Retrieve the overloaded operator kind that corresponds to
4039 /// the given binary opcode.
4040 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
4041
4042 /// predicates to categorize the respective opcodes.
4043 static bool isPtrMemOp(Opcode Opc) {
4044 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
4045 }
4046 bool isPtrMemOp() const { return isPtrMemOp(Opc: getOpcode()); }
4047
4048 static bool isMultiplicativeOp(Opcode Opc) {
4049 return Opc >= BO_Mul && Opc <= BO_Rem;
4050 }
4051 bool isMultiplicativeOp() const { return isMultiplicativeOp(Opc: getOpcode()); }
4052 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
4053 bool isAdditiveOp() const { return isAdditiveOp(Opc: getOpcode()); }
4054 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
4055 bool isShiftOp() const { return isShiftOp(Opc: getOpcode()); }
4056
4057 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
4058 bool isBitwiseOp() const { return isBitwiseOp(Opc: getOpcode()); }
4059
4060 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
4061 bool isRelationalOp() const { return isRelationalOp(Opc: getOpcode()); }
4062
4063 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
4064 bool isEqualityOp() const { return isEqualityOp(Opc: getOpcode()); }
4065
4066 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
4067 bool isComparisonOp() const { return isComparisonOp(Opc: getOpcode()); }
4068
4069 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
4070 bool isCommaOp() const { return isCommaOp(Opc: getOpcode()); }
4071
4072 static Opcode negateComparisonOp(Opcode Opc) {
4073 switch (Opc) {
4074 default:
4075 llvm_unreachable("Not a comparison operator.");
4076 case BO_LT: return BO_GE;
4077 case BO_GT: return BO_LE;
4078 case BO_LE: return BO_GT;
4079 case BO_GE: return BO_LT;
4080 case BO_EQ: return BO_NE;
4081 case BO_NE: return BO_EQ;
4082 }
4083 }
4084
4085 static Opcode reverseComparisonOp(Opcode Opc) {
4086 switch (Opc) {
4087 default:
4088 llvm_unreachable("Not a comparison operator.");
4089 case BO_LT: return BO_GT;
4090 case BO_GT: return BO_LT;
4091 case BO_LE: return BO_GE;
4092 case BO_GE: return BO_LE;
4093 case BO_EQ:
4094 case BO_NE:
4095 return Opc;
4096 }
4097 }
4098
4099 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
4100 bool isLogicalOp() const { return isLogicalOp(Opc: getOpcode()); }
4101
4102 static bool isAssignmentOp(Opcode Opc) {
4103 return Opc >= BO_Assign && Opc <= BO_OrAssign;
4104 }
4105 bool isAssignmentOp() const { return isAssignmentOp(Opc: getOpcode()); }
4106
4107 static bool isCompoundAssignmentOp(Opcode Opc) {
4108 return Opc > BO_Assign && Opc <= BO_OrAssign;
4109 }
4110 bool isCompoundAssignmentOp() const {
4111 return isCompoundAssignmentOp(Opc: getOpcode());
4112 }
4113 static Opcode getOpForCompoundAssignment(Opcode Opc) {
4114 assert(isCompoundAssignmentOp(Opc));
4115 if (Opc >= BO_AndAssign)
4116 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
4117 else
4118 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
4119 }
4120
4121 static bool isShiftAssignOp(Opcode Opc) {
4122 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
4123 }
4124 bool isShiftAssignOp() const {
4125 return isShiftAssignOp(Opc: getOpcode());
4126 }
4127
4128 /// Return true if a binary operator using the specified opcode and operands
4129 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
4130 /// integer to a pointer.
4131 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
4132 const Expr *LHS,
4133 const Expr *RHS);
4134
4135 static bool classof(const Stmt *S) {
4136 return S->getStmtClass() >= firstBinaryOperatorConstant &&
4137 S->getStmtClass() <= lastBinaryOperatorConstant;
4138 }
4139
4140 // Iterators
4141 child_range children() {
4142 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4143 }
4144 const_child_range children() const {
4145 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4146 }
4147
4148 /// Set and fetch the bit that shows whether FPFeatures needs to be
4149 /// allocated in Trailing Storage
4150 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
4151 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
4152
4153 /// Set and get the bit that informs arithmetic overflow sanitizers whether
4154 /// or not they should exclude certain BinaryOperators from instrumentation
4155 void setExcludedOverflowPattern(bool B) {
4156 BinaryOperatorBits.ExcludedOverflowPattern = B;
4157 }
4158 bool hasExcludedOverflowPattern() const {
4159 return BinaryOperatorBits.ExcludedOverflowPattern;
4160 }
4161
4162 /// Get FPFeatures from trailing storage
4163 FPOptionsOverride getStoredFPFeatures() const {
4164 assert(hasStoredFPFeatures());
4165 return *getTrailingFPFeatures();
4166 }
4167 /// Set FPFeatures in trailing storage, used only by Serialization
4168 void setStoredFPFeatures(FPOptionsOverride F) {
4169 assert(BinaryOperatorBits.HasFPFeatures);
4170 *getTrailingFPFeatures() = F;
4171 }
4172 /// Get the store FPOptionsOverride or default if not stored.
4173 FPOptionsOverride getStoredFPFeaturesOrDefault() const {
4174 return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
4175 }
4176
4177 /// Get the FP features status of this operator. Only meaningful for
4178 /// operations on floating point types.
4179 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4180 if (BinaryOperatorBits.HasFPFeatures)
4181 return getStoredFPFeatures().applyOverrides(LO);
4182 return FPOptions::defaultWithoutTrailingStorage(LO);
4183 }
4184
4185 // This is used in ASTImporter
4186 FPOptionsOverride getFPFeatures() const {
4187 if (BinaryOperatorBits.HasFPFeatures)
4188 return getStoredFPFeatures();
4189 return FPOptionsOverride();
4190 }
4191
4192 /// Get the FP contractibility status of this operator. Only meaningful for
4193 /// operations on floating point types.
4194 bool isFPContractableWithinStatement(const LangOptions &LO) const {
4195 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4196 }
4197
4198 /// Get the FENV_ACCESS status of this operator. Only meaningful for
4199 /// operations on floating point types.
4200 bool isFEnvAccessOn(const LangOptions &LO) const {
4201 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4202 }
4203
4204protected:
4205 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4206 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4207 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4208 bool dead2);
4209
4210 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4211 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4212 BinaryOperatorBits.Opc = BO_MulAssign;
4213 }
4214
4215 /// Return the size in bytes needed for the trailing objects.
4216 /// Used to allocate the right amount of storage.
4217 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4218 return HasFPFeatures * sizeof(FPOptionsOverride);
4219 }
4220};
4221
4222/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4223/// track of the type the operation is performed in. Due to the semantics of
4224/// these operators, the operands are promoted, the arithmetic performed, an
4225/// implicit conversion back to the result type done, then the assignment takes
4226/// place. This captures the intermediate type which the computation is done
4227/// in.
4228class CompoundAssignOperator : public BinaryOperator {
4229 QualType ComputationLHSType;
4230 QualType ComputationResultType;
4231
4232 /// Construct an empty CompoundAssignOperator.
4233 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4234 bool hasFPFeatures)
4235 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4236
4237protected:
4238 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4239 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4240 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4241 QualType CompLHSType, QualType CompResultType)
4242 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4243 true),
4244 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4245 assert(isCompoundAssignmentOp() &&
4246 "Only should be used for compound assignments");
4247 }
4248
4249public:
4250 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4251 bool hasFPFeatures);
4252
4253 static CompoundAssignOperator *
4254 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4255 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4256 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4257 QualType CompResultType = QualType());
4258
4259 // The two computation types are the type the LHS is converted
4260 // to for the computation and the type of the result; the two are
4261 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4262 QualType getComputationLHSType() const { return ComputationLHSType; }
4263 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4264
4265 QualType getComputationResultType() const { return ComputationResultType; }
4266 void setComputationResultType(QualType T) { ComputationResultType = T; }
4267
4268 static bool classof(const Stmt *S) {
4269 return S->getStmtClass() == CompoundAssignOperatorClass;
4270 }
4271};
4272
4273inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4274 assert(BinaryOperatorBits.HasFPFeatures);
4275 return isa<CompoundAssignOperator>(Val: this) ? sizeof(CompoundAssignOperator)
4276 : sizeof(BinaryOperator);
4277}
4278
4279/// AbstractConditionalOperator - An abstract base class for
4280/// ConditionalOperator and BinaryConditionalOperator.
4281class AbstractConditionalOperator : public Expr {
4282 SourceLocation QuestionLoc, ColonLoc;
4283 friend class ASTStmtReader;
4284
4285protected:
4286 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4287 ExprObjectKind OK, SourceLocation qloc,
4288 SourceLocation cloc)
4289 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4290
4291 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4292 : Expr(SC, Empty) { }
4293
4294public:
4295 /// getCond - Return the expression representing the condition for
4296 /// the ?: operator.
4297 Expr *getCond() const;
4298
4299 /// getTrueExpr - Return the subexpression representing the value of
4300 /// the expression if the condition evaluates to true.
4301 Expr *getTrueExpr() const;
4302
4303 /// getFalseExpr - Return the subexpression representing the value of
4304 /// the expression if the condition evaluates to false. This is
4305 /// the same as getRHS.
4306 Expr *getFalseExpr() const;
4307
4308 SourceLocation getQuestionLoc() const { return QuestionLoc; }
4309 SourceLocation getColonLoc() const { return ColonLoc; }
4310
4311 static bool classof(const Stmt *T) {
4312 return T->getStmtClass() == ConditionalOperatorClass ||
4313 T->getStmtClass() == BinaryConditionalOperatorClass;
4314 }
4315};
4316
4317/// ConditionalOperator - The ?: ternary operator. The GNU "missing
4318/// middle" extension is a BinaryConditionalOperator.
4319class ConditionalOperator : public AbstractConditionalOperator {
4320 enum { COND, LHS, RHS, END_EXPR };
4321 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4322
4323 friend class ASTStmtReader;
4324public:
4325 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4326 SourceLocation CLoc, Expr *rhs, QualType t,
4327 ExprValueKind VK, ExprObjectKind OK)
4328 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4329 CLoc) {
4330 SubExprs[COND] = cond;
4331 SubExprs[LHS] = lhs;
4332 SubExprs[RHS] = rhs;
4333 setDependence(computeDependence(E: this));
4334 }
4335
4336 /// Build an empty conditional operator.
4337 explicit ConditionalOperator(EmptyShell Empty)
4338 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4339
4340 /// getCond - Return the expression representing the condition for
4341 /// the ?: operator.
4342 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4343
4344 /// getTrueExpr - Return the subexpression representing the value of
4345 /// the expression if the condition evaluates to true.
4346 Expr *getTrueExpr() const { return cast<Expr>(Val: SubExprs[LHS]); }
4347
4348 /// getFalseExpr - Return the subexpression representing the value of
4349 /// the expression if the condition evaluates to false. This is
4350 /// the same as getRHS.
4351 Expr *getFalseExpr() const { return cast<Expr>(Val: SubExprs[RHS]); }
4352
4353 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
4354 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
4355
4356 SourceLocation getBeginLoc() const LLVM_READONLY {
4357 return getCond()->getBeginLoc();
4358 }
4359 SourceLocation getEndLoc() const LLVM_READONLY {
4360 return getRHS()->getEndLoc();
4361 }
4362
4363 static bool classof(const Stmt *T) {
4364 return T->getStmtClass() == ConditionalOperatorClass;
4365 }
4366
4367 // Iterators
4368 child_range children() {
4369 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4370 }
4371 const_child_range children() const {
4372 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4373 }
4374};
4375
4376/// BinaryConditionalOperator - The GNU extension to the conditional
4377/// operator which allows the middle operand to be omitted.
4378///
4379/// This is a different expression kind on the assumption that almost
4380/// every client ends up needing to know that these are different.
4381class BinaryConditionalOperator : public AbstractConditionalOperator {
4382 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4383
4384 /// - the common condition/left-hand-side expression, which will be
4385 /// evaluated as the opaque value
4386 /// - the condition, expressed in terms of the opaque value
4387 /// - the left-hand-side, expressed in terms of the opaque value
4388 /// - the right-hand-side
4389 Stmt *SubExprs[NUM_SUBEXPRS];
4390 OpaqueValueExpr *OpaqueValue;
4391
4392 friend class ASTStmtReader;
4393public:
4394 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4395 Expr *cond, Expr *lhs, Expr *rhs,
4396 SourceLocation qloc, SourceLocation cloc,
4397 QualType t, ExprValueKind VK, ExprObjectKind OK)
4398 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4399 qloc, cloc),
4400 OpaqueValue(opaqueValue) {
4401 SubExprs[COMMON] = common;
4402 SubExprs[COND] = cond;
4403 SubExprs[LHS] = lhs;
4404 SubExprs[RHS] = rhs;
4405 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4406 setDependence(computeDependence(E: this));
4407 }
4408
4409 /// Build an empty conditional operator.
4410 explicit BinaryConditionalOperator(EmptyShell Empty)
4411 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4412
4413 /// getCommon - Return the common expression, written to the
4414 /// left of the condition. The opaque value will be bound to the
4415 /// result of this expression.
4416 Expr *getCommon() const { return cast<Expr>(Val: SubExprs[COMMON]); }
4417
4418 /// getOpaqueValue - Return the opaque value placeholder.
4419 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4420
4421 /// getCond - Return the condition expression; this is defined
4422 /// in terms of the opaque value.
4423 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4424
4425 /// getTrueExpr - Return the subexpression which will be
4426 /// evaluated if the condition evaluates to true; this is defined
4427 /// in terms of the opaque value.
4428 Expr *getTrueExpr() const {
4429 return cast<Expr>(Val: SubExprs[LHS]);
4430 }
4431
4432 /// getFalseExpr - Return the subexpression which will be
4433 /// evaluated if the condition evaluates to false; this is
4434 /// defined in terms of the opaque value.
4435 Expr *getFalseExpr() const {
4436 return cast<Expr>(Val: SubExprs[RHS]);
4437 }
4438
4439 SourceLocation getBeginLoc() const LLVM_READONLY {
4440 return getCommon()->getBeginLoc();
4441 }
4442 SourceLocation getEndLoc() const LLVM_READONLY {
4443 return getFalseExpr()->getEndLoc();
4444 }
4445
4446 static bool classof(const Stmt *T) {
4447 return T->getStmtClass() == BinaryConditionalOperatorClass;
4448 }
4449
4450 // Iterators
4451 child_range children() {
4452 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4453 }
4454 const_child_range children() const {
4455 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4456 }
4457};
4458
4459inline Expr *AbstractConditionalOperator::getCond() const {
4460 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4461 return co->getCond();
4462 return cast<BinaryConditionalOperator>(Val: this)->getCond();
4463}
4464
4465inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4466 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4467 return co->getTrueExpr();
4468 return cast<BinaryConditionalOperator>(Val: this)->getTrueExpr();
4469}
4470
4471inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4472 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4473 return co->getFalseExpr();
4474 return cast<BinaryConditionalOperator>(Val: this)->getFalseExpr();
4475}
4476
4477/// AddrLabelExpr - The GNU address of label extension, representing &&label.
4478class AddrLabelExpr : public Expr {
4479 SourceLocation AmpAmpLoc, LabelLoc;
4480 LabelDecl *Label;
4481public:
4482 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4483 QualType t)
4484 : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4485 LabelLoc(LLoc), Label(L) {
4486 setDependence(ExprDependence::None);
4487 }
4488
4489 /// Build an empty address of a label expression.
4490 explicit AddrLabelExpr(EmptyShell Empty)
4491 : Expr(AddrLabelExprClass, Empty) { }
4492
4493 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
4494 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
4495 SourceLocation getLabelLoc() const { return LabelLoc; }
4496 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4497
4498 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
4499 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4500
4501 LabelDecl *getLabel() const { return Label; }
4502 void setLabel(LabelDecl *L) { Label = L; }
4503
4504 static bool classof(const Stmt *T) {
4505 return T->getStmtClass() == AddrLabelExprClass;
4506 }
4507
4508 // Iterators
4509 child_range children() {
4510 return child_range(child_iterator(), child_iterator());
4511 }
4512 const_child_range children() const {
4513 return const_child_range(const_child_iterator(), const_child_iterator());
4514 }
4515};
4516
4517/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4518/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4519/// takes the value of the last subexpression.
4520///
4521/// A StmtExpr is always an r-value; values "returned" out of a
4522/// StmtExpr will be copied.
4523class StmtExpr : public Expr {
4524 Stmt *SubStmt;
4525 SourceLocation LParenLoc, RParenLoc;
4526public:
4527 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4528 SourceLocation RParenLoc, unsigned TemplateDepth)
4529 : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4530 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4531 setDependence(computeDependence(E: this, TemplateDepth));
4532 // FIXME: A templated statement expression should have an associated
4533 // DeclContext so that nested declarations always have a dependent context.
4534 StmtExprBits.TemplateDepth = TemplateDepth;
4535 }
4536
4537 /// Build an empty statement expression.
4538 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4539
4540 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(Val: SubStmt); }
4541 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(Val: SubStmt); }
4542 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4543
4544 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4545 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4546
4547 SourceLocation getLParenLoc() const { return LParenLoc; }
4548 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
4549 SourceLocation getRParenLoc() const { return RParenLoc; }
4550 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4551
4552 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4553
4554 static bool classof(const Stmt *T) {
4555 return T->getStmtClass() == StmtExprClass;
4556 }
4557
4558 // Iterators
4559 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
4560 const_child_range children() const {
4561 return const_child_range(&SubStmt, &SubStmt + 1);
4562 }
4563};
4564
4565/// ShuffleVectorExpr - clang-specific builtin-in function
4566/// __builtin_shufflevector.
4567/// This AST node represents a operator that does a constant
4568/// shuffle, similar to LLVM's shufflevector instruction. It takes
4569/// two vectors and a variable number of constant indices,
4570/// and returns the appropriately shuffled vector.
4571class ShuffleVectorExpr : public Expr {
4572 SourceLocation BuiltinLoc, RParenLoc;
4573
4574 // SubExprs - the list of values passed to the __builtin_shufflevector
4575 // function. The first two are vectors, and the rest are constant
4576 // indices. The number of values in this list is always
4577 // 2+the number of indices in the vector type.
4578 Stmt **SubExprs;
4579
4580public:
4581 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4582 SourceLocation BLoc, SourceLocation RP);
4583
4584 /// Build an empty vector-shuffle expression.
4585 explicit ShuffleVectorExpr(EmptyShell Empty)
4586 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4587
4588 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4589 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4590
4591 SourceLocation getRParenLoc() const { return RParenLoc; }
4592 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4593
4594 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4595 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4596
4597 static bool classof(const Stmt *T) {
4598 return T->getStmtClass() == ShuffleVectorExprClass;
4599 }
4600
4601 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4602 /// constant expression, the actual arguments passed in, and the function
4603 /// pointers.
4604 unsigned getNumSubExprs() const { return ShuffleVectorExprBits.NumExprs; }
4605
4606 /// Retrieve the array of expressions.
4607 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4608
4609 /// getExpr - Return the Expr at the specified index.
4610 Expr *getExpr(unsigned Index) {
4611 assert((Index < ShuffleVectorExprBits.NumExprs) &&
4612 "Arg access out of range!");
4613 return cast<Expr>(Val: SubExprs[Index]);
4614 }
4615 const Expr *getExpr(unsigned Index) const {
4616 assert((Index < ShuffleVectorExprBits.NumExprs) &&
4617 "Arg access out of range!");
4618 return cast<Expr>(Val: SubExprs[Index]);
4619 }
4620
4621 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4622
4623 llvm::APSInt getShuffleMaskIdx(unsigned N) const {
4624 assert((N < ShuffleVectorExprBits.NumExprs - 2) &&
4625 "Shuffle idx out of range!");
4626 assert(isa<ConstantExpr>(getExpr(N + 2)) &&
4627 "Index expression must be a ConstantExpr");
4628 return cast<ConstantExpr>(Val: getExpr(Index: N + 2))->getAPValueResult().getInt();
4629 }
4630
4631 // Iterators
4632 child_range children() {
4633 return child_range(&SubExprs[0],
4634 &SubExprs[0] + ShuffleVectorExprBits.NumExprs);
4635 }
4636 const_child_range children() const {
4637 return const_child_range(&SubExprs[0],
4638 &SubExprs[0] + ShuffleVectorExprBits.NumExprs);
4639 }
4640};
4641
4642/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4643/// This AST node provides support for converting a vector type to another
4644/// vector type of the same arity.
4645class ConvertVectorExpr final
4646 : public Expr,
4647 private llvm::TrailingObjects<ConvertVectorExpr, FPOptionsOverride> {
4648private:
4649 Stmt *SrcExpr;
4650 TypeSourceInfo *TInfo;
4651 SourceLocation BuiltinLoc, RParenLoc;
4652
4653 friend TrailingObjects;
4654 friend class ASTReader;
4655 friend class ASTStmtReader;
4656 explicit ConvertVectorExpr(bool HasFPFeatures, EmptyShell Empty)
4657 : Expr(ConvertVectorExprClass, Empty) {
4658 ConvertVectorExprBits.HasFPFeatures = HasFPFeatures;
4659 }
4660
4661 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4662 ExprValueKind VK, ExprObjectKind OK,
4663 SourceLocation BuiltinLoc, SourceLocation RParenLoc,
4664 FPOptionsOverride FPFeatures)
4665 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4666 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4667 ConvertVectorExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4668 if (hasStoredFPFeatures())
4669 setStoredFPFeatures(FPFeatures);
4670 setDependence(computeDependence(E: this));
4671 }
4672
4673 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
4674 return ConvertVectorExprBits.HasFPFeatures ? 1 : 0;
4675 }
4676
4677 FPOptionsOverride &getTrailingFPFeatures() {
4678 assert(ConvertVectorExprBits.HasFPFeatures);
4679 return *getTrailingObjects();
4680 }
4681
4682 const FPOptionsOverride &getTrailingFPFeatures() const {
4683 assert(ConvertVectorExprBits.HasFPFeatures);
4684 return *getTrailingObjects();
4685 }
4686
4687public:
4688 static ConvertVectorExpr *CreateEmpty(const ASTContext &C,
4689 bool hasFPFeatures);
4690
4691 static ConvertVectorExpr *Create(const ASTContext &C, Expr *SrcExpr,
4692 TypeSourceInfo *TI, QualType DstType,
4693 ExprValueKind VK, ExprObjectKind OK,
4694 SourceLocation BuiltinLoc,
4695 SourceLocation RParenLoc,
4696 FPOptionsOverride FPFeatures);
4697
4698 /// Get the FP contractibility status of this operator. Only meaningful for
4699 /// operations on floating point types.
4700 bool isFPContractableWithinStatement(const LangOptions &LO) const {
4701 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4702 }
4703
4704 /// Is FPFeatures in Trailing Storage?
4705 bool hasStoredFPFeatures() const {
4706 return ConvertVectorExprBits.HasFPFeatures;
4707 }
4708
4709 /// Get FPFeatures from trailing storage.
4710 FPOptionsOverride getStoredFPFeatures() const {
4711 return getTrailingFPFeatures();
4712 }
4713
4714 /// Get the store FPOptionsOverride or default if not stored.
4715 FPOptionsOverride getStoredFPFeaturesOrDefault() const {
4716 return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
4717 }
4718
4719 /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
4720 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
4721
4722 /// Get the FP features status of this operator. Only meaningful for
4723 /// operations on floating point types.
4724 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4725 if (ConvertVectorExprBits.HasFPFeatures)
4726 return getStoredFPFeatures().applyOverrides(LO);
4727 return FPOptions::defaultWithoutTrailingStorage(LO);
4728 }
4729
4730 FPOptionsOverride getFPOptionsOverride() const {
4731 if (ConvertVectorExprBits.HasFPFeatures)
4732 return getStoredFPFeatures();
4733 return FPOptionsOverride();
4734 }
4735
4736 /// getSrcExpr - Return the Expr to be converted.
4737 Expr *getSrcExpr() const { return cast<Expr>(Val: SrcExpr); }
4738
4739 /// getTypeSourceInfo - Return the destination type.
4740 TypeSourceInfo *getTypeSourceInfo() const {
4741 return TInfo;
4742 }
4743 void setTypeSourceInfo(TypeSourceInfo *ti) {
4744 TInfo = ti;
4745 }
4746
4747 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4748 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4749
4750 /// getRParenLoc - Return the location of final right parenthesis.
4751 SourceLocation getRParenLoc() const { return RParenLoc; }
4752
4753 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4754 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4755
4756 static bool classof(const Stmt *T) {
4757 return T->getStmtClass() == ConvertVectorExprClass;
4758 }
4759
4760 // Iterators
4761 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4762 const_child_range children() const {
4763 return const_child_range(&SrcExpr, &SrcExpr + 1);
4764 }
4765};
4766
4767/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4768/// This AST node is similar to the conditional operator (?:) in C, with
4769/// the following exceptions:
4770/// - the test expression must be a integer constant expression.
4771/// - the expression returned acts like the chosen subexpression in every
4772/// visible way: the type is the same as that of the chosen subexpression,
4773/// and all predicates (whether it's an l-value, whether it's an integer
4774/// constant expression, etc.) return the same result as for the chosen
4775/// sub-expression.
4776class ChooseExpr : public Expr {
4777 enum { COND, LHS, RHS, END_EXPR };
4778 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4779 SourceLocation BuiltinLoc, RParenLoc;
4780
4781public:
4782 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4783 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4784 bool condIsTrue)
4785 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP) {
4786 ChooseExprBits.CondIsTrue = condIsTrue;
4787 SubExprs[COND] = cond;
4788 SubExprs[LHS] = lhs;
4789 SubExprs[RHS] = rhs;
4790
4791 setDependence(computeDependence(E: this));
4792 }
4793
4794 /// Build an empty __builtin_choose_expr.
4795 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4796
4797 /// isConditionTrue - Return whether the condition is true (i.e. not
4798 /// equal to zero).
4799 bool isConditionTrue() const {
4800 assert(!isConditionDependent() &&
4801 "Dependent condition isn't true or false");
4802 return ChooseExprBits.CondIsTrue;
4803 }
4804 void setIsConditionTrue(bool isTrue) { ChooseExprBits.CondIsTrue = isTrue; }
4805
4806 bool isConditionDependent() const {
4807 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4808 }
4809
4810 /// getChosenSubExpr - Return the subexpression chosen according to the
4811 /// condition.
4812 Expr *getChosenSubExpr() const {
4813 return isConditionTrue() ? getLHS() : getRHS();
4814 }
4815
4816 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4817 void setCond(Expr *E) { SubExprs[COND] = E; }
4818 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
4819 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4820 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
4821 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4822
4823 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4824 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4825
4826 SourceLocation getRParenLoc() const { return RParenLoc; }
4827 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4828
4829 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4830 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4831
4832 static bool classof(const Stmt *T) {
4833 return T->getStmtClass() == ChooseExprClass;
4834 }
4835
4836 // Iterators
4837 child_range children() {
4838 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4839 }
4840 const_child_range children() const {
4841 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4842 }
4843};
4844
4845/// GNUNullExpr - Implements the GNU __null extension, which is a name
4846/// for a null pointer constant that has integral type (e.g., int or
4847/// long) and is the same size and alignment as a pointer. The __null
4848/// extension is typically only used by system headers, which define
4849/// NULL as __null in C++ rather than using 0 (which is an integer
4850/// that may not match the size of a pointer).
4851class GNUNullExpr : public Expr {
4852 /// TokenLoc - The location of the __null keyword.
4853 SourceLocation TokenLoc;
4854
4855public:
4856 GNUNullExpr(QualType Ty, SourceLocation Loc)
4857 : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4858 setDependence(ExprDependence::None);
4859 }
4860
4861 /// Build an empty GNU __null expression.
4862 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4863
4864 /// getTokenLocation - The location of the __null token.
4865 SourceLocation getTokenLocation() const { return TokenLoc; }
4866 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4867
4868 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
4869 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4870
4871 static bool classof(const Stmt *T) {
4872 return T->getStmtClass() == GNUNullExprClass;
4873 }
4874
4875 // Iterators
4876 child_range children() {
4877 return child_range(child_iterator(), child_iterator());
4878 }
4879 const_child_range children() const {
4880 return const_child_range(const_child_iterator(), const_child_iterator());
4881 }
4882};
4883
4884/// Represents a call to the builtin function \c __builtin_va_arg.
4885class VAArgExpr : public Expr {
4886 Stmt *Val;
4887 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4888 SourceLocation BuiltinLoc, RParenLoc;
4889public:
4890 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4891 SourceLocation RPLoc, QualType t, bool IsMS)
4892 : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4893 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4894 setDependence(computeDependence(E: this));
4895 }
4896
4897 /// Create an empty __builtin_va_arg expression.
4898 explicit VAArgExpr(EmptyShell Empty)
4899 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4900
4901 const Expr *getSubExpr() const { return cast<Expr>(Val); }
4902 Expr *getSubExpr() { return cast<Expr>(Val); }
4903 void setSubExpr(Expr *E) { Val = E; }
4904
4905 /// Returns whether this is really a Win64 ABI va_arg expression.
4906 bool isMicrosoftABI() const { return TInfo.getInt(); }
4907 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4908
4909 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4910 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4911
4912 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4913 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4914
4915 SourceLocation getRParenLoc() const { return RParenLoc; }
4916 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4917
4918 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4919 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4920
4921 static bool classof(const Stmt *T) {
4922 return T->getStmtClass() == VAArgExprClass;
4923 }
4924
4925 // Iterators
4926 child_range children() { return child_range(&Val, &Val+1); }
4927 const_child_range children() const {
4928 return const_child_range(&Val, &Val + 1);
4929 }
4930};
4931
4932enum class SourceLocIdentKind {
4933 Function,
4934 FuncSig,
4935 File,
4936 FileName,
4937 Line,
4938 Column,
4939 SourceLocStruct
4940};
4941
4942/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4943/// __builtin_FUNCTION(), __builtin_FUNCSIG(), __builtin_FILE(),
4944/// __builtin_FILE_NAME() or __builtin_source_location().
4945class SourceLocExpr final : public Expr {
4946 SourceLocation BuiltinLoc, RParenLoc;
4947 DeclContext *ParentContext;
4948
4949public:
4950 SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Type,
4951 QualType ResultTy, SourceLocation BLoc,
4952 SourceLocation RParenLoc, DeclContext *Context);
4953
4954 /// Build an empty call expression.
4955 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4956
4957 /// Return the result of evaluating this SourceLocExpr in the specified
4958 /// (and possibly null) default argument or initialization context.
4959 APValue EvaluateInContext(const ASTContext &Ctx,
4960 const Expr *DefaultExpr) const;
4961
4962 /// Return a string representing the name of the specific builtin function.
4963 StringRef getBuiltinStr() const;
4964
4965 SourceLocIdentKind getIdentKind() const {
4966 return static_cast<SourceLocIdentKind>(SourceLocExprBits.Kind);
4967 }
4968
4969 bool isIntType() const {
4970 switch (getIdentKind()) {
4971 case SourceLocIdentKind::File:
4972 case SourceLocIdentKind::FileName:
4973 case SourceLocIdentKind::Function:
4974 case SourceLocIdentKind::FuncSig:
4975 case SourceLocIdentKind::SourceLocStruct:
4976 return false;
4977 case SourceLocIdentKind::Line:
4978 case SourceLocIdentKind::Column:
4979 return true;
4980 }
4981 llvm_unreachable("unknown source location expression kind");
4982 }
4983
4984 /// If the SourceLocExpr has been resolved return the subexpression
4985 /// representing the resolved value. Otherwise return null.
4986 const DeclContext *getParentContext() const { return ParentContext; }
4987 DeclContext *getParentContext() { return ParentContext; }
4988
4989 SourceLocation getLocation() const { return BuiltinLoc; }
4990 SourceLocation getBeginLoc() const { return BuiltinLoc; }
4991 SourceLocation getEndLoc() const { return RParenLoc; }
4992
4993 child_range children() {
4994 return child_range(child_iterator(), child_iterator());
4995 }
4996
4997 const_child_range children() const {
4998 return const_child_range(child_iterator(), child_iterator());
4999 }
5000
5001 static bool classof(const Stmt *T) {
5002 return T->getStmtClass() == SourceLocExprClass;
5003 }
5004
5005 static bool MayBeDependent(SourceLocIdentKind Kind) {
5006 switch (Kind) {
5007 case SourceLocIdentKind::Function:
5008 case SourceLocIdentKind::FuncSig:
5009 case SourceLocIdentKind::SourceLocStruct:
5010 return true;
5011 default:
5012 return false;
5013 }
5014 }
5015
5016private:
5017 friend class ASTStmtReader;
5018};
5019
5020/// Stores data related to a single #embed directive.
5021struct EmbedDataStorage {
5022 StringLiteral *BinaryData;
5023 // FileName string already includes braces, i.e. it is <files/my_file> for a
5024 // directive #embed <files/my_file>.
5025 StringRef FileName;
5026 size_t getDataElementCount() const { return BinaryData->getByteLength(); }
5027};
5028
5029/// Represents a reference to #emded data. By default, this references the whole
5030/// range. Otherwise it represents a subrange of data imported by #embed
5031/// directive. Needed to handle nested initializer lists with #embed directives.
5032/// Example:
5033/// struct S {
5034/// int x, y;
5035/// };
5036///
5037/// struct T {
5038/// int x[2];
5039/// struct S s
5040/// };
5041///
5042/// struct T t[] = {
5043/// #embed "data" // data contains 10 elements;
5044/// };
5045///
5046/// The resulting semantic form of initializer list will contain (EE stands
5047/// for EmbedExpr):
5048/// { {EE(first two data elements), {EE(3rd element), EE(4th element) }},
5049/// { {EE(5th and 6th element), {EE(7th element), EE(8th element) }},
5050/// { {EE(9th and 10th element), { zeroinitializer }}}
5051///
5052/// EmbedExpr inside of a semantic initializer list and referencing more than
5053/// one element can only appear for arrays of scalars.
5054class EmbedExpr final : public Expr {
5055 SourceLocation EmbedKeywordLoc;
5056 IntegerLiteral *FakeChildNode = nullptr;
5057 const ASTContext *Ctx = nullptr;
5058 EmbedDataStorage *Data;
5059 unsigned Begin = 0;
5060 unsigned NumOfElements;
5061
5062public:
5063 EmbedExpr(const ASTContext &Ctx, SourceLocation Loc, EmbedDataStorage *Data,
5064 unsigned Begin, unsigned NumOfElements);
5065 explicit EmbedExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
5066
5067 SourceLocation getLocation() const { return EmbedKeywordLoc; }
5068 SourceLocation getBeginLoc() const { return EmbedKeywordLoc; }
5069 SourceLocation getEndLoc() const { return EmbedKeywordLoc; }
5070
5071 StringLiteral *getDataStringLiteral() const { return Data->BinaryData; }
5072 StringRef getFileName() const { return Data->FileName; }
5073 EmbedDataStorage *getData() const { return Data; }
5074
5075 unsigned getStartingElementPos() const { return Begin; }
5076 size_t getDataElementCount() const { return NumOfElements; }
5077
5078 // Allows accessing every byte of EmbedExpr data and iterating over it.
5079 // An Iterator knows the EmbedExpr that it refers to, and an offset value
5080 // within the data.
5081 // Dereferencing an Iterator results in construction of IntegerLiteral AST
5082 // node filled with byte of data of the corresponding EmbedExpr within offset
5083 // that the Iterator currently has.
5084 template <bool Const>
5085 class ChildElementIter
5086 : public llvm::iterator_facade_base<
5087 ChildElementIter<Const>, std::random_access_iterator_tag,
5088 std::conditional_t<Const, const IntegerLiteral *,
5089 IntegerLiteral *>> {
5090 friend class EmbedExpr;
5091
5092 EmbedExpr *EExpr = nullptr;
5093 unsigned long long CurOffset = ULLONG_MAX;
5094 using BaseTy = typename ChildElementIter::iterator_facade_base;
5095
5096 ChildElementIter(EmbedExpr *E) : EExpr(E) {
5097 if (E)
5098 CurOffset = E->getStartingElementPos();
5099 }
5100
5101 public:
5102 ChildElementIter() : CurOffset(ULLONG_MAX) {}
5103 typename BaseTy::reference operator*() const {
5104 assert(EExpr && CurOffset != ULLONG_MAX &&
5105 "trying to dereference an invalid iterator");
5106 IntegerLiteral *N = EExpr->FakeChildNode;
5107 N->setValue(C: *EExpr->Ctx,
5108 Val: llvm::APInt(N->getValue().getBitWidth(),
5109 EExpr->Data->BinaryData->getCodeUnit(i: CurOffset),
5110 N->getType()->isSignedIntegerType()));
5111 // We want to return a reference to the fake child node in the
5112 // EmbedExpr, not the local variable N.
5113 return const_cast<typename BaseTy::reference>(EExpr->FakeChildNode);
5114 }
5115 typename BaseTy::pointer operator->() const { return **this; }
5116 using BaseTy::operator++;
5117 ChildElementIter &operator++() {
5118 assert(EExpr && "trying to increment an invalid iterator");
5119 assert(CurOffset != ULLONG_MAX &&
5120 "Already at the end of what we can iterate over");
5121 if (++CurOffset >=
5122 EExpr->getDataElementCount() + EExpr->getStartingElementPos()) {
5123 CurOffset = ULLONG_MAX;
5124 EExpr = nullptr;
5125 }
5126 return *this;
5127 }
5128 bool operator==(ChildElementIter Other) const {
5129 return (EExpr == Other.EExpr && CurOffset == Other.CurOffset);
5130 }
5131 }; // class ChildElementIter
5132
5133public:
5134 using fake_child_range = llvm::iterator_range<ChildElementIter<false>>;
5135 using const_fake_child_range = llvm::iterator_range<ChildElementIter<true>>;
5136
5137 fake_child_range underlying_data_elements() {
5138 return fake_child_range(ChildElementIter<false>(this),
5139 ChildElementIter<false>());
5140 }
5141
5142 const_fake_child_range underlying_data_elements() const {
5143 return const_fake_child_range(
5144 ChildElementIter<true>(const_cast<EmbedExpr *>(this)),
5145 ChildElementIter<true>());
5146 }
5147
5148 child_range children() {
5149 return child_range(child_iterator(), child_iterator());
5150 }
5151
5152 const_child_range children() const {
5153 return const_child_range(const_child_iterator(), const_child_iterator());
5154 }
5155
5156 static bool classof(const Stmt *T) {
5157 return T->getStmtClass() == EmbedExprClass;
5158 }
5159
5160 ChildElementIter<false> begin() { return ChildElementIter<false>(this); }
5161
5162 ChildElementIter<true> begin() const {
5163 return ChildElementIter<true>(const_cast<EmbedExpr *>(this));
5164 }
5165
5166 template <typename Call, typename... Targs>
5167 bool doForEachDataElement(Call &&C, unsigned &StartingIndexInArray,
5168 Targs &&...Fargs) const {
5169 for (auto It : underlying_data_elements()) {
5170 if (!std::invoke(std::forward<Call>(C), const_cast<IntegerLiteral *>(It),
5171 StartingIndexInArray, std::forward<Targs>(Fargs)...))
5172 return false;
5173 StartingIndexInArray++;
5174 }
5175 return true;
5176 }
5177
5178private:
5179 friend class ASTStmtReader;
5180};
5181
5182/// Describes an C or C++ initializer list.
5183///
5184/// InitListExpr describes an initializer list, which can be used to
5185/// initialize objects of different types, including
5186/// struct/class/union types, arrays, and vectors. For example:
5187///
5188/// @code
5189/// struct foo x = { 1, { 2, 3 } };
5190/// @endcode
5191///
5192/// Prior to semantic analysis, an initializer list will represent the
5193/// initializer list as written by the user, but will have the
5194/// placeholder type "void". This initializer list is called the
5195/// syntactic form of the initializer, and may contain C99 designated
5196/// initializers (represented as DesignatedInitExprs), initializations
5197/// of subobject members without explicit braces, and so on. Clients
5198/// interested in the original syntax of the initializer list should
5199/// use the syntactic form of the initializer list.
5200///
5201/// After semantic analysis, the initializer list will represent the
5202/// semantic form of the initializer, where the initializations of all
5203/// subobjects are made explicit with nested InitListExpr nodes and
5204/// C99 designators have been eliminated by placing the designated
5205/// initializations into the subobject they initialize. Additionally,
5206/// any "holes" in the initialization, where no initializer has been
5207/// specified for a particular subobject, will be replaced with
5208/// implicitly-generated ImplicitValueInitExpr expressions that
5209/// value-initialize the subobjects. Note, however, that the
5210/// initializer lists may still have fewer initializers than there are
5211/// elements to initialize within the object.
5212///
5213/// After semantic analysis has completed, given an initializer list,
5214/// method isSemanticForm() returns true if and only if this is the
5215/// semantic form of the initializer list (note: the same AST node
5216/// may at the same time be the syntactic form).
5217/// Given the semantic form of the initializer list, one can retrieve
5218/// the syntactic form of that initializer list (when different)
5219/// using method getSyntacticForm(); the method returns null if applied
5220/// to a initializer list which is already in syntactic form.
5221/// Similarly, given the syntactic form (i.e., an initializer list such
5222/// that isSemanticForm() returns false), one can retrieve the semantic
5223/// form using method getSemanticForm().
5224/// Since many initializer lists have the same syntactic and semantic forms,
5225/// getSyntacticForm() may return NULL, indicating that the current
5226/// semantic initializer list also serves as its syntactic form.
5227class InitListExpr : public Expr {
5228 // FIXME: Eliminate this vector in favor of ASTContext allocation
5229 typedef ASTVector<Stmt *> InitExprsTy;
5230 InitExprsTy InitExprs;
5231 SourceLocation LBraceLoc, RBraceLoc;
5232
5233 /// The alternative form of the initializer list (if it exists).
5234 /// The int part of the pair stores whether this initializer list is
5235 /// in semantic form. If not null, the pointer points to:
5236 /// - the syntactic form, if this is in semantic form;
5237 /// - the semantic form, if this is in syntactic form.
5238 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
5239
5240 /// Either:
5241 /// If this initializer list initializes an array with more elements than
5242 /// there are initializers in the list, specifies an expression to be used
5243 /// for value initialization of the rest of the elements.
5244 /// Or
5245 /// If this initializer list initializes a union, specifies which
5246 /// field within the union will be initialized.
5247 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
5248
5249public:
5250 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
5251 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
5252
5253 /// Build an empty initializer list.
5254 explicit InitListExpr(EmptyShell Empty)
5255 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
5256
5257 unsigned getNumInits() const { return InitExprs.size(); }
5258
5259 /// getNumInits but if the list has an EmbedExpr inside includes full length
5260 /// of embedded data.
5261 unsigned getNumInitsWithEmbedExpanded() const {
5262 unsigned Sum = InitExprs.size();
5263 for (auto *IE : InitExprs)
5264 if (auto *EE = dyn_cast<EmbedExpr>(Val: IE))
5265 Sum += EE->getDataElementCount() - 1;
5266 return Sum;
5267 }
5268
5269 /// Retrieve the set of initializers.
5270 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
5271
5272 /// Retrieve the set of initializers.
5273 Expr * const *getInits() const {
5274 return reinterpret_cast<Expr * const *>(InitExprs.data());
5275 }
5276
5277 ArrayRef<Expr *> inits() { return {getInits(), getNumInits()}; }
5278
5279 ArrayRef<Expr *> inits() const { return {getInits(), getNumInits()}; }
5280
5281 const Expr *getInit(unsigned Init) const {
5282 assert(Init < getNumInits() && "Initializer access out of range!");
5283 return cast_or_null<Expr>(Val: InitExprs[Init]);
5284 }
5285
5286 Expr *getInit(unsigned Init) {
5287 assert(Init < getNumInits() && "Initializer access out of range!");
5288 return cast_or_null<Expr>(Val: InitExprs[Init]);
5289 }
5290
5291 void setInit(unsigned Init, Expr *expr) {
5292 assert(Init < getNumInits() && "Initializer access out of range!");
5293 InitExprs[Init] = expr;
5294
5295 if (expr)
5296 setDependence(getDependence() | expr->getDependence());
5297 }
5298
5299 /// Mark the semantic form of the InitListExpr as error when the semantic
5300 /// analysis fails.
5301 void markError() {
5302 assert(isSemanticForm());
5303 setDependence(getDependence() | ExprDependence::ErrorDependent);
5304 }
5305
5306 /// Reserve space for some number of initializers.
5307 void reserveInits(const ASTContext &C, unsigned NumInits);
5308
5309 /// Specify the number of initializers
5310 ///
5311 /// If there are more than @p NumInits initializers, the remaining
5312 /// initializers will be destroyed. If there are fewer than @p
5313 /// NumInits initializers, NULL expressions will be added for the
5314 /// unknown initializers.
5315 void resizeInits(const ASTContext &Context, unsigned NumInits);
5316
5317 /// Updates the initializer at index @p Init with the new
5318 /// expression @p expr, and returns the old expression at that
5319 /// location.
5320 ///
5321 /// When @p Init is out of range for this initializer list, the
5322 /// initializer list will be extended with NULL expressions to
5323 /// accommodate the new entry.
5324 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
5325
5326 /// If this initializer list initializes an array with more elements
5327 /// than there are initializers in the list, specifies an expression to be
5328 /// used for value initialization of the rest of the elements.
5329 Expr *getArrayFiller() {
5330 return dyn_cast_if_present<Expr *>(Val&: ArrayFillerOrUnionFieldInit);
5331 }
5332 const Expr *getArrayFiller() const {
5333 return const_cast<InitListExpr *>(this)->getArrayFiller();
5334 }
5335 void setArrayFiller(Expr *filler);
5336
5337 /// Return true if this is an array initializer and its array "filler"
5338 /// has been set.
5339 bool hasArrayFiller() const { return getArrayFiller(); }
5340
5341 /// Determine whether this initializer list contains a designated initializer.
5342 bool hasDesignatedInit() const {
5343 return llvm::any_of(
5344 Range: *this, P: [](const Stmt *S) { return isa<DesignatedInitExpr>(Val: S); });
5345 }
5346
5347 /// If this initializes a union, specifies which field in the
5348 /// union to initialize.
5349 ///
5350 /// Typically, this field is the first named field within the
5351 /// union. However, a designated initializer can specify the
5352 /// initialization of a different field within the union.
5353 FieldDecl *getInitializedFieldInUnion() {
5354 return dyn_cast_if_present<FieldDecl *>(Val&: ArrayFillerOrUnionFieldInit);
5355 }
5356 const FieldDecl *getInitializedFieldInUnion() const {
5357 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
5358 }
5359 void setInitializedFieldInUnion(FieldDecl *FD) {
5360 assert((FD == nullptr
5361 || getInitializedFieldInUnion() == nullptr
5362 || getInitializedFieldInUnion() == FD)
5363 && "Only one field of a union may be initialized at a time!");
5364 ArrayFillerOrUnionFieldInit = FD;
5365 }
5366
5367 // Explicit InitListExpr's originate from source code (and have valid source
5368 // locations). Implicit InitListExpr's are created by the semantic analyzer.
5369 // FIXME: This is wrong; InitListExprs created by semantic analysis have
5370 // valid source locations too!
5371 bool isExplicit() const {
5372 return LBraceLoc.isValid() && RBraceLoc.isValid();
5373 }
5374
5375 /// Is this an initializer for an array of characters, initialized by a string
5376 /// literal or an @encode?
5377 bool isStringLiteralInit() const;
5378
5379 /// Is this a transparent initializer list (that is, an InitListExpr that is
5380 /// purely syntactic, and whose semantics are that of the sole contained
5381 /// initializer)?
5382 bool isTransparent() const;
5383
5384 /// Is this the zero initializer {0} in a language which considers it
5385 /// idiomatic?
5386 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
5387
5388 SourceLocation getLBraceLoc() const { return LBraceLoc; }
5389 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
5390 SourceLocation getRBraceLoc() const { return RBraceLoc; }
5391 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
5392
5393 bool isSemanticForm() const { return AltForm.getInt(); }
5394 InitListExpr *getSemanticForm() const {
5395 return isSemanticForm() ? nullptr : AltForm.getPointer();
5396 }
5397 bool isSyntacticForm() const {
5398 return !AltForm.getInt() || !AltForm.getPointer();
5399 }
5400 InitListExpr *getSyntacticForm() const {
5401 return isSemanticForm() ? AltForm.getPointer() : nullptr;
5402 }
5403
5404 void setSyntacticForm(InitListExpr *Init) {
5405 AltForm.setPointer(Init);
5406 AltForm.setInt(true);
5407 Init->AltForm.setPointer(this);
5408 Init->AltForm.setInt(false);
5409 }
5410
5411 bool hadArrayRangeDesignator() const {
5412 return InitListExprBits.HadArrayRangeDesignator != 0;
5413 }
5414 void sawArrayRangeDesignator(bool ARD = true) {
5415 InitListExprBits.HadArrayRangeDesignator = ARD;
5416 }
5417
5418 SourceLocation getBeginLoc() const LLVM_READONLY;
5419 SourceLocation getEndLoc() const LLVM_READONLY;
5420
5421 static bool classof(const Stmt *T) {
5422 return T->getStmtClass() == InitListExprClass;
5423 }
5424
5425 // Iterators
5426 child_range children() {
5427 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
5428 return child_range(cast_away_const(RHS: CCR.begin()),
5429 cast_away_const(RHS: CCR.end()));
5430 }
5431
5432 const_child_range children() const {
5433 // FIXME: This does not include the array filler expression.
5434 if (InitExprs.empty())
5435 return const_child_range(const_child_iterator(), const_child_iterator());
5436 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
5437 }
5438
5439 typedef InitExprsTy::iterator iterator;
5440 typedef InitExprsTy::const_iterator const_iterator;
5441 typedef InitExprsTy::reverse_iterator reverse_iterator;
5442 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
5443
5444 iterator begin() { return InitExprs.begin(); }
5445 const_iterator begin() const { return InitExprs.begin(); }
5446 iterator end() { return InitExprs.end(); }
5447 const_iterator end() const { return InitExprs.end(); }
5448 reverse_iterator rbegin() { return InitExprs.rbegin(); }
5449 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
5450 reverse_iterator rend() { return InitExprs.rend(); }
5451 const_reverse_iterator rend() const { return InitExprs.rend(); }
5452
5453 friend class ASTStmtReader;
5454 friend class ASTStmtWriter;
5455};
5456
5457/// Represents a C99 designated initializer expression.
5458///
5459/// A designated initializer expression (C99 6.7.8) contains one or
5460/// more designators (which can be field designators, array
5461/// designators, or GNU array-range designators) followed by an
5462/// expression that initializes the field or element(s) that the
5463/// designators refer to. For example, given:
5464///
5465/// @code
5466/// struct point {
5467/// double x;
5468/// double y;
5469/// };
5470/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
5471/// @endcode
5472///
5473/// The InitListExpr contains three DesignatedInitExprs, the first of
5474/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
5475/// designators, one array designator for @c [2] followed by one field
5476/// designator for @c .y. The initialization expression will be 1.0.
5477class DesignatedInitExpr final
5478 : public Expr,
5479 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
5480public:
5481 /// Forward declaration of the Designator class.
5482 class Designator;
5483
5484private:
5485 /// The location of the '=' or ':' prior to the actual initializer
5486 /// expression.
5487 SourceLocation EqualOrColonLoc;
5488
5489 /// Whether this designated initializer used the GNU deprecated
5490 /// syntax rather than the C99 '=' syntax.
5491 LLVM_PREFERRED_TYPE(bool)
5492 unsigned GNUSyntax : 1;
5493
5494 /// The number of designators in this initializer expression.
5495 unsigned NumDesignators : 15;
5496
5497 /// The number of subexpressions of this initializer expression,
5498 /// which contains both the initializer and any additional
5499 /// expressions used by array and array-range designators.
5500 unsigned NumSubExprs : 16;
5501
5502 /// The designators in this designated initialization
5503 /// expression.
5504 Designator *Designators;
5505
5506 DesignatedInitExpr(const ASTContext &C, QualType Ty,
5507 ArrayRef<Designator> Designators,
5508 SourceLocation EqualOrColonLoc, bool GNUSyntax,
5509 ArrayRef<Expr *> IndexExprs, Expr *Init);
5510
5511 explicit DesignatedInitExpr(unsigned NumSubExprs)
5512 : Expr(DesignatedInitExprClass, EmptyShell()),
5513 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
5514
5515public:
5516 /// Represents a single C99 designator.
5517 ///
5518 /// @todo This class is infuriatingly similar to clang::Designator,
5519 /// but minor differences (storing indices vs. storing pointers)
5520 /// keep us from reusing it. Try harder, later, to rectify these
5521 /// differences.
5522 class Designator {
5523 /// A field designator, e.g., ".x".
5524 struct FieldDesignatorInfo {
5525 /// Refers to the field that is being initialized. The low bit
5526 /// of this field determines whether this is actually a pointer
5527 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
5528 /// initially constructed, a field designator will store an
5529 /// IdentifierInfo*. After semantic analysis has resolved that
5530 /// name, the field designator will instead store a FieldDecl*.
5531 uintptr_t NameOrField;
5532
5533 /// The location of the '.' in the designated initializer.
5534 SourceLocation DotLoc;
5535
5536 /// The location of the field name in the designated initializer.
5537 SourceLocation FieldLoc;
5538
5539 FieldDesignatorInfo(const IdentifierInfo *II, SourceLocation DotLoc,
5540 SourceLocation FieldLoc)
5541 : NameOrField(reinterpret_cast<uintptr_t>(II) | 0x1), DotLoc(DotLoc),
5542 FieldLoc(FieldLoc) {}
5543 };
5544
5545 /// An array or GNU array-range designator, e.g., "[9]" or "[10...15]".
5546 struct ArrayOrRangeDesignatorInfo {
5547 /// Location of the first index expression within the designated
5548 /// initializer expression's list of subexpressions.
5549 unsigned Index;
5550
5551 /// The location of the '[' starting the array range designator.
5552 SourceLocation LBracketLoc;
5553
5554 /// The location of the ellipsis separating the start and end
5555 /// indices. Only valid for GNU array-range designators.
5556 SourceLocation EllipsisLoc;
5557
5558 /// The location of the ']' terminating the array range designator.
5559 SourceLocation RBracketLoc;
5560
5561 ArrayOrRangeDesignatorInfo(unsigned Index, SourceLocation LBracketLoc,
5562 SourceLocation RBracketLoc)
5563 : Index(Index), LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc) {}
5564
5565 ArrayOrRangeDesignatorInfo(unsigned Index,
5566 SourceLocation LBracketLoc,
5567 SourceLocation EllipsisLoc,
5568 SourceLocation RBracketLoc)
5569 : Index(Index), LBracketLoc(LBracketLoc), EllipsisLoc(EllipsisLoc),
5570 RBracketLoc(RBracketLoc) {}
5571 };
5572
5573 /// The kind of designator this describes.
5574 enum DesignatorKind {
5575 FieldDesignator,
5576 ArrayDesignator,
5577 ArrayRangeDesignator
5578 };
5579
5580 DesignatorKind Kind;
5581
5582 union {
5583 /// A field designator, e.g., ".x".
5584 struct FieldDesignatorInfo FieldInfo;
5585
5586 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5587 struct ArrayOrRangeDesignatorInfo ArrayOrRangeInfo;
5588 };
5589
5590 Designator(DesignatorKind Kind) : Kind(Kind) {}
5591
5592 public:
5593 Designator() {}
5594
5595 bool isFieldDesignator() const { return Kind == FieldDesignator; }
5596 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
5597 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
5598
5599 //===------------------------------------------------------------------===//
5600 // FieldDesignatorInfo
5601
5602 /// Creates a field designator.
5603 static Designator CreateFieldDesignator(const IdentifierInfo *FieldName,
5604 SourceLocation DotLoc,
5605 SourceLocation FieldLoc) {
5606 Designator D(FieldDesignator);
5607 new (&D.FieldInfo) FieldDesignatorInfo(FieldName, DotLoc, FieldLoc);
5608 return D;
5609 }
5610
5611 const IdentifierInfo *getFieldName() const;
5612
5613 FieldDecl *getFieldDecl() const {
5614 assert(isFieldDesignator() && "Only valid on a field designator");
5615 if (FieldInfo.NameOrField & 0x01)
5616 return nullptr;
5617 return reinterpret_cast<FieldDecl *>(FieldInfo.NameOrField);
5618 }
5619
5620 void setFieldDecl(FieldDecl *FD) {
5621 assert(isFieldDesignator() && "Only valid on a field designator");
5622 FieldInfo.NameOrField = reinterpret_cast<uintptr_t>(FD);
5623 }
5624
5625 SourceLocation getDotLoc() const {
5626 assert(isFieldDesignator() && "Only valid on a field designator");
5627 return FieldInfo.DotLoc;
5628 }
5629
5630 SourceLocation getFieldLoc() const {
5631 assert(isFieldDesignator() && "Only valid on a field designator");
5632 return FieldInfo.FieldLoc;
5633 }
5634
5635 //===------------------------------------------------------------------===//
5636 // ArrayOrRangeDesignator
5637
5638 /// Creates an array designator.
5639 static Designator CreateArrayDesignator(unsigned Index,
5640 SourceLocation LBracketLoc,
5641 SourceLocation RBracketLoc) {
5642 Designator D(ArrayDesignator);
5643 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5644 RBracketLoc);
5645 return D;
5646 }
5647
5648 /// Creates a GNU array-range designator.
5649 static Designator CreateArrayRangeDesignator(unsigned Index,
5650 SourceLocation LBracketLoc,
5651 SourceLocation EllipsisLoc,
5652 SourceLocation RBracketLoc) {
5653 Designator D(ArrayRangeDesignator);
5654 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5655 EllipsisLoc,
5656 RBracketLoc);
5657 return D;
5658 }
5659
5660 unsigned getArrayIndex() const {
5661 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5662 "Only valid on an array or array-range designator");
5663 return ArrayOrRangeInfo.Index;
5664 }
5665
5666 SourceLocation getLBracketLoc() const {
5667 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5668 "Only valid on an array or array-range designator");
5669 return ArrayOrRangeInfo.LBracketLoc;
5670 }
5671
5672 SourceLocation getEllipsisLoc() const {
5673 assert(isArrayRangeDesignator() &&
5674 "Only valid on an array-range designator");
5675 return ArrayOrRangeInfo.EllipsisLoc;
5676 }
5677
5678 SourceLocation getRBracketLoc() const {
5679 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5680 "Only valid on an array or array-range designator");
5681 return ArrayOrRangeInfo.RBracketLoc;
5682 }
5683
5684 SourceLocation getBeginLoc() const LLVM_READONLY {
5685 if (isFieldDesignator())
5686 return getDotLoc().isInvalid() ? getFieldLoc() : getDotLoc();
5687 return getLBracketLoc();
5688 }
5689
5690 SourceLocation getEndLoc() const LLVM_READONLY {
5691 return isFieldDesignator() ? getFieldLoc() : getRBracketLoc();
5692 }
5693
5694 SourceRange getSourceRange() const LLVM_READONLY {
5695 return SourceRange(getBeginLoc(), getEndLoc());
5696 }
5697 };
5698
5699 static DesignatedInitExpr *Create(const ASTContext &C,
5700 ArrayRef<Designator> Designators,
5701 ArrayRef<Expr *> IndexExprs,
5702 SourceLocation EqualOrColonLoc,
5703 bool GNUSyntax, Expr *Init);
5704
5705 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
5706 unsigned NumIndexExprs);
5707
5708 /// Returns the number of designators in this initializer.
5709 unsigned size() const { return NumDesignators; }
5710
5711 // Iterator access to the designators.
5712 MutableArrayRef<Designator> designators() {
5713 return {Designators, NumDesignators};
5714 }
5715
5716 ArrayRef<Designator> designators() const {
5717 return {Designators, NumDesignators};
5718 }
5719
5720 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
5721 const Designator *getDesignator(unsigned Idx) const {
5722 return &designators()[Idx];
5723 }
5724
5725 void setDesignators(const ASTContext &C, const Designator *Desigs,
5726 unsigned NumDesigs);
5727
5728 Expr *getArrayIndex(const Designator &D) const;
5729 Expr *getArrayRangeStart(const Designator &D) const;
5730 Expr *getArrayRangeEnd(const Designator &D) const;
5731
5732 /// Retrieve the location of the '=' that precedes the
5733 /// initializer value itself, if present.
5734 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
5735 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
5736
5737 /// Whether this designated initializer should result in direct-initialization
5738 /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
5739 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
5740
5741 /// Determines whether this designated initializer used the
5742 /// deprecated GNU syntax for designated initializers.
5743 bool usesGNUSyntax() const { return GNUSyntax; }
5744 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
5745
5746 /// Retrieve the initializer value.
5747 Expr *getInit() const {
5748 return cast<Expr>(Val: *const_cast<DesignatedInitExpr*>(this)->child_begin());
5749 }
5750
5751 void setInit(Expr *init) {
5752 *child_begin() = init;
5753 }
5754
5755 /// Retrieve the total number of subexpressions in this
5756 /// designated initializer expression, including the actual
5757 /// initialized value and any expressions that occur within array
5758 /// and array-range designators.
5759 unsigned getNumSubExprs() const { return NumSubExprs; }
5760
5761 Expr *getSubExpr(unsigned Idx) const {
5762 return cast<Expr>(Val: getTrailingObjects(N: NumSubExprs)[Idx]);
5763 }
5764
5765 void setSubExpr(unsigned Idx, Expr *E) {
5766 getTrailingObjects(N: NumSubExprs)[Idx] = E;
5767 }
5768
5769 /// Replaces the designator at index @p Idx with the series
5770 /// of designators in [First, Last).
5771 void ExpandDesignator(const ASTContext &C, unsigned Idx,
5772 const Designator *First, const Designator *Last);
5773
5774 SourceRange getDesignatorsSourceRange() const;
5775
5776 SourceLocation getBeginLoc() const LLVM_READONLY;
5777 SourceLocation getEndLoc() const LLVM_READONLY;
5778
5779 static bool classof(const Stmt *T) {
5780 return T->getStmtClass() == DesignatedInitExprClass;
5781 }
5782
5783 // Iterators
5784 child_range children() {
5785 Stmt **begin = getTrailingObjects();
5786 return child_range(begin, begin + NumSubExprs);
5787 }
5788 const_child_range children() const {
5789 Stmt *const *begin = getTrailingObjects();
5790 return const_child_range(begin, begin + NumSubExprs);
5791 }
5792
5793 friend TrailingObjects;
5794};
5795
5796/// Represents a place-holder for an object not to be initialized by
5797/// anything.
5798///
5799/// This only makes sense when it appears as part of an updater of a
5800/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
5801/// initializes a big object, and the NoInitExpr's mark the spots within the
5802/// big object not to be overwritten by the updater.
5803///
5804/// \see DesignatedInitUpdateExpr
5805class NoInitExpr : public Expr {
5806public:
5807 explicit NoInitExpr(QualType ty)
5808 : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5809 setDependence(computeDependence(E: this));
5810 }
5811
5812 explicit NoInitExpr(EmptyShell Empty)
5813 : Expr(NoInitExprClass, Empty) { }
5814
5815 static bool classof(const Stmt *T) {
5816 return T->getStmtClass() == NoInitExprClass;
5817 }
5818
5819 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5820 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5821
5822 // Iterators
5823 child_range children() {
5824 return child_range(child_iterator(), child_iterator());
5825 }
5826 const_child_range children() const {
5827 return const_child_range(const_child_iterator(), const_child_iterator());
5828 }
5829};
5830
5831// In cases like:
5832// struct Q { int a, b, c; };
5833// Q *getQ();
5834// void foo() {
5835// struct A { Q q; } a = { *getQ(), .q.b = 3 };
5836// }
5837//
5838// We will have an InitListExpr for a, with type A, and then a
5839// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
5840// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
5841//
5842class DesignatedInitUpdateExpr : public Expr {
5843 // BaseAndUpdaterExprs[0] is the base expression;
5844 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
5845 Stmt *BaseAndUpdaterExprs[2];
5846
5847public:
5848 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
5849 Expr *baseExprs, SourceLocation rBraceLoc);
5850
5851 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
5852 : Expr(DesignatedInitUpdateExprClass, Empty) { }
5853
5854 SourceLocation getBeginLoc() const LLVM_READONLY;
5855 SourceLocation getEndLoc() const LLVM_READONLY;
5856
5857 static bool classof(const Stmt *T) {
5858 return T->getStmtClass() == DesignatedInitUpdateExprClass;
5859 }
5860
5861 Expr *getBase() const { return cast<Expr>(Val: BaseAndUpdaterExprs[0]); }
5862 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
5863
5864 InitListExpr *getUpdater() const {
5865 return cast<InitListExpr>(Val: BaseAndUpdaterExprs[1]);
5866 }
5867 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
5868
5869 // Iterators
5870 // children = the base and the updater
5871 child_range children() {
5872 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
5873 }
5874 const_child_range children() const {
5875 return const_child_range(&BaseAndUpdaterExprs[0],
5876 &BaseAndUpdaterExprs[0] + 2);
5877 }
5878};
5879
5880/// Represents a loop initializing the elements of an array.
5881///
5882/// The need to initialize the elements of an array occurs in a number of
5883/// contexts:
5884///
5885/// * in the implicit copy/move constructor for a class with an array member
5886/// * when a lambda-expression captures an array by value
5887/// * when a decomposition declaration decomposes an array
5888///
5889/// There are two subexpressions: a common expression (the source array)
5890/// that is evaluated once up-front, and a per-element initializer that
5891/// runs once for each array element.
5892///
5893/// Within the per-element initializer, the common expression may be referenced
5894/// via an OpaqueValueExpr, and the current index may be obtained via an
5895/// ArrayInitIndexExpr.
5896class ArrayInitLoopExpr : public Expr {
5897 Stmt *SubExprs[2];
5898
5899 explicit ArrayInitLoopExpr(EmptyShell Empty)
5900 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5901
5902public:
5903 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5904 : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
5905 SubExprs{CommonInit, ElementInit} {
5906 setDependence(computeDependence(E: this));
5907 }
5908
5909 /// Get the common subexpression shared by all initializations (the source
5910 /// array).
5911 OpaqueValueExpr *getCommonExpr() const {
5912 return cast<OpaqueValueExpr>(Val: SubExprs[0]);
5913 }
5914
5915 /// Get the initializer to use for each array element.
5916 Expr *getSubExpr() const { return cast<Expr>(Val: SubExprs[1]); }
5917
5918 llvm::APInt getArraySize() const {
5919 return cast<ConstantArrayType>(Val: getType()->castAsArrayTypeUnsafe())
5920 ->getSize();
5921 }
5922
5923 static bool classof(const Stmt *S) {
5924 return S->getStmtClass() == ArrayInitLoopExprClass;
5925 }
5926
5927 SourceLocation getBeginLoc() const LLVM_READONLY {
5928 return getCommonExpr()->getBeginLoc();
5929 }
5930 SourceLocation getEndLoc() const LLVM_READONLY {
5931 return getCommonExpr()->getEndLoc();
5932 }
5933
5934 child_range children() {
5935 return child_range(SubExprs, SubExprs + 2);
5936 }
5937 const_child_range children() const {
5938 return const_child_range(SubExprs, SubExprs + 2);
5939 }
5940
5941 friend class ASTReader;
5942 friend class ASTStmtReader;
5943 friend class ASTStmtWriter;
5944};
5945
5946/// Represents the index of the current element of an array being
5947/// initialized by an ArrayInitLoopExpr. This can only appear within the
5948/// subexpression of an ArrayInitLoopExpr.
5949class ArrayInitIndexExpr : public Expr {
5950 explicit ArrayInitIndexExpr(EmptyShell Empty)
5951 : Expr(ArrayInitIndexExprClass, Empty) {}
5952
5953public:
5954 explicit ArrayInitIndexExpr(QualType T)
5955 : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
5956 setDependence(ExprDependence::None);
5957 }
5958
5959 static bool classof(const Stmt *S) {
5960 return S->getStmtClass() == ArrayInitIndexExprClass;
5961 }
5962
5963 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5964 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5965
5966 child_range children() {
5967 return child_range(child_iterator(), child_iterator());
5968 }
5969 const_child_range children() const {
5970 return const_child_range(const_child_iterator(), const_child_iterator());
5971 }
5972
5973 friend class ASTReader;
5974 friend class ASTStmtReader;
5975};
5976
5977/// Represents an implicitly-generated value initialization of
5978/// an object of a given type.
5979///
5980/// Implicit value initializations occur within semantic initializer
5981/// list expressions (InitListExpr) as placeholders for subobject
5982/// initializations not explicitly specified by the user.
5983///
5984/// \see InitListExpr
5985class ImplicitValueInitExpr : public Expr {
5986public:
5987 explicit ImplicitValueInitExpr(QualType ty)
5988 : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5989 setDependence(computeDependence(E: this));
5990 }
5991
5992 /// Construct an empty implicit value initialization.
5993 explicit ImplicitValueInitExpr(EmptyShell Empty)
5994 : Expr(ImplicitValueInitExprClass, Empty) { }
5995
5996 static bool classof(const Stmt *T) {
5997 return T->getStmtClass() == ImplicitValueInitExprClass;
5998 }
5999
6000 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
6001 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
6002
6003 // Iterators
6004 child_range children() {
6005 return child_range(child_iterator(), child_iterator());
6006 }
6007 const_child_range children() const {
6008 return const_child_range(const_child_iterator(), const_child_iterator());
6009 }
6010};
6011
6012class ParenListExpr final
6013 : public Expr,
6014 private llvm::TrailingObjects<ParenListExpr, Stmt *> {
6015 friend class ASTStmtReader;
6016 friend TrailingObjects;
6017
6018 /// The location of the left and right parentheses.
6019 SourceLocation LParenLoc, RParenLoc;
6020
6021 /// Build a paren list.
6022 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
6023 SourceLocation RParenLoc);
6024
6025 /// Build an empty paren list.
6026 ParenListExpr(EmptyShell Empty, unsigned NumExprs);
6027
6028public:
6029 /// Create a paren list.
6030 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
6031 ArrayRef<Expr *> Exprs,
6032 SourceLocation RParenLoc);
6033
6034 /// Create an empty paren list.
6035 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
6036
6037 /// Return the number of expressions in this paren list.
6038 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
6039
6040 Expr *getExpr(unsigned Init) {
6041 assert(Init < getNumExprs() && "Initializer access out of range!");
6042 return getExprs()[Init];
6043 }
6044
6045 const Expr *getExpr(unsigned Init) const {
6046 return const_cast<ParenListExpr *>(this)->getExpr(Init);
6047 }
6048
6049 Expr **getExprs() { return reinterpret_cast<Expr **>(getTrailingObjects()); }
6050
6051 ArrayRef<Expr *> exprs() { return {getExprs(), getNumExprs()}; }
6052
6053 SourceLocation getLParenLoc() const { return LParenLoc; }
6054 SourceLocation getRParenLoc() const { return RParenLoc; }
6055 SourceLocation getBeginLoc() const { return getLParenLoc(); }
6056 SourceLocation getEndLoc() const { return getRParenLoc(); }
6057
6058 static bool classof(const Stmt *T) {
6059 return T->getStmtClass() == ParenListExprClass;
6060 }
6061
6062 // Iterators
6063 child_range children() {
6064 return child_range(getTrailingObjects(N: getNumExprs()));
6065 }
6066 const_child_range children() const {
6067 return const_child_range(getTrailingObjects(N: getNumExprs()));
6068 }
6069};
6070
6071/// Represents a C11 generic selection.
6072///
6073/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
6074/// expression, followed by one or more generic associations. Each generic
6075/// association specifies a type name and an expression, or "default" and an
6076/// expression (in which case it is known as a default generic association).
6077/// The type and value of the generic selection are identical to those of its
6078/// result expression, which is defined as the expression in the generic
6079/// association with a type name that is compatible with the type of the
6080/// controlling expression, or the expression in the default generic association
6081/// if no types are compatible. For example:
6082///
6083/// @code
6084/// _Generic(X, double: 1, float: 2, default: 3)
6085/// @endcode
6086///
6087/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
6088/// or 3 if "hello".
6089///
6090/// As an extension, generic selections are allowed in C++, where the following
6091/// additional semantics apply:
6092///
6093/// Any generic selection whose controlling expression is type-dependent or
6094/// which names a dependent type in its association list is result-dependent,
6095/// which means that the choice of result expression is dependent.
6096/// Result-dependent generic associations are both type- and value-dependent.
6097///
6098/// We also allow an extended form in both C and C++ where the controlling
6099/// predicate for the selection expression is a type rather than an expression.
6100/// This type argument form does not perform any conversions for the
6101/// controlling type, which makes it suitable for use with qualified type
6102/// associations, which is not possible with the expression form.
6103class GenericSelectionExpr final
6104 : public Expr,
6105 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
6106 TypeSourceInfo *> {
6107 friend class ASTStmtReader;
6108 friend class ASTStmtWriter;
6109 friend TrailingObjects;
6110
6111 /// The number of association expressions and the index of the result
6112 /// expression in the case where the generic selection expression is not
6113 /// result-dependent. The result index is equal to ResultDependentIndex
6114 /// if and only if the generic selection expression is result-dependent.
6115 unsigned NumAssocs : 15;
6116 unsigned ResultIndex : 15; // NB: ResultDependentIndex is tied to this width.
6117 LLVM_PREFERRED_TYPE(bool)
6118 unsigned IsExprPredicate : 1;
6119 enum : unsigned {
6120 ResultDependentIndex = 0x7FFF
6121 };
6122
6123 unsigned getIndexOfControllingExpression() const {
6124 // If controlled by an expression, the first offset into the Stmt *
6125 // trailing array is the controlling expression, the associated expressions
6126 // follow this.
6127 assert(isExprPredicate() && "Asking for the controlling expression of a "
6128 "selection expr predicated by a type");
6129 return 0;
6130 }
6131
6132 unsigned getIndexOfControllingType() const {
6133 // If controlled by a type, the first offset into the TypeSourceInfo *
6134 // trailing array is the controlling type, the associated types follow this.
6135 assert(isTypePredicate() && "Asking for the controlling type of a "
6136 "selection expr predicated by an expression");
6137 return 0;
6138 }
6139
6140 unsigned getIndexOfStartOfAssociatedExprs() const {
6141 // If the predicate is a type, then the associated expressions are the only
6142 // Stmt * in the trailing array, otherwise we need to offset past the
6143 // predicate expression.
6144 return (int)isExprPredicate();
6145 }
6146
6147 unsigned getIndexOfStartOfAssociatedTypes() const {
6148 // If the predicate is a type, then the associated types follow it in the
6149 // trailing array. Otherwise, the associated types are the only
6150 // TypeSourceInfo * in the trailing array.
6151 return (int)isTypePredicate();
6152 }
6153
6154
6155 /// The location of the "default" and of the right parenthesis.
6156 SourceLocation DefaultLoc, RParenLoc;
6157
6158 // GenericSelectionExpr is followed by several trailing objects.
6159 // They are (in order):
6160 //
6161 // * A single Stmt * for the controlling expression or a TypeSourceInfo * for
6162 // the controlling type, depending on the result of isTypePredicate() or
6163 // isExprPredicate().
6164 // * An array of getNumAssocs() Stmt * for the association expressions.
6165 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
6166 // association expressions.
6167 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
6168 // Add one to account for the controlling expression; the remainder
6169 // are the associated expressions.
6170 return getNumAssocs() + (int)isExprPredicate();
6171 }
6172
6173 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
6174 // Add one to account for the controlling type predicate, the remainder
6175 // are the associated types.
6176 return getNumAssocs() + (int)isTypePredicate();
6177 }
6178
6179 template <bool Const> class AssociationIteratorTy;
6180 /// Bundle together an association expression and its TypeSourceInfo.
6181 /// The Const template parameter is for the const and non-const versions
6182 /// of AssociationTy.
6183 template <bool Const> class AssociationTy {
6184 friend class GenericSelectionExpr;
6185 template <bool OtherConst> friend class AssociationIteratorTy;
6186 using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
6187 using TSIPtrTy =
6188 std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
6189 ExprPtrTy E;
6190 TSIPtrTy TSI;
6191 bool Selected;
6192 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
6193 : E(E), TSI(TSI), Selected(Selected) {}
6194
6195 public:
6196 ExprPtrTy getAssociationExpr() const { return E; }
6197 TSIPtrTy getTypeSourceInfo() const { return TSI; }
6198 QualType getType() const { return TSI ? TSI->getType() : QualType(); }
6199 bool isSelected() const { return Selected; }
6200 AssociationTy *operator->() { return this; }
6201 const AssociationTy *operator->() const { return this; }
6202 }; // class AssociationTy
6203
6204 /// Iterator over const and non-const Association objects. The Association
6205 /// objects are created on the fly when the iterator is dereferenced.
6206 /// This abstract over how exactly the association expressions and the
6207 /// corresponding TypeSourceInfo * are stored.
6208 template <bool Const>
6209 class AssociationIteratorTy
6210 : public llvm::iterator_facade_base<
6211 AssociationIteratorTy<Const>, std::input_iterator_tag,
6212 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
6213 AssociationTy<Const>> {
6214 friend class GenericSelectionExpr;
6215 // FIXME: This iterator could conceptually be a random access iterator, and
6216 // it would be nice if we could strengthen the iterator category someday.
6217 // However this iterator does not satisfy two requirements of forward
6218 // iterators:
6219 // a) reference = T& or reference = const T&
6220 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
6221 // if *It1 and *It2 are bound to the same objects.
6222 // An alternative design approach was discussed during review;
6223 // store an Association object inside the iterator, and return a reference
6224 // to it when dereferenced. This idea was discarded because of nasty
6225 // lifetime issues:
6226 // AssociationIterator It = ...;
6227 // const Association &Assoc = *It++; // Oops, Assoc is dangling.
6228 using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
6229 using StmtPtrPtrTy =
6230 std::conditional_t<Const, const Stmt *const *, Stmt **>;
6231 using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
6232 TypeSourceInfo **>;
6233 StmtPtrPtrTy E = nullptr;
6234 TSIPtrPtrTy TSI; // Kept in sync with E.
6235 unsigned Offset = 0, SelectedOffset = 0;
6236 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
6237 unsigned SelectedOffset)
6238 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
6239
6240 public:
6241 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
6242 typename BaseTy::reference operator*() const {
6243 return AssociationTy<Const>(cast<Expr>(*E), *TSI,
6244 Offset == SelectedOffset);
6245 }
6246 typename BaseTy::pointer operator->() const { return **this; }
6247 using BaseTy::operator++;
6248 AssociationIteratorTy &operator++() {
6249 ++E;
6250 ++TSI;
6251 ++Offset;
6252 return *this;
6253 }
6254 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
6255 }; // class AssociationIterator
6256
6257 /// Build a non-result-dependent generic selection expression accepting an
6258 /// expression predicate.
6259 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6260 Expr *ControllingExpr,
6261 ArrayRef<TypeSourceInfo *> AssocTypes,
6262 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6263 SourceLocation RParenLoc,
6264 bool ContainsUnexpandedParameterPack,
6265 unsigned ResultIndex);
6266
6267 /// Build a result-dependent generic selection expression accepting an
6268 /// expression predicate.
6269 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6270 Expr *ControllingExpr,
6271 ArrayRef<TypeSourceInfo *> AssocTypes,
6272 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6273 SourceLocation RParenLoc,
6274 bool ContainsUnexpandedParameterPack);
6275
6276 /// Build a non-result-dependent generic selection expression accepting a
6277 /// type predicate.
6278 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6279 TypeSourceInfo *ControllingType,
6280 ArrayRef<TypeSourceInfo *> AssocTypes,
6281 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6282 SourceLocation RParenLoc,
6283 bool ContainsUnexpandedParameterPack,
6284 unsigned ResultIndex);
6285
6286 /// Build a result-dependent generic selection expression accepting a type
6287 /// predicate.
6288 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6289 TypeSourceInfo *ControllingType,
6290 ArrayRef<TypeSourceInfo *> AssocTypes,
6291 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6292 SourceLocation RParenLoc,
6293 bool ContainsUnexpandedParameterPack);
6294
6295 /// Build an empty generic selection expression for deserialization.
6296 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
6297
6298public:
6299 /// Create a non-result-dependent generic selection expression accepting an
6300 /// expression predicate.
6301 static GenericSelectionExpr *
6302 Create(const ASTContext &Context, SourceLocation GenericLoc,
6303 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
6304 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6305 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
6306 unsigned ResultIndex);
6307
6308 /// Create a result-dependent generic selection expression accepting an
6309 /// expression predicate.
6310 static GenericSelectionExpr *
6311 Create(const ASTContext &Context, SourceLocation GenericLoc,
6312 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
6313 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6314 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
6315
6316 /// Create a non-result-dependent generic selection expression accepting a
6317 /// type predicate.
6318 static GenericSelectionExpr *
6319 Create(const ASTContext &Context, SourceLocation GenericLoc,
6320 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
6321 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6322 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
6323 unsigned ResultIndex);
6324
6325 /// Create a result-dependent generic selection expression accepting a type
6326 /// predicate
6327 static GenericSelectionExpr *
6328 Create(const ASTContext &Context, SourceLocation GenericLoc,
6329 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
6330 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6331 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
6332
6333 /// Create an empty generic selection expression for deserialization.
6334 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
6335 unsigned NumAssocs);
6336
6337 using Association = AssociationTy<false>;
6338 using ConstAssociation = AssociationTy<true>;
6339 using AssociationIterator = AssociationIteratorTy<false>;
6340 using ConstAssociationIterator = AssociationIteratorTy<true>;
6341 using association_range = llvm::iterator_range<AssociationIterator>;
6342 using const_association_range =
6343 llvm::iterator_range<ConstAssociationIterator>;
6344
6345 /// The number of association expressions.
6346 unsigned getNumAssocs() const { return NumAssocs; }
6347
6348 /// The zero-based index of the result expression's generic association in
6349 /// the generic selection's association list. Defined only if the
6350 /// generic selection is not result-dependent.
6351 unsigned getResultIndex() const {
6352 assert(!isResultDependent() &&
6353 "Generic selection is result-dependent but getResultIndex called!");
6354 return ResultIndex;
6355 }
6356
6357 /// Whether this generic selection is result-dependent.
6358 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
6359
6360 /// Whether this generic selection uses an expression as its controlling
6361 /// argument.
6362 bool isExprPredicate() const { return IsExprPredicate; }
6363 /// Whether this generic selection uses a type as its controlling argument.
6364 bool isTypePredicate() const { return !IsExprPredicate; }
6365
6366 /// Return the controlling expression of this generic selection expression.
6367 /// Only valid to call if the selection expression used an expression as its
6368 /// controlling argument.
6369 Expr *getControllingExpr() {
6370 return cast<Expr>(
6371 Val: getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
6372 }
6373 const Expr *getControllingExpr() const {
6374 return cast<Expr>(
6375 Val: getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
6376 }
6377
6378 /// Return the controlling type of this generic selection expression. Only
6379 /// valid to call if the selection expression used a type as its controlling
6380 /// argument.
6381 TypeSourceInfo *getControllingType() {
6382 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
6383 }
6384 const TypeSourceInfo* getControllingType() const {
6385 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
6386 }
6387
6388 /// Return the result expression of this controlling expression. Defined if
6389 /// and only if the generic selection expression is not result-dependent.
6390 Expr *getResultExpr() {
6391 return cast<Expr>(
6392 Val: getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6393 getResultIndex()]);
6394 }
6395 const Expr *getResultExpr() const {
6396 return cast<Expr>(
6397 Val: getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6398 getResultIndex()]);
6399 }
6400
6401 ArrayRef<Expr *> getAssocExprs() const {
6402 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
6403 getIndexOfStartOfAssociatedExprs()),
6404 NumAssocs};
6405 }
6406 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
6407 return {getTrailingObjects<TypeSourceInfo *>() +
6408 getIndexOfStartOfAssociatedTypes(),
6409 NumAssocs};
6410 }
6411
6412 /// Return the Ith association expression with its TypeSourceInfo,
6413 /// bundled together in GenericSelectionExpr::(Const)Association.
6414 Association getAssociation(unsigned I) {
6415 assert(I < getNumAssocs() &&
6416 "Out-of-range index in GenericSelectionExpr::getAssociation!");
6417 return Association(
6418 cast<Expr>(
6419 Val: getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6420 I]),
6421 getTrailingObjects<
6422 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6423 !isResultDependent() && (getResultIndex() == I));
6424 }
6425 ConstAssociation getAssociation(unsigned I) const {
6426 assert(I < getNumAssocs() &&
6427 "Out-of-range index in GenericSelectionExpr::getAssociation!");
6428 return ConstAssociation(
6429 cast<Expr>(
6430 Val: getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6431 I]),
6432 getTrailingObjects<
6433 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6434 !isResultDependent() && (getResultIndex() == I));
6435 }
6436
6437 association_range associations() {
6438 AssociationIterator Begin(getTrailingObjects<Stmt *>() +
6439 getIndexOfStartOfAssociatedExprs(),
6440 getTrailingObjects<TypeSourceInfo *>() +
6441 getIndexOfStartOfAssociatedTypes(),
6442 /*Offset=*/0, ResultIndex);
6443 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6444 /*Offset=*/NumAssocs, ResultIndex);
6445 return llvm::make_range(x: Begin, y: End);
6446 }
6447
6448 const_association_range associations() const {
6449 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
6450 getIndexOfStartOfAssociatedExprs(),
6451 getTrailingObjects<TypeSourceInfo *>() +
6452 getIndexOfStartOfAssociatedTypes(),
6453 /*Offset=*/0, ResultIndex);
6454 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6455 /*Offset=*/NumAssocs, ResultIndex);
6456 return llvm::make_range(x: Begin, y: End);
6457 }
6458
6459 SourceLocation getGenericLoc() const {
6460 return GenericSelectionExprBits.GenericLoc;
6461 }
6462 SourceLocation getDefaultLoc() const { return DefaultLoc; }
6463 SourceLocation getRParenLoc() const { return RParenLoc; }
6464 SourceLocation getBeginLoc() const { return getGenericLoc(); }
6465 SourceLocation getEndLoc() const { return getRParenLoc(); }
6466
6467 static bool classof(const Stmt *T) {
6468 return T->getStmtClass() == GenericSelectionExprClass;
6469 }
6470
6471 child_range children() {
6472 return child_range(getTrailingObjects<Stmt *>(
6473 N: numTrailingObjects(OverloadToken<Stmt *>())));
6474 }
6475 const_child_range children() const {
6476 return const_child_range(getTrailingObjects<Stmt *>(
6477 N: numTrailingObjects(OverloadToken<Stmt *>())));
6478 }
6479};
6480
6481//===----------------------------------------------------------------------===//
6482// Clang Extensions
6483//===----------------------------------------------------------------------===//
6484
6485/// ExtVectorElementExpr - This represents access to specific elements of a
6486/// vector, and may occur on the left hand side or right hand side. For example
6487/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
6488///
6489/// Note that the base may have either vector or pointer to vector type, just
6490/// like a struct field reference.
6491///
6492class ExtVectorElementExpr : public Expr {
6493 Stmt *Base;
6494 IdentifierInfo *Accessor;
6495 SourceLocation AccessorLoc;
6496public:
6497 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
6498 IdentifierInfo &accessor, SourceLocation loc)
6499 : Expr(ExtVectorElementExprClass, ty, VK,
6500 (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
6501 Base(base), Accessor(&accessor), AccessorLoc(loc) {
6502 setDependence(computeDependence(E: this));
6503 }
6504
6505 /// Build an empty vector element expression.
6506 explicit ExtVectorElementExpr(EmptyShell Empty)
6507 : Expr(ExtVectorElementExprClass, Empty) { }
6508
6509 const Expr *getBase() const { return cast<Expr>(Val: Base); }
6510 Expr *getBase() { return cast<Expr>(Val: Base); }
6511 void setBase(Expr *E) { Base = E; }
6512
6513 IdentifierInfo &getAccessor() const { return *Accessor; }
6514 void setAccessor(IdentifierInfo *II) { Accessor = II; }
6515
6516 SourceLocation getAccessorLoc() const { return AccessorLoc; }
6517 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
6518
6519 /// getNumElements - Get the number of components being selected.
6520 unsigned getNumElements() const;
6521
6522 /// containsDuplicateElements - Return true if any element access is
6523 /// repeated.
6524 bool containsDuplicateElements() const;
6525
6526 /// getEncodedElementAccess - Encode the elements accessed into an llvm
6527 /// aggregate Constant of ConstantInt(s).
6528 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
6529
6530 SourceLocation getBeginLoc() const LLVM_READONLY {
6531 return getBase()->getBeginLoc();
6532 }
6533 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
6534
6535 /// isArrow - Return true if the base expression is a pointer to vector,
6536 /// return false if the base expression is a vector.
6537 bool isArrow() const;
6538
6539 static bool classof(const Stmt *T) {
6540 return T->getStmtClass() == ExtVectorElementExprClass;
6541 }
6542
6543 // Iterators
6544 child_range children() { return child_range(&Base, &Base+1); }
6545 const_child_range children() const {
6546 return const_child_range(&Base, &Base + 1);
6547 }
6548};
6549
6550/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
6551/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
6552class BlockExpr : public Expr {
6553protected:
6554 BlockDecl *TheBlock;
6555public:
6556 BlockExpr(BlockDecl *BD, QualType ty, bool ContainsUnexpandedParameterPack)
6557 : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
6558 setDependence(computeDependence(E: this, ContainsUnexpandedParameterPack));
6559 }
6560
6561 /// Build an empty block expression.
6562 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
6563
6564 const BlockDecl *getBlockDecl() const { return TheBlock; }
6565 BlockDecl *getBlockDecl() { return TheBlock; }
6566 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
6567
6568 // Convenience functions for probing the underlying BlockDecl.
6569 SourceLocation getCaretLocation() const;
6570 const Stmt *getBody() const;
6571 Stmt *getBody();
6572
6573 SourceLocation getBeginLoc() const LLVM_READONLY {
6574 return getCaretLocation();
6575 }
6576 SourceLocation getEndLoc() const LLVM_READONLY {
6577 return getBody()->getEndLoc();
6578 }
6579
6580 /// getFunctionType - Return the underlying function type for this block.
6581 const FunctionProtoType *getFunctionType() const;
6582
6583 static bool classof(const Stmt *T) {
6584 return T->getStmtClass() == BlockExprClass;
6585 }
6586
6587 // Iterators
6588 child_range children() {
6589 return child_range(child_iterator(), child_iterator());
6590 }
6591 const_child_range children() const {
6592 return const_child_range(const_child_iterator(), const_child_iterator());
6593 }
6594};
6595
6596/// Copy initialization expr of a __block variable and a boolean flag that
6597/// indicates whether the expression can throw.
6598struct BlockVarCopyInit {
6599 BlockVarCopyInit() = default;
6600 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
6601 : ExprAndFlag(CopyExpr, CanThrow) {}
6602 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
6603 ExprAndFlag.setPointerAndInt(PtrVal: CopyExpr, IntVal: CanThrow);
6604 }
6605 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
6606 bool canThrow() const { return ExprAndFlag.getInt(); }
6607 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
6608};
6609
6610/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
6611/// This AST node provides support for reinterpreting a type to another
6612/// type of the same size.
6613class AsTypeExpr : public Expr {
6614private:
6615 Stmt *SrcExpr;
6616 SourceLocation BuiltinLoc, RParenLoc;
6617
6618 friend class ASTReader;
6619 friend class ASTStmtReader;
6620 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
6621
6622public:
6623 AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
6624 ExprObjectKind OK, SourceLocation BuiltinLoc,
6625 SourceLocation RParenLoc)
6626 : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
6627 BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
6628 setDependence(computeDependence(E: this));
6629 }
6630
6631 /// getSrcExpr - Return the Expr to be converted.
6632 Expr *getSrcExpr() const { return cast<Expr>(Val: SrcExpr); }
6633
6634 /// getBuiltinLoc - Return the location of the __builtin_astype token.
6635 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6636
6637 /// getRParenLoc - Return the location of final right parenthesis.
6638 SourceLocation getRParenLoc() const { return RParenLoc; }
6639
6640 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6641 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6642
6643 static bool classof(const Stmt *T) {
6644 return T->getStmtClass() == AsTypeExprClass;
6645 }
6646
6647 // Iterators
6648 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
6649 const_child_range children() const {
6650 return const_child_range(&SrcExpr, &SrcExpr + 1);
6651 }
6652};
6653
6654/// PseudoObjectExpr - An expression which accesses a pseudo-object
6655/// l-value. A pseudo-object is an abstract object, accesses to which
6656/// are translated to calls. The pseudo-object expression has a
6657/// syntactic form, which shows how the expression was actually
6658/// written in the source code, and a semantic form, which is a series
6659/// of expressions to be executed in order which detail how the
6660/// operation is actually evaluated. Optionally, one of the semantic
6661/// forms may also provide a result value for the expression.
6662///
6663/// If any of the semantic-form expressions is an OpaqueValueExpr,
6664/// that OVE is required to have a source expression, and it is bound
6665/// to the result of that source expression. Such OVEs may appear
6666/// only in subsequent semantic-form expressions and as
6667/// sub-expressions of the syntactic form.
6668///
6669/// PseudoObjectExpr should be used only when an operation can be
6670/// usefully described in terms of fairly simple rewrite rules on
6671/// objects and functions that are meant to be used by end-developers.
6672/// For example, under the Itanium ABI, dynamic casts are implemented
6673/// as a call to a runtime function called __dynamic_cast; using this
6674/// class to describe that would be inappropriate because that call is
6675/// not really part of the user-visible semantics, and instead the
6676/// cast is properly reflected in the AST and IR-generation has been
6677/// taught to generate the call as necessary. In contrast, an
6678/// Objective-C property access is semantically defined to be
6679/// equivalent to a particular message send, and this is very much
6680/// part of the user model. The name of this class encourages this
6681/// modelling design.
6682class PseudoObjectExpr final
6683 : public Expr,
6684 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
6685 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
6686 // Always at least two, because the first sub-expression is the
6687 // syntactic form.
6688
6689 // PseudoObjectExprBits.ResultIndex - The index of the
6690 // sub-expression holding the result. 0 means the result is void,
6691 // which is unambiguous because it's the index of the syntactic
6692 // form. Note that this is therefore 1 higher than the value passed
6693 // in to Create, which is an index within the semantic forms.
6694 // Note also that ASTStmtWriter assumes this encoding.
6695
6696 PseudoObjectExpr(QualType type, ExprValueKind VK,
6697 Expr *syntactic, ArrayRef<Expr*> semantic,
6698 unsigned resultIndex);
6699
6700 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
6701
6702 unsigned getNumSubExprs() const {
6703 return PseudoObjectExprBits.NumSubExprs;
6704 }
6705
6706public:
6707 /// NoResult - A value for the result index indicating that there is
6708 /// no semantic result.
6709 enum : unsigned { NoResult = ~0U };
6710
6711 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
6712 ArrayRef<Expr*> semantic,
6713 unsigned resultIndex);
6714
6715 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
6716 unsigned numSemanticExprs);
6717
6718 /// Return the syntactic form of this expression, i.e. the
6719 /// expression it actually looks like. Likely to be expressed in
6720 /// terms of OpaqueValueExprs bound in the semantic form.
6721 Expr *getSyntacticForm() { return getTrailingObjects()[0]; }
6722 const Expr *getSyntacticForm() const { return getTrailingObjects()[0]; }
6723
6724 /// Return the index of the result-bearing expression into the semantics
6725 /// expressions, or PseudoObjectExpr::NoResult if there is none.
6726 unsigned getResultExprIndex() const {
6727 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
6728 return PseudoObjectExprBits.ResultIndex - 1;
6729 }
6730
6731 /// Return the result-bearing expression, or null if there is none.
6732 Expr *getResultExpr() {
6733 if (PseudoObjectExprBits.ResultIndex == 0)
6734 return nullptr;
6735 return getTrailingObjects()[PseudoObjectExprBits.ResultIndex];
6736 }
6737 const Expr *getResultExpr() const {
6738 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
6739 }
6740
6741 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
6742
6743 typedef Expr * const *semantics_iterator;
6744 typedef const Expr * const *const_semantics_iterator;
6745 semantics_iterator semantics_begin() { return getTrailingObjects() + 1; }
6746 const_semantics_iterator semantics_begin() const {
6747 return getTrailingObjects() + 1;
6748 }
6749 semantics_iterator semantics_end() {
6750 return getTrailingObjects() + getNumSubExprs();
6751 }
6752 const_semantics_iterator semantics_end() const {
6753 return getTrailingObjects() + getNumSubExprs();
6754 }
6755
6756 ArrayRef<Expr*> semantics() {
6757 return getTrailingObjects(N: getNumSubExprs()).drop_front();
6758 }
6759 ArrayRef<const Expr*> semantics() const {
6760 return getTrailingObjects(N: getNumSubExprs()).drop_front();
6761 }
6762
6763 Expr *getSemanticExpr(unsigned index) {
6764 return getTrailingObjects(N: getNumSubExprs())[index + 1];
6765 }
6766 const Expr *getSemanticExpr(unsigned index) const {
6767 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
6768 }
6769
6770 SourceLocation getExprLoc() const LLVM_READONLY {
6771 return getSyntacticForm()->getExprLoc();
6772 }
6773
6774 SourceLocation getBeginLoc() const LLVM_READONLY {
6775 return getSyntacticForm()->getBeginLoc();
6776 }
6777 SourceLocation getEndLoc() const LLVM_READONLY {
6778 return getSyntacticForm()->getEndLoc();
6779 }
6780
6781 child_range children() {
6782 const_child_range CCR =
6783 const_cast<const PseudoObjectExpr *>(this)->children();
6784 return child_range(cast_away_const(RHS: CCR.begin()),
6785 cast_away_const(RHS: CCR.end()));
6786 }
6787 const_child_range children() const {
6788 Stmt *const *cs = const_cast<Stmt *const *>(
6789 reinterpret_cast<const Stmt *const *>(getTrailingObjects()));
6790 return const_child_range(cs, cs + getNumSubExprs());
6791 }
6792
6793 static bool classof(const Stmt *T) {
6794 return T->getStmtClass() == PseudoObjectExprClass;
6795 }
6796
6797 friend TrailingObjects;
6798 friend class ASTStmtReader;
6799};
6800
6801/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
6802/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
6803/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
6804/// and corresponding __opencl_atomic_* for OpenCL 2.0.
6805/// All of these instructions take one primary pointer, at least one memory
6806/// order. The instructions for which getScopeModel returns non-null value
6807/// take one sync scope.
6808class AtomicExpr : public Expr {
6809public:
6810 enum AtomicOp {
6811#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
6812#include "clang/Basic/Builtins.inc"
6813 // Avoid trailing comma
6814 BI_First = 0
6815 };
6816
6817private:
6818 /// Location of sub-expressions.
6819 /// The location of Scope sub-expression is NumSubExprs - 1, which is
6820 /// not fixed, therefore is not defined in enum.
6821 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
6822 Stmt *SubExprs[END_EXPR + 1];
6823 unsigned NumSubExprs;
6824 SourceLocation BuiltinLoc, RParenLoc;
6825 AtomicOp Op;
6826
6827 friend class ASTStmtReader;
6828public:
6829 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
6830 AtomicOp op, SourceLocation RP);
6831
6832 /// Determine the number of arguments the specified atomic builtin
6833 /// should have.
6834 static unsigned getNumSubExprs(AtomicOp Op);
6835
6836 /// Build an empty AtomicExpr.
6837 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
6838
6839 Expr *getPtr() const {
6840 return cast<Expr>(Val: SubExprs[PTR]);
6841 }
6842 Expr *getOrder() const {
6843 return cast<Expr>(Val: SubExprs[ORDER]);
6844 }
6845 Expr *getScope() const {
6846 assert(getScopeModel() && "No scope");
6847 return cast<Expr>(Val: SubExprs[NumSubExprs - 1]);
6848 }
6849 Expr *getVal1() const {
6850 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
6851 return cast<Expr>(Val: SubExprs[ORDER]);
6852 assert(NumSubExprs > VAL1);
6853 return cast<Expr>(Val: SubExprs[VAL1]);
6854 }
6855 Expr *getOrderFail() const {
6856 assert(NumSubExprs > ORDER_FAIL);
6857 return cast<Expr>(Val: SubExprs[ORDER_FAIL]);
6858 }
6859 Expr *getVal2() const {
6860 if (Op == AO__atomic_exchange || Op == AO__scoped_atomic_exchange)
6861 return cast<Expr>(Val: SubExprs[ORDER_FAIL]);
6862 assert(NumSubExprs > VAL2);
6863 return cast<Expr>(Val: SubExprs[VAL2]);
6864 }
6865 Expr *getWeak() const {
6866 assert(NumSubExprs > WEAK);
6867 return cast<Expr>(Val: SubExprs[WEAK]);
6868 }
6869 QualType getValueType() const;
6870
6871 AtomicOp getOp() const { return Op; }
6872 StringRef getOpAsString() const {
6873 switch (Op) {
6874#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
6875 case AO##ID: \
6876 return #ID;
6877#include "clang/Basic/Builtins.inc"
6878 }
6879 llvm_unreachable("not an atomic operator?");
6880 }
6881 unsigned getNumSubExprs() const { return NumSubExprs; }
6882
6883 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
6884 const Expr * const *getSubExprs() const {
6885 return reinterpret_cast<Expr * const *>(SubExprs);
6886 }
6887
6888 bool isVolatile() const {
6889 return getPtr()->getType()->getPointeeType().isVolatileQualified();
6890 }
6891
6892 bool isCmpXChg() const {
6893 return getOp() == AO__c11_atomic_compare_exchange_strong ||
6894 getOp() == AO__c11_atomic_compare_exchange_weak ||
6895 getOp() == AO__hip_atomic_compare_exchange_strong ||
6896 getOp() == AO__opencl_atomic_compare_exchange_strong ||
6897 getOp() == AO__opencl_atomic_compare_exchange_weak ||
6898 getOp() == AO__hip_atomic_compare_exchange_weak ||
6899 getOp() == AO__atomic_compare_exchange ||
6900 getOp() == AO__atomic_compare_exchange_n ||
6901 getOp() == AO__scoped_atomic_compare_exchange ||
6902 getOp() == AO__scoped_atomic_compare_exchange_n;
6903 }
6904
6905 bool isOpenCL() const {
6906 return getOp() >= AO__opencl_atomic_compare_exchange_strong &&
6907 getOp() <= AO__opencl_atomic_store;
6908 }
6909
6910 bool isHIP() const {
6911 return Op >= AO__hip_atomic_compare_exchange_strong &&
6912 Op <= AO__hip_atomic_store;
6913 }
6914
6915 /// Return true if atomics operations targeting allocations in private memory
6916 /// are undefined.
6917 bool threadPrivateMemoryAtomicsAreUndefined() const {
6918 return isOpenCL() || isHIP();
6919 }
6920
6921 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6922 SourceLocation getRParenLoc() const { return RParenLoc; }
6923
6924 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6925 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6926
6927 static bool classof(const Stmt *T) {
6928 return T->getStmtClass() == AtomicExprClass;
6929 }
6930
6931 // Iterators
6932 child_range children() {
6933 return child_range(SubExprs, SubExprs+NumSubExprs);
6934 }
6935 const_child_range children() const {
6936 return const_child_range(SubExprs, SubExprs + NumSubExprs);
6937 }
6938
6939 /// Get atomic scope model for the atomic op code.
6940 /// \return empty atomic scope model if the atomic op code does not have
6941 /// scope operand.
6942 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
6943 // FIXME: Allow grouping of builtins to be able to only check >= and <=
6944 if (Op >= AO__opencl_atomic_compare_exchange_strong &&
6945 Op <= AO__opencl_atomic_store && Op != AO__opencl_atomic_init)
6946 return AtomicScopeModel::create(K: AtomicScopeModelKind::OpenCL);
6947 if (Op >= AO__hip_atomic_compare_exchange_strong &&
6948 Op <= AO__hip_atomic_store)
6949 return AtomicScopeModel::create(K: AtomicScopeModelKind::HIP);
6950 if (Op >= AO__scoped_atomic_add_fetch && Op <= AO__scoped_atomic_xor_fetch)
6951 return AtomicScopeModel::create(K: AtomicScopeModelKind::Generic);
6952 return AtomicScopeModel::create(K: AtomicScopeModelKind::None);
6953 }
6954
6955 /// Get atomic scope model.
6956 /// \return empty atomic scope model if this atomic expression does not have
6957 /// scope operand.
6958 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
6959 return getScopeModel(Op: getOp());
6960 }
6961};
6962
6963/// This class represents BOTH the OpenMP Array Section and OpenACC 'subarray',
6964/// with a boolean differentiator.
6965/// OpenMP 5.0 [2.1.5, Array Sections].
6966/// To specify an array section in an OpenMP construct, array subscript
6967/// expressions are extended with the following syntax:
6968/// \code
6969/// [ lower-bound : length : stride ]
6970/// [ lower-bound : length : ]
6971/// [ lower-bound : length ]
6972/// [ lower-bound : : stride ]
6973/// [ lower-bound : : ]
6974/// [ lower-bound : ]
6975/// [ : length : stride ]
6976/// [ : length : ]
6977/// [ : length ]
6978/// [ : : stride ]
6979/// [ : : ]
6980/// [ : ]
6981/// \endcode
6982/// The array section must be a subset of the original array.
6983/// Array sections are allowed on multidimensional arrays. Base language array
6984/// subscript expressions can be used to specify length-one dimensions of
6985/// multidimensional array sections.
6986/// Each of the lower-bound, length, and stride expressions if specified must be
6987/// an integral type expressions of the base language. When evaluated
6988/// they represent a set of integer values as follows:
6989/// \code
6990/// { lower-bound, lower-bound + stride, lower-bound + 2 * stride,... ,
6991/// lower-bound + ((length - 1) * stride) }
6992/// \endcode
6993/// The lower-bound and length must evaluate to non-negative integers.
6994/// The stride must evaluate to a positive integer.
6995/// When the size of the array dimension is not known, the length must be
6996/// specified explicitly.
6997/// When the stride is absent it defaults to 1.
6998/// When the length is absent it defaults to ⌈(size − lower-bound)/stride⌉,
6999/// where size is the size of the array dimension. When the lower-bound is
7000/// absent it defaults to 0.
7001///
7002///
7003/// OpenACC 3.3 [2.7.1 Data Specification in Data Clauses]
7004/// In C and C++, a subarray is an array name followed by an extended array
7005/// range specification in brackets, with start and length, such as
7006///
7007/// AA[2:n]
7008///
7009/// If the lower bound is missing, zero is used. If the length is missing and
7010/// the array has known size, the size of the array is used; otherwise the
7011/// length is required. The subarray AA[2:n] means elements AA[2], AA[3], . . .
7012/// , AA[2+n-1]. In C and C++, a two dimensional array may be declared in at
7013/// least four ways:
7014///
7015/// -Statically-sized array: float AA[100][200];
7016/// -Pointer to statically sized rows: typedef float row[200]; row* BB;
7017/// -Statically-sized array of pointers: float* CC[200];
7018/// -Pointer to pointers: float** DD;
7019///
7020/// Each dimension may be statically sized, or a pointer to dynamically
7021/// allocated memory. Each of these may be included in a data clause using
7022/// subarray notation to specify a rectangular array:
7023///
7024/// -AA[2:n][0:200]
7025/// -BB[2:n][0:m]
7026/// -CC[2:n][0:m]
7027/// -DD[2:n][0:m]
7028///
7029/// Multidimensional rectangular subarrays in C and C++ may be specified for any
7030/// array with any combination of statically-sized or dynamically-allocated
7031/// dimensions. For statically sized dimensions, all dimensions except the first
7032/// must specify the whole extent to preserve the contiguous data restriction,
7033/// discussed below. For dynamically allocated dimensions, the implementation
7034/// will allocate pointers in device memory corresponding to the pointers in
7035/// local memory and will fill in those pointers as appropriate.
7036///
7037/// In Fortran, a subarray is an array name followed by a comma-separated list
7038/// of range specifications in parentheses, with lower and upper bound
7039/// subscripts, such as
7040///
7041/// arr(1:high,low:100)
7042///
7043/// If either the lower or upper bounds are missing, the declared or allocated
7044/// bounds of the array, if known, are used. All dimensions except the last must
7045/// specify the whole extent, to preserve the contiguous data restriction,
7046/// discussed below.
7047///
7048/// Restrictions
7049///
7050/// -In Fortran, the upper bound for the last dimension of an assumed-size dummy
7051/// array must be specified.
7052///
7053/// -In C and C++, the length for dynamically allocated dimensions of an array
7054/// must be explicitly specified.
7055///
7056/// -In C and C++, modifying pointers in pointer arrays during the data
7057/// lifetime, either on the host or on the device, may result in undefined
7058/// behavior.
7059///
7060/// -If a subarray appears in a data clause, the implementation may choose to
7061/// allocate memory for only that subarray on the accelerator.
7062///
7063/// -In Fortran, array pointers may appear, but pointer association is not
7064/// preserved in device memory.
7065///
7066/// -Any array or subarray in a data clause, including Fortran array pointers,
7067/// must be a contiguous section of memory, except for dynamic multidimensional
7068/// C arrays.
7069///
7070/// -In C and C++, if a variable or array of composite type appears, all the
7071/// data members of the struct or class are allocated and copied, as
7072/// appropriate. If a composite member is a pointer type, the data addressed by
7073/// that pointer are not implicitly copied.
7074///
7075/// -In Fortran, if a variable or array of composite type appears, all the
7076/// members of that derived type are allocated and copied, as appropriate. If
7077/// any member has the allocatable or pointer attribute, the data accessed
7078/// through that member are not copied.
7079///
7080/// -If an expression is used in a subscript or subarray expression in a clause
7081/// on a data construct, the same value is used when copying data at the end of
7082/// the data region, even if the values of variables in the expression change
7083/// during the data region.
7084class ArraySectionExpr : public Expr {
7085 friend class ASTStmtReader;
7086 friend class ASTStmtWriter;
7087
7088public:
7089 enum ArraySectionType { OMPArraySection, OpenACCArraySection };
7090
7091private:
7092 enum {
7093 BASE,
7094 LOWER_BOUND,
7095 LENGTH,
7096 STRIDE,
7097 END_EXPR,
7098 OPENACC_END_EXPR = STRIDE
7099 };
7100
7101 ArraySectionType ASType = OMPArraySection;
7102 Stmt *SubExprs[END_EXPR] = {nullptr};
7103 SourceLocation ColonLocFirst;
7104 SourceLocation ColonLocSecond;
7105 SourceLocation RBracketLoc;
7106
7107public:
7108 // Constructor for OMP array sections, which include a 'stride'.
7109 ArraySectionExpr(Expr *Base, Expr *LowerBound, Expr *Length, Expr *Stride,
7110 QualType Type, ExprValueKind VK, ExprObjectKind OK,
7111 SourceLocation ColonLocFirst, SourceLocation ColonLocSecond,
7112 SourceLocation RBracketLoc)
7113 : Expr(ArraySectionExprClass, Type, VK, OK), ASType(OMPArraySection),
7114 ColonLocFirst(ColonLocFirst), ColonLocSecond(ColonLocSecond),
7115 RBracketLoc(RBracketLoc) {
7116 setBase(Base);
7117 setLowerBound(LowerBound);
7118 setLength(Length);
7119 setStride(Stride);
7120 setDependence(computeDependence(E: this));
7121 }
7122
7123 // Constructor for OpenACC sub-arrays, which do not permit a 'stride'.
7124 ArraySectionExpr(Expr *Base, Expr *LowerBound, Expr *Length, QualType Type,
7125 ExprValueKind VK, ExprObjectKind OK, SourceLocation ColonLoc,
7126 SourceLocation RBracketLoc)
7127 : Expr(ArraySectionExprClass, Type, VK, OK), ASType(OpenACCArraySection),
7128 ColonLocFirst(ColonLoc), RBracketLoc(RBracketLoc) {
7129 setBase(Base);
7130 setLowerBound(LowerBound);
7131 setLength(Length);
7132 setDependence(computeDependence(E: this));
7133 }
7134
7135 /// Create an empty array section expression.
7136 explicit ArraySectionExpr(EmptyShell Shell)
7137 : Expr(ArraySectionExprClass, Shell) {}
7138
7139 /// Return original type of the base expression for array section.
7140 static QualType getBaseOriginalType(const Expr *Base);
7141
7142 static bool classof(const Stmt *T) {
7143 return T->getStmtClass() == ArraySectionExprClass;
7144 }
7145
7146 bool isOMPArraySection() const { return ASType == OMPArraySection; }
7147 bool isOpenACCArraySection() const { return ASType == OpenACCArraySection; }
7148
7149 /// Get base of the array section.
7150 Expr *getBase() { return cast<Expr>(Val: SubExprs[BASE]); }
7151 const Expr *getBase() const { return cast<Expr>(Val: SubExprs[BASE]); }
7152
7153 /// Get lower bound of array section.
7154 Expr *getLowerBound() { return cast_or_null<Expr>(Val: SubExprs[LOWER_BOUND]); }
7155 const Expr *getLowerBound() const {
7156 return cast_or_null<Expr>(Val: SubExprs[LOWER_BOUND]);
7157 }
7158
7159 /// Get length of array section.
7160 Expr *getLength() { return cast_or_null<Expr>(Val: SubExprs[LENGTH]); }
7161 const Expr *getLength() const { return cast_or_null<Expr>(Val: SubExprs[LENGTH]); }
7162
7163 /// Get stride of array section.
7164 Expr *getStride() {
7165 assert(ASType != OpenACCArraySection &&
7166 "Stride not valid in OpenACC subarrays");
7167 return cast_or_null<Expr>(Val: SubExprs[STRIDE]);
7168 }
7169
7170 const Expr *getStride() const {
7171 assert(ASType != OpenACCArraySection &&
7172 "Stride not valid in OpenACC subarrays");
7173 return cast_or_null<Expr>(Val: SubExprs[STRIDE]);
7174 }
7175
7176 SourceLocation getBeginLoc() const LLVM_READONLY {
7177 return getBase()->getBeginLoc();
7178 }
7179 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
7180
7181 SourceLocation getColonLocFirst() const { return ColonLocFirst; }
7182 SourceLocation getColonLocSecond() const {
7183 assert(ASType != OpenACCArraySection &&
7184 "second colon for stride not valid in OpenACC subarrays");
7185 return ColonLocSecond;
7186 }
7187 SourceLocation getRBracketLoc() const { return RBracketLoc; }
7188
7189 SourceLocation getExprLoc() const LLVM_READONLY {
7190 return getBase()->getExprLoc();
7191 }
7192
7193 child_range children() {
7194 return child_range(
7195 &SubExprs[BASE],
7196 &SubExprs[ASType == OMPArraySection ? END_EXPR : OPENACC_END_EXPR]);
7197 }
7198
7199 const_child_range children() const {
7200 return const_child_range(
7201 &SubExprs[BASE],
7202 &SubExprs[ASType == OMPArraySection ? END_EXPR : OPENACC_END_EXPR]);
7203 }
7204
7205private:
7206 /// Set base of the array section.
7207 void setBase(Expr *E) { SubExprs[BASE] = E; }
7208
7209 /// Set lower bound of the array section.
7210 void setLowerBound(Expr *E) { SubExprs[LOWER_BOUND] = E; }
7211
7212 /// Set length of the array section.
7213 void setLength(Expr *E) { SubExprs[LENGTH] = E; }
7214
7215 /// Set length of the array section.
7216 void setStride(Expr *E) {
7217 assert(ASType != OpenACCArraySection &&
7218 "Stride not valid in OpenACC subarrays");
7219 SubExprs[STRIDE] = E;
7220 }
7221
7222 void setColonLocFirst(SourceLocation L) { ColonLocFirst = L; }
7223
7224 void setColonLocSecond(SourceLocation L) {
7225 assert(ASType != OpenACCArraySection &&
7226 "second colon for stride not valid in OpenACC subarrays");
7227 ColonLocSecond = L;
7228 }
7229 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
7230};
7231
7232/// This class represents temporary values used to represent inout and out
7233/// arguments in HLSL. From the callee perspective these parameters are more or
7234/// less __restrict__ T&. They are guaranteed to not alias any memory. inout
7235/// parameters are initialized by the caller, and out parameters are references
7236/// to uninitialized memory.
7237///
7238/// In the caller, the argument expression creates a temporary in local memory
7239/// and the address of the temporary is passed into the callee. There may be
7240/// implicit conversion sequences to initialize the temporary, and on expiration
7241/// of the temporary an inverse conversion sequence is applied as a write-back
7242/// conversion to the source l-value.
7243///
7244/// This AST node has three sub-expressions:
7245/// - An OpaqueValueExpr with a source that is the argument lvalue expression.
7246/// - An OpaqueValueExpr with a source that is an implicit conversion
7247/// sequence from the source lvalue to the argument type.
7248/// - An expression that assigns the second expression into the first,
7249/// performing any necessary conversions.
7250class HLSLOutArgExpr : public Expr {
7251 friend class ASTStmtReader;
7252
7253 enum {
7254 BaseLValue,
7255 CastedTemporary,
7256 WritebackCast,
7257 NumSubExprs,
7258 };
7259
7260 Stmt *SubExprs[NumSubExprs];
7261 bool IsInOut;
7262
7263 HLSLOutArgExpr(QualType Ty, OpaqueValueExpr *B, OpaqueValueExpr *OpV,
7264 Expr *WB, bool IsInOut)
7265 : Expr(HLSLOutArgExprClass, Ty, VK_LValue, OK_Ordinary),
7266 IsInOut(IsInOut) {
7267 SubExprs[BaseLValue] = B;
7268 SubExprs[CastedTemporary] = OpV;
7269 SubExprs[WritebackCast] = WB;
7270 assert(!Ty->isDependentType() && "HLSLOutArgExpr given a dependent type!");
7271 }
7272
7273 explicit HLSLOutArgExpr(EmptyShell Shell)
7274 : Expr(HLSLOutArgExprClass, Shell) {}
7275
7276public:
7277 static HLSLOutArgExpr *Create(const ASTContext &C, QualType Ty,
7278 OpaqueValueExpr *Base, OpaqueValueExpr *OpV,
7279 Expr *WB, bool IsInOut);
7280 static HLSLOutArgExpr *CreateEmpty(const ASTContext &Ctx);
7281
7282 const OpaqueValueExpr *getOpaqueArgLValue() const {
7283 return cast<OpaqueValueExpr>(Val: SubExprs[BaseLValue]);
7284 }
7285 OpaqueValueExpr *getOpaqueArgLValue() {
7286 return cast<OpaqueValueExpr>(Val: SubExprs[BaseLValue]);
7287 }
7288
7289 /// Return the l-value expression that was written as the argument
7290 /// in source. Everything else here is implicitly generated.
7291 const Expr *getArgLValue() const {
7292 return getOpaqueArgLValue()->getSourceExpr();
7293 }
7294 Expr *getArgLValue() { return getOpaqueArgLValue()->getSourceExpr(); }
7295
7296 const Expr *getWritebackCast() const {
7297 return cast<Expr>(Val: SubExprs[WritebackCast]);
7298 }
7299 Expr *getWritebackCast() { return cast<Expr>(Val: SubExprs[WritebackCast]); }
7300
7301 const OpaqueValueExpr *getCastedTemporary() const {
7302 return cast<OpaqueValueExpr>(Val: SubExprs[CastedTemporary]);
7303 }
7304 OpaqueValueExpr *getCastedTemporary() {
7305 return cast<OpaqueValueExpr>(Val: SubExprs[CastedTemporary]);
7306 }
7307
7308 /// returns true if the parameter is inout and false if the parameter is out.
7309 bool isInOut() const { return IsInOut; }
7310
7311 SourceLocation getBeginLoc() const LLVM_READONLY {
7312 return SubExprs[BaseLValue]->getBeginLoc();
7313 }
7314
7315 SourceLocation getEndLoc() const LLVM_READONLY {
7316 return SubExprs[BaseLValue]->getEndLoc();
7317 }
7318
7319 static bool classof(const Stmt *T) {
7320 return T->getStmtClass() == HLSLOutArgExprClass;
7321 }
7322
7323 // Iterators
7324 child_range children() {
7325 return child_range(&SubExprs[BaseLValue], &SubExprs[NumSubExprs]);
7326 }
7327};
7328
7329/// Frontend produces RecoveryExprs on semantic errors that prevent creating
7330/// other well-formed expressions. E.g. when type-checking of a binary operator
7331/// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
7332/// to produce a recovery expression storing left and right operands.
7333///
7334/// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
7335/// preserve expressions in AST that would otherwise be dropped. It captures
7336/// subexpressions of some expression that we could not construct and source
7337/// range covered by the expression.
7338///
7339/// By default, RecoveryExpr uses dependence-bits to take advantage of existing
7340/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
7341/// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
7342/// addition to that, clang does not report most errors on dependent
7343/// expressions, so we get rid of bogus errors for free. However, note that
7344/// unlike other dependent expressions, RecoveryExpr can be produced in
7345/// non-template contexts.
7346///
7347/// We will preserve the type in RecoveryExpr when the type is known, e.g.
7348/// preserving the return type for a broken non-overloaded function call, a
7349/// overloaded call where all candidates have the same return type. In this
7350/// case, the expression is not type-dependent (unless the known type is itself
7351/// dependent)
7352///
7353/// One can also reliably suppress all bogus errors on expressions containing
7354/// recovery expressions by examining results of Expr::containsErrors().
7355class RecoveryExpr final : public Expr,
7356 private llvm::TrailingObjects<RecoveryExpr, Expr *> {
7357public:
7358 static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
7359 SourceLocation BeginLoc, SourceLocation EndLoc,
7360 ArrayRef<Expr *> SubExprs);
7361 static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
7362
7363 ArrayRef<Expr *> subExpressions() { return getTrailingObjects(N: NumExprs); }
7364
7365 ArrayRef<const Expr *> subExpressions() const {
7366 return const_cast<RecoveryExpr *>(this)->subExpressions();
7367 }
7368
7369 child_range children() {
7370 Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects());
7371 return child_range(B, B + NumExprs);
7372 }
7373
7374 SourceLocation getBeginLoc() const { return BeginLoc; }
7375 SourceLocation getEndLoc() const { return EndLoc; }
7376
7377 static bool classof(const Stmt *T) {
7378 return T->getStmtClass() == RecoveryExprClass;
7379 }
7380
7381private:
7382 RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
7383 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
7384 RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
7385 : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
7386
7387 size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
7388
7389 SourceLocation BeginLoc, EndLoc;
7390 unsigned NumExprs;
7391 friend TrailingObjects;
7392 friend class ASTStmtReader;
7393 friend class ASTStmtWriter;
7394};
7395
7396/// Insertion operator for diagnostics. This allows sending
7397/// Expr into a diagnostic with <<.
7398inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
7399 const Expr *E) {
7400 DB.AddTaggedVal(V: reinterpret_cast<uint64_t>(E), Kind: DiagnosticsEngine::ak_expr);
7401 return DB;
7402}
7403
7404} // end namespace clang
7405
7406#endif // LLVM_CLANG_AST_EXPR_H
7407

source code of clang/include/clang/AST/Expr.h