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