1//===- ExprCXX.h - Classes for representing expressions ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Defines the clang::Expr interface and subclasses for C++ expressions.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_EXPRCXX_H
16#define LLVM_CLANG_AST_EXPRCXX_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/OperationKinds.h"
25#include "clang/AST/Stmt.h"
26#include "clang/AST/TemplateBase.h"
27#include "clang/AST/Type.h"
28#include "clang/AST/UnresolvedSet.h"
29#include "clang/Basic/ExceptionSpecificationType.h"
30#include "clang/Basic/ExpressionTraits.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TypeTraits.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/PointerUnion.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/TrailingObjects.h"
47#include <cassert>
48#include <cstddef>
49#include <cstdint>
50#include <memory>
51
52namespace clang {
53
54class ASTContext;
55class DeclAccessPair;
56class IdentifierInfo;
57class LambdaCapture;
58class NonTypeTemplateParmDecl;
59class TemplateParameterList;
60
61//===--------------------------------------------------------------------===//
62// C++ Expressions.
63//===--------------------------------------------------------------------===//
64
65/// A call to an overloaded operator written using operator
66/// syntax.
67///
68/// Represents a call to an overloaded operator written using operator
69/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
70/// normal call, this AST node provides better information about the
71/// syntactic representation of the call.
72///
73/// In a C++ template, this expression node kind will be used whenever
74/// any of the arguments are type-dependent. In this case, the
75/// function itself will be a (possibly empty) set of functions and
76/// function templates that were found by name lookup at template
77/// definition time.
78class CXXOperatorCallExpr : public CallExpr {
79 /// The overloaded operator.
80 OverloadedOperatorKind Operator;
81
82 SourceRange Range;
83
84 // Only meaningful for floating point types.
85 FPOptions FPFeatures;
86
87 SourceRange getSourceRangeImpl() const LLVM_READONLY;
88
89public:
90 friend class ASTStmtReader;
91 friend class ASTStmtWriter;
92
93 CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
94 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
95 SourceLocation operatorloc, FPOptions FPFeatures)
96 : CallExpr(C, CXXOperatorCallExprClass, fn, args, t, VK, operatorloc),
97 Operator(Op), FPFeatures(FPFeatures) {
98 Range = getSourceRangeImpl();
99 }
100
101 explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty)
102 : CallExpr(C, CXXOperatorCallExprClass, Empty) {}
103
104 /// Returns the kind of overloaded operator that this
105 /// expression refers to.
106 OverloadedOperatorKind getOperator() const { return Operator; }
107
108 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
109 return Opc == OO_Equal || Opc == OO_StarEqual ||
110 Opc == OO_SlashEqual || Opc == OO_PercentEqual ||
111 Opc == OO_PlusEqual || Opc == OO_MinusEqual ||
112 Opc == OO_LessLessEqual || Opc == OO_GreaterGreaterEqual ||
113 Opc == OO_AmpEqual || Opc == OO_CaretEqual ||
114 Opc == OO_PipeEqual;
115 }
116 bool isAssignmentOp() const { return isAssignmentOp(getOperator()); }
117
118 /// Is this written as an infix binary operator?
119 bool isInfixBinaryOp() const;
120
121 /// Returns the location of the operator symbol in the expression.
122 ///
123 /// When \c getOperator()==OO_Call, this is the location of the right
124 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
125 /// of the right bracket.
126 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
127
128 SourceLocation getExprLoc() const LLVM_READONLY {
129 return (Operator < OO_Plus || Operator >= OO_Arrow ||
130 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
131 ? getBeginLoc()
132 : getOperatorLoc();
133 }
134
135 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
136 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
137 SourceRange getSourceRange() const { return Range; }
138
139 static bool classof(const Stmt *T) {
140 return T->getStmtClass() == CXXOperatorCallExprClass;
141 }
142
143 // Set the FP contractability status of this operator. Only meaningful for
144 // operations on floating point types.
145 void setFPFeatures(FPOptions F) { FPFeatures = F; }
146
147 FPOptions getFPFeatures() const { return FPFeatures; }
148
149 // Get the FP contractability status of this operator. Only meaningful for
150 // operations on floating point types.
151 bool isFPContractableWithinStatement() const {
152 return FPFeatures.allowFPContractWithinStatement();
153 }
154};
155
156/// Represents a call to a member function that
157/// may be written either with member call syntax (e.g., "obj.func()"
158/// or "objptr->func()") or with normal function-call syntax
159/// ("func()") within a member function that ends up calling a member
160/// function. The callee in either case is a MemberExpr that contains
161/// both the object argument and the member function, while the
162/// arguments are the arguments within the parentheses (not including
163/// the object argument).
164class CXXMemberCallExpr : public CallExpr {
165public:
166 CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
167 QualType t, ExprValueKind VK, SourceLocation RP)
168 : CallExpr(C, CXXMemberCallExprClass, fn, args, t, VK, RP) {}
169
170 CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
171 : CallExpr(C, CXXMemberCallExprClass, Empty) {}
172
173 /// Retrieves the implicit object argument for the member call.
174 ///
175 /// For example, in "x.f(5)", this returns the sub-expression "x".
176 Expr *getImplicitObjectArgument() const;
177
178 /// Retrieves the declaration of the called method.
179 CXXMethodDecl *getMethodDecl() const;
180
181 /// Retrieves the CXXRecordDecl for the underlying type of
182 /// the implicit object argument.
183 ///
184 /// Note that this is may not be the same declaration as that of the class
185 /// context of the CXXMethodDecl which this function is calling.
186 /// FIXME: Returns 0 for member pointer call exprs.
187 CXXRecordDecl *getRecordDecl() const;
188
189 SourceLocation getExprLoc() const LLVM_READONLY {
190 SourceLocation CLoc = getCallee()->getExprLoc();
191 if (CLoc.isValid())
192 return CLoc;
193
194 return getBeginLoc();
195 }
196
197 static bool classof(const Stmt *T) {
198 return T->getStmtClass() == CXXMemberCallExprClass;
199 }
200};
201
202/// Represents a call to a CUDA kernel function.
203class CUDAKernelCallExpr : public CallExpr {
204private:
205 enum { CONFIG, END_PREARG };
206
207public:
208 CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
209 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
210 SourceLocation RP)
211 : CallExpr(C, CUDAKernelCallExprClass, fn, Config, args, t, VK, RP) {}
212
213 CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
214 : CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) {}
215
216 const CallExpr *getConfig() const {
217 return cast_or_null<CallExpr>(getPreArg(CONFIG));
218 }
219 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
220
221 /// Sets the kernel configuration expression.
222 ///
223 /// Note that this method cannot be called if config has already been set to a
224 /// non-null value.
225 void setConfig(CallExpr *E) {
226 assert(!getConfig() &&
227 "Cannot call setConfig if config is not null");
228 setPreArg(CONFIG, E);
229 setInstantiationDependent(isInstantiationDependent() ||
230 E->isInstantiationDependent());
231 setContainsUnexpandedParameterPack(containsUnexpandedParameterPack() ||
232 E->containsUnexpandedParameterPack());
233 }
234
235 static bool classof(const Stmt *T) {
236 return T->getStmtClass() == CUDAKernelCallExprClass;
237 }
238};
239
240/// Abstract class common to all of the C++ "named"/"keyword" casts.
241///
242/// This abstract class is inherited by all of the classes
243/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
244/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
245/// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
246class CXXNamedCastExpr : public ExplicitCastExpr {
247private:
248 // the location of the casting op
249 SourceLocation Loc;
250
251 // the location of the right parenthesis
252 SourceLocation RParenLoc;
253
254 // range for '<' '>'
255 SourceRange AngleBrackets;
256
257protected:
258 friend class ASTStmtReader;
259
260 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
261 CastKind kind, Expr *op, unsigned PathSize,
262 TypeSourceInfo *writtenTy, SourceLocation l,
263 SourceLocation RParenLoc,
264 SourceRange AngleBrackets)
265 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
266 RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
267
268 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
269 : ExplicitCastExpr(SC, Shell, PathSize) {}
270
271public:
272 const char *getCastName() const;
273
274 /// Retrieve the location of the cast operator keyword, e.g.,
275 /// \c static_cast.
276 SourceLocation getOperatorLoc() const { return Loc; }
277
278 /// Retrieve the location of the closing parenthesis.
279 SourceLocation getRParenLoc() const { return RParenLoc; }
280
281 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
282 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
283 SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
284
285 static bool classof(const Stmt *T) {
286 switch (T->getStmtClass()) {
287 case CXXStaticCastExprClass:
288 case CXXDynamicCastExprClass:
289 case CXXReinterpretCastExprClass:
290 case CXXConstCastExprClass:
291 return true;
292 default:
293 return false;
294 }
295 }
296};
297
298/// A C++ \c static_cast expression (C++ [expr.static.cast]).
299///
300/// This expression node represents a C++ static cast, e.g.,
301/// \c static_cast<int>(1.0).
302class CXXStaticCastExpr final
303 : public CXXNamedCastExpr,
304 private llvm::TrailingObjects<CXXStaticCastExpr, CastExpr::BasePathSizeTy,
305 CXXBaseSpecifier *> {
306 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
307 unsigned pathSize, TypeSourceInfo *writtenTy,
308 SourceLocation l, SourceLocation RParenLoc,
309 SourceRange AngleBrackets)
310 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
311 writtenTy, l, RParenLoc, AngleBrackets) {}
312
313 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
314 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) {}
315
316 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
317 return path_empty() ? 0 : 1;
318 }
319
320public:
321 friend class CastExpr;
322 friend TrailingObjects;
323
324 static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
325 ExprValueKind VK, CastKind K, Expr *Op,
326 const CXXCastPath *Path,
327 TypeSourceInfo *Written, SourceLocation L,
328 SourceLocation RParenLoc,
329 SourceRange AngleBrackets);
330 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
331 unsigned PathSize);
332
333 static bool classof(const Stmt *T) {
334 return T->getStmtClass() == CXXStaticCastExprClass;
335 }
336};
337
338/// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
339///
340/// This expression node represents a dynamic cast, e.g.,
341/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
342/// check to determine how to perform the type conversion.
343class CXXDynamicCastExpr final
344 : public CXXNamedCastExpr,
345 private llvm::TrailingObjects<
346 CXXDynamicCastExpr, CastExpr::BasePathSizeTy, CXXBaseSpecifier *> {
347 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
348 Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
349 SourceLocation l, SourceLocation RParenLoc,
350 SourceRange AngleBrackets)
351 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
352 writtenTy, l, RParenLoc, AngleBrackets) {}
353
354 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
355 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) {}
356
357 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
358 return path_empty() ? 0 : 1;
359 }
360
361public:
362 friend class CastExpr;
363 friend TrailingObjects;
364
365 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
366 ExprValueKind VK, CastKind Kind, Expr *Op,
367 const CXXCastPath *Path,
368 TypeSourceInfo *Written, SourceLocation L,
369 SourceLocation RParenLoc,
370 SourceRange AngleBrackets);
371
372 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
373 unsigned pathSize);
374
375 bool isAlwaysNull() const;
376
377 static bool classof(const Stmt *T) {
378 return T->getStmtClass() == CXXDynamicCastExprClass;
379 }
380};
381
382/// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
383///
384/// This expression node represents a reinterpret cast, e.g.,
385/// @c reinterpret_cast<int>(VoidPtr).
386///
387/// A reinterpret_cast provides a differently-typed view of a value but
388/// (in Clang, as in most C++ implementations) performs no actual work at
389/// run time.
390class CXXReinterpretCastExpr final
391 : public CXXNamedCastExpr,
392 private llvm::TrailingObjects<CXXReinterpretCastExpr,
393 CastExpr::BasePathSizeTy,
394 CXXBaseSpecifier *> {
395 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
396 Expr *op, unsigned pathSize,
397 TypeSourceInfo *writtenTy, SourceLocation l,
398 SourceLocation RParenLoc,
399 SourceRange AngleBrackets)
400 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
401 pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
402
403 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
404 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) {}
405
406 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
407 return path_empty() ? 0 : 1;
408 }
409
410public:
411 friend class CastExpr;
412 friend TrailingObjects;
413
414 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
415 ExprValueKind VK, CastKind Kind,
416 Expr *Op, const CXXCastPath *Path,
417 TypeSourceInfo *WrittenTy, SourceLocation L,
418 SourceLocation RParenLoc,
419 SourceRange AngleBrackets);
420 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
421 unsigned pathSize);
422
423 static bool classof(const Stmt *T) {
424 return T->getStmtClass() == CXXReinterpretCastExprClass;
425 }
426};
427
428/// A C++ \c const_cast expression (C++ [expr.const.cast]).
429///
430/// This expression node represents a const cast, e.g.,
431/// \c const_cast<char*>(PtrToConstChar).
432///
433/// A const_cast can remove type qualifiers but does not change the underlying
434/// value.
435class CXXConstCastExpr final
436 : public CXXNamedCastExpr,
437 private llvm::TrailingObjects<CXXConstCastExpr, CastExpr::BasePathSizeTy,
438 CXXBaseSpecifier *> {
439 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
440 TypeSourceInfo *writtenTy, SourceLocation l,
441 SourceLocation RParenLoc, SourceRange AngleBrackets)
442 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
443 0, writtenTy, l, RParenLoc, AngleBrackets) {}
444
445 explicit CXXConstCastExpr(EmptyShell Empty)
446 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) {}
447
448 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
449 return path_empty() ? 0 : 1;
450 }
451
452public:
453 friend class CastExpr;
454 friend TrailingObjects;
455
456 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
457 ExprValueKind VK, Expr *Op,
458 TypeSourceInfo *WrittenTy, SourceLocation L,
459 SourceLocation RParenLoc,
460 SourceRange AngleBrackets);
461 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
462
463 static bool classof(const Stmt *T) {
464 return T->getStmtClass() == CXXConstCastExprClass;
465 }
466};
467
468/// A call to a literal operator (C++11 [over.literal])
469/// written as a user-defined literal (C++11 [lit.ext]).
470///
471/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
472/// is semantically equivalent to a normal call, this AST node provides better
473/// information about the syntactic representation of the literal.
474///
475/// Since literal operators are never found by ADL and can only be declared at
476/// namespace scope, a user-defined literal is never dependent.
477class UserDefinedLiteral : public CallExpr {
478 /// The location of a ud-suffix within the literal.
479 SourceLocation UDSuffixLoc;
480
481public:
482 friend class ASTStmtReader;
483 friend class ASTStmtWriter;
484
485 UserDefinedLiteral(const ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
486 QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
487 SourceLocation SuffixLoc)
488 : CallExpr(C, UserDefinedLiteralClass, Fn, Args, T, VK, LitEndLoc),
489 UDSuffixLoc(SuffixLoc) {}
490
491 explicit UserDefinedLiteral(const ASTContext &C, EmptyShell Empty)
492 : CallExpr(C, UserDefinedLiteralClass, Empty) {}
493
494 /// The kind of literal operator which is invoked.
495 enum LiteralOperatorKind {
496 /// Raw form: operator "" X (const char *)
497 LOK_Raw,
498
499 /// Raw form: operator "" X<cs...> ()
500 LOK_Template,
501
502 /// operator "" X (unsigned long long)
503 LOK_Integer,
504
505 /// operator "" X (long double)
506 LOK_Floating,
507
508 /// operator "" X (const CharT *, size_t)
509 LOK_String,
510
511 /// operator "" X (CharT)
512 LOK_Character
513 };
514
515 /// Returns the kind of literal operator invocation
516 /// which this expression represents.
517 LiteralOperatorKind getLiteralOperatorKind() const;
518
519 /// If this is not a raw user-defined literal, get the
520 /// underlying cooked literal (representing the literal with the suffix
521 /// removed).
522 Expr *getCookedLiteral();
523 const Expr *getCookedLiteral() const {
524 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
525 }
526
527 SourceLocation getBeginLoc() const {
528 if (getLiteralOperatorKind() == LOK_Template)
529 return getRParenLoc();
530 return getArg(0)->getBeginLoc();
531 }
532
533 SourceLocation getEndLoc() const { return getRParenLoc(); }
534
535 /// Returns the location of a ud-suffix in the expression.
536 ///
537 /// For a string literal, there may be multiple identical suffixes. This
538 /// returns the first.
539 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
540
541 /// Returns the ud-suffix specified for this literal.
542 const IdentifierInfo *getUDSuffix() const;
543
544 static bool classof(const Stmt *S) {
545 return S->getStmtClass() == UserDefinedLiteralClass;
546 }
547};
548
549/// A boolean literal, per ([C++ lex.bool] Boolean literals).
550class CXXBoolLiteralExpr : public Expr {
551 bool Value;
552 SourceLocation Loc;
553
554public:
555 CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l)
556 : Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
557 false, false),
558 Value(val), Loc(l) {}
559
560 explicit CXXBoolLiteralExpr(EmptyShell Empty)
561 : Expr(CXXBoolLiteralExprClass, Empty) {}
562
563 bool getValue() const { return Value; }
564 void setValue(bool V) { Value = V; }
565
566 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
567 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
568
569 SourceLocation getLocation() const { return Loc; }
570 void setLocation(SourceLocation L) { Loc = L; }
571
572 static bool classof(const Stmt *T) {
573 return T->getStmtClass() == CXXBoolLiteralExprClass;
574 }
575
576 // Iterators
577 child_range children() {
578 return child_range(child_iterator(), child_iterator());
579 }
580};
581
582/// The null pointer literal (C++11 [lex.nullptr])
583///
584/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
585class CXXNullPtrLiteralExpr : public Expr {
586 SourceLocation Loc;
587
588public:
589 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l)
590 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false,
591 false, false, false),
592 Loc(l) {}
593
594 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
595 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
596
597 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
598 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
599
600 SourceLocation getLocation() const { return Loc; }
601 void setLocation(SourceLocation L) { Loc = L; }
602
603 static bool classof(const Stmt *T) {
604 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
605 }
606
607 child_range children() {
608 return child_range(child_iterator(), child_iterator());
609 }
610};
611
612/// Implicit construction of a std::initializer_list<T> object from an
613/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
614class CXXStdInitializerListExpr : public Expr {
615 Stmt *SubExpr = nullptr;
616
617 CXXStdInitializerListExpr(EmptyShell Empty)
618 : Expr(CXXStdInitializerListExprClass, Empty) {}
619
620public:
621 friend class ASTReader;
622 friend class ASTStmtReader;
623
624 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
625 : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
626 Ty->isDependentType(), SubExpr->isValueDependent(),
627 SubExpr->isInstantiationDependent(),
628 SubExpr->containsUnexpandedParameterPack()),
629 SubExpr(SubExpr) {}
630
631 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
632 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
633
634 SourceLocation getBeginLoc() const LLVM_READONLY {
635 return SubExpr->getBeginLoc();
636 }
637
638 SourceLocation getEndLoc() const LLVM_READONLY {
639 return SubExpr->getEndLoc();
640 }
641
642 /// Retrieve the source range of the expression.
643 SourceRange getSourceRange() const LLVM_READONLY {
644 return SubExpr->getSourceRange();
645 }
646
647 static bool classof(const Stmt *S) {
648 return S->getStmtClass() == CXXStdInitializerListExprClass;
649 }
650
651 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
652};
653
654/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
655/// the \c type_info that corresponds to the supplied type, or the (possibly
656/// dynamic) type of the supplied expression.
657///
658/// This represents code like \c typeid(int) or \c typeid(*objPtr)
659class CXXTypeidExpr : public Expr {
660private:
661 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
662 SourceRange Range;
663
664public:
665 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
666 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
667 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
668 false,
669 // typeid is value-dependent if the type or expression are
670 // dependent
671 Operand->getType()->isDependentType(),
672 Operand->getType()->isInstantiationDependentType(),
673 Operand->getType()->containsUnexpandedParameterPack()),
674 Operand(Operand), Range(R) {}
675
676 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
677 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
678 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
679 false,
680 // typeid is value-dependent if the type or expression are
681 // dependent
682 Operand->isTypeDependent() || Operand->isValueDependent(),
683 Operand->isInstantiationDependent(),
684 Operand->containsUnexpandedParameterPack()),
685 Operand(Operand), Range(R) {}
686
687 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
688 : Expr(CXXTypeidExprClass, Empty) {
689 if (isExpr)
690 Operand = (Expr*)nullptr;
691 else
692 Operand = (TypeSourceInfo*)nullptr;
693 }
694
695 /// Determine whether this typeid has a type operand which is potentially
696 /// evaluated, per C++11 [expr.typeid]p3.
697 bool isPotentiallyEvaluated() const;
698
699 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
700
701 /// Retrieves the type operand of this typeid() expression after
702 /// various required adjustments (removing reference types, cv-qualifiers).
703 QualType getTypeOperand(ASTContext &Context) const;
704
705 /// Retrieve source information for the type operand.
706 TypeSourceInfo *getTypeOperandSourceInfo() const {
707 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
708 return Operand.get<TypeSourceInfo *>();
709 }
710
711 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
712 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
713 Operand = TSI;
714 }
715
716 Expr *getExprOperand() const {
717 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
718 return static_cast<Expr*>(Operand.get<Stmt *>());
719 }
720
721 void setExprOperand(Expr *E) {
722 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
723 Operand = E;
724 }
725
726 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
727 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
728 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
729 void setSourceRange(SourceRange R) { Range = R; }
730
731 static bool classof(const Stmt *T) {
732 return T->getStmtClass() == CXXTypeidExprClass;
733 }
734
735 // Iterators
736 child_range children() {
737 if (isTypeOperand())
738 return child_range(child_iterator(), child_iterator());
739 auto **begin = reinterpret_cast<Stmt **>(&Operand);
740 return child_range(begin, begin + 1);
741 }
742};
743
744/// A member reference to an MSPropertyDecl.
745///
746/// This expression always has pseudo-object type, and therefore it is
747/// typically not encountered in a fully-typechecked expression except
748/// within the syntactic form of a PseudoObjectExpr.
749class MSPropertyRefExpr : public Expr {
750 Expr *BaseExpr;
751 MSPropertyDecl *TheDecl;
752 SourceLocation MemberLoc;
753 bool IsArrow;
754 NestedNameSpecifierLoc QualifierLoc;
755
756public:
757 friend class ASTStmtReader;
758
759 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
760 QualType ty, ExprValueKind VK,
761 NestedNameSpecifierLoc qualifierLoc,
762 SourceLocation nameLoc)
763 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
764 /*type-dependent*/ false, baseExpr->isValueDependent(),
765 baseExpr->isInstantiationDependent(),
766 baseExpr->containsUnexpandedParameterPack()),
767 BaseExpr(baseExpr), TheDecl(decl),
768 MemberLoc(nameLoc), IsArrow(isArrow),
769 QualifierLoc(qualifierLoc) {}
770
771 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
772
773 SourceRange getSourceRange() const LLVM_READONLY {
774 return SourceRange(getBeginLoc(), getEndLoc());
775 }
776
777 bool isImplicitAccess() const {
778 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
779 }
780
781 SourceLocation getBeginLoc() const {
782 if (!isImplicitAccess())
783 return BaseExpr->getBeginLoc();
784 else if (QualifierLoc)
785 return QualifierLoc.getBeginLoc();
786 else
787 return MemberLoc;
788 }
789
790 SourceLocation getEndLoc() const { return getMemberLoc(); }
791
792 child_range children() {
793 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
794 }
795
796 static bool classof(const Stmt *T) {
797 return T->getStmtClass() == MSPropertyRefExprClass;
798 }
799
800 Expr *getBaseExpr() const { return BaseExpr; }
801 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
802 bool isArrow() const { return IsArrow; }
803 SourceLocation getMemberLoc() const { return MemberLoc; }
804 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
805};
806
807/// MS property subscript expression.
808/// MSVC supports 'property' attribute and allows to apply it to the
809/// declaration of an empty array in a class or structure definition.
810/// For example:
811/// \code
812/// __declspec(property(get=GetX, put=PutX)) int x[];
813/// \endcode
814/// The above statement indicates that x[] can be used with one or more array
815/// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
816/// p->x[a][b] = i will be turned into p->PutX(a, b, i).
817/// This is a syntactic pseudo-object expression.
818class MSPropertySubscriptExpr : public Expr {
819 friend class ASTStmtReader;
820
821 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
822
823 Stmt *SubExprs[NUM_SUBEXPRS];
824 SourceLocation RBracketLoc;
825
826 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
827 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
828
829public:
830 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
831 ExprObjectKind OK, SourceLocation RBracketLoc)
832 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK, Idx->isTypeDependent(),
833 Idx->isValueDependent(), Idx->isInstantiationDependent(),
834 Idx->containsUnexpandedParameterPack()),
835 RBracketLoc(RBracketLoc) {
836 SubExprs[BASE_EXPR] = Base;
837 SubExprs[IDX_EXPR] = Idx;
838 }
839
840 /// Create an empty array subscript expression.
841 explicit MSPropertySubscriptExpr(EmptyShell Shell)
842 : Expr(MSPropertySubscriptExprClass, Shell) {}
843
844 Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
845 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
846
847 Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
848 const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
849
850 SourceLocation getBeginLoc() const LLVM_READONLY {
851 return getBase()->getBeginLoc();
852 }
853
854 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
855
856 SourceLocation getRBracketLoc() const { return RBracketLoc; }
857 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
858
859 SourceLocation getExprLoc() const LLVM_READONLY {
860 return getBase()->getExprLoc();
861 }
862
863 static bool classof(const Stmt *T) {
864 return T->getStmtClass() == MSPropertySubscriptExprClass;
865 }
866
867 // Iterators
868 child_range children() {
869 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
870 }
871};
872
873/// A Microsoft C++ @c __uuidof expression, which gets
874/// the _GUID that corresponds to the supplied type or expression.
875///
876/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
877class CXXUuidofExpr : public Expr {
878private:
879 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
880 StringRef UuidStr;
881 SourceRange Range;
882
883public:
884 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, StringRef UuidStr,
885 SourceRange R)
886 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
887 Operand->getType()->isDependentType(),
888 Operand->getType()->isInstantiationDependentType(),
889 Operand->getType()->containsUnexpandedParameterPack()),
890 Operand(Operand), UuidStr(UuidStr), Range(R) {}
891
892 CXXUuidofExpr(QualType Ty, Expr *Operand, StringRef UuidStr, SourceRange R)
893 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
894 Operand->isTypeDependent(), Operand->isInstantiationDependent(),
895 Operand->containsUnexpandedParameterPack()),
896 Operand(Operand), UuidStr(UuidStr), Range(R) {}
897
898 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
899 : Expr(CXXUuidofExprClass, Empty) {
900 if (isExpr)
901 Operand = (Expr*)nullptr;
902 else
903 Operand = (TypeSourceInfo*)nullptr;
904 }
905
906 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
907
908 /// Retrieves the type operand of this __uuidof() expression after
909 /// various required adjustments (removing reference types, cv-qualifiers).
910 QualType getTypeOperand(ASTContext &Context) const;
911
912 /// Retrieve source information for the type operand.
913 TypeSourceInfo *getTypeOperandSourceInfo() const {
914 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
915 return Operand.get<TypeSourceInfo *>();
916 }
917
918 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
919 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
920 Operand = TSI;
921 }
922
923 Expr *getExprOperand() const {
924 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
925 return static_cast<Expr*>(Operand.get<Stmt *>());
926 }
927
928 void setExprOperand(Expr *E) {
929 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
930 Operand = E;
931 }
932
933 void setUuidStr(StringRef US) { UuidStr = US; }
934 StringRef getUuidStr() const { return UuidStr; }
935
936 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
937 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
938 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
939 void setSourceRange(SourceRange R) { Range = R; }
940
941 static bool classof(const Stmt *T) {
942 return T->getStmtClass() == CXXUuidofExprClass;
943 }
944
945 // Iterators
946 child_range children() {
947 if (isTypeOperand())
948 return child_range(child_iterator(), child_iterator());
949 auto **begin = reinterpret_cast<Stmt **>(&Operand);
950 return child_range(begin, begin + 1);
951 }
952};
953
954/// Represents the \c this expression in C++.
955///
956/// This is a pointer to the object on which the current member function is
957/// executing (C++ [expr.prim]p3). Example:
958///
959/// \code
960/// class Foo {
961/// public:
962/// void bar();
963/// void test() { this->bar(); }
964/// };
965/// \endcode
966class CXXThisExpr : public Expr {
967 SourceLocation Loc;
968 bool Implicit : 1;
969
970public:
971 CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
972 : Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
973 // 'this' is type-dependent if the class type of the enclosing
974 // member function is dependent (C++ [temp.dep.expr]p2)
975 Type->isDependentType(), Type->isDependentType(),
976 Type->isInstantiationDependentType(),
977 /*ContainsUnexpandedParameterPack=*/false),
978 Loc(L), Implicit(isImplicit) {}
979
980 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
981
982 SourceLocation getLocation() const { return Loc; }
983 void setLocation(SourceLocation L) { Loc = L; }
984
985 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
986 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
987
988 bool isImplicit() const { return Implicit; }
989 void setImplicit(bool I) { Implicit = I; }
990
991 static bool classof(const Stmt *T) {
992 return T->getStmtClass() == CXXThisExprClass;
993 }
994
995 // Iterators
996 child_range children() {
997 return child_range(child_iterator(), child_iterator());
998 }
999};
1000
1001/// A C++ throw-expression (C++ [except.throw]).
1002///
1003/// This handles 'throw' (for re-throwing the current exception) and
1004/// 'throw' assignment-expression. When assignment-expression isn't
1005/// present, Op will be null.
1006class CXXThrowExpr : public Expr {
1007 friend class ASTStmtReader;
1008
1009 Stmt *Op;
1010 SourceLocation ThrowLoc;
1011
1012 /// Whether the thrown variable (if any) is in scope.
1013 unsigned IsThrownVariableInScope : 1;
1014
1015public:
1016 // \p Ty is the void type which is used as the result type of the
1017 // expression. The \p l is the location of the throw keyword. \p expr
1018 // can by null, if the optional expression to throw isn't present.
1019 CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
1020 bool IsThrownVariableInScope)
1021 : Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
1022 expr && expr->isInstantiationDependent(),
1023 expr && expr->containsUnexpandedParameterPack()),
1024 Op(expr), ThrowLoc(l),
1025 IsThrownVariableInScope(IsThrownVariableInScope) {}
1026 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1027
1028 const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
1029 Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
1030
1031 SourceLocation getThrowLoc() const { return ThrowLoc; }
1032
1033 /// Determines whether the variable thrown by this expression (if any!)
1034 /// is within the innermost try block.
1035 ///
1036 /// This information is required to determine whether the NRVO can apply to
1037 /// this variable.
1038 bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
1039
1040 SourceLocation getBeginLoc() const LLVM_READONLY { return ThrowLoc; }
1041
1042 SourceLocation getEndLoc() const LLVM_READONLY {
1043 if (!getSubExpr())
1044 return ThrowLoc;
1045 return getSubExpr()->getEndLoc();
1046 }
1047
1048 static bool classof(const Stmt *T) {
1049 return T->getStmtClass() == CXXThrowExprClass;
1050 }
1051
1052 // Iterators
1053 child_range children() {
1054 return child_range(&Op, Op ? &Op+1 : &Op);
1055 }
1056};
1057
1058/// A default argument (C++ [dcl.fct.default]).
1059///
1060/// This wraps up a function call argument that was created from the
1061/// corresponding parameter's default argument, when the call did not
1062/// explicitly supply arguments for all of the parameters.
1063class CXXDefaultArgExpr final : public Expr {
1064 /// The parameter whose default is being used.
1065 ParmVarDecl *Param;
1066
1067 /// The location where the default argument expression was used.
1068 SourceLocation Loc;
1069
1070 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
1071 : Expr(SC,
1072 param->hasUnparsedDefaultArg()
1073 ? param->getType().getNonReferenceType()
1074 : param->getDefaultArg()->getType(),
1075 param->getDefaultArg()->getValueKind(),
1076 param->getDefaultArg()->getObjectKind(), false, false, false,
1077 false),
1078 Param(param), Loc(Loc) {}
1079
1080public:
1081 friend class ASTStmtReader;
1082 friend class ASTStmtWriter;
1083
1084 CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
1085
1086 // \p Param is the parameter whose default argument is used by this
1087 // expression.
1088 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1089 ParmVarDecl *Param) {
1090 return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
1091 }
1092
1093 // Retrieve the parameter that the argument was created from.
1094 const ParmVarDecl *getParam() const { return Param; }
1095 ParmVarDecl *getParam() { return Param; }
1096
1097 // Retrieve the actual argument to the function call.
1098 const Expr *getExpr() const {
1099 return getParam()->getDefaultArg();
1100 }
1101 Expr *getExpr() {
1102 return getParam()->getDefaultArg();
1103 }
1104
1105 /// Retrieve the location where this default argument was actually
1106 /// used.
1107 SourceLocation getUsedLocation() const { return Loc; }
1108
1109 /// Default argument expressions have no representation in the
1110 /// source, so they have an empty source range.
1111 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
1112 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
1113
1114 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1115
1116 static bool classof(const Stmt *T) {
1117 return T->getStmtClass() == CXXDefaultArgExprClass;
1118 }
1119
1120 // Iterators
1121 child_range children() {
1122 return child_range(child_iterator(), child_iterator());
1123 }
1124};
1125
1126/// A use of a default initializer in a constructor or in aggregate
1127/// initialization.
1128///
1129/// This wraps a use of a C++ default initializer (technically,
1130/// a brace-or-equal-initializer for a non-static data member) when it
1131/// is implicitly used in a mem-initializer-list in a constructor
1132/// (C++11 [class.base.init]p8) or in aggregate initialization
1133/// (C++1y [dcl.init.aggr]p7).
1134class CXXDefaultInitExpr : public Expr {
1135 /// The field whose default is being used.
1136 FieldDecl *Field;
1137
1138 /// The location where the default initializer expression was used.
1139 SourceLocation Loc;
1140
1141 CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc, FieldDecl *Field,
1142 QualType T);
1143
1144 CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1145
1146public:
1147 friend class ASTReader;
1148 friend class ASTStmtReader;
1149
1150 /// \p Field is the non-static data member whose default initializer is used
1151 /// by this expression.
1152 static CXXDefaultInitExpr *Create(const ASTContext &C, SourceLocation Loc,
1153 FieldDecl *Field) {
1154 return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
1155 }
1156
1157 /// Get the field whose initializer will be used.
1158 FieldDecl *getField() { return Field; }
1159 const FieldDecl *getField() const { return Field; }
1160
1161 /// Get the initialization expression that will be used.
1162 const Expr *getExpr() const {
1163 assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1164 return Field->getInClassInitializer();
1165 }
1166 Expr *getExpr() {
1167 assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
1168 return Field->getInClassInitializer();
1169 }
1170
1171 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1172 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1173
1174 static bool classof(const Stmt *T) {
1175 return T->getStmtClass() == CXXDefaultInitExprClass;
1176 }
1177
1178 // Iterators
1179 child_range children() {
1180 return child_range(child_iterator(), child_iterator());
1181 }
1182};
1183
1184/// Represents a C++ temporary.
1185class CXXTemporary {
1186 /// The destructor that needs to be called.
1187 const CXXDestructorDecl *Destructor;
1188
1189 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1190 : Destructor(destructor) {}
1191
1192public:
1193 static CXXTemporary *Create(const ASTContext &C,
1194 const CXXDestructorDecl *Destructor);
1195
1196 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1197
1198 void setDestructor(const CXXDestructorDecl *Dtor) {
1199 Destructor = Dtor;
1200 }
1201};
1202
1203/// Represents binding an expression to a temporary.
1204///
1205/// This ensures the destructor is called for the temporary. It should only be
1206/// needed for non-POD, non-trivially destructable class types. For example:
1207///
1208/// \code
1209/// struct S {
1210/// S() { } // User defined constructor makes S non-POD.
1211/// ~S() { } // User defined destructor makes it non-trivial.
1212/// };
1213/// void test() {
1214/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1215/// }
1216/// \endcode
1217class CXXBindTemporaryExpr : public Expr {
1218 CXXTemporary *Temp = nullptr;
1219 Stmt *SubExpr = nullptr;
1220
1221 CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1222 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1223 VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1224 SubExpr->isValueDependent(),
1225 SubExpr->isInstantiationDependent(),
1226 SubExpr->containsUnexpandedParameterPack()),
1227 Temp(temp), SubExpr(SubExpr) {}
1228
1229public:
1230 CXXBindTemporaryExpr(EmptyShell Empty)
1231 : Expr(CXXBindTemporaryExprClass, Empty) {}
1232
1233 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1234 Expr* SubExpr);
1235
1236 CXXTemporary *getTemporary() { return Temp; }
1237 const CXXTemporary *getTemporary() const { return Temp; }
1238 void setTemporary(CXXTemporary *T) { Temp = T; }
1239
1240 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1241 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1242 void setSubExpr(Expr *E) { SubExpr = E; }
1243
1244 SourceLocation getBeginLoc() const LLVM_READONLY {
1245 return SubExpr->getBeginLoc();
1246 }
1247
1248 SourceLocation getEndLoc() const LLVM_READONLY {
1249 return SubExpr->getEndLoc();
1250 }
1251
1252 // Implement isa/cast/dyncast/etc.
1253 static bool classof(const Stmt *T) {
1254 return T->getStmtClass() == CXXBindTemporaryExprClass;
1255 }
1256
1257 // Iterators
1258 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1259};
1260
1261/// Represents a call to a C++ constructor.
1262class CXXConstructExpr : public Expr {
1263public:
1264 enum ConstructionKind {
1265 CK_Complete,
1266 CK_NonVirtualBase,
1267 CK_VirtualBase,
1268 CK_Delegating
1269 };
1270
1271private:
1272 CXXConstructorDecl *Constructor = nullptr;
1273 SourceLocation Loc;
1274 SourceRange ParenOrBraceRange;
1275 unsigned NumArgs : 16;
1276 unsigned Elidable : 1;
1277 unsigned HadMultipleCandidates : 1;
1278 unsigned ListInitialization : 1;
1279 unsigned StdInitListInitialization : 1;
1280 unsigned ZeroInitialization : 1;
1281 unsigned ConstructKind : 2;
1282 Stmt **Args = nullptr;
1283
1284 void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
1285
1286protected:
1287 CXXConstructExpr(const ASTContext &C, StmtClass SC, QualType T,
1288 SourceLocation Loc,
1289 CXXConstructorDecl *Ctor,
1290 bool Elidable,
1291 ArrayRef<Expr *> Args,
1292 bool HadMultipleCandidates,
1293 bool ListInitialization,
1294 bool StdInitListInitialization,
1295 bool ZeroInitialization,
1296 ConstructionKind ConstructKind,
1297 SourceRange ParenOrBraceRange);
1298
1299 /// Construct an empty C++ construction expression.
1300 CXXConstructExpr(StmtClass SC, EmptyShell Empty)
1301 : Expr(SC, Empty), NumArgs(0), Elidable(false),
1302 HadMultipleCandidates(false), ListInitialization(false),
1303 ZeroInitialization(false), ConstructKind(0) {}
1304
1305public:
1306 friend class ASTStmtReader;
1307
1308 /// Construct an empty C++ construction expression.
1309 explicit CXXConstructExpr(EmptyShell Empty)
1310 : CXXConstructExpr(CXXConstructExprClass, Empty) {}
1311
1312 static CXXConstructExpr *Create(const ASTContext &C, QualType T,
1313 SourceLocation Loc,
1314 CXXConstructorDecl *Ctor,
1315 bool Elidable,
1316 ArrayRef<Expr *> Args,
1317 bool HadMultipleCandidates,
1318 bool ListInitialization,
1319 bool StdInitListInitialization,
1320 bool ZeroInitialization,
1321 ConstructionKind ConstructKind,
1322 SourceRange ParenOrBraceRange);
1323
1324 /// Get the constructor that this expression will (ultimately) call.
1325 CXXConstructorDecl *getConstructor() const { return Constructor; }
1326
1327 SourceLocation getLocation() const { return Loc; }
1328 void setLocation(SourceLocation Loc) { this->Loc = Loc; }
1329
1330 /// Whether this construction is elidable.
1331 bool isElidable() const { return Elidable; }
1332 void setElidable(bool E) { Elidable = E; }
1333
1334 /// Whether the referred constructor was resolved from
1335 /// an overloaded set having size greater than 1.
1336 bool hadMultipleCandidates() const { return HadMultipleCandidates; }
1337 void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
1338
1339 /// Whether this constructor call was written as list-initialization.
1340 bool isListInitialization() const { return ListInitialization; }
1341 void setListInitialization(bool V) { ListInitialization = V; }
1342
1343 /// Whether this constructor call was written as list-initialization,
1344 /// but was interpreted as forming a std::initializer_list<T> from the list
1345 /// and passing that as a single constructor argument.
1346 /// See C++11 [over.match.list]p1 bullet 1.
1347 bool isStdInitListInitialization() const { return StdInitListInitialization; }
1348 void setStdInitListInitialization(bool V) { StdInitListInitialization = V; }
1349
1350 /// Whether this construction first requires
1351 /// zero-initialization before the initializer is called.
1352 bool requiresZeroInitialization() const { return ZeroInitialization; }
1353 void setRequiresZeroInitialization(bool ZeroInit) {
1354 ZeroInitialization = ZeroInit;
1355 }
1356
1357 /// Determine whether this constructor is actually constructing
1358 /// a base class (rather than a complete object).
1359 ConstructionKind getConstructionKind() const {
1360 return (ConstructionKind)ConstructKind;
1361 }
1362 void setConstructionKind(ConstructionKind CK) {
1363 ConstructKind = CK;
1364 }
1365
1366 using arg_iterator = ExprIterator;
1367 using const_arg_iterator = ConstExprIterator;
1368 using arg_range = llvm::iterator_range<arg_iterator>;
1369 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1370
1371 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1372 const_arg_range arguments() const {
1373 return const_arg_range(arg_begin(), arg_end());
1374 }
1375
1376 arg_iterator arg_begin() { return Args; }
1377 arg_iterator arg_end() { return Args + NumArgs; }
1378 const_arg_iterator arg_begin() const { return Args; }
1379 const_arg_iterator arg_end() const { return Args + NumArgs; }
1380
1381 Expr **getArgs() { return reinterpret_cast<Expr **>(Args); }
1382 const Expr *const *getArgs() const {
1383 return const_cast<CXXConstructExpr *>(this)->getArgs();
1384 }
1385 unsigned getNumArgs() const { return NumArgs; }
1386
1387 /// Return the specified argument.
1388 Expr *getArg(unsigned Arg) {
1389 assert(Arg < NumArgs && "Arg access out of range!");
1390 return cast<Expr>(Args[Arg]);
1391 }
1392 const Expr *getArg(unsigned Arg) const {
1393 assert(Arg < NumArgs && "Arg access out of range!");
1394 return cast<Expr>(Args[Arg]);
1395 }
1396
1397 /// Set the specified argument.
1398 void setArg(unsigned Arg, Expr *ArgExpr) {
1399 assert(Arg < NumArgs && "Arg access out of range!");
1400 Args[Arg] = ArgExpr;
1401 }
1402
1403 SourceLocation getBeginLoc() const LLVM_READONLY;
1404 SourceLocation getEndLoc() const LLVM_READONLY;
1405 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1406 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1407
1408 static bool classof(const Stmt *T) {
1409 return T->getStmtClass() == CXXConstructExprClass ||
1410 T->getStmtClass() == CXXTemporaryObjectExprClass;
1411 }
1412
1413 // Iterators
1414 child_range children() {
1415 return child_range(&Args[0], &Args[0]+NumArgs);
1416 }
1417};
1418
1419/// Represents a call to an inherited base class constructor from an
1420/// inheriting constructor. This call implicitly forwards the arguments from
1421/// the enclosing context (an inheriting constructor) to the specified inherited
1422/// base class constructor.
1423class CXXInheritedCtorInitExpr : public Expr {
1424private:
1425 CXXConstructorDecl *Constructor = nullptr;
1426
1427 /// The location of the using declaration.
1428 SourceLocation Loc;
1429
1430 /// Whether this is the construction of a virtual base.
1431 unsigned ConstructsVirtualBase : 1;
1432
1433 /// Whether the constructor is inherited from a virtual base class of the
1434 /// class that we construct.
1435 unsigned InheritedFromVirtualBase : 1;
1436
1437public:
1438 friend class ASTStmtReader;
1439
1440 /// Construct a C++ inheriting construction expression.
1441 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1442 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1443 bool InheritedFromVirtualBase)
1444 : Expr(CXXInheritedCtorInitExprClass, T, VK_RValue, OK_Ordinary, false,
1445 false, false, false),
1446 Constructor(Ctor), Loc(Loc),
1447 ConstructsVirtualBase(ConstructsVirtualBase),
1448 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1449 assert(!T->isDependentType());
1450 }
1451
1452 /// Construct an empty C++ inheriting construction expression.
1453 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1454 : Expr(CXXInheritedCtorInitExprClass, Empty),
1455 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1456
1457 /// Get the constructor that this expression will call.
1458 CXXConstructorDecl *getConstructor() const { return Constructor; }
1459
1460 /// Determine whether this constructor is actually constructing
1461 /// a base class (rather than a complete object).
1462 bool constructsVBase() const { return ConstructsVirtualBase; }
1463 CXXConstructExpr::ConstructionKind getConstructionKind() const {
1464 return ConstructsVirtualBase ? CXXConstructExpr::CK_VirtualBase
1465 : CXXConstructExpr::CK_NonVirtualBase;
1466 }
1467
1468 /// Determine whether the inherited constructor is inherited from a
1469 /// virtual base of the object we construct. If so, we are not responsible
1470 /// for calling the inherited constructor (the complete object constructor
1471 /// does that), and so we don't need to pass any arguments.
1472 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1473
1474 SourceLocation getLocation() const LLVM_READONLY { return Loc; }
1475 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1476 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1477
1478 static bool classof(const Stmt *T) {
1479 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1480 }
1481
1482 child_range children() {
1483 return child_range(child_iterator(), child_iterator());
1484 }
1485};
1486
1487/// Represents an explicit C++ type conversion that uses "functional"
1488/// notation (C++ [expr.type.conv]).
1489///
1490/// Example:
1491/// \code
1492/// x = int(0.5);
1493/// \endcode
1494class CXXFunctionalCastExpr final
1495 : public ExplicitCastExpr,
1496 private llvm::TrailingObjects<
1497 CXXFunctionalCastExpr, CastExpr::BasePathSizeTy, CXXBaseSpecifier *> {
1498 SourceLocation LParenLoc;
1499 SourceLocation RParenLoc;
1500
1501 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1502 TypeSourceInfo *writtenTy,
1503 CastKind kind, Expr *castExpr, unsigned pathSize,
1504 SourceLocation lParenLoc, SourceLocation rParenLoc)
1505 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1506 castExpr, pathSize, writtenTy),
1507 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
1508
1509 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1510 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) {}
1511
1512 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
1513 return path_empty() ? 0 : 1;
1514 }
1515
1516public:
1517 friend class CastExpr;
1518 friend TrailingObjects;
1519
1520 static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
1521 ExprValueKind VK,
1522 TypeSourceInfo *Written,
1523 CastKind Kind, Expr *Op,
1524 const CXXCastPath *Path,
1525 SourceLocation LPLoc,
1526 SourceLocation RPLoc);
1527 static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
1528 unsigned PathSize);
1529
1530 SourceLocation getLParenLoc() const { return LParenLoc; }
1531 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1532 SourceLocation getRParenLoc() const { return RParenLoc; }
1533 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1534
1535 /// Determine whether this expression models list-initialization.
1536 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1537
1538 SourceLocation getBeginLoc() const LLVM_READONLY;
1539 SourceLocation getEndLoc() const LLVM_READONLY;
1540
1541 static bool classof(const Stmt *T) {
1542 return T->getStmtClass() == CXXFunctionalCastExprClass;
1543 }
1544};
1545
1546/// Represents a C++ functional cast expression that builds a
1547/// temporary object.
1548///
1549/// This expression type represents a C++ "functional" cast
1550/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1551/// constructor to build a temporary object. With N == 1 arguments the
1552/// functional cast expression will be represented by CXXFunctionalCastExpr.
1553/// Example:
1554/// \code
1555/// struct X { X(int, float); }
1556///
1557/// X create_X() {
1558/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1559/// };
1560/// \endcode
1561class CXXTemporaryObjectExpr : public CXXConstructExpr {
1562 TypeSourceInfo *Type = nullptr;
1563
1564public:
1565 friend class ASTStmtReader;
1566
1567 CXXTemporaryObjectExpr(const ASTContext &C,
1568 CXXConstructorDecl *Cons,
1569 QualType Type,
1570 TypeSourceInfo *TSI,
1571 ArrayRef<Expr *> Args,
1572 SourceRange ParenOrBraceRange,
1573 bool HadMultipleCandidates,
1574 bool ListInitialization,
1575 bool StdInitListInitialization,
1576 bool ZeroInitialization);
1577 explicit CXXTemporaryObjectExpr(EmptyShell Empty)
1578 : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty) {}
1579
1580 TypeSourceInfo *getTypeSourceInfo() const { return Type; }
1581
1582 SourceLocation getBeginLoc() const LLVM_READONLY;
1583 SourceLocation getEndLoc() const LLVM_READONLY;
1584
1585 static bool classof(const Stmt *T) {
1586 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1587 }
1588};
1589
1590/// A C++ lambda expression, which produces a function object
1591/// (of unspecified type) that can be invoked later.
1592///
1593/// Example:
1594/// \code
1595/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1596/// values.erase(std::remove_if(values.begin(), values.end(),
1597/// [=](double value) { return value > cutoff; });
1598/// }
1599/// \endcode
1600///
1601/// C++11 lambda expressions can capture local variables, either by copying
1602/// the values of those local variables at the time the function
1603/// object is constructed (not when it is called!) or by holding a
1604/// reference to the local variable. These captures can occur either
1605/// implicitly or can be written explicitly between the square
1606/// brackets ([...]) that start the lambda expression.
1607///
1608/// C++1y introduces a new form of "capture" called an init-capture that
1609/// includes an initializing expression (rather than capturing a variable),
1610/// and which can never occur implicitly.
1611class LambdaExpr final : public Expr,
1612 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1613 /// The source range that covers the lambda introducer ([...]).
1614 SourceRange IntroducerRange;
1615
1616 /// The source location of this lambda's capture-default ('=' or '&').
1617 SourceLocation CaptureDefaultLoc;
1618
1619 /// The number of captures.
1620 unsigned NumCaptures : 16;
1621
1622 /// The default capture kind, which is a value of type
1623 /// LambdaCaptureDefault.
1624 unsigned CaptureDefault : 2;
1625
1626 /// Whether this lambda had an explicit parameter list vs. an
1627 /// implicit (and empty) parameter list.
1628 unsigned ExplicitParams : 1;
1629
1630 /// Whether this lambda had the result type explicitly specified.
1631 unsigned ExplicitResultType : 1;
1632
1633 /// The location of the closing brace ('}') that completes
1634 /// the lambda.
1635 ///
1636 /// The location of the brace is also available by looking up the
1637 /// function call operator in the lambda class. However, it is
1638 /// stored here to improve the performance of getSourceRange(), and
1639 /// to avoid having to deserialize the function call operator from a
1640 /// module file just to determine the source range.
1641 SourceLocation ClosingBrace;
1642
1643 /// Construct a lambda expression.
1644 LambdaExpr(QualType T, SourceRange IntroducerRange,
1645 LambdaCaptureDefault CaptureDefault,
1646 SourceLocation CaptureDefaultLoc, ArrayRef<LambdaCapture> Captures,
1647 bool ExplicitParams, bool ExplicitResultType,
1648 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
1649 bool ContainsUnexpandedParameterPack);
1650
1651 /// Construct an empty lambda expression.
1652 LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1653 : Expr(LambdaExprClass, Empty), NumCaptures(NumCaptures),
1654 CaptureDefault(LCD_None), ExplicitParams(false),
1655 ExplicitResultType(false) {
1656 getStoredStmts()[NumCaptures] = nullptr;
1657 }
1658
1659 Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1660
1661 Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1662
1663public:
1664 friend class ASTStmtReader;
1665 friend class ASTStmtWriter;
1666 friend TrailingObjects;
1667
1668 /// Construct a new lambda expression.
1669 static LambdaExpr *
1670 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1671 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1672 ArrayRef<LambdaCapture> Captures, bool ExplicitParams,
1673 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1674 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1675
1676 /// Construct a new lambda expression that will be deserialized from
1677 /// an external source.
1678 static LambdaExpr *CreateDeserialized(const ASTContext &C,
1679 unsigned NumCaptures);
1680
1681 /// Determine the default capture kind for this lambda.
1682 LambdaCaptureDefault getCaptureDefault() const {
1683 return static_cast<LambdaCaptureDefault>(CaptureDefault);
1684 }
1685
1686 /// Retrieve the location of this lambda's capture-default, if any.
1687 SourceLocation getCaptureDefaultLoc() const {
1688 return CaptureDefaultLoc;
1689 }
1690
1691 /// Determine whether one of this lambda's captures is an init-capture.
1692 bool isInitCapture(const LambdaCapture *Capture) const;
1693
1694 /// An iterator that walks over the captures of the lambda,
1695 /// both implicit and explicit.
1696 using capture_iterator = const LambdaCapture *;
1697
1698 /// An iterator over a range of lambda captures.
1699 using capture_range = llvm::iterator_range<capture_iterator>;
1700
1701 /// Retrieve this lambda's captures.
1702 capture_range captures() const;
1703
1704 /// Retrieve an iterator pointing to the first lambda capture.
1705 capture_iterator capture_begin() const;
1706
1707 /// Retrieve an iterator pointing past the end of the
1708 /// sequence of lambda captures.
1709 capture_iterator capture_end() const;
1710
1711 /// Determine the number of captures in this lambda.
1712 unsigned capture_size() const { return NumCaptures; }
1713
1714 /// Retrieve this lambda's explicit captures.
1715 capture_range explicit_captures() const;
1716
1717 /// Retrieve an iterator pointing to the first explicit
1718 /// lambda capture.
1719 capture_iterator explicit_capture_begin() const;
1720
1721 /// Retrieve an iterator pointing past the end of the sequence of
1722 /// explicit lambda captures.
1723 capture_iterator explicit_capture_end() const;
1724
1725 /// Retrieve this lambda's implicit captures.
1726 capture_range implicit_captures() const;
1727
1728 /// Retrieve an iterator pointing to the first implicit
1729 /// lambda capture.
1730 capture_iterator implicit_capture_begin() const;
1731
1732 /// Retrieve an iterator pointing past the end of the sequence of
1733 /// implicit lambda captures.
1734 capture_iterator implicit_capture_end() const;
1735
1736 /// Iterator that walks over the capture initialization
1737 /// arguments.
1738 using capture_init_iterator = Expr **;
1739
1740 /// Const iterator that walks over the capture initialization
1741 /// arguments.
1742 using const_capture_init_iterator = Expr *const *;
1743
1744 /// Retrieve the initialization expressions for this lambda's captures.
1745 llvm::iterator_range<capture_init_iterator> capture_inits() {
1746 return llvm::make_range(capture_init_begin(), capture_init_end());
1747 }
1748
1749 /// Retrieve the initialization expressions for this lambda's captures.
1750 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1751 return llvm::make_range(capture_init_begin(), capture_init_end());
1752 }
1753
1754 /// Retrieve the first initialization argument for this
1755 /// lambda expression (which initializes the first capture field).
1756 capture_init_iterator capture_init_begin() {
1757 return reinterpret_cast<Expr **>(getStoredStmts());
1758 }
1759
1760 /// Retrieve the first initialization argument for this
1761 /// lambda expression (which initializes the first capture field).
1762 const_capture_init_iterator capture_init_begin() const {
1763 return reinterpret_cast<Expr *const *>(getStoredStmts());
1764 }
1765
1766 /// Retrieve the iterator pointing one past the last
1767 /// initialization argument for this lambda expression.
1768 capture_init_iterator capture_init_end() {
1769 return capture_init_begin() + NumCaptures;
1770 }
1771
1772 /// Retrieve the iterator pointing one past the last
1773 /// initialization argument for this lambda expression.
1774 const_capture_init_iterator capture_init_end() const {
1775 return capture_init_begin() + NumCaptures;
1776 }
1777
1778 /// Retrieve the source range covering the lambda introducer,
1779 /// which contains the explicit capture list surrounded by square
1780 /// brackets ([...]).
1781 SourceRange getIntroducerRange() const { return IntroducerRange; }
1782
1783 /// Retrieve the class that corresponds to the lambda.
1784 ///
1785 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
1786 /// captures in its fields and provides the various operations permitted
1787 /// on a lambda (copying, calling).
1788 CXXRecordDecl *getLambdaClass() const;
1789
1790 /// Retrieve the function call operator associated with this
1791 /// lambda expression.
1792 CXXMethodDecl *getCallOperator() const;
1793
1794 /// If this is a generic lambda expression, retrieve the template
1795 /// parameter list associated with it, or else return null.
1796 TemplateParameterList *getTemplateParameterList() const;
1797
1798 /// Whether this is a generic lambda.
1799 bool isGenericLambda() const { return getTemplateParameterList(); }
1800
1801 /// Retrieve the body of the lambda.
1802 CompoundStmt *getBody() const;
1803
1804 /// Determine whether the lambda is mutable, meaning that any
1805 /// captures values can be modified.
1806 bool isMutable() const;
1807
1808 /// Determine whether this lambda has an explicit parameter
1809 /// list vs. an implicit (empty) parameter list.
1810 bool hasExplicitParameters() const { return ExplicitParams; }
1811
1812 /// Whether this lambda had its result type explicitly specified.
1813 bool hasExplicitResultType() const { return ExplicitResultType; }
1814
1815 static bool classof(const Stmt *T) {
1816 return T->getStmtClass() == LambdaExprClass;
1817 }
1818
1819 SourceLocation getBeginLoc() const LLVM_READONLY {
1820 return IntroducerRange.getBegin();
1821 }
1822
1823 SourceLocation getEndLoc() const LLVM_READONLY { return ClosingBrace; }
1824
1825 child_range children() {
1826 // Includes initialization exprs plus body stmt
1827 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
1828 }
1829};
1830
1831/// An expression "T()" which creates a value-initialized rvalue of type
1832/// T, which is a non-class type. See (C++98 [5.2.3p2]).
1833class CXXScalarValueInitExpr : public Expr {
1834 friend class ASTStmtReader;
1835
1836 SourceLocation RParenLoc;
1837 TypeSourceInfo *TypeInfo;
1838
1839public:
1840 /// Create an explicitly-written scalar-value initialization
1841 /// expression.
1842 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
1843 SourceLocation rParenLoc)
1844 : Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
1845 false, false, Type->isInstantiationDependentType(),
1846 Type->containsUnexpandedParameterPack()),
1847 RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
1848
1849 explicit CXXScalarValueInitExpr(EmptyShell Shell)
1850 : Expr(CXXScalarValueInitExprClass, Shell) {}
1851
1852 TypeSourceInfo *getTypeSourceInfo() const {
1853 return TypeInfo;
1854 }
1855
1856 SourceLocation getRParenLoc() const { return RParenLoc; }
1857
1858 SourceLocation getBeginLoc() const LLVM_READONLY;
1859 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
1860
1861 static bool classof(const Stmt *T) {
1862 return T->getStmtClass() == CXXScalarValueInitExprClass;
1863 }
1864
1865 // Iterators
1866 child_range children() {
1867 return child_range(child_iterator(), child_iterator());
1868 }
1869};
1870
1871/// Represents a new-expression for memory allocation and constructor
1872/// calls, e.g: "new CXXNewExpr(foo)".
1873class CXXNewExpr : public Expr {
1874 friend class ASTStmtReader;
1875 friend class ASTStmtWriter;
1876
1877 /// Contains an optional array size expression, an optional initialization
1878 /// expression, and any number of optional placement arguments, in that order.
1879 Stmt **SubExprs = nullptr;
1880
1881 /// Points to the allocation function used.
1882 FunctionDecl *OperatorNew;
1883
1884 /// Points to the deallocation function used in case of error. May be
1885 /// null.
1886 FunctionDecl *OperatorDelete;
1887
1888 /// The allocated type-source information, as written in the source.
1889 TypeSourceInfo *AllocatedTypeInfo;
1890
1891 /// If the allocated type was expressed as a parenthesized type-id,
1892 /// the source range covering the parenthesized type-id.
1893 SourceRange TypeIdParens;
1894
1895 /// Range of the entire new expression.
1896 SourceRange Range;
1897
1898 /// Source-range of a paren-delimited initializer.
1899 SourceRange DirectInitRange;
1900
1901 /// Was the usage ::new, i.e. is the global new to be used?
1902 unsigned GlobalNew : 1;
1903
1904 /// Do we allocate an array? If so, the first SubExpr is the size expression.
1905 unsigned Array : 1;
1906
1907 /// Should the alignment be passed to the allocation function?
1908 unsigned PassAlignment : 1;
1909
1910 /// If this is an array allocation, does the usual deallocation
1911 /// function for the allocated type want to know the allocated size?
1912 unsigned UsualArrayDeleteWantsSize : 1;
1913
1914 /// The number of placement new arguments.
1915 unsigned NumPlacementArgs : 26;
1916
1917 /// What kind of initializer do we have? Could be none, parens, or braces.
1918 /// In storage, we distinguish between "none, and no initializer expr", and
1919 /// "none, but an implicit initializer expr".
1920 unsigned StoredInitializationStyle : 2;
1921
1922public:
1923 enum InitializationStyle {
1924 /// New-expression has no initializer as written.
1925 NoInit,
1926
1927 /// New-expression has a C++98 paren-delimited initializer.
1928 CallInit,
1929
1930 /// New-expression has a C++11 list-initializer.
1931 ListInit
1932 };
1933
1934 CXXNewExpr(const ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
1935 FunctionDecl *operatorDelete, bool PassAlignment,
1936 bool usualArrayDeleteWantsSize, ArrayRef<Expr*> placementArgs,
1937 SourceRange typeIdParens, Expr *arraySize,
1938 InitializationStyle initializationStyle, Expr *initializer,
1939 QualType ty, TypeSourceInfo *AllocatedTypeInfo,
1940 SourceRange Range, SourceRange directInitRange);
1941 explicit CXXNewExpr(EmptyShell Shell)
1942 : Expr(CXXNewExprClass, Shell) {}
1943
1944 void AllocateArgsArray(const ASTContext &C, bool isArray,
1945 unsigned numPlaceArgs, bool hasInitializer);
1946
1947 QualType getAllocatedType() const {
1948 assert(getType()->isPointerType());
1949 return getType()->getAs<PointerType>()->getPointeeType();
1950 }
1951
1952 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
1953 return AllocatedTypeInfo;
1954 }
1955
1956 /// True if the allocation result needs to be null-checked.
1957 ///
1958 /// C++11 [expr.new]p13:
1959 /// If the allocation function returns null, initialization shall
1960 /// not be done, the deallocation function shall not be called,
1961 /// and the value of the new-expression shall be null.
1962 ///
1963 /// C++ DR1748:
1964 /// If the allocation function is a reserved placement allocation
1965 /// function that returns null, the behavior is undefined.
1966 ///
1967 /// An allocation function is not allowed to return null unless it
1968 /// has a non-throwing exception-specification. The '03 rule is
1969 /// identical except that the definition of a non-throwing
1970 /// exception specification is just "is it throw()?".
1971 bool shouldNullCheckAllocation(const ASTContext &Ctx) const;
1972
1973 FunctionDecl *getOperatorNew() const { return OperatorNew; }
1974 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
1975 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1976 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
1977
1978 bool isArray() const { return Array; }
1979
1980 Expr *getArraySize() {
1981 return Array ? cast<Expr>(SubExprs[0]) : nullptr;
1982 }
1983 const Expr *getArraySize() const {
1984 return Array ? cast<Expr>(SubExprs[0]) : nullptr;
1985 }
1986
1987 unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
1988
1989 Expr **getPlacementArgs() {
1990 return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
1991 }
1992
1993 Expr *getPlacementArg(unsigned i) {
1994 assert(i < NumPlacementArgs && "Index out of range");
1995 return getPlacementArgs()[i];
1996 }
1997 const Expr *getPlacementArg(unsigned i) const {
1998 assert(i < NumPlacementArgs && "Index out of range");
1999 return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
2000 }
2001
2002 bool isParenTypeId() const { return TypeIdParens.isValid(); }
2003 SourceRange getTypeIdParens() const { return TypeIdParens; }
2004
2005 bool isGlobalNew() const { return GlobalNew; }
2006
2007 /// Whether this new-expression has any initializer at all.
2008 bool hasInitializer() const { return StoredInitializationStyle > 0; }
2009
2010 /// The kind of initializer this new-expression has.
2011 InitializationStyle getInitializationStyle() const {
2012 if (StoredInitializationStyle == 0)
2013 return NoInit;
2014 return static_cast<InitializationStyle>(StoredInitializationStyle-1);
2015 }
2016
2017 /// The initializer of this new-expression.
2018 Expr *getInitializer() {
2019 return hasInitializer() ? cast<Expr>(SubExprs[Array]) : nullptr;
2020 }
2021 const Expr *getInitializer() const {
2022 return hasInitializer() ? cast<Expr>(SubExprs[Array]) : nullptr;
2023 }
2024
2025 /// Returns the CXXConstructExpr from this new-expression, or null.
2026 const CXXConstructExpr *getConstructExpr() const {
2027 return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
2028 }
2029
2030 /// Indicates whether the required alignment should be implicitly passed to
2031 /// the allocation function.
2032 bool passAlignment() const {
2033 return PassAlignment;
2034 }
2035
2036 /// Answers whether the usual array deallocation function for the
2037 /// allocated type expects the size of the allocation as a
2038 /// parameter.
2039 bool doesUsualArrayDeleteWantSize() const {
2040 return UsualArrayDeleteWantsSize;
2041 }
2042
2043 using arg_iterator = ExprIterator;
2044 using const_arg_iterator = ConstExprIterator;
2045
2046 llvm::iterator_range<arg_iterator> placement_arguments() {
2047 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2048 }
2049
2050 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2051 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2052 }
2053
2054 arg_iterator placement_arg_begin() {
2055 return SubExprs + Array + hasInitializer();
2056 }
2057 arg_iterator placement_arg_end() {
2058 return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
2059 }
2060 const_arg_iterator placement_arg_begin() const {
2061 return SubExprs + Array + hasInitializer();
2062 }
2063 const_arg_iterator placement_arg_end() const {
2064 return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
2065 }
2066
2067 using raw_arg_iterator = Stmt **;
2068
2069 raw_arg_iterator raw_arg_begin() { return SubExprs; }
2070 raw_arg_iterator raw_arg_end() {
2071 return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
2072 }
2073 const_arg_iterator raw_arg_begin() const { return SubExprs; }
2074 const_arg_iterator raw_arg_end() const {
2075 return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
2076 }
2077
2078 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2079 SourceLocation getEndLoc() const { return Range.getEnd(); }
2080
2081 SourceRange getDirectInitRange() const { return DirectInitRange; }
2082
2083 SourceRange getSourceRange() const LLVM_READONLY {
2084 return Range;
2085 }
2086
2087
2088 static bool classof(const Stmt *T) {
2089 return T->getStmtClass() == CXXNewExprClass;
2090 }
2091
2092 // Iterators
2093 child_range children() {
2094 return child_range(raw_arg_begin(), raw_arg_end());
2095 }
2096};
2097
2098/// Represents a \c delete expression for memory deallocation and
2099/// destructor calls, e.g. "delete[] pArray".
2100class CXXDeleteExpr : public Expr {
2101 /// Points to the operator delete overload that is used. Could be a member.
2102 FunctionDecl *OperatorDelete = nullptr;
2103
2104 /// The pointer expression to be deleted.
2105 Stmt *Argument = nullptr;
2106
2107 /// Location of the expression.
2108 SourceLocation Loc;
2109
2110 /// Is this a forced global delete, i.e. "::delete"?
2111 bool GlobalDelete : 1;
2112
2113 /// Is this the array form of delete, i.e. "delete[]"?
2114 bool ArrayForm : 1;
2115
2116 /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
2117 /// to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
2118 /// will be true).
2119 bool ArrayFormAsWritten : 1;
2120
2121 /// Does the usual deallocation function for the element type require
2122 /// a size_t argument?
2123 bool UsualArrayDeleteWantsSize : 1;
2124
2125public:
2126 friend class ASTStmtReader;
2127
2128 CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
2129 bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
2130 FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
2131 : Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
2132 arg->isInstantiationDependent(),
2133 arg->containsUnexpandedParameterPack()),
2134 OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
2135 GlobalDelete(globalDelete),
2136 ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
2137 UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) {}
2138 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2139
2140 bool isGlobalDelete() const { return GlobalDelete; }
2141 bool isArrayForm() const { return ArrayForm; }
2142 bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
2143
2144 /// Answers whether the usual array deallocation function for the
2145 /// allocated type expects the size of the allocation as a
2146 /// parameter. This can be true even if the actual deallocation
2147 /// function that we're using doesn't want a size.
2148 bool doesUsualArrayDeleteWantSize() const {
2149 return UsualArrayDeleteWantsSize;
2150 }
2151
2152 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2153
2154 Expr *getArgument() { return cast<Expr>(Argument); }
2155 const Expr *getArgument() const { return cast<Expr>(Argument); }
2156
2157 /// Retrieve the type being destroyed.
2158 ///
2159 /// If the type being destroyed is a dependent type which may or may not
2160 /// be a pointer, return an invalid type.
2161 QualType getDestroyedType() const;
2162
2163 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2164 SourceLocation getEndLoc() const LLVM_READONLY {
2165 return Argument->getEndLoc();
2166 }
2167
2168 static bool classof(const Stmt *T) {
2169 return T->getStmtClass() == CXXDeleteExprClass;
2170 }
2171
2172 // Iterators
2173 child_range children() { return child_range(&Argument, &Argument+1); }
2174};
2175
2176/// Stores the type being destroyed by a pseudo-destructor expression.
2177class PseudoDestructorTypeStorage {
2178 /// Either the type source information or the name of the type, if
2179 /// it couldn't be resolved due to type-dependence.
2180 llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2181
2182 /// The starting source location of the pseudo-destructor type.
2183 SourceLocation Location;
2184
2185public:
2186 PseudoDestructorTypeStorage() = default;
2187
2188 PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2189 : Type(II), Location(Loc) {}
2190
2191 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2192
2193 TypeSourceInfo *getTypeSourceInfo() const {
2194 return Type.dyn_cast<TypeSourceInfo *>();
2195 }
2196
2197 IdentifierInfo *getIdentifier() const {
2198 return Type.dyn_cast<IdentifierInfo *>();
2199 }
2200
2201 SourceLocation getLocation() const { return Location; }
2202};
2203
2204/// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2205///
2206/// A pseudo-destructor is an expression that looks like a member access to a
2207/// destructor of a scalar type, except that scalar types don't have
2208/// destructors. For example:
2209///
2210/// \code
2211/// typedef int T;
2212/// void f(int *p) {
2213/// p->T::~T();
2214/// }
2215/// \endcode
2216///
2217/// Pseudo-destructors typically occur when instantiating templates such as:
2218///
2219/// \code
2220/// template<typename T>
2221/// void destroy(T* ptr) {
2222/// ptr->T::~T();
2223/// }
2224/// \endcode
2225///
2226/// for scalar types. A pseudo-destructor expression has no run-time semantics
2227/// beyond evaluating the base expression.
2228class CXXPseudoDestructorExpr : public Expr {
2229 friend class ASTStmtReader;
2230
2231 /// The base expression (that is being destroyed).
2232 Stmt *Base = nullptr;
2233
2234 /// Whether the operator was an arrow ('->'); otherwise, it was a
2235 /// period ('.').
2236 bool IsArrow : 1;
2237
2238 /// The location of the '.' or '->' operator.
2239 SourceLocation OperatorLoc;
2240
2241 /// The nested-name-specifier that follows the operator, if present.
2242 NestedNameSpecifierLoc QualifierLoc;
2243
2244 /// The type that precedes the '::' in a qualified pseudo-destructor
2245 /// expression.
2246 TypeSourceInfo *ScopeType = nullptr;
2247
2248 /// The location of the '::' in a qualified pseudo-destructor
2249 /// expression.
2250 SourceLocation ColonColonLoc;
2251
2252 /// The location of the '~'.
2253 SourceLocation TildeLoc;
2254
2255 /// The type being destroyed, or its name if we were unable to
2256 /// resolve the name.
2257 PseudoDestructorTypeStorage DestroyedType;
2258
2259public:
2260 CXXPseudoDestructorExpr(const ASTContext &Context,
2261 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2262 NestedNameSpecifierLoc QualifierLoc,
2263 TypeSourceInfo *ScopeType,
2264 SourceLocation ColonColonLoc,
2265 SourceLocation TildeLoc,
2266 PseudoDestructorTypeStorage DestroyedType);
2267
2268 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2269 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2270
2271 Expr *getBase() const { return cast<Expr>(Base); }
2272
2273 /// Determines whether this member expression actually had
2274 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2275 /// x->Base::foo.
2276 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2277
2278 /// Retrieves the nested-name-specifier that qualifies the type name,
2279 /// with source-location information.
2280 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2281
2282 /// If the member name was qualified, retrieves the
2283 /// nested-name-specifier that precedes the member name. Otherwise, returns
2284 /// null.
2285 NestedNameSpecifier *getQualifier() const {
2286 return QualifierLoc.getNestedNameSpecifier();
2287 }
2288
2289 /// Determine whether this pseudo-destructor expression was written
2290 /// using an '->' (otherwise, it used a '.').
2291 bool isArrow() const { return IsArrow; }
2292
2293 /// Retrieve the location of the '.' or '->' operator.
2294 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2295
2296 /// Retrieve the scope type in a qualified pseudo-destructor
2297 /// expression.
2298 ///
2299 /// Pseudo-destructor expressions can have extra qualification within them
2300 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2301 /// Here, if the object type of the expression is (or may be) a scalar type,
2302 /// \p T may also be a scalar type and, therefore, cannot be part of a
2303 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2304 /// destructor expression.
2305 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2306
2307 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2308 /// expression.
2309 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2310
2311 /// Retrieve the location of the '~'.
2312 SourceLocation getTildeLoc() const { return TildeLoc; }
2313
2314 /// Retrieve the source location information for the type
2315 /// being destroyed.
2316 ///
2317 /// This type-source information is available for non-dependent
2318 /// pseudo-destructor expressions and some dependent pseudo-destructor
2319 /// expressions. Returns null if we only have the identifier for a
2320 /// dependent pseudo-destructor expression.
2321 TypeSourceInfo *getDestroyedTypeInfo() const {
2322 return DestroyedType.getTypeSourceInfo();
2323 }
2324
2325 /// In a dependent pseudo-destructor expression for which we do not
2326 /// have full type information on the destroyed type, provides the name
2327 /// of the destroyed type.
2328 IdentifierInfo *getDestroyedTypeIdentifier() const {
2329 return DestroyedType.getIdentifier();
2330 }
2331
2332 /// Retrieve the type being destroyed.
2333 QualType getDestroyedType() const;
2334
2335 /// Retrieve the starting location of the type being destroyed.
2336 SourceLocation getDestroyedTypeLoc() const {
2337 return DestroyedType.getLocation();
2338 }
2339
2340 /// Set the name of destroyed type for a dependent pseudo-destructor
2341 /// expression.
2342 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2343 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2344 }
2345
2346 /// Set the destroyed type.
2347 void setDestroyedType(TypeSourceInfo *Info) {
2348 DestroyedType = PseudoDestructorTypeStorage(Info);
2349 }
2350
2351 SourceLocation getBeginLoc() const LLVM_READONLY {
2352 return Base->getBeginLoc();
2353 }
2354 SourceLocation getEndLoc() const LLVM_READONLY;
2355
2356 static bool classof(const Stmt *T) {
2357 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2358 }
2359
2360 // Iterators
2361 child_range children() { return child_range(&Base, &Base + 1); }
2362};
2363
2364/// A type trait used in the implementation of various C++11 and
2365/// Library TR1 trait templates.
2366///
2367/// \code
2368/// __is_pod(int) == true
2369/// __is_enum(std::string) == false
2370/// __is_trivially_constructible(vector<int>, int*, int*)
2371/// \endcode
2372class TypeTraitExpr final
2373 : public Expr,
2374 private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2375 /// The location of the type trait keyword.
2376 SourceLocation Loc;
2377
2378 /// The location of the closing parenthesis.
2379 SourceLocation RParenLoc;
2380
2381 // Note: The TypeSourceInfos for the arguments are allocated after the
2382 // TypeTraitExpr.
2383
2384 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2385 ArrayRef<TypeSourceInfo *> Args,
2386 SourceLocation RParenLoc,
2387 bool Value);
2388
2389 TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) {}
2390
2391 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2392 return getNumArgs();
2393 }
2394
2395public:
2396 friend class ASTStmtReader;
2397 friend class ASTStmtWriter;
2398 friend TrailingObjects;
2399
2400 /// Create a new type trait expression.
2401 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2402 SourceLocation Loc, TypeTrait Kind,
2403 ArrayRef<TypeSourceInfo *> Args,
2404 SourceLocation RParenLoc,
2405 bool Value);
2406
2407 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2408 unsigned NumArgs);
2409
2410 /// Determine which type trait this expression uses.
2411 TypeTrait getTrait() const {
2412 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2413 }
2414
2415 bool getValue() const {
2416 assert(!isValueDependent());
2417 return TypeTraitExprBits.Value;
2418 }
2419
2420 /// Determine the number of arguments to this type trait.
2421 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2422
2423 /// Retrieve the Ith argument.
2424 TypeSourceInfo *getArg(unsigned I) const {
2425 assert(I < getNumArgs() && "Argument out-of-range");
2426 return getArgs()[I];
2427 }
2428
2429 /// Retrieve the argument types.
2430 ArrayRef<TypeSourceInfo *> getArgs() const {
2431 return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2432 getNumArgs());
2433 }
2434
2435 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2436 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2437
2438 static bool classof(const Stmt *T) {
2439 return T->getStmtClass() == TypeTraitExprClass;
2440 }
2441
2442 // Iterators
2443 child_range children() {
2444 return child_range(child_iterator(), child_iterator());
2445 }
2446};
2447
2448/// An Embarcadero array type trait, as used in the implementation of
2449/// __array_rank and __array_extent.
2450///
2451/// Example:
2452/// \code
2453/// __array_rank(int[10][20]) == 2
2454/// __array_extent(int, 1) == 20
2455/// \endcode
2456class ArrayTypeTraitExpr : public Expr {
2457 /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2458 unsigned ATT : 2;
2459
2460 /// The value of the type trait. Unspecified if dependent.
2461 uint64_t Value = 0;
2462
2463 /// The array dimension being queried, or -1 if not used.
2464 Expr *Dimension;
2465
2466 /// The location of the type trait keyword.
2467 SourceLocation Loc;
2468
2469 /// The location of the closing paren.
2470 SourceLocation RParen;
2471
2472 /// The type being queried.
2473 TypeSourceInfo *QueriedType = nullptr;
2474
2475 virtual void anchor();
2476
2477public:
2478 friend class ASTStmtReader;
2479
2480 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2481 TypeSourceInfo *queried, uint64_t value,
2482 Expr *dimension, SourceLocation rparen, QualType ty)
2483 : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2484 false, queried->getType()->isDependentType(),
2485 (queried->getType()->isInstantiationDependentType() ||
2486 (dimension && dimension->isInstantiationDependent())),
2487 queried->getType()->containsUnexpandedParameterPack()),
2488 ATT(att), Value(value), Dimension(dimension),
2489 Loc(loc), RParen(rparen), QueriedType(queried) {}
2490
2491 explicit ArrayTypeTraitExpr(EmptyShell Empty)
2492 : Expr(ArrayTypeTraitExprClass, Empty), ATT(0) {}
2493
2494 virtual ~ArrayTypeTraitExpr() = default;
2495
2496 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2497 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
2498
2499 ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2500
2501 QualType getQueriedType() const { return QueriedType->getType(); }
2502
2503 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2504
2505 uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
2506
2507 Expr *getDimensionExpression() const { return Dimension; }
2508
2509 static bool classof(const Stmt *T) {
2510 return T->getStmtClass() == ArrayTypeTraitExprClass;
2511 }
2512
2513 // Iterators
2514 child_range children() {
2515 return child_range(child_iterator(), child_iterator());
2516 }
2517};
2518
2519/// An expression trait intrinsic.
2520///
2521/// Example:
2522/// \code
2523/// __is_lvalue_expr(std::cout) == true
2524/// __is_lvalue_expr(1) == false
2525/// \endcode
2526class ExpressionTraitExpr : public Expr {
2527 /// The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2528 unsigned ET : 31;
2529
2530 /// The value of the type trait. Unspecified if dependent.
2531 unsigned Value : 1;
2532
2533 /// The location of the type trait keyword.
2534 SourceLocation Loc;
2535
2536 /// The location of the closing paren.
2537 SourceLocation RParen;
2538
2539 /// The expression being queried.
2540 Expr* QueriedExpression = nullptr;
2541
2542public:
2543 friend class ASTStmtReader;
2544
2545 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2546 Expr *queried, bool value,
2547 SourceLocation rparen, QualType resultType)
2548 : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2549 false, // Not type-dependent
2550 // Value-dependent if the argument is type-dependent.
2551 queried->isTypeDependent(),
2552 queried->isInstantiationDependent(),
2553 queried->containsUnexpandedParameterPack()),
2554 ET(et), Value(value), Loc(loc), RParen(rparen),
2555 QueriedExpression(queried) {}
2556
2557 explicit ExpressionTraitExpr(EmptyShell Empty)
2558 : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false) {}
2559
2560 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
2561 SourceLocation getEndLoc() const LLVM_READONLY { return RParen; }
2562
2563 ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2564
2565 Expr *getQueriedExpression() const { return QueriedExpression; }
2566
2567 bool getValue() const { return Value; }
2568
2569 static bool classof(const Stmt *T) {
2570 return T->getStmtClass() == ExpressionTraitExprClass;
2571 }
2572
2573 // Iterators
2574 child_range children() {
2575 return child_range(child_iterator(), child_iterator());
2576 }
2577};
2578
2579/// A reference to an overloaded function set, either an
2580/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2581class OverloadExpr : public Expr {
2582 /// The common name of these declarations.
2583 DeclarationNameInfo NameInfo;
2584
2585 /// The nested-name-specifier that qualifies the name, if any.
2586 NestedNameSpecifierLoc QualifierLoc;
2587
2588 /// The results. These are undesugared, which is to say, they may
2589 /// include UsingShadowDecls. Access is relative to the naming
2590 /// class.
2591 // FIXME: Allocate this data after the OverloadExpr subclass.
2592 DeclAccessPair *Results = nullptr;
2593
2594 unsigned NumResults = 0;
2595
2596protected:
2597 /// Whether the name includes info for explicit template
2598 /// keyword and arguments.
2599 bool HasTemplateKWAndArgsInfo = false;
2600
2601 OverloadExpr(StmtClass K, const ASTContext &C,
2602 NestedNameSpecifierLoc QualifierLoc,
2603 SourceLocation TemplateKWLoc,
2604 const DeclarationNameInfo &NameInfo,
2605 const TemplateArgumentListInfo *TemplateArgs,
2606 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2607 bool KnownDependent,
2608 bool KnownInstantiationDependent,
2609 bool KnownContainsUnexpandedParameterPack);
2610
2611 OverloadExpr(StmtClass K, EmptyShell Empty) : Expr(K, Empty) {}
2612
2613 /// Return the optional template keyword and arguments info.
2614 ASTTemplateKWAndArgsInfo *
2615 getTrailingASTTemplateKWAndArgsInfo(); // defined far below.
2616
2617 /// Return the optional template keyword and arguments info.
2618 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2619 return const_cast<OverloadExpr *>(this)
2620 ->getTrailingASTTemplateKWAndArgsInfo();
2621 }
2622
2623 /// Return the optional template arguments.
2624 TemplateArgumentLoc *getTrailingTemplateArgumentLoc(); // defined far below
2625
2626 void initializeResults(const ASTContext &C,
2627 UnresolvedSetIterator Begin,
2628 UnresolvedSetIterator End);
2629
2630public:
2631 friend class ASTStmtReader;
2632 friend class ASTStmtWriter;
2633
2634 struct FindResult {
2635 OverloadExpr *Expression;
2636 bool IsAddressOfOperand;
2637 bool HasFormOfMemberPointer;
2638 };
2639
2640 /// Finds the overloaded expression in the given expression \p E of
2641 /// OverloadTy.
2642 ///
2643 /// \return the expression (which must be there) and true if it has
2644 /// the particular form of a member pointer expression
2645 static FindResult find(Expr *E) {
2646 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
2647
2648 FindResult Result;
2649
2650 E = E->IgnoreParens();
2651 if (isa<UnaryOperator>(E)) {
2652 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
2653 E = cast<UnaryOperator>(E)->getSubExpr();
2654 auto *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2655
2656 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2657 Result.IsAddressOfOperand = true;
2658 Result.Expression = Ovl;
2659 } else {
2660 Result.HasFormOfMemberPointer = false;
2661 Result.IsAddressOfOperand = false;
2662 Result.Expression = cast<OverloadExpr>(E);
2663 }
2664
2665 return Result;
2666 }
2667
2668 /// Gets the naming class of this lookup, if any.
2669 CXXRecordDecl *getNamingClass() const;
2670
2671 using decls_iterator = UnresolvedSetImpl::iterator;
2672
2673 decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
2674 decls_iterator decls_end() const {
2675 return UnresolvedSetIterator(Results + NumResults);
2676 }
2677 llvm::iterator_range<decls_iterator> decls() const {
2678 return llvm::make_range(decls_begin(), decls_end());
2679 }
2680
2681 /// Gets the number of declarations in the unresolved set.
2682 unsigned getNumDecls() const { return NumResults; }
2683
2684 /// Gets the full name info.
2685 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2686
2687 /// Gets the name looked up.
2688 DeclarationName getName() const { return NameInfo.getName(); }
2689
2690 /// Gets the location of the name.
2691 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2692
2693 /// Fetches the nested-name qualifier, if one was given.
2694 NestedNameSpecifier *getQualifier() const {
2695 return QualifierLoc.getNestedNameSpecifier();
2696 }
2697
2698 /// Fetches the nested-name qualifier with source-location
2699 /// information, if one was given.
2700 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2701
2702 /// Retrieve the location of the template keyword preceding
2703 /// this name, if any.
2704 SourceLocation getTemplateKeywordLoc() const {
2705 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2706 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
2707 }
2708
2709 /// Retrieve the location of the left angle bracket starting the
2710 /// explicit template argument list following the name, if any.
2711 SourceLocation getLAngleLoc() const {
2712 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2713 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
2714 }
2715
2716 /// Retrieve the location of the right angle bracket ending the
2717 /// explicit template argument list following the name, if any.
2718 SourceLocation getRAngleLoc() const {
2719 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2720 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
2721 }
2722
2723 /// Determines whether the name was preceded by the template keyword.
2724 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2725
2726 /// Determines whether this expression had explicit template arguments.
2727 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2728
2729 TemplateArgumentLoc const *getTemplateArgs() const {
2730 if (!hasExplicitTemplateArgs())
2731 return nullptr;
2732 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2733 }
2734
2735 unsigned getNumTemplateArgs() const {
2736 if (!hasExplicitTemplateArgs())
2737 return 0;
2738
2739 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
2740 }
2741
2742 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2743 return {getTemplateArgs(), getNumTemplateArgs()};
2744 }
2745
2746 /// Copies the template arguments into the given structure.
2747 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2748 if (hasExplicitTemplateArgs())
2749 getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
2750 }
2751
2752 static bool classof(const Stmt *T) {
2753 return T->getStmtClass() == UnresolvedLookupExprClass ||
2754 T->getStmtClass() == UnresolvedMemberExprClass;
2755 }
2756};
2757
2758/// A reference to a name which we were able to look up during
2759/// parsing but could not resolve to a specific declaration.
2760///
2761/// This arises in several ways:
2762/// * we might be waiting for argument-dependent lookup;
2763/// * the name might resolve to an overloaded function;
2764/// and eventually:
2765/// * the lookup might have included a function template.
2766///
2767/// These never include UnresolvedUsingValueDecls, which are always class
2768/// members and therefore appear only in UnresolvedMemberLookupExprs.
2769class UnresolvedLookupExpr final
2770 : public OverloadExpr,
2771 private llvm::TrailingObjects<
2772 UnresolvedLookupExpr, ASTTemplateKWAndArgsInfo, TemplateArgumentLoc> {
2773 friend class ASTStmtReader;
2774 friend class OverloadExpr;
2775 friend TrailingObjects;
2776
2777 /// True if these lookup results should be extended by
2778 /// argument-dependent lookup if this is the operand of a function
2779 /// call.
2780 bool RequiresADL = false;
2781
2782 /// True if these lookup results are overloaded. This is pretty
2783 /// trivially rederivable if we urgently need to kill this field.
2784 bool Overloaded = false;
2785
2786 /// The naming class (C++ [class.access.base]p5) of the lookup, if
2787 /// any. This can generally be recalculated from the context chain,
2788 /// but that can be fairly expensive for unqualified lookups. If we
2789 /// want to improve memory use here, this could go in a union
2790 /// against the qualified-lookup bits.
2791 CXXRecordDecl *NamingClass = nullptr;
2792
2793 UnresolvedLookupExpr(const ASTContext &C,
2794 CXXRecordDecl *NamingClass,
2795 NestedNameSpecifierLoc QualifierLoc,
2796 SourceLocation TemplateKWLoc,
2797 const DeclarationNameInfo &NameInfo,
2798 bool RequiresADL, bool Overloaded,
2799 const TemplateArgumentListInfo *TemplateArgs,
2800 UnresolvedSetIterator Begin, UnresolvedSetIterator End)
2801 : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
2802 NameInfo, TemplateArgs, Begin,