]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/ExprCXX.h
Update llvm, clang and lldb to trunk r257626, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / AST / ExprCXX.h
1 //===--- ExprCXX.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 /// \file
11 /// \brief Defines the clang::Expr interface and subclasses for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_AST_EXPRCXX_H
16 #define LLVM_CLANG_AST_EXPRCXX_H
17
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/LambdaCapture.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/AST/UnresolvedSet.h"
23 #include "clang/Basic/ExpressionTraits.h"
24 #include "clang/Basic/TypeTraits.h"
25 #include "llvm/Support/Compiler.h"
26
27 namespace clang {
28
29 class CXXConstructorDecl;
30 class CXXDestructorDecl;
31 class CXXMethodDecl;
32 class CXXTemporary;
33 class MSPropertyDecl;
34 class TemplateArgumentListInfo;
35 class UuidAttr;
36
37 //===--------------------------------------------------------------------===//
38 // C++ Expressions.
39 //===--------------------------------------------------------------------===//
40
41 /// \brief A call to an overloaded operator written using operator
42 /// syntax.
43 ///
44 /// Represents a call to an overloaded operator written using operator
45 /// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
46 /// normal call, this AST node provides better information about the
47 /// syntactic representation of the call.
48 ///
49 /// In a C++ template, this expression node kind will be used whenever
50 /// any of the arguments are type-dependent. In this case, the
51 /// function itself will be a (possibly empty) set of functions and
52 /// function templates that were found by name lookup at template
53 /// definition time.
54 class CXXOperatorCallExpr : public CallExpr {
55   /// \brief The overloaded operator.
56   OverloadedOperatorKind Operator;
57   SourceRange Range;
58
59   // Record the FP_CONTRACT state that applies to this operator call. Only
60   // meaningful for floating point types. For other types this value can be
61   // set to false.
62   unsigned FPContractable : 1;
63
64   SourceRange getSourceRangeImpl() const LLVM_READONLY;
65 public:
66   CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
67                       ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
68                       SourceLocation operatorloc, bool fpContractable)
69     : CallExpr(C, CXXOperatorCallExprClass, fn, 0, args, t, VK,
70                operatorloc),
71       Operator(Op), FPContractable(fpContractable) {
72     Range = getSourceRangeImpl();
73   }
74   explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) :
75     CallExpr(C, CXXOperatorCallExprClass, Empty) { }
76
77
78   /// \brief Returns the kind of overloaded operator that this
79   /// expression refers to.
80   OverloadedOperatorKind getOperator() const { return Operator; }
81
82   /// \brief Returns the location of the operator symbol in the expression.
83   ///
84   /// When \c getOperator()==OO_Call, this is the location of the right
85   /// parentheses; when \c getOperator()==OO_Subscript, this is the location
86   /// of the right bracket.
87   SourceLocation getOperatorLoc() const { return getRParenLoc(); }
88
89   SourceLocation getExprLoc() const LLVM_READONLY {
90     return (Operator < OO_Plus || Operator >= OO_Arrow ||
91             Operator == OO_PlusPlus || Operator == OO_MinusMinus)
92                ? getLocStart()
93                : getOperatorLoc();
94   }
95
96   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
97   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
98   SourceRange getSourceRange() const { return Range; }
99
100   static bool classof(const Stmt *T) {
101     return T->getStmtClass() == CXXOperatorCallExprClass;
102   }
103
104   // Set the FP contractability status of this operator. Only meaningful for
105   // operations on floating point types.
106   void setFPContractable(bool FPC) { FPContractable = FPC; }
107
108   // Get the FP contractability status of this operator. Only meaningful for
109   // operations on floating point types.
110   bool isFPContractable() const { return FPContractable; }
111
112   friend class ASTStmtReader;
113   friend class ASTStmtWriter;
114 };
115
116 /// Represents a call to a member function that
117 /// may be written either with member call syntax (e.g., "obj.func()"
118 /// or "objptr->func()") or with normal function-call syntax
119 /// ("func()") within a member function that ends up calling a member
120 /// function. The callee in either case is a MemberExpr that contains
121 /// both the object argument and the member function, while the
122 /// arguments are the arguments within the parentheses (not including
123 /// the object argument).
124 class CXXMemberCallExpr : public CallExpr {
125 public:
126   CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
127                     QualType t, ExprValueKind VK, SourceLocation RP)
128     : CallExpr(C, CXXMemberCallExprClass, fn, 0, args, t, VK, RP) {}
129
130   CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
131     : CallExpr(C, CXXMemberCallExprClass, Empty) { }
132
133   /// \brief Retrieves the implicit object argument for the member call.
134   ///
135   /// For example, in "x.f(5)", this returns the sub-expression "x".
136   Expr *getImplicitObjectArgument() const;
137
138   /// \brief Retrieves the declaration of the called method.
139   CXXMethodDecl *getMethodDecl() const;
140
141   /// \brief Retrieves the CXXRecordDecl for the underlying type of
142   /// the implicit object argument.
143   ///
144   /// Note that this is may not be the same declaration as that of the class
145   /// context of the CXXMethodDecl which this function is calling.
146   /// FIXME: Returns 0 for member pointer call exprs.
147   CXXRecordDecl *getRecordDecl() const;
148
149   static bool classof(const Stmt *T) {
150     return T->getStmtClass() == CXXMemberCallExprClass;
151   }
152 };
153
154 /// \brief Represents a call to a CUDA kernel function.
155 class CUDAKernelCallExpr : public CallExpr {
156 private:
157   enum { CONFIG, END_PREARG };
158
159 public:
160   CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
161                      ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
162                      SourceLocation RP)
163     : CallExpr(C, CUDAKernelCallExprClass, fn, END_PREARG, args, t, VK, RP) {
164     setConfig(Config);
165   }
166
167   CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
168     : CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) { }
169
170   const CallExpr *getConfig() const {
171     return cast_or_null<CallExpr>(getPreArg(CONFIG));
172   }
173   CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
174   void setConfig(CallExpr *E) { setPreArg(CONFIG, E); }
175
176   static bool classof(const Stmt *T) {
177     return T->getStmtClass() == CUDAKernelCallExprClass;
178   }
179 };
180
181 /// \brief Abstract class common to all of the C++ "named"/"keyword" casts.
182 ///
183 /// This abstract class is inherited by all of the classes
184 /// representing "named" casts: CXXStaticCastExpr for \c static_cast,
185 /// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
186 /// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
187 class CXXNamedCastExpr : public ExplicitCastExpr {
188 private:
189   SourceLocation Loc; // the location of the casting op
190   SourceLocation RParenLoc; // the location of the right parenthesis
191   SourceRange AngleBrackets; // range for '<' '>'
192
193 protected:
194   CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
195                    CastKind kind, Expr *op, unsigned PathSize,
196                    TypeSourceInfo *writtenTy, SourceLocation l,
197                    SourceLocation RParenLoc,
198                    SourceRange AngleBrackets)
199     : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
200       RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
201
202   explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
203     : ExplicitCastExpr(SC, Shell, PathSize) { }
204
205   friend class ASTStmtReader;
206
207 public:
208   const char *getCastName() const;
209
210   /// \brief Retrieve the location of the cast operator keyword, e.g.,
211   /// \c static_cast.
212   SourceLocation getOperatorLoc() const { return Loc; }
213
214   /// \brief Retrieve the location of the closing parenthesis.
215   SourceLocation getRParenLoc() const { return RParenLoc; }
216
217   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
218   SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
219   SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
220
221   static bool classof(const Stmt *T) {
222     switch (T->getStmtClass()) {
223     case CXXStaticCastExprClass:
224     case CXXDynamicCastExprClass:
225     case CXXReinterpretCastExprClass:
226     case CXXConstCastExprClass:
227       return true;
228     default:
229       return false;
230     }
231   }
232 };
233
234 /// \brief A C++ \c static_cast expression (C++ [expr.static.cast]).
235 ///
236 /// This expression node represents a C++ static cast, e.g.,
237 /// \c static_cast<int>(1.0).
238 class CXXStaticCastExpr final
239     : public CXXNamedCastExpr,
240       private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *> {
241   CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
242                     unsigned pathSize, TypeSourceInfo *writtenTy,
243                     SourceLocation l, SourceLocation RParenLoc,
244                     SourceRange AngleBrackets)
245     : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
246                        writtenTy, l, RParenLoc, AngleBrackets) {}
247
248   explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
249     : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { }
250
251 public:
252   static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
253                                    ExprValueKind VK, CastKind K, Expr *Op,
254                                    const CXXCastPath *Path,
255                                    TypeSourceInfo *Written, SourceLocation L,
256                                    SourceLocation RParenLoc,
257                                    SourceRange AngleBrackets);
258   static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
259                                         unsigned PathSize);
260
261   static bool classof(const Stmt *T) {
262     return T->getStmtClass() == CXXStaticCastExprClass;
263   }
264
265   friend TrailingObjects;
266   friend class CastExpr;
267 };
268
269 /// \brief A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
270 ///
271 /// This expression node represents a dynamic cast, e.g.,
272 /// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
273 /// check to determine how to perform the type conversion.
274 class CXXDynamicCastExpr final
275     : public CXXNamedCastExpr,
276       private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
277   CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
278                      Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
279                      SourceLocation l, SourceLocation RParenLoc,
280                      SourceRange AngleBrackets)
281     : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
282                        writtenTy, l, RParenLoc, AngleBrackets) {}
283
284   explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
285     : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { }
286
287 public:
288   static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
289                                     ExprValueKind VK, CastKind Kind, Expr *Op,
290                                     const CXXCastPath *Path,
291                                     TypeSourceInfo *Written, SourceLocation L,
292                                     SourceLocation RParenLoc,
293                                     SourceRange AngleBrackets);
294
295   static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
296                                          unsigned pathSize);
297
298   bool isAlwaysNull() const;
299
300   static bool classof(const Stmt *T) {
301     return T->getStmtClass() == CXXDynamicCastExprClass;
302   }
303
304   friend TrailingObjects;
305   friend class CastExpr;
306 };
307
308 /// \brief A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
309 ///
310 /// This expression node represents a reinterpret cast, e.g.,
311 /// @c reinterpret_cast<int>(VoidPtr).
312 ///
313 /// A reinterpret_cast provides a differently-typed view of a value but
314 /// (in Clang, as in most C++ implementations) performs no actual work at
315 /// run time.
316 class CXXReinterpretCastExpr final
317     : public CXXNamedCastExpr,
318       private llvm::TrailingObjects<CXXReinterpretCastExpr,
319                                     CXXBaseSpecifier *> {
320   CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
321                          Expr *op, unsigned pathSize,
322                          TypeSourceInfo *writtenTy, SourceLocation l,
323                          SourceLocation RParenLoc,
324                          SourceRange AngleBrackets)
325     : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
326                        pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
327
328   CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
329     : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { }
330
331 public:
332   static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
333                                         ExprValueKind VK, CastKind Kind,
334                                         Expr *Op, const CXXCastPath *Path,
335                                  TypeSourceInfo *WrittenTy, SourceLocation L,
336                                         SourceLocation RParenLoc,
337                                         SourceRange AngleBrackets);
338   static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
339                                              unsigned pathSize);
340
341   static bool classof(const Stmt *T) {
342     return T->getStmtClass() == CXXReinterpretCastExprClass;
343   }
344
345   friend TrailingObjects;
346   friend class CastExpr;
347 };
348
349 /// \brief A C++ \c const_cast expression (C++ [expr.const.cast]).
350 ///
351 /// This expression node represents a const cast, e.g.,
352 /// \c const_cast<char*>(PtrToConstChar).
353 ///
354 /// A const_cast can remove type qualifiers but does not change the underlying
355 /// value.
356 class CXXConstCastExpr final
357     : public CXXNamedCastExpr,
358       private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
359   CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
360                    TypeSourceInfo *writtenTy, SourceLocation l,
361                    SourceLocation RParenLoc, SourceRange AngleBrackets)
362     : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
363                        0, writtenTy, l, RParenLoc, AngleBrackets) {}
364
365   explicit CXXConstCastExpr(EmptyShell Empty)
366     : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { }
367
368 public:
369   static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
370                                   ExprValueKind VK, Expr *Op,
371                                   TypeSourceInfo *WrittenTy, SourceLocation L,
372                                   SourceLocation RParenLoc,
373                                   SourceRange AngleBrackets);
374   static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
375
376   static bool classof(const Stmt *T) {
377     return T->getStmtClass() == CXXConstCastExprClass;
378   }
379
380   friend TrailingObjects;
381   friend class CastExpr;
382 };
383
384 /// \brief A call to a literal operator (C++11 [over.literal])
385 /// written as a user-defined literal (C++11 [lit.ext]).
386 ///
387 /// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
388 /// is semantically equivalent to a normal call, this AST node provides better
389 /// information about the syntactic representation of the literal.
390 ///
391 /// Since literal operators are never found by ADL and can only be declared at
392 /// namespace scope, a user-defined literal is never dependent.
393 class UserDefinedLiteral : public CallExpr {
394   /// \brief The location of a ud-suffix within the literal.
395   SourceLocation UDSuffixLoc;
396
397 public:
398   UserDefinedLiteral(const ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
399                      QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
400                      SourceLocation SuffixLoc)
401     : CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, T, VK, LitEndLoc),
402       UDSuffixLoc(SuffixLoc) {}
403   explicit UserDefinedLiteral(const ASTContext &C, EmptyShell Empty)
404     : CallExpr(C, UserDefinedLiteralClass, Empty) {}
405
406   /// The kind of literal operator which is invoked.
407   enum LiteralOperatorKind {
408     LOK_Raw,      ///< Raw form: operator "" X (const char *)
409     LOK_Template, ///< Raw form: operator "" X<cs...> ()
410     LOK_Integer,  ///< operator "" X (unsigned long long)
411     LOK_Floating, ///< operator "" X (long double)
412     LOK_String,   ///< operator "" X (const CharT *, size_t)
413     LOK_Character ///< operator "" X (CharT)
414   };
415
416   /// \brief Returns the kind of literal operator invocation
417   /// which this expression represents.
418   LiteralOperatorKind getLiteralOperatorKind() const;
419
420   /// \brief If this is not a raw user-defined literal, get the
421   /// underlying cooked literal (representing the literal with the suffix
422   /// removed).
423   Expr *getCookedLiteral();
424   const Expr *getCookedLiteral() const {
425     return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
426   }
427
428   SourceLocation getLocStart() const {
429     if (getLiteralOperatorKind() == LOK_Template)
430       return getRParenLoc();
431     return getArg(0)->getLocStart();
432   }
433   SourceLocation getLocEnd() const { return getRParenLoc(); }
434
435
436   /// \brief Returns the location of a ud-suffix in the expression.
437   ///
438   /// For a string literal, there may be multiple identical suffixes. This
439   /// returns the first.
440   SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
441
442   /// \brief Returns the ud-suffix specified for this literal.
443   const IdentifierInfo *getUDSuffix() const;
444
445   static bool classof(const Stmt *S) {
446     return S->getStmtClass() == UserDefinedLiteralClass;
447   }
448
449   friend class ASTStmtReader;
450   friend class ASTStmtWriter;
451 };
452
453 /// \brief A boolean literal, per ([C++ lex.bool] Boolean literals).
454 ///
455 class CXXBoolLiteralExpr : public Expr {
456   bool Value;
457   SourceLocation Loc;
458 public:
459   CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
460     Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
461          false, false),
462     Value(val), Loc(l) {}
463
464   explicit CXXBoolLiteralExpr(EmptyShell Empty)
465     : Expr(CXXBoolLiteralExprClass, Empty) { }
466
467   bool getValue() const { return Value; }
468   void setValue(bool V) { Value = V; }
469
470   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
471   SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
472
473   SourceLocation getLocation() const { return Loc; }
474   void setLocation(SourceLocation L) { Loc = L; }
475
476   static bool classof(const Stmt *T) {
477     return T->getStmtClass() == CXXBoolLiteralExprClass;
478   }
479
480   // Iterators
481   child_range children() {
482     return child_range(child_iterator(), child_iterator());
483   }
484 };
485
486 /// \brief The null pointer literal (C++11 [lex.nullptr])
487 ///
488 /// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
489 class CXXNullPtrLiteralExpr : public Expr {
490   SourceLocation Loc;
491 public:
492   CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) :
493     Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
494          false, false),
495     Loc(l) {}
496
497   explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
498     : Expr(CXXNullPtrLiteralExprClass, Empty) { }
499
500   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
501   SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
502
503   SourceLocation getLocation() const { return Loc; }
504   void setLocation(SourceLocation L) { Loc = L; }
505
506   static bool classof(const Stmt *T) {
507     return T->getStmtClass() == CXXNullPtrLiteralExprClass;
508   }
509
510   child_range children() {
511     return child_range(child_iterator(), child_iterator());
512   }
513 };
514
515 /// \brief Implicit construction of a std::initializer_list<T> object from an
516 /// array temporary within list-initialization (C++11 [dcl.init.list]p5).
517 class CXXStdInitializerListExpr : public Expr {
518   Stmt *SubExpr;
519
520   CXXStdInitializerListExpr(EmptyShell Empty)
521     : Expr(CXXStdInitializerListExprClass, Empty), SubExpr(nullptr) {}
522
523 public:
524   CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
525     : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
526            Ty->isDependentType(), SubExpr->isValueDependent(),
527            SubExpr->isInstantiationDependent(),
528            SubExpr->containsUnexpandedParameterPack()),
529       SubExpr(SubExpr) {}
530
531   Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
532   const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
533
534   SourceLocation getLocStart() const LLVM_READONLY {
535     return SubExpr->getLocStart();
536   }
537   SourceLocation getLocEnd() const LLVM_READONLY {
538     return SubExpr->getLocEnd();
539   }
540   SourceRange getSourceRange() const LLVM_READONLY {
541     return SubExpr->getSourceRange();
542   }
543
544   static bool classof(const Stmt *S) {
545     return S->getStmtClass() == CXXStdInitializerListExprClass;
546   }
547
548   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
549
550   friend class ASTReader;
551   friend class ASTStmtReader;
552 };
553
554 /// A C++ \c typeid expression (C++ [expr.typeid]), which gets
555 /// the \c type_info that corresponds to the supplied type, or the (possibly
556 /// dynamic) type of the supplied expression.
557 ///
558 /// This represents code like \c typeid(int) or \c typeid(*objPtr)
559 class CXXTypeidExpr : public Expr {
560 private:
561   llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
562   SourceRange Range;
563
564 public:
565   CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
566     : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
567            // typeid is never type-dependent (C++ [temp.dep.expr]p4)
568            false,
569            // typeid is value-dependent if the type or expression are dependent
570            Operand->getType()->isDependentType(),
571            Operand->getType()->isInstantiationDependentType(),
572            Operand->getType()->containsUnexpandedParameterPack()),
573       Operand(Operand), Range(R) { }
574
575   CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
576     : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
577         // typeid is never type-dependent (C++ [temp.dep.expr]p4)
578            false,
579         // typeid is value-dependent if the type or expression are dependent
580            Operand->isTypeDependent() || Operand->isValueDependent(),
581            Operand->isInstantiationDependent(),
582            Operand->containsUnexpandedParameterPack()),
583       Operand(Operand), Range(R) { }
584
585   CXXTypeidExpr(EmptyShell Empty, bool isExpr)
586     : Expr(CXXTypeidExprClass, Empty) {
587     if (isExpr)
588       Operand = (Expr*)nullptr;
589     else
590       Operand = (TypeSourceInfo*)nullptr;
591   }
592
593   /// Determine whether this typeid has a type operand which is potentially
594   /// evaluated, per C++11 [expr.typeid]p3.
595   bool isPotentiallyEvaluated() const;
596
597   bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
598
599   /// \brief Retrieves the type operand of this typeid() expression after
600   /// various required adjustments (removing reference types, cv-qualifiers).
601   QualType getTypeOperand(ASTContext &Context) const;
602
603   /// \brief Retrieve source information for the type operand.
604   TypeSourceInfo *getTypeOperandSourceInfo() const {
605     assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
606     return Operand.get<TypeSourceInfo *>();
607   }
608
609   void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
610     assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
611     Operand = TSI;
612   }
613
614   Expr *getExprOperand() const {
615     assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
616     return static_cast<Expr*>(Operand.get<Stmt *>());
617   }
618
619   void setExprOperand(Expr *E) {
620     assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
621     Operand = E;
622   }
623
624   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
625   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
626   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
627   void setSourceRange(SourceRange R) { Range = R; }
628
629   static bool classof(const Stmt *T) {
630     return T->getStmtClass() == CXXTypeidExprClass;
631   }
632
633   // Iterators
634   child_range children() {
635     if (isTypeOperand())
636       return child_range(child_iterator(), child_iterator());
637     Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
638     return child_range(begin, begin + 1);
639   }
640 };
641
642 /// \brief A member reference to an MSPropertyDecl. 
643 ///
644 /// This expression always has pseudo-object type, and therefore it is
645 /// typically not encountered in a fully-typechecked expression except
646 /// within the syntactic form of a PseudoObjectExpr.
647 class MSPropertyRefExpr : public Expr {
648   Expr *BaseExpr;
649   MSPropertyDecl *TheDecl;
650   SourceLocation MemberLoc;
651   bool IsArrow;
652   NestedNameSpecifierLoc QualifierLoc;
653
654 public:
655   MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
656                     QualType ty, ExprValueKind VK,
657                     NestedNameSpecifierLoc qualifierLoc,
658                     SourceLocation nameLoc)
659   : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
660          /*type-dependent*/ false, baseExpr->isValueDependent(),
661          baseExpr->isInstantiationDependent(),
662          baseExpr->containsUnexpandedParameterPack()),
663     BaseExpr(baseExpr), TheDecl(decl),
664     MemberLoc(nameLoc), IsArrow(isArrow),
665     QualifierLoc(qualifierLoc) {}
666
667   MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
668
669   SourceRange getSourceRange() const LLVM_READONLY {
670     return SourceRange(getLocStart(), getLocEnd());
671   }
672   bool isImplicitAccess() const {
673     return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
674   }
675   SourceLocation getLocStart() const {
676     if (!isImplicitAccess())
677       return BaseExpr->getLocStart();
678     else if (QualifierLoc)
679       return QualifierLoc.getBeginLoc();
680     else
681         return MemberLoc;
682   }
683   SourceLocation getLocEnd() const { return getMemberLoc(); }
684
685   child_range children() {
686     return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
687   }
688   static bool classof(const Stmt *T) {
689     return T->getStmtClass() == MSPropertyRefExprClass;
690   }
691
692   Expr *getBaseExpr() const { return BaseExpr; }
693   MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
694   bool isArrow() const { return IsArrow; }
695   SourceLocation getMemberLoc() const { return MemberLoc; }
696   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
697
698   friend class ASTStmtReader;
699 };
700
701 /// MS property subscript expression.
702 /// MSVC supports 'property' attribute and allows to apply it to the
703 /// declaration of an empty array in a class or structure definition.
704 /// For example:
705 /// \code
706 /// __declspec(property(get=GetX, put=PutX)) int x[];
707 /// \endcode
708 /// The above statement indicates that x[] can be used with one or more array
709 /// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
710 /// p->x[a][b] = i will be turned into p->PutX(a, b, i).
711 /// This is a syntactic pseudo-object expression.
712 class MSPropertySubscriptExpr : public Expr {
713   friend class ASTStmtReader;
714   enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
715   Stmt *SubExprs[NUM_SUBEXPRS];
716   SourceLocation RBracketLoc;
717
718   void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
719   void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
720
721 public:
722   MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
723                           ExprObjectKind OK, SourceLocation RBracketLoc)
724       : Expr(MSPropertySubscriptExprClass, Ty, VK, OK, Idx->isTypeDependent(),
725              Idx->isValueDependent(), Idx->isInstantiationDependent(),
726              Idx->containsUnexpandedParameterPack()),
727         RBracketLoc(RBracketLoc) {
728     SubExprs[BASE_EXPR] = Base;
729     SubExprs[IDX_EXPR] = Idx;
730   }
731
732   /// \brief Create an empty array subscript expression.
733   explicit MSPropertySubscriptExpr(EmptyShell Shell)
734       : Expr(MSPropertySubscriptExprClass, Shell) {}
735
736   Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
737   const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
738
739   Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
740   const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
741
742   SourceLocation getLocStart() const LLVM_READONLY {
743     return getBase()->getLocStart();
744   }
745   SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
746
747   SourceLocation getRBracketLoc() const { return RBracketLoc; }
748   void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
749
750   SourceLocation getExprLoc() const LLVM_READONLY {
751     return getBase()->getExprLoc();
752   }
753
754   static bool classof(const Stmt *T) {
755     return T->getStmtClass() == MSPropertySubscriptExprClass;
756   }
757
758   // Iterators
759   child_range children() {
760     return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
761   }
762 };
763
764 /// A Microsoft C++ @c __uuidof expression, which gets
765 /// the _GUID that corresponds to the supplied type or expression.
766 ///
767 /// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
768 class CXXUuidofExpr : public Expr {
769 private:
770   llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
771   SourceRange Range;
772
773 public:
774   CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
775     : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
776            false, Operand->getType()->isDependentType(),
777            Operand->getType()->isInstantiationDependentType(),
778            Operand->getType()->containsUnexpandedParameterPack()),
779       Operand(Operand), Range(R) { }
780
781   CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
782     : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
783            false, Operand->isTypeDependent(),
784            Operand->isInstantiationDependent(),
785            Operand->containsUnexpandedParameterPack()),
786       Operand(Operand), Range(R) { }
787
788   CXXUuidofExpr(EmptyShell Empty, bool isExpr)
789     : Expr(CXXUuidofExprClass, Empty) {
790     if (isExpr)
791       Operand = (Expr*)nullptr;
792     else
793       Operand = (TypeSourceInfo*)nullptr;
794   }
795
796   bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
797
798   /// \brief Retrieves the type operand of this __uuidof() expression after
799   /// various required adjustments (removing reference types, cv-qualifiers).
800   QualType getTypeOperand(ASTContext &Context) const;
801
802   /// \brief Retrieve source information for the type operand.
803   TypeSourceInfo *getTypeOperandSourceInfo() const {
804     assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
805     return Operand.get<TypeSourceInfo *>();
806   }
807
808   void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
809     assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
810     Operand = TSI;
811   }
812
813   Expr *getExprOperand() const {
814     assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
815     return static_cast<Expr*>(Operand.get<Stmt *>());
816   }
817
818   void setExprOperand(Expr *E) {
819     assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
820     Operand = E;
821   }
822
823   StringRef getUuidAsStringRef(ASTContext &Context) const;
824
825   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
826   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
827   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
828   void setSourceRange(SourceRange R) { Range = R; }
829
830   static bool classof(const Stmt *T) {
831     return T->getStmtClass() == CXXUuidofExprClass;
832   }
833
834   /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
835   /// a single GUID.
836   static const UuidAttr *GetUuidAttrOfType(QualType QT,
837                                            bool *HasMultipleGUIDsPtr = nullptr);
838
839   // Iterators
840   child_range children() {
841     if (isTypeOperand())
842       return child_range(child_iterator(), child_iterator());
843     Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
844     return child_range(begin, begin + 1);
845   }
846 };
847
848 /// \brief Represents the \c this expression in C++.
849 ///
850 /// This is a pointer to the object on which the current member function is
851 /// executing (C++ [expr.prim]p3). Example:
852 ///
853 /// \code
854 /// class Foo {
855 /// public:
856 ///   void bar();
857 ///   void test() { this->bar(); }
858 /// };
859 /// \endcode
860 class CXXThisExpr : public Expr {
861   SourceLocation Loc;
862   bool Implicit : 1;
863
864 public:
865   CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
866     : Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
867            // 'this' is type-dependent if the class type of the enclosing
868            // member function is dependent (C++ [temp.dep.expr]p2)
869            Type->isDependentType(), Type->isDependentType(),
870            Type->isInstantiationDependentType(),
871            /*ContainsUnexpandedParameterPack=*/false),
872       Loc(L), Implicit(isImplicit) { }
873
874   CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
875
876   SourceLocation getLocation() const { return Loc; }
877   void setLocation(SourceLocation L) { Loc = L; }
878
879   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
880   SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
881
882   bool isImplicit() const { return Implicit; }
883   void setImplicit(bool I) { Implicit = I; }
884
885   static bool classof(const Stmt *T) {
886     return T->getStmtClass() == CXXThisExprClass;
887   }
888
889   // Iterators
890   child_range children() {
891     return child_range(child_iterator(), child_iterator());
892   }
893 };
894
895 /// \brief A C++ throw-expression (C++ [except.throw]).
896 ///
897 /// This handles 'throw' (for re-throwing the current exception) and
898 /// 'throw' assignment-expression.  When assignment-expression isn't
899 /// present, Op will be null.
900 class CXXThrowExpr : public Expr {
901   Stmt *Op;
902   SourceLocation ThrowLoc;
903   /// \brief Whether the thrown variable (if any) is in scope.
904   unsigned IsThrownVariableInScope : 1;
905
906   friend class ASTStmtReader;
907
908 public:
909   // \p Ty is the void type which is used as the result type of the
910   // expression.  The \p l is the location of the throw keyword.  \p expr
911   // can by null, if the optional expression to throw isn't present.
912   CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
913                bool IsThrownVariableInScope) :
914     Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
915          expr && expr->isInstantiationDependent(),
916          expr && expr->containsUnexpandedParameterPack()),
917     Op(expr), ThrowLoc(l), IsThrownVariableInScope(IsThrownVariableInScope) {}
918   CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
919
920   const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
921   Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
922
923   SourceLocation getThrowLoc() const { return ThrowLoc; }
924
925   /// \brief Determines whether the variable thrown by this expression (if any!)
926   /// is within the innermost try block.
927   ///
928   /// This information is required to determine whether the NRVO can apply to
929   /// this variable.
930   bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
931
932   SourceLocation getLocStart() const LLVM_READONLY { return ThrowLoc; }
933   SourceLocation getLocEnd() const LLVM_READONLY {
934     if (!getSubExpr())
935       return ThrowLoc;
936     return getSubExpr()->getLocEnd();
937   }
938
939   static bool classof(const Stmt *T) {
940     return T->getStmtClass() == CXXThrowExprClass;
941   }
942
943   // Iterators
944   child_range children() {
945     return child_range(&Op, Op ? &Op+1 : &Op);
946   }
947 };
948
949 /// \brief A default argument (C++ [dcl.fct.default]).
950 ///
951 /// This wraps up a function call argument that was created from the
952 /// corresponding parameter's default argument, when the call did not
953 /// explicitly supply arguments for all of the parameters.
954 class CXXDefaultArgExpr final : public Expr {
955   /// \brief The parameter whose default is being used.
956   ParmVarDecl *Param;
957
958   /// \brief The location where the default argument expression was used.
959   SourceLocation Loc;
960
961   CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
962     : Expr(SC,
963            param->hasUnparsedDefaultArg()
964              ? param->getType().getNonReferenceType()
965              : param->getDefaultArg()->getType(),
966            param->getDefaultArg()->getValueKind(),
967            param->getDefaultArg()->getObjectKind(), false, false, false, false),
968       Param(param), Loc(Loc) { }
969
970 public:
971   CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
972
973   // \p Param is the parameter whose default argument is used by this
974   // expression.
975   static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
976                                    ParmVarDecl *Param) {
977     return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
978   }
979
980   // Retrieve the parameter that the argument was created from.
981   const ParmVarDecl *getParam() const { return Param; }
982   ParmVarDecl *getParam() { return Param; }
983
984   // Retrieve the actual argument to the function call.
985   const Expr *getExpr() const {
986     return getParam()->getDefaultArg();
987   }
988   Expr *getExpr() {
989     return getParam()->getDefaultArg();
990   }
991
992   /// \brief Retrieve the location where this default argument was actually
993   /// used.
994   SourceLocation getUsedLocation() const { return Loc; }
995
996   /// Default argument expressions have no representation in the
997   /// source, so they have an empty source range.
998   SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
999   SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
1000
1001   SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1002
1003   static bool classof(const Stmt *T) {
1004     return T->getStmtClass() == CXXDefaultArgExprClass;
1005   }
1006
1007   // Iterators
1008   child_range children() {
1009     return child_range(child_iterator(), child_iterator());
1010   }
1011
1012   friend class ASTStmtReader;
1013   friend class ASTStmtWriter;
1014 };
1015
1016 /// \brief A use of a default initializer in a constructor or in aggregate
1017 /// initialization.
1018 ///
1019 /// This wraps a use of a C++ default initializer (technically,
1020 /// a brace-or-equal-initializer for a non-static data member) when it
1021 /// is implicitly used in a mem-initializer-list in a constructor
1022 /// (C++11 [class.base.init]p8) or in aggregate initialization
1023 /// (C++1y [dcl.init.aggr]p7).
1024 class CXXDefaultInitExpr : public Expr {
1025   /// \brief The field whose default is being used.
1026   FieldDecl *Field;
1027
1028   /// \brief The location where the default initializer expression was used.
1029   SourceLocation Loc;
1030
1031   CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc, FieldDecl *Field,
1032                      QualType T);
1033
1034   CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1035
1036 public:
1037   /// \p Field is the non-static data member whose default initializer is used
1038   /// by this expression.
1039   static CXXDefaultInitExpr *Create(const ASTContext &C, SourceLocation Loc,
1040                                     FieldDecl *Field) {
1041     return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
1042   }
1043
1044   /// \brief Get the field whose initializer will be used.
1045   FieldDecl *getField() { return Field; }
1046   const FieldDecl *getField() const { return Field; }
1047
1048   /// \brief Get the initialization expression that will be used.
1049   const Expr *getExpr() const {
1050     assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1051     return Field->getInClassInitializer();
1052   }
1053   Expr *getExpr() {
1054     assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1055     return Field->getInClassInitializer();
1056   }
1057
1058   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1059   SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1060
1061   static bool classof(const Stmt *T) {
1062     return T->getStmtClass() == CXXDefaultInitExprClass;
1063   }
1064
1065   // Iterators
1066   child_range children() {
1067     return child_range(child_iterator(), child_iterator());
1068   }
1069
1070   friend class ASTReader;
1071   friend class ASTStmtReader;
1072 };
1073
1074 /// \brief Represents a C++ temporary.
1075 class CXXTemporary {
1076   /// \brief The destructor that needs to be called.
1077   const CXXDestructorDecl *Destructor;
1078
1079   explicit CXXTemporary(const CXXDestructorDecl *destructor)
1080     : Destructor(destructor) { }
1081
1082 public:
1083   static CXXTemporary *Create(const ASTContext &C,
1084                               const CXXDestructorDecl *Destructor);
1085
1086   const CXXDestructorDecl *getDestructor() const { return Destructor; }
1087   void setDestructor(const CXXDestructorDecl *Dtor) {
1088     Destructor = Dtor;
1089   }
1090 };
1091
1092 /// \brief Represents binding an expression to a temporary.
1093 ///
1094 /// This ensures the destructor is called for the temporary. It should only be
1095 /// needed for non-POD, non-trivially destructable class types. For example:
1096 ///
1097 /// \code
1098 ///   struct S {
1099 ///     S() { }  // User defined constructor makes S non-POD.
1100 ///     ~S() { } // User defined destructor makes it non-trivial.
1101 ///   };
1102 ///   void test() {
1103 ///     const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1104 ///   }
1105 /// \endcode
1106 class CXXBindTemporaryExpr : public Expr {
1107   CXXTemporary *Temp;
1108
1109   Stmt *SubExpr;
1110
1111   CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1112    : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1113           VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1114           SubExpr->isValueDependent(),
1115           SubExpr->isInstantiationDependent(),
1116           SubExpr->containsUnexpandedParameterPack()),
1117      Temp(temp), SubExpr(SubExpr) { }
1118
1119 public:
1120   CXXBindTemporaryExpr(EmptyShell Empty)
1121     : Expr(CXXBindTemporaryExprClass, Empty), Temp(nullptr), SubExpr(nullptr) {}
1122
1123   static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1124                                       Expr* SubExpr);
1125
1126   CXXTemporary *getTemporary() { return Temp; }
1127   const CXXTemporary *getTemporary() const { return Temp; }
1128   void setTemporary(CXXTemporary *T) { Temp = T; }
1129
1130   const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1131   Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1132   void setSubExpr(Expr *E) { SubExpr = E; }
1133
1134   SourceLocation getLocStart() const LLVM_READONLY {
1135     return SubExpr->getLocStart();
1136   }
1137   SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
1138
1139   // Implement isa/cast/dyncast/etc.
1140   static bool classof(const Stmt *T) {
1141     return T->getStmtClass() == CXXBindTemporaryExprClass;
1142   }
1143
1144   // Iterators
1145   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1146 };
1147
1148 /// \brief Represents a call to a C++ constructor.
1149 class CXXConstructExpr : public Expr {
1150 public:
1151   enum ConstructionKind {
1152     CK_Complete,
1153     CK_NonVirtualBase,
1154     CK_VirtualBase,
1155     CK_Delegating
1156   };
1157
1158 private:
1159   CXXConstructorDecl *Constructor;
1160
1161   SourceLocation Loc;
1162   SourceRange ParenOrBraceRange;
1163   unsigned NumArgs : 16;
1164   bool Elidable : 1;
1165   bool HadMultipleCandidates : 1;
1166   bool ListInitialization : 1;
1167   bool StdInitListInitialization : 1;
1168   bool ZeroInitialization : 1;
1169   unsigned ConstructKind : 2;
1170   Stmt **Args;
1171
1172 protected:
1173   CXXConstructExpr(const ASTContext &C, StmtClass SC, QualType T,
1174                    SourceLocation Loc,
1175                    CXXConstructorDecl *d, bool elidable,
1176                    ArrayRef<Expr *> Args,
1177                    bool HadMultipleCandidates,
1178                    bool ListInitialization,
1179                    bool StdInitListInitialization,
1180                    bool ZeroInitialization,
1181                    ConstructionKind ConstructKind,
1182                    SourceRange ParenOrBraceRange);
1183
1184   /// \brief Construct an empty C++ construction expression.
1185   CXXConstructExpr(StmtClass SC, EmptyShell Empty)
1186     : Expr(SC, Empty), Constructor(nullptr), NumArgs(0), Elidable(false),
1187       HadMultipleCandidates(false), ListInitialization(false),
1188       ZeroInitialization(false), ConstructKind(0), Args(nullptr)
1189   { }
1190
1191 public:
1192   /// \brief Construct an empty C++ construction expression.
1193   explicit CXXConstructExpr(EmptyShell Empty)
1194     : Expr(CXXConstructExprClass, Empty), Constructor(nullptr),
1195       NumArgs(0), Elidable(false), HadMultipleCandidates(false),
1196       ListInitialization(false), ZeroInitialization(false),
1197       ConstructKind(0), Args(nullptr)
1198   { }
1199
1200   static CXXConstructExpr *Create(const ASTContext &C, QualType T,
1201                                   SourceLocation Loc,
1202                                   CXXConstructorDecl *D, bool Elidable,
1203                                   ArrayRef<Expr *> Args,
1204                                   bool HadMultipleCandidates,
1205                                   bool ListInitialization,
1206                                   bool StdInitListInitialization,
1207                                   bool ZeroInitialization,
1208                                   ConstructionKind ConstructKind,
1209                                   SourceRange ParenOrBraceRange);
1210
1211   CXXConstructorDecl *getConstructor() const { return Constructor; }
1212   void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
1213
1214   SourceLocation getLocation() const { return Loc; }
1215   void setLocation(SourceLocation Loc) { this->Loc = Loc; }
1216
1217   /// \brief Whether this construction is elidable.
1218   bool isElidable() const { return Elidable; }
1219   void setElidable(bool E) { Elidable = E; }
1220
1221   /// \brief Whether the referred constructor was resolved from
1222   /// an overloaded set having size greater than 1.
1223   bool hadMultipleCandidates() const { return HadMultipleCandidates; }
1224   void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
1225
1226   /// \brief Whether this constructor call was written as list-initialization.
1227   bool isListInitialization() const { return ListInitialization; }
1228   void setListInitialization(bool V) { ListInitialization = V; }
1229
1230   /// \brief Whether this constructor call was written as list-initialization,
1231   /// but was interpreted as forming a std::initializer_list<T> from the list
1232   /// and passing that as a single constructor argument.
1233   /// See C++11 [over.match.list]p1 bullet 1.
1234   bool isStdInitListInitialization() const { return StdInitListInitialization; }
1235   void setStdInitListInitialization(bool V) { StdInitListInitialization = V; }
1236
1237   /// \brief Whether this construction first requires
1238   /// zero-initialization before the initializer is called.
1239   bool requiresZeroInitialization() const { return ZeroInitialization; }
1240   void setRequiresZeroInitialization(bool ZeroInit) {
1241     ZeroInitialization = ZeroInit;
1242   }
1243
1244   /// \brief Determine whether this constructor is actually constructing
1245   /// a base class (rather than a complete object).
1246   ConstructionKind getConstructionKind() const {
1247     return (ConstructionKind)ConstructKind;
1248   }
1249   void setConstructionKind(ConstructionKind CK) {
1250     ConstructKind = CK;
1251   }
1252
1253   typedef ExprIterator arg_iterator;
1254   typedef ConstExprIterator const_arg_iterator;
1255   typedef llvm::iterator_range<arg_iterator> arg_range;
1256   typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
1257
1258   arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1259   arg_const_range arguments() const {
1260     return arg_const_range(arg_begin(), arg_end());
1261   }
1262
1263   arg_iterator arg_begin() { return Args; }
1264   arg_iterator arg_end() { return Args + NumArgs; }
1265   const_arg_iterator arg_begin() const { return Args; }
1266   const_arg_iterator arg_end() const { return Args + NumArgs; }
1267
1268   Expr **getArgs() { return reinterpret_cast<Expr **>(Args); }
1269   const Expr *const *getArgs() const {
1270     return const_cast<CXXConstructExpr *>(this)->getArgs();
1271   }
1272   unsigned getNumArgs() const { return NumArgs; }
1273
1274   /// \brief Return the specified argument.
1275   Expr *getArg(unsigned Arg) {
1276     assert(Arg < NumArgs && "Arg access out of range!");
1277     return cast<Expr>(Args[Arg]);
1278   }
1279   const Expr *getArg(unsigned Arg) const {
1280     assert(Arg < NumArgs && "Arg access out of range!");
1281     return cast<Expr>(Args[Arg]);
1282   }
1283
1284   /// \brief Set the specified argument.
1285   void setArg(unsigned Arg, Expr *ArgExpr) {
1286     assert(Arg < NumArgs && "Arg access out of range!");
1287     Args[Arg] = ArgExpr;
1288   }
1289
1290   SourceLocation getLocStart() const LLVM_READONLY;
1291   SourceLocation getLocEnd() const LLVM_READONLY;
1292   SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1293   void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1294
1295   static bool classof(const Stmt *T) {
1296     return T->getStmtClass() == CXXConstructExprClass ||
1297       T->getStmtClass() == CXXTemporaryObjectExprClass;
1298   }
1299
1300   // Iterators
1301   child_range children() {
1302     return child_range(&Args[0], &Args[0]+NumArgs);
1303   }
1304
1305   friend class ASTStmtReader;
1306 };
1307
1308 /// \brief Represents an explicit C++ type conversion that uses "functional"
1309 /// notation (C++ [expr.type.conv]).
1310 ///
1311 /// Example:
1312 /// \code
1313 ///   x = int(0.5);
1314 /// \endcode
1315 class CXXFunctionalCastExpr final
1316     : public ExplicitCastExpr,
1317       private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *> {
1318   SourceLocation LParenLoc;
1319   SourceLocation RParenLoc;
1320
1321   CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1322                         TypeSourceInfo *writtenTy,
1323                         CastKind kind, Expr *castExpr, unsigned pathSize,
1324                         SourceLocation lParenLoc, SourceLocation rParenLoc)
1325     : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1326                        castExpr, pathSize, writtenTy),
1327       LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
1328
1329   explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1330     : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { }
1331
1332 public:
1333   static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
1334                                        ExprValueKind VK,
1335                                        TypeSourceInfo *Written,
1336                                        CastKind Kind, Expr *Op,
1337                                        const CXXCastPath *Path,
1338                                        SourceLocation LPLoc,
1339                                        SourceLocation RPLoc);
1340   static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
1341                                             unsigned PathSize);
1342
1343   SourceLocation getLParenLoc() const { return LParenLoc; }
1344   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1345   SourceLocation getRParenLoc() const { return RParenLoc; }
1346   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1347
1348   SourceLocation getLocStart() const LLVM_READONLY;
1349   SourceLocation getLocEnd() const LLVM_READONLY;
1350
1351   static bool classof(const Stmt *T) {
1352     return T->getStmtClass() == CXXFunctionalCastExprClass;
1353   }
1354
1355   friend TrailingObjects;
1356   friend class CastExpr;
1357 };
1358
1359 /// @brief Represents a C++ functional cast expression that builds a
1360 /// temporary object.
1361 ///
1362 /// This expression type represents a C++ "functional" cast
1363 /// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1364 /// constructor to build a temporary object. With N == 1 arguments the
1365 /// functional cast expression will be represented by CXXFunctionalCastExpr.
1366 /// Example:
1367 /// \code
1368 /// struct X { X(int, float); }
1369 ///
1370 /// X create_X() {
1371 ///   return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1372 /// };
1373 /// \endcode
1374 class CXXTemporaryObjectExpr : public CXXConstructExpr {
1375   TypeSourceInfo *Type;
1376
1377 public:
1378   CXXTemporaryObjectExpr(const ASTContext &C, CXXConstructorDecl *Cons,
1379                          TypeSourceInfo *Type,
1380                          ArrayRef<Expr *> Args,
1381                          SourceRange ParenOrBraceRange,
1382                          bool HadMultipleCandidates,
1383                          bool ListInitialization,
1384                          bool StdInitListInitialization,
1385                          bool ZeroInitialization);
1386   explicit CXXTemporaryObjectExpr(EmptyShell Empty)
1387     : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty), Type() { }
1388
1389   TypeSourceInfo *getTypeSourceInfo() const { return Type; }
1390
1391   SourceLocation getLocStart() const LLVM_READONLY;
1392   SourceLocation getLocEnd() const LLVM_READONLY;
1393
1394   static bool classof(const Stmt *T) {
1395     return T->getStmtClass() == CXXTemporaryObjectExprClass;
1396   }
1397
1398   friend class ASTStmtReader;
1399 };
1400
1401 /// \brief A C++ lambda expression, which produces a function object
1402 /// (of unspecified type) that can be invoked later.
1403 ///
1404 /// Example:
1405 /// \code
1406 /// void low_pass_filter(std::vector<double> &values, double cutoff) {
1407 ///   values.erase(std::remove_if(values.begin(), values.end(),
1408 ///                               [=](double value) { return value > cutoff; });
1409 /// }
1410 /// \endcode
1411 ///
1412 /// C++11 lambda expressions can capture local variables, either by copying
1413 /// the values of those local variables at the time the function
1414 /// object is constructed (not when it is called!) or by holding a
1415 /// reference to the local variable. These captures can occur either
1416 /// implicitly or can be written explicitly between the square
1417 /// brackets ([...]) that start the lambda expression.
1418 ///
1419 /// C++1y introduces a new form of "capture" called an init-capture that
1420 /// includes an initializing expression (rather than capturing a variable),
1421 /// and which can never occur implicitly.
1422 class LambdaExpr final
1423     : public Expr,
1424       private llvm::TrailingObjects<LambdaExpr, Stmt *, unsigned, VarDecl *> {
1425   /// \brief The source range that covers the lambda introducer ([...]).
1426   SourceRange IntroducerRange;
1427
1428   /// \brief The source location of this lambda's capture-default ('=' or '&').
1429   SourceLocation CaptureDefaultLoc;
1430
1431   /// \brief The number of captures.
1432   unsigned NumCaptures : 16;
1433   
1434   /// \brief The default capture kind, which is a value of type
1435   /// LambdaCaptureDefault.
1436   unsigned CaptureDefault : 2;
1437
1438   /// \brief Whether this lambda had an explicit parameter list vs. an
1439   /// implicit (and empty) parameter list.
1440   unsigned ExplicitParams : 1;
1441
1442   /// \brief Whether this lambda had the result type explicitly specified.
1443   unsigned ExplicitResultType : 1;
1444   
1445   /// \brief Whether there are any array index variables stored at the end of
1446   /// this lambda expression.
1447   unsigned HasArrayIndexVars : 1;
1448   
1449   /// \brief The location of the closing brace ('}') that completes
1450   /// the lambda.
1451   /// 
1452   /// The location of the brace is also available by looking up the
1453   /// function call operator in the lambda class. However, it is
1454   /// stored here to improve the performance of getSourceRange(), and
1455   /// to avoid having to deserialize the function call operator from a
1456   /// module file just to determine the source range.
1457   SourceLocation ClosingBrace;
1458
1459   size_t numTrailingObjects(OverloadToken<Stmt *>) const {
1460     return NumCaptures + 1;
1461   }
1462
1463   size_t numTrailingObjects(OverloadToken<unsigned>) const {
1464     return HasArrayIndexVars ? NumCaptures + 1 : 0;
1465   }
1466
1467   /// \brief Construct a lambda expression.
1468   LambdaExpr(QualType T, SourceRange IntroducerRange,
1469              LambdaCaptureDefault CaptureDefault,
1470              SourceLocation CaptureDefaultLoc, ArrayRef<LambdaCapture> Captures,
1471              bool ExplicitParams, bool ExplicitResultType,
1472              ArrayRef<Expr *> CaptureInits, ArrayRef<VarDecl *> ArrayIndexVars,
1473              ArrayRef<unsigned> ArrayIndexStarts, SourceLocation ClosingBrace,
1474              bool ContainsUnexpandedParameterPack);
1475
1476   /// \brief Construct an empty lambda expression.
1477   LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVars)
1478     : Expr(LambdaExprClass, Empty),
1479       NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(false),
1480       ExplicitResultType(false), HasArrayIndexVars(true) { 
1481     getStoredStmts()[NumCaptures] = nullptr;
1482   }
1483
1484   Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1485
1486   Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1487
1488   /// \brief Retrieve the mapping from captures to the first array index
1489   /// variable.
1490   unsigned *getArrayIndexStarts() { return getTrailingObjects<unsigned>(); }
1491
1492   const unsigned *getArrayIndexStarts() const {
1493     return getTrailingObjects<unsigned>();
1494   }
1495
1496   /// \brief Retrieve the complete set of array-index variables.
1497   VarDecl **getArrayIndexVars() { return getTrailingObjects<VarDecl *>(); }
1498
1499   VarDecl *const *getArrayIndexVars() const {
1500     return getTrailingObjects<VarDecl *>();
1501   }
1502
1503 public:
1504   /// \brief Construct a new lambda expression.
1505   static LambdaExpr *
1506   Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1507          LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1508          ArrayRef<LambdaCapture> Captures, bool ExplicitParams,
1509          bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1510          ArrayRef<VarDecl *> ArrayIndexVars,
1511          ArrayRef<unsigned> ArrayIndexStarts, SourceLocation ClosingBrace,
1512          bool ContainsUnexpandedParameterPack);
1513
1514   /// \brief Construct a new lambda expression that will be deserialized from
1515   /// an external source.
1516   static LambdaExpr *CreateDeserialized(const ASTContext &C,
1517                                         unsigned NumCaptures,
1518                                         unsigned NumArrayIndexVars);
1519
1520   /// \brief Determine the default capture kind for this lambda.
1521   LambdaCaptureDefault getCaptureDefault() const {
1522     return static_cast<LambdaCaptureDefault>(CaptureDefault);
1523   }
1524
1525   /// \brief Retrieve the location of this lambda's capture-default, if any.
1526   SourceLocation getCaptureDefaultLoc() const {
1527     return CaptureDefaultLoc;
1528   }
1529
1530   /// \brief Determine whether one of this lambda's captures is an init-capture.
1531   bool isInitCapture(const LambdaCapture *Capture) const;
1532
1533   /// \brief An iterator that walks over the captures of the lambda,
1534   /// both implicit and explicit.
1535   typedef const LambdaCapture *capture_iterator;
1536
1537   /// \brief An iterator over a range of lambda captures.
1538   typedef llvm::iterator_range<capture_iterator> capture_range;
1539
1540   /// \brief Retrieve this lambda's captures.
1541   capture_range captures() const;
1542   
1543   /// \brief Retrieve an iterator pointing to the first lambda capture.
1544   capture_iterator capture_begin() const;
1545
1546   /// \brief Retrieve an iterator pointing past the end of the
1547   /// sequence of lambda captures.
1548   capture_iterator capture_end() const;
1549
1550   /// \brief Determine the number of captures in this lambda.
1551   unsigned capture_size() const { return NumCaptures; }
1552
1553   /// \brief Retrieve this lambda's explicit captures.
1554   capture_range explicit_captures() const;
1555   
1556   /// \brief Retrieve an iterator pointing to the first explicit
1557   /// lambda capture.
1558   capture_iterator explicit_capture_begin() const;
1559
1560   /// \brief Retrieve an iterator pointing past the end of the sequence of
1561   /// explicit lambda captures.
1562   capture_iterator explicit_capture_end() const;
1563
1564   /// \brief Retrieve this lambda's implicit captures.
1565   capture_range implicit_captures() const;
1566
1567   /// \brief Retrieve an iterator pointing to the first implicit
1568   /// lambda capture.
1569   capture_iterator implicit_capture_begin() const;
1570
1571   /// \brief Retrieve an iterator pointing past the end of the sequence of
1572   /// implicit lambda captures.
1573   capture_iterator implicit_capture_end() const;
1574
1575   /// \brief Iterator that walks over the capture initialization
1576   /// arguments.
1577   typedef Expr **capture_init_iterator;
1578
1579   /// \brief Const iterator that walks over the capture initialization
1580   /// arguments.
1581   typedef Expr *const *const_capture_init_iterator;
1582
1583   /// \brief Retrieve the initialization expressions for this lambda's captures.
1584   llvm::iterator_range<capture_init_iterator> capture_inits() {
1585     return llvm::make_range(capture_init_begin(), capture_init_end());
1586   }
1587
1588   /// \brief Retrieve the initialization expressions for this lambda's captures.
1589   llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1590     return llvm::make_range(capture_init_begin(), capture_init_end());
1591   }
1592
1593   /// \brief Retrieve the first initialization argument for this
1594   /// lambda expression (which initializes the first capture field).
1595   capture_init_iterator capture_init_begin() {
1596     return reinterpret_cast<Expr **>(getStoredStmts());
1597   }
1598
1599   /// \brief Retrieve the first initialization argument for this
1600   /// lambda expression (which initializes the first capture field).
1601   const_capture_init_iterator capture_init_begin() const {
1602     return reinterpret_cast<Expr *const *>(getStoredStmts());
1603   }
1604
1605   /// \brief Retrieve the iterator pointing one past the last
1606   /// initialization argument for this lambda expression.
1607   capture_init_iterator capture_init_end() {
1608     return capture_init_begin() + NumCaptures;
1609   }
1610
1611   /// \brief Retrieve the iterator pointing one past the last
1612   /// initialization argument for this lambda expression.
1613   const_capture_init_iterator capture_init_end() const {
1614     return capture_init_begin() + NumCaptures;
1615   }
1616
1617   /// \brief Retrieve the set of index variables used in the capture
1618   /// initializer of an array captured by copy.
1619   ///
1620   /// \param Iter The iterator that points at the capture initializer for
1621   /// which we are extracting the corresponding index variables.
1622   ArrayRef<VarDecl *>
1623   getCaptureInitIndexVars(const_capture_init_iterator Iter) const;
1624
1625   /// \brief Retrieve the source range covering the lambda introducer,
1626   /// which contains the explicit capture list surrounded by square
1627   /// brackets ([...]).
1628   SourceRange getIntroducerRange() const { return IntroducerRange; }
1629
1630   /// \brief Retrieve the class that corresponds to the lambda.
1631   /// 
1632   /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
1633   /// captures in its fields and provides the various operations permitted
1634   /// on a lambda (copying, calling).
1635   CXXRecordDecl *getLambdaClass() const;
1636
1637   /// \brief Retrieve the function call operator associated with this
1638   /// lambda expression. 
1639   CXXMethodDecl *getCallOperator() const;
1640
1641   /// \brief If this is a generic lambda expression, retrieve the template 
1642   /// parameter list associated with it, or else return null. 
1643   TemplateParameterList *getTemplateParameterList() const;
1644
1645   /// \brief Whether this is a generic lambda.
1646   bool isGenericLambda() const { return getTemplateParameterList(); }
1647
1648   /// \brief Retrieve the body of the lambda.
1649   CompoundStmt *getBody() const;
1650
1651   /// \brief Determine whether the lambda is mutable, meaning that any
1652   /// captures values can be modified.
1653   bool isMutable() const;
1654
1655   /// \brief Determine whether this lambda has an explicit parameter
1656   /// list vs. an implicit (empty) parameter list.
1657   bool hasExplicitParameters() const { return ExplicitParams; }
1658
1659   /// \brief Whether this lambda had its result type explicitly specified.
1660   bool hasExplicitResultType() const { return ExplicitResultType; }
1661     
1662   static bool classof(const Stmt *T) {
1663     return T->getStmtClass() == LambdaExprClass;
1664   }
1665
1666   SourceLocation getLocStart() const LLVM_READONLY {
1667     return IntroducerRange.getBegin();
1668   }
1669   SourceLocation getLocEnd() const LLVM_READONLY { return ClosingBrace; }
1670
1671   child_range children() {
1672     // Includes initialization exprs plus body stmt
1673     return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
1674   }
1675
1676   friend TrailingObjects;
1677   friend class ASTStmtReader;
1678   friend class ASTStmtWriter;
1679 };
1680
1681 /// An expression "T()" which creates a value-initialized rvalue of type
1682 /// T, which is a non-class type.  See (C++98 [5.2.3p2]).
1683 class CXXScalarValueInitExpr : public Expr {
1684   SourceLocation RParenLoc;
1685   TypeSourceInfo *TypeInfo;
1686
1687   friend class ASTStmtReader;
1688
1689 public:
1690   /// \brief Create an explicitly-written scalar-value initialization
1691   /// expression.
1692   CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
1693                          SourceLocation rParenLoc)
1694       : Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
1695              false, false, Type->isInstantiationDependentType(),
1696              Type->containsUnexpandedParameterPack()),
1697         RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
1698
1699   explicit CXXScalarValueInitExpr(EmptyShell Shell)
1700     : Expr(CXXScalarValueInitExprClass, Shell) { }
1701
1702   TypeSourceInfo *getTypeSourceInfo() const {
1703     return TypeInfo;
1704   }
1705
1706   SourceLocation getRParenLoc() const { return RParenLoc; }
1707
1708   SourceLocation getLocStart() const LLVM_READONLY;
1709   SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1710
1711   static bool classof(const Stmt *T) {
1712     return T->getStmtClass() == CXXScalarValueInitExprClass;
1713   }
1714
1715   // Iterators
1716   child_range children() {
1717     return child_range(child_iterator(), child_iterator());
1718   }
1719 };
1720
1721 /// \brief Represents a new-expression for memory allocation and constructor
1722 /// calls, e.g: "new CXXNewExpr(foo)".
1723 class CXXNewExpr : public Expr {
1724   /// Contains an optional array size expression, an optional initialization
1725   /// expression, and any number of optional placement arguments, in that order.
1726   Stmt **SubExprs;
1727   /// \brief Points to the allocation function used.
1728   FunctionDecl *OperatorNew;
1729   /// \brief Points to the deallocation function used in case of error. May be
1730   /// null.
1731   FunctionDecl *OperatorDelete;
1732
1733   /// \brief The allocated type-source information, as written in the source.
1734   TypeSourceInfo *AllocatedTypeInfo;
1735
1736   /// \brief If the allocated type was expressed as a parenthesized type-id,
1737   /// the source range covering the parenthesized type-id.
1738   SourceRange TypeIdParens;
1739
1740   /// \brief Range of the entire new expression.
1741   SourceRange Range;
1742
1743   /// \brief Source-range of a paren-delimited initializer.
1744   SourceRange DirectInitRange;
1745
1746   /// Was the usage ::new, i.e. is the global new to be used?
1747   bool GlobalNew : 1;
1748   /// Do we allocate an array? If so, the first SubExpr is the size expression.
1749   bool Array : 1;
1750   /// If this is an array allocation, does the usual deallocation
1751   /// function for the allocated type want to know the allocated size?
1752   bool UsualArrayDeleteWantsSize : 1;
1753   /// The number of placement new arguments.
1754   unsigned NumPlacementArgs : 13;
1755   /// What kind of initializer do we have? Could be none, parens, or braces.
1756   /// In storage, we distinguish between "none, and no initializer expr", and
1757   /// "none, but an implicit initializer expr".
1758   unsigned StoredInitializationStyle : 2;
1759
1760   friend class ASTStmtReader;
1761   friend class ASTStmtWriter;
1762 public:
1763   enum InitializationStyle {
1764     NoInit,   ///< New-expression has no initializer as written.
1765     CallInit, ///< New-expression has a C++98 paren-delimited initializer.
1766     ListInit  ///< New-expression has a C++11 list-initializer.
1767   };
1768
1769   CXXNewExpr(const ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
1770              FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
1771              ArrayRef<Expr*> placementArgs,
1772              SourceRange typeIdParens, Expr *arraySize,
1773              InitializationStyle initializationStyle, Expr *initializer,
1774              QualType ty, TypeSourceInfo *AllocatedTypeInfo,
1775              SourceRange Range, SourceRange directInitRange);
1776   explicit CXXNewExpr(EmptyShell Shell)
1777     : Expr(CXXNewExprClass, Shell), SubExprs(nullptr) { }
1778
1779   void AllocateArgsArray(const ASTContext &C, bool isArray,
1780                          unsigned numPlaceArgs, bool hasInitializer);
1781
1782   QualType getAllocatedType() const {
1783     assert(getType()->isPointerType());
1784     return getType()->getAs<PointerType>()->getPointeeType();
1785   }
1786
1787   TypeSourceInfo *getAllocatedTypeSourceInfo() const {
1788     return AllocatedTypeInfo;
1789   }
1790
1791   /// \brief True if the allocation result needs to be null-checked.
1792   ///
1793   /// C++11 [expr.new]p13:
1794   ///   If the allocation function returns null, initialization shall
1795   ///   not be done, the deallocation function shall not be called,
1796   ///   and the value of the new-expression shall be null.
1797   ///
1798   /// C++ DR1748:
1799   ///   If the allocation function is a reserved placement allocation
1800   ///   function that returns null, the behavior is undefined.
1801   ///
1802   /// An allocation function is not allowed to return null unless it
1803   /// has a non-throwing exception-specification.  The '03 rule is
1804   /// identical except that the definition of a non-throwing
1805   /// exception specification is just "is it throw()?".
1806   bool shouldNullCheckAllocation(const ASTContext &Ctx) const;
1807
1808   FunctionDecl *getOperatorNew() const { return OperatorNew; }
1809   void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
1810   FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1811   void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
1812
1813   bool isArray() const { return Array; }
1814   Expr *getArraySize() {
1815     return Array ? cast<Expr>(SubExprs[0]) : nullptr;
1816   }
1817   const Expr *getArraySize() const {
1818     return Array ? cast<Expr>(SubExprs[0]) : nullptr;
1819   }
1820
1821   unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
1822   Expr **getPlacementArgs() {
1823     return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
1824   }
1825
1826   Expr *getPlacementArg(unsigned i) {
1827     assert(i < NumPlacementArgs && "Index out of range");
1828     return getPlacementArgs()[i];
1829   }
1830   const Expr *getPlacementArg(unsigned i) const {
1831     assert(i < NumPlacementArgs && "Index out of range");
1832     return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
1833   }
1834
1835   bool isParenTypeId() const { return TypeIdParens.isValid(); }
1836   SourceRange getTypeIdParens() const { return TypeIdParens; }
1837
1838   bool isGlobalNew() const { return GlobalNew; }
1839
1840   /// \brief Whether this new-expression has any initializer at all.
1841   bool hasInitializer() const { return StoredInitializationStyle > 0; }
1842
1843   /// \brief The kind of initializer this new-expression has.
1844   InitializationStyle getInitializationStyle() const {
1845     if (StoredInitializationStyle == 0)
1846       return NoInit;
1847     return static_cast<InitializationStyle>(StoredInitializationStyle-1);
1848   }
1849
1850   /// \brief The initializer of this new-expression.
1851   Expr *getInitializer() {
1852     return hasInitializer() ? cast<Expr>(SubExprs[Array]) : nullptr;
1853   }
1854   const Expr *getInitializer() const {
1855     return hasInitializer() ? cast<Expr>(SubExprs[Array]) : nullptr;
1856   }
1857
1858   /// \brief Returns the CXXConstructExpr from this new-expression, or null.
1859   const CXXConstructExpr* getConstructExpr() const {
1860     return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
1861   }
1862
1863   /// Answers whether the usual array deallocation function for the
1864   /// allocated type expects the size of the allocation as a
1865   /// parameter.
1866   bool doesUsualArrayDeleteWantSize() const {
1867     return UsualArrayDeleteWantsSize;
1868   }
1869
1870   typedef ExprIterator arg_iterator;
1871   typedef ConstExprIterator const_arg_iterator;
1872
1873   llvm::iterator_range<arg_iterator> placement_arguments() {
1874     return llvm::make_range(placement_arg_begin(), placement_arg_end());
1875   }
1876
1877   llvm::iterator_range<const_arg_iterator> placement_arguments() const {
1878     return llvm::make_range(placement_arg_begin(), placement_arg_end());
1879   }
1880
1881   arg_iterator placement_arg_begin() {
1882     return SubExprs + Array + hasInitializer();
1883   }
1884   arg_iterator placement_arg_end() {
1885     return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1886   }
1887   const_arg_iterator placement_arg_begin() const {
1888     return SubExprs + Array + hasInitializer();
1889   }
1890   const_arg_iterator placement_arg_end() const {
1891     return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1892   }
1893
1894   typedef Stmt **raw_arg_iterator;
1895   raw_arg_iterator raw_arg_begin() { return SubExprs; }
1896   raw_arg_iterator raw_arg_end() {
1897     return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1898   }
1899   const_arg_iterator raw_arg_begin() const { return SubExprs; }
1900   const_arg_iterator raw_arg_end() const {
1901     return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1902   }
1903
1904   SourceLocation getStartLoc() const { return Range.getBegin(); }
1905   SourceLocation getEndLoc() const { return Range.getEnd(); }
1906
1907   SourceRange getDirectInitRange() const { return DirectInitRange; }
1908
1909   SourceRange getSourceRange() const LLVM_READONLY {
1910     return Range;
1911   }
1912   SourceLocation getLocStart() const LLVM_READONLY { return getStartLoc(); }
1913   SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1914
1915   static bool classof(const Stmt *T) {
1916     return T->getStmtClass() == CXXNewExprClass;
1917   }
1918
1919   // Iterators
1920   child_range children() {
1921     return child_range(raw_arg_begin(), raw_arg_end());
1922   }
1923 };
1924
1925 /// \brief Represents a \c delete expression for memory deallocation and
1926 /// destructor calls, e.g. "delete[] pArray".
1927 class CXXDeleteExpr : public Expr {
1928   /// Points to the operator delete overload that is used. Could be a member.
1929   FunctionDecl *OperatorDelete;
1930   /// The pointer expression to be deleted.
1931   Stmt *Argument;
1932   /// Location of the expression.
1933   SourceLocation Loc;
1934   /// Is this a forced global delete, i.e. "::delete"?
1935   bool GlobalDelete : 1;
1936   /// Is this the array form of delete, i.e. "delete[]"?
1937   bool ArrayForm : 1;
1938   /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
1939   /// to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
1940   /// will be true).
1941   bool ArrayFormAsWritten : 1;
1942   /// Does the usual deallocation function for the element type require
1943   /// a size_t argument?
1944   bool UsualArrayDeleteWantsSize : 1;
1945 public:
1946   CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
1947                 bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
1948                 FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
1949     : Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
1950            arg->isInstantiationDependent(),
1951            arg->containsUnexpandedParameterPack()),
1952       OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
1953       GlobalDelete(globalDelete),
1954       ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
1955       UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
1956   explicit CXXDeleteExpr(EmptyShell Shell)
1957     : Expr(CXXDeleteExprClass, Shell), OperatorDelete(nullptr),
1958       Argument(nullptr) {}
1959
1960   bool isGlobalDelete() const { return GlobalDelete; }
1961   bool isArrayForm() const { return ArrayForm; }
1962   bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
1963
1964   /// Answers whether the usual array deallocation function for the
1965   /// allocated type expects the size of the allocation as a
1966   /// parameter.  This can be true even if the actual deallocation
1967   /// function that we're using doesn't want a size.
1968   bool doesUsualArrayDeleteWantSize() const {
1969     return UsualArrayDeleteWantsSize;
1970   }
1971
1972   FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1973
1974   Expr *getArgument() { return cast<Expr>(Argument); }
1975   const Expr *getArgument() const { return cast<Expr>(Argument); }
1976
1977   /// \brief Retrieve the type being destroyed. 
1978   ///
1979   /// If the type being destroyed is a dependent type which may or may not
1980   /// be a pointer, return an invalid type.
1981   QualType getDestroyedType() const;
1982
1983   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1984   SourceLocation getLocEnd() const LLVM_READONLY {return Argument->getLocEnd();}
1985
1986   static bool classof(const Stmt *T) {
1987     return T->getStmtClass() == CXXDeleteExprClass;
1988   }
1989
1990   // Iterators
1991   child_range children() { return child_range(&Argument, &Argument+1); }
1992
1993   friend class ASTStmtReader;
1994 };
1995
1996 /// \brief Stores the type being destroyed by a pseudo-destructor expression.
1997 class PseudoDestructorTypeStorage {
1998   /// \brief Either the type source information or the name of the type, if
1999   /// it couldn't be resolved due to type-dependence.
2000   llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2001
2002   /// \brief The starting source location of the pseudo-destructor type.
2003   SourceLocation Location;
2004
2005 public:
2006   PseudoDestructorTypeStorage() { }
2007
2008   PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2009     : Type(II), Location(Loc) { }
2010
2011   PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2012
2013   TypeSourceInfo *getTypeSourceInfo() const {
2014     return Type.dyn_cast<TypeSourceInfo *>();
2015   }
2016
2017   IdentifierInfo *getIdentifier() const {
2018     return Type.dyn_cast<IdentifierInfo *>();
2019   }
2020
2021   SourceLocation getLocation() const { return Location; }
2022 };
2023
2024 /// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2025 ///
2026 /// A pseudo-destructor is an expression that looks like a member access to a
2027 /// destructor of a scalar type, except that scalar types don't have
2028 /// destructors. For example:
2029 ///
2030 /// \code
2031 /// typedef int T;
2032 /// void f(int *p) {
2033 ///   p->T::~T();
2034 /// }
2035 /// \endcode
2036 ///
2037 /// Pseudo-destructors typically occur when instantiating templates such as:
2038 ///
2039 /// \code
2040 /// template<typename T>
2041 /// void destroy(T* ptr) {
2042 ///   ptr->T::~T();
2043 /// }
2044 /// \endcode
2045 ///
2046 /// for scalar types. A pseudo-destructor expression has no run-time semantics
2047 /// beyond evaluating the base expression.
2048 class CXXPseudoDestructorExpr : public Expr {
2049   /// \brief The base expression (that is being destroyed).
2050   Stmt *Base;
2051
2052   /// \brief Whether the operator was an arrow ('->'); otherwise, it was a
2053   /// period ('.').
2054   bool IsArrow : 1;
2055
2056   /// \brief The location of the '.' or '->' operator.
2057   SourceLocation OperatorLoc;
2058
2059   /// \brief The nested-name-specifier that follows the operator, if present.
2060   NestedNameSpecifierLoc QualifierLoc;
2061
2062   /// \brief The type that precedes the '::' in a qualified pseudo-destructor
2063   /// expression.
2064   TypeSourceInfo *ScopeType;
2065
2066   /// \brief The location of the '::' in a qualified pseudo-destructor
2067   /// expression.
2068   SourceLocation ColonColonLoc;
2069
2070   /// \brief The location of the '~'.
2071   SourceLocation TildeLoc;
2072
2073   /// \brief The type being destroyed, or its name if we were unable to
2074   /// resolve the name.
2075   PseudoDestructorTypeStorage DestroyedType;
2076
2077   friend class ASTStmtReader;
2078
2079 public:
2080   CXXPseudoDestructorExpr(const ASTContext &Context,
2081                           Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2082                           NestedNameSpecifierLoc QualifierLoc,
2083                           TypeSourceInfo *ScopeType,
2084                           SourceLocation ColonColonLoc,
2085                           SourceLocation TildeLoc,
2086                           PseudoDestructorTypeStorage DestroyedType);
2087
2088   explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2089     : Expr(CXXPseudoDestructorExprClass, Shell),
2090       Base(nullptr), IsArrow(false), QualifierLoc(), ScopeType(nullptr) { }
2091
2092   Expr *getBase() const { return cast<Expr>(Base); }
2093
2094   /// \brief Determines whether this member expression actually had
2095   /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2096   /// x->Base::foo.
2097   bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2098
2099   /// \brief Retrieves the nested-name-specifier that qualifies the type name,
2100   /// with source-location information.
2101   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2102
2103   /// \brief If the member name was qualified, retrieves the
2104   /// nested-name-specifier that precedes the member name. Otherwise, returns
2105   /// null.
2106   NestedNameSpecifier *getQualifier() const {
2107     return QualifierLoc.getNestedNameSpecifier();
2108   }
2109
2110   /// \brief Determine whether this pseudo-destructor expression was written
2111   /// using an '->' (otherwise, it used a '.').
2112   bool isArrow() const { return IsArrow; }
2113
2114   /// \brief Retrieve the location of the '.' or '->' operator.
2115   SourceLocation getOperatorLoc() const { return OperatorLoc; }
2116
2117   /// \brief Retrieve the scope type in a qualified pseudo-destructor
2118   /// expression.
2119   ///
2120   /// Pseudo-destructor expressions can have extra qualification within them
2121   /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2122   /// Here, if the object type of the expression is (or may be) a scalar type,
2123   /// \p T may also be a scalar type and, therefore, cannot be part of a
2124   /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2125   /// destructor expression.
2126   TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2127
2128   /// \brief Retrieve the location of the '::' in a qualified pseudo-destructor
2129   /// expression.
2130   SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2131
2132   /// \brief Retrieve the location of the '~'.
2133   SourceLocation getTildeLoc() const { return TildeLoc; }
2134
2135   /// \brief Retrieve the source location information for the type
2136   /// being destroyed.
2137   ///
2138   /// This type-source information is available for non-dependent
2139   /// pseudo-destructor expressions and some dependent pseudo-destructor
2140   /// expressions. Returns null if we only have the identifier for a
2141   /// dependent pseudo-destructor expression.
2142   TypeSourceInfo *getDestroyedTypeInfo() const {
2143     return DestroyedType.getTypeSourceInfo();
2144   }
2145
2146   /// \brief In a dependent pseudo-destructor expression for which we do not
2147   /// have full type information on the destroyed type, provides the name
2148   /// of the destroyed type.
2149   IdentifierInfo *getDestroyedTypeIdentifier() const {
2150     return DestroyedType.getIdentifier();
2151   }
2152
2153   /// \brief Retrieve the type being destroyed.
2154   QualType getDestroyedType() const;
2155
2156   /// \brief Retrieve the starting location of the type being destroyed.
2157   SourceLocation getDestroyedTypeLoc() const {
2158     return DestroyedType.getLocation();
2159   }
2160
2161   /// \brief Set the name of destroyed type for a dependent pseudo-destructor
2162   /// expression.
2163   void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2164     DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2165   }
2166
2167   /// \brief Set the destroyed type.
2168   void setDestroyedType(TypeSourceInfo *Info) {
2169     DestroyedType = PseudoDestructorTypeStorage(Info);
2170   }
2171
2172   SourceLocation getLocStart() const LLVM_READONLY {return Base->getLocStart();}
2173   SourceLocation getLocEnd() const LLVM_READONLY;
2174
2175   static bool classof(const Stmt *T) {
2176     return T->getStmtClass() == CXXPseudoDestructorExprClass;
2177   }
2178
2179   // Iterators
2180   child_range children() { return child_range(&Base, &Base + 1); }
2181 };
2182
2183 /// \brief A type trait used in the implementation of various C++11 and
2184 /// Library TR1 trait templates.
2185 ///
2186 /// \code
2187 ///   __is_pod(int) == true
2188 ///   __is_enum(std::string) == false
2189 ///   __is_trivially_constructible(vector<int>, int*, int*)
2190 /// \endcode
2191 class TypeTraitExpr final
2192     : public Expr,
2193       private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2194   /// \brief The location of the type trait keyword.
2195   SourceLocation Loc;
2196   
2197   /// \brief  The location of the closing parenthesis.
2198   SourceLocation RParenLoc;
2199   
2200   // Note: The TypeSourceInfos for the arguments are allocated after the
2201   // TypeTraitExpr.
2202   
2203   TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2204                 ArrayRef<TypeSourceInfo *> Args,
2205                 SourceLocation RParenLoc,
2206                 bool Value);
2207
2208   TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
2209
2210   size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2211     return getNumArgs();
2212   }
2213
2214 public:
2215   /// \brief Create a new type trait expression.
2216   static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2217                                SourceLocation Loc, TypeTrait Kind,
2218                                ArrayRef<TypeSourceInfo *> Args,
2219                                SourceLocation RParenLoc,
2220                                bool Value);
2221
2222   static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2223                                            unsigned NumArgs);
2224   
2225   /// \brief Determine which type trait this expression uses.
2226   TypeTrait getTrait() const {
2227     return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2228   }
2229
2230   bool getValue() const { 
2231     assert(!isValueDependent()); 
2232     return TypeTraitExprBits.Value; 
2233   }
2234   
2235   /// \brief Determine the number of arguments to this type trait.
2236   unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2237   
2238   /// \brief Retrieve the Ith argument.
2239   TypeSourceInfo *getArg(unsigned I) const {
2240     assert(I < getNumArgs() && "Argument out-of-range");
2241     return getArgs()[I];
2242   }
2243   
2244   /// \brief Retrieve the argument types.
2245   ArrayRef<TypeSourceInfo *> getArgs() const {
2246     return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2247                               getNumArgs());
2248   }
2249
2250   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2251   SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2252
2253   static bool classof(const Stmt *T) {
2254     return T->getStmtClass() == TypeTraitExprClass;
2255   }
2256   
2257   // Iterators
2258   child_range children() {
2259     return child_range(child_iterator(), child_iterator());
2260   }
2261
2262   friend TrailingObjects;
2263   friend class ASTStmtReader;
2264   friend class ASTStmtWriter;
2265 };
2266
2267 /// \brief An Embarcadero array type trait, as used in the implementation of
2268 /// __array_rank and __array_extent.
2269 ///
2270 /// Example:
2271 /// \code
2272 ///   __array_rank(int[10][20]) == 2
2273 ///   __array_extent(int, 1)    == 20
2274 /// \endcode
2275 class ArrayTypeTraitExpr : public Expr {
2276   virtual void anchor();
2277
2278   /// \brief The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2279   unsigned ATT : 2;
2280
2281   /// \brief The value of the type trait. Unspecified if dependent.
2282   uint64_t Value;
2283
2284   /// \brief The array dimension being queried, or -1 if not used.
2285   Expr *Dimension;
2286
2287   /// \brief The location of the type trait keyword.
2288   SourceLocation Loc;
2289
2290   /// \brief The location of the closing paren.
2291   SourceLocation RParen;
2292
2293   /// \brief The type being queried.
2294   TypeSourceInfo *QueriedType;
2295
2296 public:
2297   ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2298                      TypeSourceInfo *queried, uint64_t value,
2299                      Expr *dimension, SourceLocation rparen, QualType ty)
2300     : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2301            false, queried->getType()->isDependentType(),
2302            (queried->getType()->isInstantiationDependentType() ||
2303             (dimension && dimension->isInstantiationDependent())),
2304            queried->getType()->containsUnexpandedParameterPack()),
2305       ATT(att), Value(value), Dimension(dimension),
2306       Loc(loc), RParen(rparen), QueriedType(queried) { }
2307
2308
2309   explicit ArrayTypeTraitExpr(EmptyShell Empty)
2310     : Expr(ArrayTypeTraitExprClass, Empty), ATT(0), Value(false),
2311       QueriedType() { }
2312
2313   virtual ~ArrayTypeTraitExpr() { }
2314
2315   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2316   SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2317
2318   ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2319
2320   QualType getQueriedType() const { return QueriedType->getType(); }
2321
2322   TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2323
2324   uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
2325
2326   Expr *getDimensionExpression() const { return Dimension; }
2327
2328   static bool classof(const Stmt *T) {
2329     return T->getStmtClass() == ArrayTypeTraitExprClass;
2330   }
2331
2332   // Iterators
2333   child_range children() {
2334     return child_range(child_iterator(), child_iterator());
2335   }
2336
2337   friend class ASTStmtReader;
2338 };
2339
2340 /// \brief An expression trait intrinsic.
2341 ///
2342 /// Example:
2343 /// \code
2344 ///   __is_lvalue_expr(std::cout) == true
2345 ///   __is_lvalue_expr(1) == false
2346 /// \endcode
2347 class ExpressionTraitExpr : public Expr {
2348   /// \brief The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2349   unsigned ET : 31;
2350   /// \brief The value of the type trait. Unspecified if dependent.
2351   bool Value : 1;
2352
2353   /// \brief The location of the type trait keyword.
2354   SourceLocation Loc;
2355
2356   /// \brief The location of the closing paren.
2357   SourceLocation RParen;
2358
2359   /// \brief The expression being queried.
2360   Expr* QueriedExpression;
2361 public:
2362   ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2363                      Expr *queried, bool value,
2364                      SourceLocation rparen, QualType resultType)
2365     : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2366            false, // Not type-dependent
2367            // Value-dependent if the argument is type-dependent.
2368            queried->isTypeDependent(),
2369            queried->isInstantiationDependent(),
2370            queried->containsUnexpandedParameterPack()),
2371       ET(et), Value(value), Loc(loc), RParen(rparen),
2372       QueriedExpression(queried) { }
2373
2374   explicit ExpressionTraitExpr(EmptyShell Empty)
2375     : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
2376       QueriedExpression() { }
2377
2378   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2379   SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2380
2381   ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2382
2383   Expr *getQueriedExpression() const { return QueriedExpression; }
2384
2385   bool getValue() const { return Value; }
2386
2387   static bool classof(const Stmt *T) {
2388     return T->getStmtClass() == ExpressionTraitExprClass;
2389   }
2390
2391   // Iterators
2392   child_range children() {
2393     return child_range(child_iterator(), child_iterator());
2394   }
2395
2396   friend class ASTStmtReader;
2397 };
2398
2399
2400 /// \brief A reference to an overloaded function set, either an
2401 /// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2402 class OverloadExpr : public Expr {
2403   /// \brief The common name of these declarations.
2404   DeclarationNameInfo NameInfo;
2405
2406   /// \brief The nested-name-specifier that qualifies the name, if any.
2407   NestedNameSpecifierLoc QualifierLoc;
2408
2409   /// The results.  These are undesugared, which is to say, they may
2410   /// include UsingShadowDecls.  Access is relative to the naming
2411   /// class.
2412   // FIXME: Allocate this data after the OverloadExpr subclass.
2413   DeclAccessPair *Results;
2414   unsigned NumResults;
2415
2416 protected:
2417   /// \brief Whether the name includes info for explicit template
2418   /// keyword and arguments.
2419   bool HasTemplateKWAndArgsInfo;
2420
2421   /// \brief Return the optional template keyword and arguments info.
2422   ASTTemplateKWAndArgsInfo *
2423   getTrailingASTTemplateKWAndArgsInfo(); // defined far below.
2424
2425   /// \brief Return the optional template keyword and arguments info.
2426   const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2427     return const_cast<OverloadExpr *>(this)
2428         ->getTrailingASTTemplateKWAndArgsInfo();
2429   }
2430
2431   /// Return the optional template arguments.
2432   TemplateArgumentLoc *getTrailingTemplateArgumentLoc(); // defined far below
2433
2434   OverloadExpr(StmtClass K, const ASTContext &C,
2435                NestedNameSpecifierLoc QualifierLoc,
2436                SourceLocation TemplateKWLoc,
2437                const DeclarationNameInfo &NameInfo,
2438                const TemplateArgumentListInfo *TemplateArgs,
2439                UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2440                bool KnownDependent,
2441                bool KnownInstantiationDependent,
2442                bool KnownContainsUnexpandedParameterPack);
2443
2444   OverloadExpr(StmtClass K, EmptyShell Empty)
2445     : Expr(K, Empty), QualifierLoc(), Results(nullptr), NumResults(0),
2446       HasTemplateKWAndArgsInfo(false) { }
2447
2448   void initializeResults(const ASTContext &C,
2449                          UnresolvedSetIterator Begin,
2450                          UnresolvedSetIterator End);
2451
2452 public:
2453   struct FindResult {
2454     OverloadExpr *Expression;
2455     bool IsAddressOfOperand;
2456     bool HasFormOfMemberPointer;
2457   };
2458
2459   /// \brief Finds the overloaded expression in the given expression \p E of
2460   /// OverloadTy.
2461   ///
2462   /// \return the expression (which must be there) and true if it has
2463   /// the particular form of a member pointer expression
2464   static FindResult find(Expr *E) {
2465     assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
2466
2467     FindResult Result;
2468
2469     E = E->IgnoreParens();
2470     if (isa<UnaryOperator>(E)) {
2471       assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
2472       E = cast<UnaryOperator>(E)->getSubExpr();
2473       OverloadExpr *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2474
2475       Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2476       Result.IsAddressOfOperand = true;
2477       Result.Expression = Ovl;
2478     } else {
2479       Result.HasFormOfMemberPointer = false;
2480       Result.IsAddressOfOperand = false;
2481       Result.Expression = cast<OverloadExpr>(E);
2482     }
2483
2484     return Result;
2485   }
2486
2487   /// \brief Gets the naming class of this lookup, if any.
2488   CXXRecordDecl *getNamingClass() const;
2489
2490   typedef UnresolvedSetImpl::iterator decls_iterator;
2491   decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
2492   decls_iterator decls_end() const {
2493     return UnresolvedSetIterator(Results + NumResults);
2494   }
2495   llvm::iterator_range<decls_iterator> decls() const {
2496     return llvm::make_range(decls_begin(), decls_end());
2497   }
2498
2499   /// \brief Gets the number of declarations in the unresolved set.
2500   unsigned getNumDecls() const { return NumResults; }
2501
2502   /// \brief Gets the full name info.
2503   const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2504
2505   /// \brief Gets the name looked up.
2506   DeclarationName getName() const { return NameInfo.getName(); }
2507
2508   /// \brief Gets the location of the name.
2509   SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2510
2511   /// \brief Fetches the nested-name qualifier, if one was given.
2512   NestedNameSpecifier *getQualifier() const {
2513     return QualifierLoc.getNestedNameSpecifier();
2514   }
2515
2516   /// \brief Fetches the nested-name qualifier with source-location
2517   /// information, if one was given.
2518   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2519
2520   /// \brief Retrieve the location of the template keyword preceding
2521   /// this name, if any.
2522   SourceLocation getTemplateKeywordLoc() const {
2523     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2524     return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
2525   }
2526
2527   /// \brief Retrieve the location of the left angle bracket starting the
2528   /// explicit template argument list following the name, if any.
2529   SourceLocation getLAngleLoc() const {
2530     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2531     return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
2532   }
2533
2534   /// \brief Retrieve the location of the right angle bracket ending the
2535   /// explicit template argument list following the name, if any.
2536   SourceLocation getRAngleLoc() const {
2537     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2538     return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
2539   }
2540
2541   /// \brief Determines whether the name was preceded by the template keyword.
2542   bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2543
2544   /// \brief Determines whether this expression had explicit template arguments.
2545   bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2546
2547   TemplateArgumentLoc const *getTemplateArgs() const {
2548     if (!hasExplicitTemplateArgs())
2549       return nullptr;
2550     return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2551   }
2552
2553   unsigned getNumTemplateArgs() const {
2554     if (!hasExplicitTemplateArgs())
2555       return 0;
2556
2557     return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
2558   }
2559
2560   /// \brief Copies the template arguments into the given structure.
2561   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2562     if (hasExplicitTemplateArgs())
2563       getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
2564   }
2565
2566   static bool classof(const Stmt *T) {
2567     return T->getStmtClass() == UnresolvedLookupExprClass ||
2568            T->getStmtClass() == UnresolvedMemberExprClass;
2569   }
2570
2571   friend class ASTStmtReader;
2572   friend class ASTStmtWriter;
2573 };
2574
2575 /// \brief A reference to a name which we were able to look up during
2576 /// parsing but could not resolve to a specific declaration.
2577 ///
2578 /// This arises in several ways:
2579 ///   * we might be waiting for argument-dependent lookup;
2580 ///   * the name might resolve to an overloaded function;
2581 /// and eventually:
2582 ///   * the lookup might have included a function template.
2583 ///
2584 /// These never include UnresolvedUsingValueDecls, which are always class
2585 /// members and therefore appear only in UnresolvedMemberLookupExprs.
2586 class UnresolvedLookupExpr final
2587     : public OverloadExpr,
2588       private llvm::TrailingObjects<
2589           UnresolvedLookupExpr, ASTTemplateKWAndArgsInfo, TemplateArgumentLoc> {
2590   /// True if these lookup results should be extended by
2591   /// argument-dependent lookup if this is the operand of a function
2592   /// call.
2593   bool RequiresADL;
2594
2595   /// True if these lookup results are overloaded.  This is pretty
2596   /// trivially rederivable if we urgently need to kill this field.
2597   bool Overloaded;
2598
2599   /// The naming class (C++ [class.access.base]p5) of the lookup, if
2600   /// any.  This can generally be recalculated from the context chain,
2601   /// but that can be fairly expensive for unqualified lookups.  If we
2602   /// want to improve memory use here, this could go in a union
2603   /// against the qualified-lookup bits.
2604   CXXRecordDecl *NamingClass;
2605
2606   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2607     return HasTemplateKWAndArgsInfo ? 1 : 0;
2608   }
2609
2610   UnresolvedLookupExpr(const ASTContext &C,
2611                        CXXRecordDecl *NamingClass,
2612                        NestedNameSpecifierLoc QualifierLoc,
2613                        SourceLocation TemplateKWLoc,
2614                        const DeclarationNameInfo &NameInfo,
2615                        bool RequiresADL, bool Overloaded,
2616                        const TemplateArgumentListInfo *TemplateArgs,
2617                        UnresolvedSetIterator Begin, UnresolvedSetIterator End)
2618     : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
2619                    NameInfo, TemplateArgs, Begin, End, false, false, false),
2620       RequiresADL(RequiresADL),
2621       Overloaded(Overloaded), NamingClass(NamingClass)
2622   {}
2623
2624   UnresolvedLookupExpr(EmptyShell Empty)
2625     : OverloadExpr(UnresolvedLookupExprClass, Empty),
2626       RequiresADL(false), Overloaded(false), NamingClass(nullptr)
2627   {}
2628
2629   friend TrailingObjects;
2630   friend class OverloadExpr;
2631   friend class ASTStmtReader;
2632
2633 public:
2634   static UnresolvedLookupExpr *Create(const ASTContext &C,
2635                                       CXXRecordDecl *NamingClass,
2636                                       NestedNameSpecifierLoc QualifierLoc,
2637                                       const DeclarationNameInfo &NameInfo,
2638                                       bool ADL, bool Overloaded,
2639                                       UnresolvedSetIterator Begin,
2640                                       UnresolvedSetIterator End) {
2641     return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
2642                                        SourceLocation(), NameInfo,
2643                                        ADL, Overloaded, nullptr, Begin, End);
2644   }
2645
2646   static UnresolvedLookupExpr *Create(const ASTContext &C,
2647                                       CXXRecordDecl *NamingClass,
2648                                       NestedNameSpecifierLoc QualifierLoc,
2649                                       SourceLocation TemplateKWLoc,
2650                                       const DeclarationNameInfo &NameInfo,
2651                                       bool ADL,
2652                                       const TemplateArgumentListInfo *Args,
2653                                       UnresolvedSetIterator Begin,
2654                                       UnresolvedSetIterator End);
2655
2656   static UnresolvedLookupExpr *CreateEmpty(const ASTContext &C,
2657                                            bool HasTemplateKWAndArgsInfo,
2658                                            unsigned NumTemplateArgs);
2659
2660   /// True if this declaration should be extended by
2661   /// argument-dependent lookup.
2662   bool requiresADL() const { return RequiresADL; }
2663
2664   /// True if this lookup is overloaded.
2665   bool isOverloaded() const { return Overloaded; }
2666
2667   /// Gets the 'naming class' (in the sense of C++0x
2668   /// [class.access.base]p5) of the lookup.  This is the scope
2669   /// that was looked in to find these results.
2670   CXXRecordDecl *getNamingClass() const { return NamingClass; }
2671
2672   SourceLocation getLocStart() const LLVM_READONLY {
2673     if (NestedNameSpecifierLoc l = getQualifierLoc())
2674       return l.getBeginLoc();
2675     return getNameInfo().getLocStart();
2676   }
2677   SourceLocation getLocEnd() const LLVM_READONLY {
2678     if (hasExplicitTemplateArgs())
2679       return getRAngleLoc();
2680     return getNameInfo().getLocEnd();
2681   }
2682
2683   child_range children() {
2684     return child_range(child_iterator(), child_iterator());
2685   }
2686
2687   static bool classof(const Stmt *T) {
2688     return T->getStmtClass() == UnresolvedLookupExprClass;
2689   }
2690 };
2691
2692 /// \brief A qualified reference to a name whose declaration cannot
2693 /// yet be resolved.
2694 ///
2695 /// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
2696 /// it expresses a reference to a declaration such as
2697 /// X<T>::value. The difference, however, is that an
2698 /// DependentScopeDeclRefExpr node is used only within C++ templates when
2699 /// the qualification (e.g., X<T>::) refers to a dependent type. In
2700 /// this case, X<T>::value cannot resolve to a declaration because the
2701 /// declaration will differ from one instantiation of X<T> to the
2702 /// next. Therefore, DependentScopeDeclRefExpr keeps track of the
2703 /// qualifier (X<T>::) and the name of the entity being referenced
2704 /// ("value"). Such expressions will instantiate to a DeclRefExpr once the
2705 /// declaration can be found.
2706 class DependentScopeDeclRefExpr final
2707     : public Expr,
2708       private llvm::TrailingObjects<DependentScopeDeclRefExpr,
2709                                     ASTTemplateKWAndArgsInfo,
2710                                     TemplateArgumentLoc> {
2711   /// \brief The nested-name-specifier that qualifies this unresolved
2712   /// declaration name.
2713   NestedNameSpecifierLoc QualifierLoc;
2714
2715   /// \brief The name of the entity we will be referencing.
2716   DeclarationNameInfo NameInfo;
2717
2718   /// \brief Whether the name includes info for explicit template
2719   /// keyword and arguments.
2720   bool HasTemplateKWAndArgsInfo;
2721
2722   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2723     return HasTemplateKWAndArgsInfo ? 1 : 0;
2724   }
2725
2726   DependentScopeDeclRefExpr(QualType T,
2727                             NestedNameSpecifierLoc QualifierLoc,
2728                             SourceLocation TemplateKWLoc,
2729                             const DeclarationNameInfo &NameInfo,
2730                             const TemplateArgumentListInfo *Args);
2731
2732 public:
2733   static DependentScopeDeclRefExpr *Create(const ASTContext &C,
2734                                            NestedNameSpecifierLoc QualifierLoc,
2735                                            SourceLocation TemplateKWLoc,
2736                                            const DeclarationNameInfo &NameInfo,
2737                               const TemplateArgumentListInfo *TemplateArgs);
2738
2739   static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &C,
2740                                                 bool HasTemplateKWAndArgsInfo,
2741                                                 unsigned NumTemplateArgs);
2742
2743   /// \brief Retrieve the name that this expression refers to.
2744   const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2745
2746   /// \brief Retrieve the name that this expression refers to.
2747   DeclarationName getDeclName() const { return NameInfo.getName(); }
2748
2749   /// \brief Retrieve the location of the name within the expression.
2750   ///
2751   /// For example, in "X<T>::value" this is the location of "value".
2752   SourceLocation getLocation() const { return NameInfo.getLoc(); }
2753
2754   /// \brief Retrieve the nested-name-specifier that qualifies the
2755   /// name, with source location information.
2756   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2757
2758   /// \brief Retrieve the nested-name-specifier that qualifies this
2759   /// declaration.
2760   NestedNameSpecifier *getQualifier() const {
2761     return QualifierLoc.getNestedNameSpecifier();
2762   }
2763
2764   /// \brief Retrieve the location of the template keyword preceding
2765   /// this name, if any.
2766   SourceLocation getTemplateKeywordLoc() const {
2767     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2768     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2769   }
2770
2771   /// \brief Retrieve the location of the left angle bracket starting the
2772   /// explicit template argument list following the name, if any.
2773   SourceLocation getLAngleLoc() const {
2774     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2775     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2776   }
2777
2778   /// \brief Retrieve the location of the right angle bracket ending the
2779   /// explicit template argument list following the name, if any.
2780   SourceLocation getRAngleLoc() const {
2781     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2782     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2783   }
2784
2785   /// Determines whether the name was preceded by the template keyword.
2786   bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2787
2788   /// Determines whether this lookup had explicit template arguments.
2789   bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2790
2791   /// \brief Copies the template arguments (if present) into the given
2792   /// structure.
2793   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2794     if (hasExplicitTemplateArgs())
2795       getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2796           getTrailingObjects<TemplateArgumentLoc>(), List);
2797   }
2798
2799   TemplateArgumentLoc const *getTemplateArgs() const {
2800     if (!hasExplicitTemplateArgs())
2801       return nullptr;
2802
2803     return getTrailingObjects<TemplateArgumentLoc>();
2804   }
2805
2806   unsigned getNumTemplateArgs() const {
2807     if (!hasExplicitTemplateArgs())
2808       return 0;
2809
2810     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2811   }
2812
2813   /// Note: getLocStart() is the start of the whole DependentScopeDeclRefExpr,
2814   /// and differs from getLocation().getStart().
2815   SourceLocation getLocStart() const LLVM_READONLY {
2816     return QualifierLoc.getBeginLoc();
2817   }
2818   SourceLocation getLocEnd() const LLVM_READONLY {
2819     if (hasExplicitTemplateArgs())
2820       return getRAngleLoc();
2821     return getLocation();
2822   }
2823
2824   static bool classof(const Stmt *T) {
2825     return T->getStmtClass() == DependentScopeDeclRefExprClass;
2826   }
2827
2828   child_range children() {
2829     return child_range(child_iterator(), child_iterator());
2830   }
2831
2832   friend TrailingObjects;
2833   friend class ASTStmtReader;
2834   friend class ASTStmtWriter;
2835 };
2836
2837 /// Represents an expression -- generally a full-expression -- that
2838 /// introduces cleanups to be run at the end of the sub-expression's
2839 /// evaluation.  The most common source of expression-introduced
2840 /// cleanups is temporary objects in C++, but several other kinds of
2841 /// expressions can create cleanups, including basically every
2842 /// call in ARC that returns an Objective-C pointer.
2843 ///
2844 /// This expression also tracks whether the sub-expression contains a
2845 /// potentially-evaluated block literal.  The lifetime of a block
2846 /// literal is the extent of the enclosing scope.
2847 class ExprWithCleanups final
2848     : public Expr,
2849       private llvm::TrailingObjects<ExprWithCleanups, BlockDecl *> {
2850 public:
2851   /// The type of objects that are kept in the cleanup.
2852   /// It's useful to remember the set of blocks;  we could also
2853   /// remember the set of temporaries, but there's currently
2854   /// no need.
2855   typedef BlockDecl *CleanupObject;
2856
2857 private:
2858   Stmt *SubExpr;
2859
2860   ExprWithCleanups(EmptyShell, unsigned NumObjects);
2861   ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
2862
2863   friend TrailingObjects;
2864   friend class ASTStmtReader;
2865
2866 public:
2867   static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
2868                                   unsigned numObjects);
2869
2870   static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
2871                                   ArrayRef<CleanupObject> objects);
2872
2873   ArrayRef<CleanupObject> getObjects() const {
2874     return llvm::makeArrayRef(getTrailingObjects<CleanupObject>(),
2875                               getNumObjects());
2876   }
2877
2878   unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
2879
2880   CleanupObject getObject(unsigned i) const {
2881     assert(i < getNumObjects() && "Index out of range");
2882     return getObjects()[i];
2883   }
2884
2885   Expr *getSubExpr() { return cast<Expr>(SubExpr); }
2886   const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
2887
2888   /// As with any mutator of the AST, be very careful
2889   /// when modifying an existing AST to preserve its invariants.
2890   void setSubExpr(Expr *E) { SubExpr = E; }
2891
2892   SourceLocation getLocStart() const LLVM_READONLY {
2893     return SubExpr->getLocStart();
2894   }
2895   SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
2896
2897   // Implement isa/cast/dyncast/etc.
2898   static bool classof(const Stmt *T) {
2899     return T->getStmtClass() == ExprWithCleanupsClass;
2900   }
2901
2902   // Iterators
2903   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
2904 };
2905
2906 /// \brief Describes an explicit type conversion that uses functional
2907 /// notion but could not be resolved because one or more arguments are
2908 /// type-dependent.
2909 ///
2910 /// The explicit type conversions expressed by
2911 /// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
2912 /// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
2913 /// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
2914 /// type-dependent. For example, this would occur in a template such
2915 /// as:
2916 ///
2917 /// \code
2918 ///   template<typename T, typename A1>
2919 ///   inline T make_a(const A1& a1) {
2920 ///     return T(a1);
2921 ///   }
2922 /// \endcode
2923 ///
2924 /// When the returned expression is instantiated, it may resolve to a
2925 /// constructor call, conversion function call, or some kind of type
2926 /// conversion.
2927 class CXXUnresolvedConstructExpr final
2928     : public Expr,
2929       private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
2930   /// \brief The type being constructed.
2931   TypeSourceInfo *Type;
2932
2933   /// \brief The location of the left parentheses ('(').
2934   SourceLocation LParenLoc;
2935
2936   /// \brief The location of the right parentheses (')').
2937   SourceLocation RParenLoc;
2938
2939   /// \brief The number of arguments used to construct the type.
2940   unsigned NumArgs;
2941
2942   CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
2943                              SourceLocation LParenLoc,
2944                              ArrayRef<Expr*> Args,
2945                              SourceLocation RParenLoc);
2946
2947   CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
2948     : Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArgs) { }
2949
2950   friend TrailingObjects;
2951   friend class ASTStmtReader;
2952
2953 public:
2954   static CXXUnresolvedConstructExpr *Create(const ASTContext &C,
2955                                             TypeSourceInfo *Type,
2956                                             SourceLocation LParenLoc,
2957                                             ArrayRef<Expr*> Args,
2958                                             SourceLocation RParenLoc);
2959
2960   static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &C,
2961                                                  unsigned NumArgs);
2962
2963   /// \brief Retrieve the type that is being constructed, as specified
2964   /// in the source code.
2965   QualType getTypeAsWritten() const { return Type->getType(); }
2966
2967   /// \brief Retrieve the type source information for the type being
2968   /// constructed.
2969   TypeSourceInfo *getTypeSourceInfo() const { return Type; }
2970
2971   /// \brief Retrieve the location of the left parentheses ('(') that
2972   /// precedes the argument list.
2973   SourceLocation getLParenLoc() const { return LParenLoc; }
2974   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2975
2976   /// \brief Retrieve the location of the right parentheses (')') that
2977   /// follows the argument list.
2978   SourceLocation getRParenLoc() const { return RParenLoc; }
2979   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2980
2981   /// \brief Retrieve the number of arguments.
2982   unsigned arg_size() const { return NumArgs; }
2983
2984   typedef Expr** arg_iterator;
2985   arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
2986   arg_iterator arg_end() { return arg_begin() + NumArgs; }
2987
2988   typedef const Expr* const * const_arg_iterator;
2989   const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
2990   const_arg_iterator arg_end() const {
2991     return arg_begin() + NumArgs;
2992   }
2993
2994   Expr *getArg(unsigned I) {
2995     assert(I < NumArgs && "Argument index out-of-range");
2996     return *(arg_begin() + I);
2997   }
2998
2999   const Expr *getArg(unsigned I) const {
3000     assert(I < NumArgs && "Argument index out-of-range");
3001     return *(arg_begin() + I);
3002   }
3003
3004   void setArg(unsigned I, Expr *E) {
3005     assert(I < NumArgs && "Argument index out-of-range");
3006     *(arg_begin() + I) = E;
3007   }
3008
3009   SourceLocation getLocStart() const LLVM_READONLY;
3010   SourceLocation getLocEnd() const LLVM_READONLY {
3011     if (!RParenLoc.isValid() && NumArgs > 0)
3012       return getArg(NumArgs - 1)->getLocEnd();
3013     return RParenLoc;
3014   }
3015
3016   static bool classof(const Stmt *T) {
3017     return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3018   }
3019
3020   // Iterators
3021   child_range children() {
3022     Stmt **begin = reinterpret_cast<Stmt **>(arg_begin());
3023     return child_range(begin, begin + NumArgs);
3024   }
3025 };
3026
3027 /// \brief Represents a C++ member access expression where the actual
3028 /// member referenced could not be resolved because the base
3029 /// expression or the member name was dependent.
3030 ///
3031 /// Like UnresolvedMemberExprs, these can be either implicit or
3032 /// explicit accesses.  It is only possible to get one of these with
3033 /// an implicit access if a qualifier is provided.
3034 class CXXDependentScopeMemberExpr final
3035     : public Expr,
3036       private llvm::TrailingObjects<CXXDependentScopeMemberExpr,
3037                                     ASTTemplateKWAndArgsInfo,
3038                                     TemplateArgumentLoc> {
3039   /// \brief The expression for the base pointer or class reference,
3040   /// e.g., the \c x in x.f.  Can be null in implicit accesses.
3041   Stmt *Base;
3042
3043   /// \brief The type of the base expression.  Never null, even for
3044   /// implicit accesses.
3045   QualType BaseType;
3046
3047   /// \brief Whether this member expression used the '->' operator or
3048   /// the '.' operator.
3049   bool IsArrow : 1;
3050
3051   /// \brief Whether this member expression has info for explicit template
3052   /// keyword and arguments.
3053   bool HasTemplateKWAndArgsInfo : 1;
3054
3055   /// \brief The location of the '->' or '.' operator.
3056   SourceLocation OperatorLoc;
3057
3058   /// \brief The nested-name-specifier that precedes the member name, if any.
3059   NestedNameSpecifierLoc QualifierLoc;
3060
3061   /// \brief In a qualified member access expression such as t->Base::f, this
3062   /// member stores the resolves of name lookup in the context of the member
3063   /// access expression, to be used at instantiation time.
3064   ///
3065   /// FIXME: This member, along with the QualifierLoc, could
3066   /// be stuck into a structure that is optionally allocated at the end of
3067   /// the CXXDependentScopeMemberExpr, to save space in the common case.
3068   NamedDecl *FirstQualifierFoundInScope;
3069
3070   /// \brief The member to which this member expression refers, which
3071   /// can be name, overloaded operator, or destructor.
3072   ///
3073   /// FIXME: could also be a template-id
3074   DeclarationNameInfo MemberNameInfo;
3075
3076   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3077     return HasTemplateKWAndArgsInfo ? 1 : 0;
3078   }
3079
3080   CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
3081                               QualType BaseType, bool IsArrow,
3082                               SourceLocation OperatorLoc,
3083                               NestedNameSpecifierLoc QualifierLoc,
3084                               SourceLocation TemplateKWLoc,
3085                               NamedDecl *FirstQualifierFoundInScope,
3086                               DeclarationNameInfo MemberNameInfo,
3087                               const TemplateArgumentListInfo *TemplateArgs);
3088
3089 public:
3090   CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
3091                               QualType BaseType, bool IsArrow,
3092                               SourceLocation OperatorLoc,
3093                               NestedNameSpecifierLoc QualifierLoc,
3094                               NamedDecl *FirstQualifierFoundInScope,
3095                               DeclarationNameInfo MemberNameInfo);
3096
3097   static CXXDependentScopeMemberExpr *
3098   Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow,
3099          SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
3100          SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
3101          DeclarationNameInfo MemberNameInfo,
3102          const TemplateArgumentListInfo *TemplateArgs);
3103
3104   static CXXDependentScopeMemberExpr *
3105   CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
3106               unsigned NumTemplateArgs);
3107
3108   /// \brief True if this is an implicit access, i.e. one in which the
3109   /// member being accessed was not written in the source.  The source
3110   /// location of the operator is invalid in this case.
3111   bool isImplicitAccess() const;
3112
3113   /// \brief Retrieve the base object of this member expressions,
3114   /// e.g., the \c x in \c x.m.
3115   Expr *getBase() const {
3116     assert(!isImplicitAccess());
3117     return cast<Expr>(Base);
3118   }
3119
3120   QualType getBaseType() const { return BaseType; }
3121
3122   /// \brief Determine whether this member expression used the '->'
3123   /// operator; otherwise, it used the '.' operator.
3124   bool isArrow() const { return IsArrow; }
3125
3126   /// \brief Retrieve the location of the '->' or '.' operator.
3127   SourceLocation getOperatorLoc() const { return OperatorLoc; }
3128
3129   /// \brief Retrieve the nested-name-specifier that qualifies the member
3130   /// name.
3131   NestedNameSpecifier *getQualifier() const {
3132     return QualifierLoc.getNestedNameSpecifier();
3133   }
3134
3135   /// \brief Retrieve the nested-name-specifier that qualifies the member
3136   /// name, with source location information.
3137   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3138
3139
3140   /// \brief Retrieve the first part of the nested-name-specifier that was
3141   /// found in the scope of the member access expression when the member access
3142   /// was initially parsed.
3143   ///
3144   /// This function only returns a useful result when member access expression
3145   /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3146   /// returned by this function describes what was found by unqualified name
3147   /// lookup for the identifier "Base" within the scope of the member access
3148   /// expression itself. At template instantiation time, this information is
3149   /// combined with the results of name lookup into the type of the object
3150   /// expression itself (the class type of x).
3151   NamedDecl *getFirstQualifierFoundInScope() const {
3152     return FirstQualifierFoundInScope;
3153   }
3154
3155   /// \brief Retrieve the name of the member that this expression
3156   /// refers to.
3157   const DeclarationNameInfo &getMemberNameInfo() const {
3158     return MemberNameInfo;
3159   }
3160
3161   /// \brief Retrieve the name of the member that this expression
3162   /// refers to.
3163   DeclarationName getMember() const { return MemberNameInfo.getName(); }
3164
3165   // \brief Retrieve the location of the name of the member that this
3166   // expression refers to.
3167   SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3168
3169   /// \brief Retrieve the location of the template keyword preceding the
3170   /// member name, if any.
3171   SourceLocation getTemplateKeywordLoc() const {
3172     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3173     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3174   }
3175
3176   /// \brief Retrieve the location of the left angle bracket starting the
3177   /// explicit template argument list following the member name, if any.
3178   SourceLocation getLAngleLoc() const {
3179     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3180     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3181   }
3182
3183   /// \brief Retrieve the location of the right angle bracket ending the
3184   /// explicit template argument list following the member name, if any.
3185   SourceLocation getRAngleLoc() const {
3186     if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3187     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3188   }
3189
3190   /// Determines whether the member name was preceded by the template keyword.
3191   bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3192
3193   /// \brief Determines whether this member expression actually had a C++
3194   /// template argument list explicitly specified, e.g., x.f<int>.
3195   bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3196
3197   /// \brief Copies the template arguments (if present) into the given
3198   /// structure.
3199   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3200     if (hasExplicitTemplateArgs())
3201       getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3202           getTrailingObjects<TemplateArgumentLoc>(), List);
3203   }
3204
3205   /// \brief Retrieve the template arguments provided as part of this
3206   /// template-id.
3207   const TemplateArgumentLoc *getTemplateArgs() const {
3208     if (!hasExplicitTemplateArgs())
3209       return nullptr;
3210
3211     return getTrailingObjects<TemplateArgumentLoc>();
3212   }
3213
3214   /// \brief Retrieve the number of template arguments provided as part of this
3215   /// template-id.
3216   unsigned getNumTemplateArgs() const {
3217     if (!hasExplicitTemplateArgs())
3218       return 0;
3219
3220     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3221   }
3222
3223   SourceLocation getLocStart() const LLVM_READONLY {
3224     if (!isImplicitAccess())
3225       return Base->getLocStart();
3226     if (getQualifier())
3227       return getQualifierLoc().getBeginLoc();
3228     return MemberNameInfo.getBeginLoc();
3229   }
3230
3231   SourceLocation getLocEnd() const LLVM_READONLY {
3232     if (hasExplicitTemplateArgs())
3233       return getRAngleLoc();
3234     return MemberNameInfo.getEndLoc();
3235   }
3236
3237   static bool classof(const Stmt *T) {
3238     return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3239   }
3240
3241   // Iterators
3242   child_range children() {
3243     if (isImplicitAccess())
3244       return child_range(child_iterator(), child_iterator());
3245     return child_range(&Base, &Base + 1);
3246   }
3247
3248   friend TrailingObjects;
3249   friend class ASTStmtReader;
3250   friend class ASTStmtWriter;
3251 };
3252
3253 /// \brief Represents a C++ member access expression for which lookup
3254 /// produced a set of overloaded functions.
3255 ///
3256 /// The member access may be explicit or implicit:
3257 /// \code
3258 ///    struct A {
3259 ///      int a, b;
3260 ///      int explicitAccess() { return this->a + this->A::b; }
3261 ///      int implicitAccess() { return a + A::b; }
3262 ///    };
3263 /// \endcode
3264 ///
3265 /// In the final AST, an explicit access always becomes a MemberExpr.
3266 /// An implicit access may become either a MemberExpr or a
3267 /// DeclRefExpr, depending on whether the member is static.
3268 class UnresolvedMemberExpr final
3269     : public OverloadExpr,
3270       private llvm::TrailingObjects<
3271           UnresolvedMemberExpr, ASTTemplateKWAndArgsInfo, TemplateArgumentLoc> {
3272   /// \brief Whether this member expression used the '->' operator or
3273   /// the '.' operator.
3274   bool IsArrow : 1;
3275
3276   /// \brief Whether the lookup results contain an unresolved using
3277   /// declaration.
3278   bool HasUnresolvedUsing : 1;
3279
3280   /// \brief The expression for the base pointer or class reference,
3281   /// e.g., the \c x in x.f.
3282   ///
3283   /// This can be null if this is an 'unbased' member expression.
3284   Stmt *Base;
3285
3286   /// \brief The type of the base expression; never null.
3287   QualType BaseType;
3288
3289   /// \brief The location of the '->' or '.' operator.
3290   SourceLocation OperatorLoc;
3291
3292   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3293     return HasTemplateKWAndArgsInfo ? 1 : 0;
3294   }
3295
3296   UnresolvedMemberExpr(const ASTContext &C, bool HasUnresolvedUsing,
3297                        Expr *Base, QualType BaseType, bool IsArrow,
3298                        SourceLocation OperatorLoc,
3299                        NestedNameSpecifierLoc QualifierLoc,
3300                        SourceLocation TemplateKWLoc,
3301                        const DeclarationNameInfo &MemberNameInfo,
3302                        const TemplateArgumentListInfo *TemplateArgs,
3303                        UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3304
3305   UnresolvedMemberExpr(EmptyShell Empty)
3306     : OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
3307       HasUnresolvedUsing(false), Base(nullptr) { }
3308
3309   friend TrailingObjects;
3310   friend class OverloadExpr;
3311   friend class ASTStmtReader;
3312
3313 public:
3314   static UnresolvedMemberExpr *
3315   Create(const ASTContext &C, bool HasUnresolvedUsing,
3316          Expr *Base, QualType BaseType, bool IsArrow,
3317          SourceLocation OperatorLoc,
3318          NestedNameSpecifierLoc QualifierLoc,
3319          SourceLocation TemplateKWLoc,
3320          const DeclarationNameInfo &MemberNameInfo,
3321          const TemplateArgumentListInfo *TemplateArgs,
3322          UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3323
3324   static UnresolvedMemberExpr *
3325   CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
3326               unsigned NumTemplateArgs);
3327
3328   /// \brief True if this is an implicit access, i.e., one in which the
3329   /// member being accessed was not written in the source.
3330   ///
3331   /// The source location of the operator is invalid in this case.
3332   bool isImplicitAccess() const;
3333
3334   /// \brief Retrieve the base object of this member expressions,
3335   /// e.g., the \c x in \c x.m.
3336   Expr *getBase() {
3337     assert(!isImplicitAccess());
3338     return cast<Expr>(Base);
3339   }
3340   const Expr *getBase() const {
3341     assert(!isImplicitAccess());
3342     return cast<Expr>(Base);
3343   }
3344
3345   QualType getBaseType() const { return BaseType; }
3346
3347   /// \brief Determine whether the lookup results contain an unresolved using
3348   /// declaration.
3349   bool hasUnresolvedUsing() const { return HasUnresolvedUsing; }
3350
3351   /// \brief Determine whether this member expression used the '->'
3352   /// operator; otherwise, it used the '.' operator.
3353   bool isArrow() const { return IsArrow; }
3354
3355   /// \brief Retrieve the location of the '->' or '.' operator.
3356   SourceLocation getOperatorLoc() const { return OperatorLoc; }
3357
3358   /// \brief Retrieve the naming class of this lookup.
3359   CXXRecordDecl *getNamingClass() const;
3360
3361   /// \brief Retrieve the full name info for the member that this expression
3362   /// refers to.
3363   const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3364
3365   /// \brief Retrieve the name of the member that this expression
3366   /// refers to.
3367   DeclarationName getMemberName() const { return getName(); }
3368
3369   // \brief Retrieve the location of the name of the member that this
3370   // expression refers to.
3371   SourceLocation getMemberLoc() const { return getNameLoc(); }
3372
3373   // \brief Return the preferred location (the member name) for the arrow when
3374   // diagnosing a problem with this expression.
3375   SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
3376
3377   SourceLocation getLocStart() const LLVM_READONLY {
3378     if (!isImplicitAccess())
3379       return Base->getLocStart();
3380     if (NestedNameSpecifierLoc l = getQualifierLoc())
3381       return l.getBeginLoc();
3382     return getMemberNameInfo().getLocStart();
3383   }
3384   SourceLocation getLocEnd() const LLVM_READONLY {
3385     if (hasExplicitTemplateArgs())
3386       return getRAngleLoc();
3387     return getMemberNameInfo().getLocEnd();
3388   }
3389
3390   static bool classof(const Stmt *T) {
3391     return T->getStmtClass() == UnresolvedMemberExprClass;
3392   }
3393
3394   // Iterators
3395   child_range children() {
3396     if (isImplicitAccess())
3397       return child_range(child_iterator(), child_iterator());
3398     return child_range(&Base, &Base + 1);
3399   }
3400 };
3401
3402 inline ASTTemplateKWAndArgsInfo *
3403 OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
3404   if (!HasTemplateKWAndArgsInfo)
3405     return nullptr;
3406
3407   if (isa<UnresolvedLookupExpr>(this))
3408     return cast<UnresolvedLookupExpr>(this)
3409         ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3410   else
3411     return cast<UnresolvedMemberExpr>(this)
3412         ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3413 }
3414
3415 inline TemplateArgumentLoc *OverloadExpr::getTrailingTemplateArgumentLoc() {
3416   if (isa<UnresolvedLookupExpr>(this))
3417     return cast<UnresolvedLookupExpr>(this)
3418         ->getTrailingObjects<TemplateArgumentLoc>();
3419   else
3420     return cast<UnresolvedMemberExpr>(this)
3421         ->getTrailingObjects<TemplateArgumentLoc>();
3422 }
3423
3424 /// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
3425 ///
3426 /// The noexcept expression tests whether a given expression might throw. Its
3427 /// result is a boolean constant.
3428 class CXXNoexceptExpr : public Expr {
3429   bool Value : 1;
3430   Stmt *Operand;
3431   SourceRange Range;
3432
3433   friend class ASTStmtReader;
3434
3435 public:
3436   CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
3437                   SourceLocation Keyword, SourceLocation RParen)
3438     : Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
3439            /*TypeDependent*/false,
3440            /*ValueDependent*/Val == CT_Dependent,
3441            Val == CT_Dependent || Operand->isInstantiationDependent(),
3442            Operand->containsUnexpandedParameterPack()),
3443       Value(Val == CT_Cannot), Operand(Operand), Range(Keyword, RParen)
3444   { }
3445
3446   CXXNoexceptExpr(EmptyShell Empty)
3447     : Expr(CXXNoexceptExprClass, Empty)
3448   { }
3449
3450   Expr *getOperand() const { return static_cast<Expr*>(Operand); }
3451
3452   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
3453   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
3454   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
3455
3456   bool getValue() const { return Value; }
3457
3458   static bool classof(const Stmt *T) {
3459     return T->getStmtClass() == CXXNoexceptExprClass;
3460   }
3461
3462   // Iterators
3463   child_range children() { return child_range(&Operand, &Operand + 1); }
3464 };
3465
3466 /// \brief Represents a C++11 pack expansion that produces a sequence of
3467 /// expressions.
3468 ///
3469 /// A pack expansion expression contains a pattern (which itself is an
3470 /// expression) followed by an ellipsis. For example:
3471 ///
3472 /// \code
3473 /// template<typename F, typename ...Types>
3474 /// void forward(F f, Types &&...args) {
3475 ///   f(static_cast<Types&&>(args)...);
3476 /// }
3477 /// \endcode
3478 ///
3479 /// Here, the argument to the function object \c f is a pack expansion whose
3480 /// pattern is \c static_cast<Types&&>(args). When the \c forward function
3481 /// template is instantiated, the pack expansion will instantiate to zero or
3482 /// or more function arguments to the function object \c f.
3483 class PackExpansionExpr : public Expr {
3484   SourceLocation EllipsisLoc;
3485
3486   /// \brief The number of expansions that will be produced by this pack
3487   /// expansion expression, if known.
3488   ///
3489   /// When zero, the number of expansions is not known. Otherwise, this value
3490   /// is the number of expansions + 1.
3491   unsigned NumExpansions;
3492
3493   Stmt *Pattern;
3494
3495   friend class ASTStmtReader;
3496   friend class ASTStmtWriter;
3497
3498 public:
3499   PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
3500                     Optional<unsigned> NumExpansions)
3501     : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
3502            Pattern->getObjectKind(), /*TypeDependent=*/true,
3503            /*ValueDependent=*/true, /*InstantiationDependent=*/true,
3504            /*ContainsUnexpandedParameterPack=*/false),
3505       EllipsisLoc(EllipsisLoc),
3506       NumExpansions(NumExpansions? *NumExpansions + 1 : 0),
3507       Pattern(Pattern) { }
3508
3509   PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) { }
3510
3511   /// \brief Retrieve the pattern of the pack expansion.
3512   Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
3513
3514   /// \brief Retrieve the pattern of the pack expansion.
3515   const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
3516
3517   /// \brief Retrieve the location of the ellipsis that describes this pack
3518   /// expansion.
3519   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
3520
3521   /// \brief Determine the number of expansions that will be produced when
3522   /// this pack expansion is instantiated, if already known.
3523   Optional<unsigned> getNumExpansions() const {
3524     if (NumExpansions)
3525       return NumExpansions - 1;
3526
3527     return None;
3528   }
3529
3530   SourceLocation getLocStart() const LLVM_READONLY {
3531     return Pattern->getLocStart();
3532   }
3533   SourceLocation getLocEnd() const LLVM_READONLY { return EllipsisLoc; }
3534
3535   static bool classof(const Stmt *T) {
3536     return T->getStmtClass() == PackExpansionExprClass;
3537   }
3538
3539   // Iterators
3540   child_range children() {
3541     return child_range(&Pattern, &Pattern + 1);
3542   }
3543 };
3544
3545
3546 /// \brief Represents an expression that computes the length of a parameter
3547 /// pack.
3548 ///
3549 /// \code
3550 /// template<typename ...Types>
3551 /// struct count {
3552 ///   static const unsigned value = sizeof...(Types);
3553 /// };
3554 /// \endcode
3555 class SizeOfPackExpr final
3556     : public Expr,
3557       private llvm::TrailingObjects<SizeOfPackExpr, TemplateArgument> {
3558   /// \brief The location of the \c sizeof keyword.
3559   SourceLocation OperatorLoc;
3560
3561   /// \brief The location of the name of the parameter pack.
3562   SourceLocation PackLoc;
3563
3564   /// \brief The location of the closing parenthesis.
3565   SourceLocation RParenLoc;
3566
3567   /// \brief The length of the parameter pack, if known.
3568   ///
3569   /// When this expression is not value-dependent, this is the length of
3570   /// the pack. When the expression was parsed rather than instantiated
3571   /// (and thus is value-dependent), this is zero.
3572   ///
3573   /// After partial substitution into a sizeof...(X) expression (for instance,
3574   /// within an alias template or during function template argument deduction),
3575   /// we store a trailing array of partially-substituted TemplateArguments,
3576   /// and this is the length of that array.
3577   unsigned Length;
3578
3579   /// \brief The parameter pack.
3580   NamedDecl *Pack;
3581
3582   friend TrailingObjects;
3583   friend class ASTStmtReader;
3584   friend class ASTStmtWriter;
3585
3586   /// \brief Create an expression that computes the length of
3587   /// the given parameter pack.
3588   SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3589                  SourceLocation PackLoc, SourceLocation RParenLoc,
3590                  Optional<unsigned> Length, ArrayRef<TemplateArgument> PartialArgs)
3591       : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3592              /*TypeDependent=*/false, /*ValueDependent=*/!Length,
3593              /*InstantiationDependent=*/!Length,
3594              /*ContainsUnexpandedParameterPack=*/false),
3595         OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3596         Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
3597     assert((!Length || PartialArgs.empty()) &&
3598            "have partial args for non-dependent sizeof... expression");
3599     TemplateArgument *Args = getTrailingObjects<TemplateArgument>();
3600     std::uninitialized_copy(PartialArgs.begin(), PartialArgs.end(), Args);
3601   }
3602
3603   /// \brief Create an empty expression.
3604   SizeOfPackExpr(EmptyShell Empty, unsigned NumPartialArgs)
3605       : Expr(SizeOfPackExprClass, Empty), Length(NumPartialArgs), Pack() {}
3606
3607 public:
3608   static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
3609                                 NamedDecl *Pack, SourceLocation PackLoc,
3610                                 SourceLocation RParenLoc,
3611                                 Optional<unsigned> Length = None,
3612                                 ArrayRef<TemplateArgument> PartialArgs = None);
3613   static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
3614                                             unsigned NumPartialArgs);
3615
3616   /// \brief Determine the location of the 'sizeof' keyword.
3617   SourceLocation getOperatorLoc() const { return OperatorLoc; }
3618
3619   /// \brief Determine the location of the parameter pack.
3620   SourceLocation getPackLoc() const { return PackLoc; }
3621
3622   /// \brief Determine the location of the right parenthesis.
3623   SourceLocation getRParenLoc() const { return RParenLoc; }
3624
3625   /// \brief Retrieve the parameter pack.
3626   NamedDecl *getPack() const { return Pack; }
3627
3628   /// \brief Retrieve the length of the parameter pack.
3629   ///
3630   /// This routine may only be invoked when the expression is not
3631   /// value-dependent.
3632   unsigned getPackLength() const {
3633     assert(!isValueDependent() &&
3634            "Cannot get the length of a value-dependent pack size expression");
3635     return Length;
3636   }
3637
3638   /// \brief Determine whether this represents a partially-substituted sizeof...
3639   /// expression, such as is produced for:
3640   ///
3641   ///   template<typename ...Ts> using X = int[sizeof...(Ts)];
3642   ///   template<typename ...Us> void f(X<Us..., 1, 2, 3, Us...>);
3643   bool isPartiallySubstituted() const {
3644     return isValueDependent() && Length;
3645   }
3646
3647   /// \brief Get
3648   ArrayRef<TemplateArgument> getPartialArguments() const {
3649     assert(isPartiallySubstituted());
3650     const TemplateArgument *Args = getTrailingObjects<TemplateArgument>();
3651     return llvm::makeArrayRef(Args, Args + Length);
3652   }
3653
3654   SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
3655   SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3656
3657   static bool classof(const Stmt *T) {
3658     return T->getStmtClass() == SizeOfPackExprClass;
3659   }
3660
3661   // Iterators
3662   child_range children() {
3663     return child_range(child_iterator(), child_iterator());
3664   }
3665 };
3666
3667 /// \brief Represents a reference to a non-type template parameter
3668 /// that has been substituted with a template argument.
3669 class SubstNonTypeTemplateParmExpr : public Expr {
3670   /// \brief The replaced parameter.
3671   NonTypeTemplateParmDecl *Param;
3672
3673   /// \brief The replacement expression.
3674   Stmt *Replacement;
3675
3676   /// \brief The location of the non-type template parameter reference.
3677   SourceLocation NameLoc;
3678
3679   friend class ASTReader;
3680   friend class ASTStmtReader;
3681   explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
3682     : Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
3683
3684 public:
3685   SubstNonTypeTemplateParmExpr(QualType type,
3686                                ExprValueKind valueKind,
3687                                SourceLocation loc,
3688                                NonTypeTemplateParmDecl *param,
3689                                Expr *replacement)
3690     : Expr(SubstNonTypeTemplateParmExprClass, type, valueKind, OK_Ordinary,
3691            replacement->isTypeDependent(), replacement->isValueDependent(),
3692            replacement->isInstantiationDependent(),
3693            replacement->containsUnexpandedParameterPack()),
3694       Param(param), Replacement(replacement), NameLoc(loc) {}
3695
3696   SourceLocation getNameLoc() const { return NameLoc; }
3697   SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3698   SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3699
3700   Expr *getReplacement() const { return cast<Expr>(Replacement); }
3701
3702   NonTypeTemplateParmDecl *getParameter() const { return Param; }
3703
3704   static bool classof(const Stmt *s) {
3705     return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
3706   }
3707
3708   // Iterators
3709   child_range children() { return child_range(&Replacement, &Replacement+1); }
3710 };
3711
3712 /// \brief Represents a reference to a non-type template parameter pack that
3713 /// has been substituted with a non-template argument pack.
3714 ///
3715 /// When a pack expansion in the source code contains multiple parameter packs
3716 /// and those parameter packs correspond to different levels of template
3717 /// parameter lists, this node is used to represent a non-type template
3718 /// parameter pack from an outer level, which has already had its argument pack
3719 /// substituted but that still lives within a pack expansion that itself
3720 /// could not be instantiated. When actually performing a substitution into
3721 /// that pack expansion (e.g., when all template parameters have corresponding
3722 /// arguments), this type will be replaced with the appropriate underlying
3723 /// expression at the current pack substitution index.
3724 class SubstNonTypeTemplateParmPackExpr : public Expr {
3725   /// \brief The non-type template parameter pack itself.
3726   NonTypeTemplateParmDecl *Param;
3727
3728   /// \brief A pointer to the set of template arguments that this
3729   /// parameter pack is instantiated with.
3730   const TemplateArgument *Arguments;
3731
3732   /// \brief The number of template arguments in \c Arguments.
3733   unsigned NumArguments;
3734
3735   /// \brief The location of the non-type template parameter pack reference.
3736   SourceLocation NameLoc;
3737
3738   friend class ASTReader;
3739   friend class ASTStmtReader;
3740   explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
3741     : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
3742
3743 public:
3744   SubstNonTypeTemplateParmPackExpr(QualType T,
3745                                    NonTypeTemplateParmDecl *Param,
3746                                    SourceLocation NameLoc,
3747                                    const TemplateArgument &ArgPack);
3748
3749   /// \brief Retrieve the non-type template parameter pack being substituted.
3750   NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
3751
3752   /// \brief Retrieve the location of the parameter pack name.
3753   SourceLocation getParameterPackLocation() const { return NameLoc; }
3754
3755   /// \brief Retrieve the template argument pack containing the substituted
3756   /// template arguments.
3757   TemplateArgument getArgumentPack() const;
3758
3759   SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3760   SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3761
3762   static bool classof(const Stmt *T) {
3763     return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
3764   }
3765
3766   // Iterators
3767   child_range children() {
3768     return child_range(child_iterator(), child_iterator());
3769   }
3770 };
3771
3772 /// \brief Represents a reference to a function parameter pack that has been
3773 /// substituted but not yet expanded.
3774 ///
3775 /// When a pack expansion contains multiple parameter packs at different levels,
3776 /// this node is used to represent a function parameter pack at an outer level
3777 /// which we have already substituted to refer to expanded parameters, but where
3778 /// the containing pack expansion cannot yet be expanded.
3779 ///
3780 /// \code
3781 /// template<typename...Ts> struct S {
3782 ///   template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
3783 /// };
3784 /// template struct S<int, int>;
3785 /// \endcode
3786 class FunctionParmPackExpr final
3787     : public Expr,
3788       private llvm::TrailingObjects<FunctionParmPackExpr, ParmVarDecl *> {
3789   /// \brief The function parameter pack which was referenced.
3790   ParmVarDecl *ParamPack;
3791
3792   /// \brief The location of the function parameter pack reference.
3793   SourceLocation NameLoc;
3794
3795   /// \brief The number of expansions of this pack.
3796   unsigned NumParameters;
3797
3798   FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
3799                        SourceLocation NameLoc, unsigned NumParams,
3800                        ParmVarDecl *const *Params);
3801
3802   friend TrailingObjects;
3803   friend class ASTReader;
3804   friend class ASTStmtReader;
3805
3806 public:
3807   static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
3808                                       ParmVarDecl *ParamPack,
3809                                       SourceLocation NameLoc,
3810                                       ArrayRef<ParmVarDecl *> Params);
3811   static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
3812                                            unsigned NumParams);
3813
3814   /// \brief Get the parameter pack which this expression refers to.
3815   ParmVarDecl *getParameterPack() const { return ParamPack; }
3816
3817   /// \brief Get the location of the parameter pack.
3818   SourceLocation getParameterPackLocation() const { return NameLoc; }
3819
3820   /// \brief Iterators over the parameters which the parameter pack expanded
3821   /// into.
3822   typedef ParmVarDecl * const *iterator;
3823   iterator begin() const { return getTrailingObjects<ParmVarDecl *>(); }
3824   iterator end() const { return begin() + NumParameters; }
3825
3826   /// \brief Get the number of parameters in this parameter pack.
3827   unsigned getNumExpansions() const { return NumParameters; }
3828
3829   /// \brief Get an expansion of the parameter pack by index.
3830   ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
3831
3832   SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3833   SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3834
3835   static bool classof(const Stmt *T) {
3836     return T->getStmtClass() == FunctionParmPackExprClass;
3837   }
3838
3839   child_range children() {
3840     return child_range(child_iterator(), child_iterator());
3841   }
3842 };
3843
3844 /// \brief Represents a prvalue temporary that is written into memory so that
3845 /// a reference can bind to it.
3846 ///
3847 /// Prvalue expressions are materialized when they need to have an address
3848 /// in memory for a reference to bind to. This happens when binding a
3849 /// reference to the result of a conversion, e.g.,
3850 ///
3851 /// \code
3852 /// const int &r = 1.0;
3853 /// \endcode
3854 ///
3855 /// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
3856 /// then materialized via a \c MaterializeTemporaryExpr, and the reference
3857 /// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
3858 /// (either an lvalue or an xvalue, depending on the kind of reference binding
3859 /// to it), maintaining the invariant that references always bind to glvalues.
3860 ///
3861 /// Reference binding and copy-elision can both extend the lifetime of a
3862 /// temporary. When either happens, the expression will also track the
3863 /// declaration which is responsible for the lifetime extension.
3864 class MaterializeTemporaryExpr : public Expr {
3865 private:
3866   struct ExtraState {
3867     /// \brief The temporary-generating expression whose value will be
3868     /// materialized.
3869     Stmt *Temporary;
3870
3871     /// \brief The declaration which lifetime-extended this reference, if any.
3872     /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3873     const ValueDecl *ExtendingDecl;
3874
3875     unsigned ManglingNumber;
3876   };
3877   llvm::PointerUnion<Stmt *, ExtraState *> State;
3878
3879   friend class ASTStmtReader;
3880   friend class ASTStmtWriter;
3881
3882   void initializeExtraState(const ValueDecl *ExtendedBy,
3883                             unsigned ManglingNumber);
3884
3885 public:
3886   MaterializeTemporaryExpr(QualType T, Expr *Temporary,
3887                            bool BoundToLvalueReference)
3888     : Expr(MaterializeTemporaryExprClass, T,
3889            BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
3890            Temporary->isTypeDependent(), Temporary->isValueDependent(),
3891            Temporary->isInstantiationDependent(),
3892            Temporary->containsUnexpandedParameterPack()),
3893         State(Temporary) {}
3894
3895   MaterializeTemporaryExpr(EmptyShell Empty)
3896     : Expr(MaterializeTemporaryExprClass, Empty) { }
3897
3898   Stmt *getTemporary() const {
3899     return State.is<Stmt *>() ? State.get<Stmt *>()
3900                               : State.get<ExtraState *>()->Temporary;
3901   }
3902
3903   /// \brief Retrieve the temporary-generating subexpression whose value will
3904   /// be materialized into a glvalue.
3905   Expr *GetTemporaryExpr() const { return static_cast<Expr *>(getTemporary()); }
3906
3907   /// \brief Retrieve the storage duration for the materialized temporary.
3908   StorageDuration getStorageDuration() const {
3909     const ValueDecl *ExtendingDecl = getExtendingDecl();
3910     if (!ExtendingDecl)
3911       return SD_FullExpression;
3912     // FIXME: This is not necessarily correct for a temporary materialized
3913     // within a default initializer.
3914     if (isa<FieldDecl>(ExtendingDecl))
3915       return SD_Automatic;
3916     return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
3917   }
3918
3919   /// \brief Get the declaration which triggered the lifetime-extension of this
3920   /// temporary, if any.
3921   const ValueDecl *getExtendingDecl() const {
3922     return State.is<Stmt *>() ? nullptr
3923                               : State.get<ExtraState *>()->ExtendingDecl;
3924   }
3925
3926   void setExtendingDecl(const ValueDecl *ExtendedBy, unsigned ManglingNumber);
3927
3928   unsigned getManglingNumber() const {
3929     return State.is<Stmt *>() ? 0 : State.get<ExtraState *>()->ManglingNumber;
3930   }
3931
3932   /// \brief Determine whether this materialized temporary is bound to an
3933   /// lvalue reference; otherwise, it's bound to an rvalue reference.
3934   bool isBoundToLvalueReference() const {
3935     return getValueKind() == VK_LValue;
3936   }
3937
3938   SourceLocation getLocStart() const LLVM_READONLY {
3939     return getTemporary()->getLocStart();
3940   }
3941   SourceLocation getLocEnd() const LLVM_READONLY {
3942     return getTemporary()->getLocEnd();
3943   }
3944
3945   static bool classof(const Stmt *T) {
3946     return T->getStmtClass() == MaterializeTemporaryExprClass;
3947   }
3948
3949   // Iterators
3950   child_range children() {
3951     if (State.is<Stmt *>())
3952       return child_range(State.getAddrOfPtr1(), State.getAddrOfPtr1() + 1);
3953
3954     auto ES = State.get<ExtraState *>();
3955     return child_range(&ES->Temporary, &ES->Temporary + 1);
3956   }
3957 };
3958
3959 /// \brief Represents a folding of a pack over an operator.
3960 ///
3961 /// This expression is always dependent and represents a pack expansion of the
3962 /// forms:
3963 ///
3964 ///    ( expr op ... )
3965 ///    ( ... op expr )
3966 ///    ( expr op ... op expr )
3967 class CXXFoldExpr : public Expr {
3968   SourceLocation LParenLoc;
3969   SourceLocation EllipsisLoc;
3970   SourceLocation RParenLoc;
3971   Stmt *SubExprs[2];
3972   BinaryOperatorKind Opcode;
3973
3974   friend class ASTStmtReader;
3975   friend class ASTStmtWriter;
3976 public:
3977   CXXFoldExpr(QualType T, SourceLocation LParenLoc, Expr *LHS,
3978               BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS,
3979               SourceLocation RParenLoc)
3980       : Expr(CXXFoldExprClass, T, VK_RValue, OK_Ordinary,
3981              /*Dependent*/ true, true, true,
3982              /*ContainsUnexpandedParameterPack*/ false),
3983         LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
3984         Opcode(Opcode) {
3985     SubExprs[0] = LHS;
3986     SubExprs[1] = RHS;
3987   }
3988   CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
3989
3990   Expr *getLHS() const { return static_cast<Expr*>(SubExprs[0]); }
3991   Expr *getRHS() const { return static_cast<Expr*>(SubExprs[1]); }
3992
3993   /// Does this produce a right-associated sequence of operators?
3994   bool isRightFold() const {
3995     return getLHS() && getLHS()->containsUnexpandedParameterPack();
3996   }
3997   /// Does this produce a left-associated sequence of operators?
3998   bool isLeftFold() const { return !isRightFold(); }
3999   /// Get the pattern, that is, the operand that contains an unexpanded pack.
4000   Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
4001   /// Get the operand that doesn't contain a pack, for a binary fold.
4002   Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
4003
4004   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4005   BinaryOperatorKind getOperator() const { return Opcode; }
4006
4007   SourceLocation getLocStart() const LLVM_READONLY {
4008     return LParenLoc;
4009   }
4010   SourceLocation getLocEnd() const LLVM_READONLY {
4011     return RParenLoc;
4012   }
4013
4014   static bool classof(const Stmt *T) {
4015     return T->getStmtClass() == CXXFoldExprClass;
4016   }
4017
4018   // Iterators
4019   child_range children() { return child_range(SubExprs, SubExprs + 2); }
4020 };
4021
4022 /// \brief Represents an expression that might suspend coroutine execution;
4023 /// either a co_await or co_yield expression.
4024 ///
4025 /// Evaluation of this expression first evaluates its 'ready' expression. If
4026 /// that returns 'false':
4027 ///  -- execution of the coroutine is suspended
4028 ///  -- the 'suspend' expression is evaluated
4029 ///     -- if the 'suspend' expression returns 'false', the coroutine is
4030 ///        resumed
4031 ///     -- otherwise, control passes back to the resumer.
4032 /// If the coroutine is not suspended, or when it is resumed, the 'resume'
4033 /// expression is evaluated, and its result is the result of the overall
4034 /// expression.
4035 class CoroutineSuspendExpr : public Expr {
4036   SourceLocation KeywordLoc;
4037
4038   enum SubExpr { Common, Ready, Suspend, Resume, Count };
4039   Stmt *SubExprs[SubExpr::Count];
4040
4041   friend class ASTStmtReader;
4042 public:
4043   CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, Expr *Common,
4044                        Expr *Ready, Expr *Suspend, Expr *Resume)
4045       : Expr(SC, Resume->getType(), Resume->getValueKind(),
4046              Resume->getObjectKind(), Resume->isTypeDependent(),
4047              Resume->isValueDependent(), Common->isInstantiationDependent(),
4048              Common->containsUnexpandedParameterPack()),
4049         KeywordLoc(KeywordLoc) {
4050     SubExprs[SubExpr::Common] = Common;
4051     SubExprs[SubExpr::Ready] = Ready;
4052     SubExprs[SubExpr::Suspend] = Suspend;
4053     SubExprs[SubExpr::Resume] = Resume;
4054   }
4055   CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, QualType Ty,
4056                        Expr *Common)
4057       : Expr(SC, Ty, VK_RValue, OK_Ordinary, true, true, true,
4058              Common->containsUnexpandedParameterPack()),
4059         KeywordLoc(KeywordLoc) {
4060     assert(Common->isTypeDependent() && Ty->isDependentType() &&
4061            "wrong constructor for non-dependent co_await/co_yield expression");
4062     SubExprs[SubExpr::Common] = Common;
4063     SubExprs[SubExpr::Ready] = nullptr;
4064     SubExprs[SubExpr::Suspend] = nullptr;
4065     SubExprs[SubExpr::Resume] = nullptr;
4066   }
4067   CoroutineSuspendExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4068     SubExprs[SubExpr::Common] = nullptr;
4069     SubExprs[SubExpr::Ready] = nullptr;
4070     SubExprs[SubExpr::Suspend] = nullptr;
4071     SubExprs[SubExpr::Resume] = nullptr;
4072   }
4073
4074   SourceLocation getKeywordLoc() const { return KeywordLoc; }
4075   Expr *getCommonExpr() const {
4076     return static_cast<Expr*>(SubExprs[SubExpr::Common]);
4077   }
4078
4079   Expr *getReadyExpr() const {
4080     return static_cast<Expr*>(SubExprs[SubExpr::Ready]);
4081   }
4082   Expr *getSuspendExpr() const {
4083     return static_cast<Expr*>(SubExprs[SubExpr::Suspend]);
4084   }
4085   Expr *getResumeExpr() const {
4086     return static_cast<Expr*>(SubExprs[SubExpr::Resume]);
4087   }
4088
4089   SourceLocation getLocStart() const LLVM_READONLY {
4090     return KeywordLoc;
4091   }
4092   SourceLocation getLocEnd() const LLVM_READONLY {
4093     return getCommonExpr()->getLocEnd();
4094   }
4095
4096   child_range children() {
4097     return child_range(SubExprs, SubExprs + SubExpr::Count);
4098   }
4099
4100   static bool classof(const Stmt *T) {
4101     return T->getStmtClass() == CoawaitExprClass ||
4102            T->getStmtClass() == CoyieldExprClass;
4103   }
4104 };
4105
4106 /// \brief Represents a 'co_await' expression.
4107 class CoawaitExpr : public CoroutineSuspendExpr {
4108   friend class ASTStmtReader;
4109 public:
4110   CoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand, Expr *Ready,
4111               Expr *Suspend, Expr *Resume)
4112       : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Operand, Ready,
4113                              Suspend, Resume) {}
4114   CoawaitExpr(SourceLocation CoawaitLoc, QualType Ty, Expr *Operand)
4115       : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Ty, Operand) {}
4116   CoawaitExpr(EmptyShell Empty)
4117       : CoroutineSuspendExpr(CoawaitExprClass, Empty) {}
4118
4119   Expr *getOperand() const {
4120     // FIXME: Dig out the actual operand or store it.
4121     return getCommonExpr();
4122   }
4123
4124   static bool classof(const Stmt *T) {
4125     return T->getStmtClass() == CoawaitExprClass;
4126   }
4127 };
4128
4129 /// \brief Represents a 'co_yield' expression.
4130 class CoyieldExpr : public CoroutineSuspendExpr {
4131   friend class ASTStmtReader;
4132 public:
4133   CoyieldExpr(SourceLocation CoyieldLoc, Expr *Operand, Expr *Ready,
4134               Expr *Suspend, Expr *Resume)
4135       : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Operand, Ready,
4136                              Suspend, Resume) {}
4137   CoyieldExpr(SourceLocation CoyieldLoc, QualType Ty, Expr *Operand)
4138       : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Ty, Operand) {}
4139   CoyieldExpr(EmptyShell Empty)
4140       : CoroutineSuspendExpr(CoyieldExprClass, Empty) {}
4141
4142   Expr *getOperand() const {
4143     // FIXME: Dig out the actual operand or store it.
4144     return getCommonExpr();
4145   }
4146
4147   static bool classof(const Stmt *T) {
4148     return T->getStmtClass() == CoyieldExprClass;
4149   }
4150 };
4151
4152 }  // end namespace clang
4153
4154 #endif