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