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