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