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