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