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