1//===- Expr.h - Classes for representing expressions ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTVector.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/OperationKinds.h"
24#include "clang/AST/Stmt.h"
25#include "clang/AST/TemplateBase.h"
26#include "clang/AST/Type.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/LangOptions.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/SourceLocation.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/SyncScope.h"
34#include "clang/Basic/TypeTraits.h"
35#include "llvm/ADT/APFloat.h"
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/APSInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/PointerIntPair.h"
41#include "llvm/ADT/PointerUnion.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <memory>
53#include <string>
54
55namespace clang {
56
57class ASTContext;
58class CastExpr;
59class CXXBaseSpecifier;
60class CXXRecordDecl;
61class Decl;
62class Expr;
63class IdentifierInfo;
64class ObjCPropertyRefExpr;
65class SourceManager;
66class StringLiteral;
67class TargetInfo;
68
69/// \brief A simple array of base specifiers.
70using CXXCastPath = SmallVector<CXXBaseSpecifier *, 4>;
71
72/// \brief An adjustment to be made to the temporary created when emitting a
73/// reference binding, which accesses a particular subobject of that temporary.
74struct SubobjectAdjustment {
75 enum {
76 DerivedToBaseAdjustment,
77 FieldAdjustment,
78 MemberPointerAdjustment
79 } Kind;
80
81 struct DTB {
82 const CastExpr *BasePath;
83 const CXXRecordDecl *DerivedClass;
84 };
85
86 struct P {
87 const MemberPointerType *MPT;
88 Expr *RHS;
89 };
90
91 union {
92 struct DTB DerivedToBase;
93 FieldDecl *Field;
94 struct P Ptr;
95 };
96
97 SubobjectAdjustment(const CastExpr *BasePath,
98 const CXXRecordDecl *DerivedClass)
99 : Kind(DerivedToBaseAdjustment) {
100 DerivedToBase.BasePath = BasePath;
101 DerivedToBase.DerivedClass = DerivedClass;
102 }
103
104 SubobjectAdjustment(FieldDecl *Field) : Kind(FieldAdjustment) {
105 this->Field = Field;
106 }
107
108 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
109 : Kind(MemberPointerAdjustment) {
110 this->Ptr.MPT = MPT;
111 this->Ptr.RHS = RHS;
112 }
113};
114
115/// Expr - This represents one expression. Note that Expr's are subclasses of
116/// Stmt. This allows an expression to be transparently used any place a Stmt
117/// is required.
118///
119class Expr : public Stmt {
120 QualType TR;
121
122protected:
123 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
124 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
125 : Stmt(SC) {
126 ExprBits.TypeDependent = TD;
127 ExprBits.ValueDependent = VD;
128 ExprBits.InstantiationDependent = ID;
129 ExprBits.ValueKind = VK;
130 ExprBits.ObjectKind = OK;
131 assert(ExprBits.ObjectKind == OK && "truncated kind");
132 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
133 setType(T);
134 }
135
136 /// \brief Construct an empty expression.
137 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) {}
138
139public:
140 QualType getType() const { return TR; }
141
142 void setType(QualType t) {
143 // In C++, the type of an expression is always adjusted so that it
144 // will not have reference type (C++ [expr]p6). Use
145 // QualType::getNonReferenceType() to retrieve the non-reference
146 // type. Additionally, inspect Expr::isLvalue to determine whether
147 // an expression that is adjusted in this manner should be
148 // considered an lvalue.
149 assert((t.isNull() || !t->isReferenceType()) &&
150 "Expressions can't have reference type");
151
152 TR = t;
153 }
154
155 /// isValueDependent - Determines whether this expression is
156 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
157 /// array bound of "Chars" in the following example is
158 /// value-dependent.
159 /// @code
160 /// template<int Size, char (&Chars)[Size]> struct meta_string;
161 /// @endcode
162 bool isValueDependent() const { return ExprBits.ValueDependent; }
163
164 /// \brief Set whether this expression is value-dependent or not.
165 void setValueDependent(bool VD) {
166 ExprBits.ValueDependent = VD;
167 }
168
169 /// isTypeDependent - Determines whether this expression is
170 /// type-dependent (C++ [temp.dep.expr]), which means that its type
171 /// could change from one template instantiation to the next. For
172 /// example, the expressions "x" and "x + y" are type-dependent in
173 /// the following code, but "y" is not type-dependent:
174 /// @code
175 /// template<typename T>
176 /// void add(T x, int y) {
177 /// x + y;
178 /// }
179 /// @endcode
180 bool isTypeDependent() const { return ExprBits.TypeDependent; }
181
182 /// \brief Set whether this expression is type-dependent or not.
183 void setTypeDependent(bool TD) {
184 ExprBits.TypeDependent = TD;
185 }
186
187 /// \brief Whether this expression is instantiation-dependent, meaning that
188 /// it depends in some way on a template parameter, even if neither its type
189 /// nor (constant) value can change due to the template instantiation.
190 ///
191 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
192 /// instantiation-dependent (since it involves a template parameter \c T), but
193 /// is neither type- nor value-dependent, since the type of the inner
194 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
195 /// \c sizeof is known.
196 ///
197 /// \code
198 /// template<typename T>
199 /// void f(T x, T y) {
200 /// sizeof(sizeof(T() + T());
201 /// }
202 /// \endcode
203 bool isInstantiationDependent() const {
204 return ExprBits.InstantiationDependent;
205 }
206
207 /// \brief Set whether this expression is instantiation-dependent or not.
208 void setInstantiationDependent(bool ID) {
209 ExprBits.InstantiationDependent = ID;
210 }
211
212 /// \brief Whether this expression contains an unexpanded parameter
213 /// pack (for C++11 variadic templates).
214 ///
215 /// Given the following function template:
216 ///
217 /// \code
218 /// template<typename F, typename ...Types>
219 /// void forward(const F &f, Types &&...args) {
220 /// f(static_cast<Types&&>(args)...);
221 /// }
222 /// \endcode
223 ///
224 /// The expressions \c args and \c static_cast<Types&&>(args) both
225 /// contain parameter packs.
226 bool containsUnexpandedParameterPack() const {
227 return ExprBits.ContainsUnexpandedParameterPack;
228 }
229
230 /// \brief Set the bit that describes whether this expression
231 /// contains an unexpanded parameter pack.
232 void setContainsUnexpandedParameterPack(bool PP = true) {
233 ExprBits.ContainsUnexpandedParameterPack = PP;
234 }
235
236 /// getExprLoc - Return the preferred location for the arrow when diagnosing
237 /// a problem with a generic expression.
238 SourceLocation getExprLoc() const LLVM_READONLY;
239
240 /// isUnusedResultAWarning - Return true if this immediate expression should
241 /// be warned about if the result is unused. If so, fill in expr, location,
242 /// and ranges with expr to warn on and source locations/ranges appropriate
243 /// for a warning.
244 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
245 SourceRange &R1, SourceRange &R2,
246 ASTContext &Ctx) const;
247
248 /// isLValue - True if this expression is an "l-value" according to
249 /// the rules of the current language. C and C++ give somewhat
250 /// different rules for this concept, but in general, the result of
251 /// an l-value expression identifies a specific object whereas the
252 /// result of an r-value expression is a value detached from any
253 /// specific storage.
254 ///
255 /// C++11 divides the concept of "r-value" into pure r-values
256 /// ("pr-values") and so-called expiring values ("x-values"), which
257 /// identify specific objects that can be safely cannibalized for
258 /// their resources. This is an unfortunate abuse of terminology on
259 /// the part of the C++ committee. In Clang, when we say "r-value",
260 /// we generally mean a pr-value.
261 bool isLValue() const { return getValueKind() == VK_LValue; }
262 bool isRValue() const { return getValueKind() == VK_RValue; }
263 bool isXValue() const { return getValueKind() == VK_XValue; }
264 bool isGLValue() const { return getValueKind() != VK_RValue; }
265
266 enum LValueClassification {
267 LV_Valid,
268 LV_NotObjectType,
269 LV_IncompleteVoidType,
270 LV_DuplicateVectorComponents,
271 LV_InvalidExpression,
272 LV_InvalidMessageExpression,
273 LV_MemberFunction,
274 LV_SubObjCPropertySetting,
275 LV_ClassTemporary,
276 LV_ArrayTemporary
277 };
278
279 /// Reasons why an expression might not be an l-value.
280 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
281
282 enum isModifiableLvalueResult {
283 MLV_Valid,
284 MLV_NotObjectType,
285 MLV_IncompleteVoidType,
286 MLV_DuplicateVectorComponents,
287 MLV_InvalidExpression,
288 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
289 MLV_IncompleteType,
290 MLV_ConstQualified,
291 MLV_ConstQualifiedField,
292 MLV_ConstAddrSpace,
293 MLV_ArrayType,
294 MLV_NoSetterProperty,
295 MLV_MemberFunction,
296 MLV_SubObjCPropertySetting,
297 MLV_InvalidMessageExpression,
298 MLV_ClassTemporary,
299 MLV_ArrayTemporary
300 };
301
302 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
303 /// does not have an incomplete type, does not have a const-qualified type,
304 /// and if it is a structure or union, does not have any member (including,
305 /// recursively, any member or element of all contained aggregates or unions)
306 /// with a const-qualified type.
307 ///
308 /// \param Loc [in,out] - A source location which *may* be filled
309 /// in with the location of the expression making this a
310 /// non-modifiable lvalue, if specified.
311 isModifiableLvalueResult
312 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
313
314 /// \brief The return type of classify(). Represents the C++11 expression
315 /// taxonomy.
316 class Classification {
317 public:
318 /// \brief The various classification results. Most of these mean prvalue.
319 enum Kinds {
320 CL_LValue,
321 CL_XValue,
322 CL_Function, // Functions cannot be lvalues in C.
323 CL_Void, // Void cannot be an lvalue in C.
324 CL_AddressableVoid, // Void expression whose address can be taken in C.
325 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
326 CL_MemberFunction, // An expression referring to a member function
327 CL_SubObjCPropertySetting,
328 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
329 CL_ArrayTemporary, // A temporary of array type.
330 CL_ObjCMessageRValue, // ObjC message is an rvalue
331 CL_PRValue // A prvalue for any other reason, of any other type
332 };
333
334 /// \brief The results of modification testing.
335 enum ModifiableType {
336 CM_Untested, // testModifiable was false.
337 CM_Modifiable,
338 CM_RValue, // Not modifiable because it's an rvalue
339 CM_Function, // Not modifiable because it's a function; C++ only
340 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
341 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
342 CM_ConstQualified,
343 CM_ConstQualifiedField,
344 CM_ConstAddrSpace,
345 CM_ArrayType,
346 CM_IncompleteType
347 };
348
349 private:
350 friend class Expr;
351
352 unsigned short Kind;
353 unsigned short Modifiable;
354
355 explicit Classification(Kinds k, ModifiableType m)
356 : Kind(k), Modifiable(m) {}
357
358 public:
359 Classification() = default;
360
361 Kinds getKind() const { return static_cast<Kinds>(Kind); }
362
363 ModifiableType getModifiable() const {
364 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
365 return static_cast<ModifiableType>(Modifiable);
366 }
367
368 bool isLValue() const { return Kind == CL_LValue; }
369 bool isXValue() const { return Kind == CL_XValue; }
370 bool isGLValue() const { return Kind <= CL_XValue; }
371 bool isPRValue() const { return Kind >= CL_Function; }
372 bool isRValue() const { return Kind >= CL_XValue; }
373 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
374
375 /// \brief Create a simple, modifiably lvalue
376 static Classification makeSimpleLValue() {
377 return Classification(CL_LValue, CM_Modifiable);
378 }
379
380 };
381
382 /// \brief Classify - Classify this expression according to the C++11
383 /// expression taxonomy.
384 ///
385 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
386 /// old lvalue vs rvalue. This function determines the type of expression this
387 /// is. There are three expression types:
388 /// - lvalues are classical lvalues as in C++03.
389 /// - prvalues are equivalent to rvalues in C++03.
390 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
391 /// function returning an rvalue reference.
392 /// lvalues and xvalues are collectively referred to as glvalues, while
393 /// prvalues and xvalues together form rvalues.
394 Classification Classify(ASTContext &Ctx) const {
395 return ClassifyImpl(Ctx, nullptr);
396 }
397
398 /// \brief ClassifyModifiable - Classify this expression according to the
399 /// C++11 expression taxonomy, and see if it is valid on the left side
400 /// of an assignment.
401 ///
402 /// This function extends classify in that it also tests whether the
403 /// expression is modifiable (C99 6.3.2.1p1).
404 /// \param Loc A source location that might be filled with a relevant location
405 /// if the expression is not modifiable.
406 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
407 return ClassifyImpl(Ctx, &Loc);
408 }
409
410 /// getValueKindForType - Given a formal return or parameter type,
411 /// give its value kind.
412 static ExprValueKind getValueKindForType(QualType T) {
413 if (const ReferenceType *RT = T->getAs<ReferenceType>())
414 return (isa<LValueReferenceType>(RT)
415 ? VK_LValue
416 : (RT->getPointeeType()->isFunctionType()
417 ? VK_LValue : VK_XValue));
418 return VK_RValue;
419 }
420
421 /// getValueKind - The value kind that this expression produces.
422 ExprValueKind getValueKind() const {
423 return static_cast<ExprValueKind>(ExprBits.ValueKind);
424 }
425
426 /// getObjectKind - The object kind that this expression produces.
427 /// Object kinds are meaningful only for expressions that yield an
428 /// l-value or x-value.
429 ExprObjectKind getObjectKind() const {
430 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
431 }
432
433 bool isOrdinaryOrBitFieldObject() const {
434 ExprObjectKind OK = getObjectKind();
435 return (OK == OK_Ordinary || OK == OK_BitField);
436 }
437
438 /// setValueKind - Set the value kind produced by this expression.
439 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
440
441 /// setObjectKind - Set the object kind produced by this expression.
442 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
443
444private:
445 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
446
447public:
448 /// \brief Returns true if this expression is a gl-value that
449 /// potentially refers to a bit-field.
450 ///
451 /// In C++, whether a gl-value refers to a bitfield is essentially
452 /// an aspect of the value-kind type system.
453 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
454
455 /// \brief If this expression refers to a bit-field, retrieve the
456 /// declaration of that bit-field.
457 ///
458 /// Note that this returns a non-null pointer in subtly different
459 /// places than refersToBitField returns true. In particular, this can
460 /// return a non-null pointer even for r-values loaded from
461 /// bit-fields, but it will return null for a conditional bit-field.
462 FieldDecl *getSourceBitField();
463
464 const FieldDecl *getSourceBitField() const {
465 return const_cast<Expr*>(this)->getSourceBitField();
466 }
467
468 Decl *getReferencedDeclOfCallee();
469 const Decl *getReferencedDeclOfCallee() const {
470 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
471 }
472
473 /// \brief If this expression is an l-value for an Objective C
474 /// property, find the underlying property reference expression.
475 const ObjCPropertyRefExpr *getObjCProperty() const;
476
477 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
478 bool isObjCSelfExpr() const;
479
480 /// \brief Returns whether this expression refers to a vector element.
481 bool refersToVectorElement() const;
482
483 /// \brief Returns whether this expression refers to a global register
484 /// variable.
485 bool refersToGlobalRegisterVar() const;
486
487 /// \brief Returns whether this expression has a placeholder type.
488 bool hasPlaceholderType() const {
489 return getType()->isPlaceholderType();
490 }
491
492 /// \brief Returns whether this expression has a specific placeholder type.
493 bool hasPlaceholderType(BuiltinType::Kind K) const {
494 assert(BuiltinType::isPlaceholderTypeKind(K));
495 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
496 return BT->getKind() == K;
497 return false;
498 }
499
500 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
501 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
502 /// but also int expressions which are produced by things like comparisons in
503 /// C.
504 bool isKnownToHaveBooleanValue() const;
505
506 /// isIntegerConstantExpr - Return true if this expression is a valid integer
507 /// constant expression, and, if so, return its value in Result. If not a
508 /// valid i-c-e, return false and fill in Loc (if specified) with the location
509 /// of the invalid expression.
510 ///
511 /// Note: This does not perform the implicit conversions required by C++11
512 /// [expr.const]p5.
513 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
514 SourceLocation *Loc = nullptr,
515 bool isEvaluated = true) const;
516 bool isIntegerConstantExpr(const ASTContext &Ctx,
517 SourceLocation *Loc = nullptr) const;
518
519 /// isCXX98IntegralConstantExpr - Return true if this expression is an
520 /// integral constant expression in C++98. Can only be used in C++.
521 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
522
523 /// isCXX11ConstantExpr - Return true if this expression is a constant
524 /// expression in C++11. Can only be used in C++.
525 ///
526 /// Note: This does not perform the implicit conversions required by C++11
527 /// [expr.const]p5.
528 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
529 SourceLocation *Loc = nullptr) const;
530
531 /// isPotentialConstantExpr - Return true if this function's definition
532 /// might be usable in a constant expression in C++11, if it were marked
533 /// constexpr. Return false if the function can never produce a constant
534 /// expression, along with diagnostics describing why not.
535 static bool isPotentialConstantExpr(const FunctionDecl *FD,
536 SmallVectorImpl<
537 PartialDiagnosticAt> &Diags);
538
539 /// isPotentialConstantExprUnevaluted - Return true if this expression might
540 /// be usable in a constant expression in C++11 in an unevaluated context, if
541 /// it were in function FD marked constexpr. Return false if the function can
542 /// never produce a constant expression, along with diagnostics describing
543 /// why not.
544 static bool isPotentialConstantExprUnevaluated(Expr *E,
545 const FunctionDecl *FD,
546 SmallVectorImpl<
547 PartialDiagnosticAt> &Diags);
548
549 /// isConstantInitializer - Returns true if this expression can be emitted to
550 /// IR as a constant, and thus can be used as a constant initializer in C.
551 /// If this expression is not constant and Culprit is non-null,
552 /// it is used to store the address of first non constant expr.
553 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
554 const Expr **Culprit = nullptr) const;
555
556 /// EvalStatus is a struct with detailed info about an evaluation in progress.
557 struct EvalStatus {
558 /// \brief Whether the evaluated expression has side effects.
559 /// For example, (f() && 0) can be folded, but it still has side effects.
560 bool HasSideEffects = false;
561
562 /// \brief Whether the evaluation hit undefined behavior.
563 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
564 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
565 bool HasUndefinedBehavior = false;
566
567 /// Diag - If this is non-null, it will be filled in with a stack of notes
568 /// indicating why evaluation failed (or why it failed to produce a constant
569 /// expression).
570 /// If the expression is unfoldable, the notes will indicate why it's not
571 /// foldable. If the expression is foldable, but not a constant expression,
572 /// the notes will describes why it isn't a constant expression. If the
573 /// expression *is* a constant expression, no notes will be produced.
574 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
575
576 EvalStatus() = default;
577
578 // hasSideEffects - Return true if the evaluated expression has
579 // side effects.
580 bool hasSideEffects() const {
581 return HasSideEffects;
582 }
583 };
584
585 /// EvalResult is a struct with detailed info about an evaluated expression.
586 struct EvalResult : EvalStatus {
587 /// Val - This is the value the expression can be folded to.
588 APValue Val;
589
590 // isGlobalLValue - Return true if the evaluated lvalue expression
591 // is global.
592 bool isGlobalLValue() const;
593 };
594
595 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
596 /// an rvalue using any crazy technique (that has nothing to do with language
597 /// standards) that we want to, even if the expression has side-effects. If
598 /// this function returns true, it returns the folded constant in Result. If
599 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
600 /// applied.
601 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
602
603 /// EvaluateAsBooleanCondition - Return true if this is a constant
604 /// which we we can fold and convert to a boolean condition using
605 /// any crazy technique that we want to, even if the expression has
606 /// side-effects.
607 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
608
609 enum SideEffectsKind {
610 /// Strictly evaluate the expression.
611 SE_NoSideEffects,
612
613 /// Allow UB that we can give a value, but not arbitrary unmodeled side
614 /// effects.
615 SE_AllowUndefinedBehavior,
616
617 /// Allow any unmodeled side effect.
618 SE_AllowSideEffects
619 };
620
621 /// EvaluateAsInt - Return true if this is a constant which we can fold and
622 /// convert to an integer, using any crazy technique that we want to.
623 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
624 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
625
626 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
627 /// convert to a floating point value, using any crazy technique that we
628 /// want to.
629 bool
630 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
631 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
632
633 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
634 /// constant folded without side-effects, but discard the result.
635 bool isEvaluatable(const ASTContext &Ctx,
636 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
637
638 /// HasSideEffects - This routine returns true for all those expressions
639 /// which have any effect other than producing a value. Example is a function
640 /// call, volatile variable read, or throwing an exception. If
641 /// IncludePossibleEffects is false, this call treats certain expressions with
642 /// potential side effects (such as function call-like expressions,
643 /// instantiation-dependent expressions, or invocations from a macro) as not
644 /// having side effects.
645 bool HasSideEffects(const ASTContext &Ctx,
646 bool IncludePossibleEffects = true) const;
647
648 /// \brief Determine whether this expression involves a call to any function
649 /// that is not trivial.
650 bool hasNonTrivialCall(const ASTContext &Ctx) const;
651
652 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
653 /// integer. This must be called on an expression that constant folds to an
654 /// integer.
655 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
656 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
657
658 void EvaluateForOverflow(const ASTContext &Ctx) const;
659
660 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
661 /// lvalue with link time known address, with no side-effects.
662 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
663
664 /// EvaluateAsInitializer - Evaluate an expression as if it were the
665 /// initializer of the given declaration. Returns true if the initializer
666 /// can be folded to a constant, and produces any relevant notes. In C++11,
667 /// notes will be produced if the expression is not a constant expression.
668 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
669 const VarDecl *VD,
670 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
671
672 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
673 /// of a call to the given function with the given arguments, inside an
674 /// unevaluated context. Returns true if the expression could be folded to a
675 /// constant.
676 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
677 const FunctionDecl *Callee,
678 ArrayRef<const Expr*> Args,
679 const Expr *This = nullptr) const;
680
681 /// \brief If the current Expr is a pointer, this will try to statically
682 /// determine the number of bytes available where the pointer is pointing.
683 /// Returns true if all of the above holds and we were able to figure out the
684 /// size, false otherwise.
685 ///
686 /// \param Type - How to evaluate the size of the Expr, as defined by the
687 /// "type" parameter of __builtin_object_size
688 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
689 unsigned Type) const;
690
691 /// \brief Enumeration used to describe the kind of Null pointer constant
692 /// returned from \c isNullPointerConstant().
693 enum NullPointerConstantKind {
694 /// \brief Expression is not a Null pointer constant.
695 NPCK_NotNull = 0,
696
697 /// \brief Expression is a Null pointer constant built from a zero integer
698 /// expression that is not a simple, possibly parenthesized, zero literal.
699 /// C++ Core Issue 903 will classify these expressions as "not pointers"
700 /// once it is adopted.
701 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
702 NPCK_ZeroExpression,
703
704 /// \brief Expression is a Null pointer constant built from a literal zero.
705 NPCK_ZeroLiteral,
706
707 /// \brief Expression is a C++11 nullptr.
708 NPCK_CXX11_nullptr,
709
710 /// \brief Expression is a GNU-style __null constant.
711 NPCK_GNUNull
712 };
713
714 /// \brief Enumeration used to describe how \c isNullPointerConstant()
715 /// should cope with value-dependent expressions.
716 enum NullPointerConstantValueDependence {
717 /// \brief Specifies that the expression should never be value-dependent.
718 NPC_NeverValueDependent = 0,
719
720 /// \brief Specifies that a value-dependent expression of integral or
721 /// dependent type should be considered a null pointer constant.
722 NPC_ValueDependentIsNull,
723
724 /// \brief Specifies that a value-dependent expression should be considered
725 /// to never be a null pointer constant.
726 NPC_ValueDependentIsNotNull
727 };
728
729 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
730 /// a Null pointer constant. The return value can further distinguish the
731 /// kind of NULL pointer constant that was detected.
732 NullPointerConstantKind isNullPointerConstant(
733 ASTContext &Ctx,
734 NullPointerConstantValueDependence NPC) const;
735
736 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
737 /// write barrier.
738 bool isOBJCGCCandidate(ASTContext &Ctx) const;
739
740 /// \brief Returns true if this expression is a bound member function.
741 bool isBoundMemberFunction(ASTContext &Ctx) const;
742
743 /// \brief Given an expression of bound-member type, find the type
744 /// of the member. Returns null if this is an *overloaded* bound
745 /// member expression.
746 static QualType findBoundMemberType(const Expr *expr);
747
748 /// IgnoreImpCasts - Skip past any implicit casts which might
749 /// surround this expression. Only skips ImplicitCastExprs.
750 Expr *IgnoreImpCasts() LLVM_READONLY;
751
752 /// IgnoreImplicit - Skip past any implicit AST nodes which might
753 /// surround this expression.
754 Expr *IgnoreImplicit() LLVM_READONLY {
755 return cast<Expr>(Stmt::IgnoreImplicit());
756 }
757
758 const Expr *IgnoreImplicit() const LLVM_READONLY {
759 return const_cast<Expr*>(this)->IgnoreImplicit();
760 }
761
762 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
763 /// its subexpression. If that subexpression is also a ParenExpr,
764 /// then this method recursively returns its subexpression, and so forth.
765 /// Otherwise, the method returns the current Expr.
766 Expr *IgnoreParens() LLVM_READONLY;
767
768 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
769 /// or CastExprs, returning their operand.
770 Expr *IgnoreParenCasts() LLVM_READONLY;
771
772 /// Ignore casts. Strip off any CastExprs, returning their operand.
773 Expr *IgnoreCasts() LLVM_READONLY;
774
775 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
776 /// any ParenExpr or ImplicitCastExprs, returning their operand.
777 Expr *IgnoreParenImpCasts() LLVM_READONLY;
778
779 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
780 /// call to a conversion operator, return the argument.
781 Expr *IgnoreConversionOperator() LLVM_READONLY;
782
783 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
784 return const_cast<Expr*>(this)->IgnoreConversionOperator();
785 }
786
787 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
788 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
789 }
790
791 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
792 /// CastExprs that represent lvalue casts, returning their operand.
793 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
794
795 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
796 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
797 }
798
799 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
800 /// value (including ptr->int casts of the same size). Strip off any
801 /// ParenExpr or CastExprs, returning their operand.
802 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
803
804 /// Ignore parentheses and derived-to-base casts.
805 Expr *ignoreParenBaseCasts() LLVM_READONLY;
806
807 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
808 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
809 }
810
811 /// \brief Determine whether this expression is a default function argument.
812 ///
813 /// Default arguments are implicitly generated in the abstract syntax tree
814 /// by semantic analysis for function calls, object constructions, etc. in
815 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
816 /// this routine also looks through any implicit casts to determine whether
817 /// the expression is a default argument.
818 bool isDefaultArgument() const;
819
820 /// \brief Determine whether the result of this expression is a
821 /// temporary object of the given class type.
822 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
823
824 /// \brief Whether this expression is an implicit reference to 'this' in C++.
825 bool isImplicitCXXThis() const;
826
827 const Expr *IgnoreImpCasts() const LLVM_READONLY {
828 return const_cast<Expr*>(this)->IgnoreImpCasts();
829 }
830
831 const Expr *IgnoreParens() const LLVM_READONLY {
832 return const_cast<Expr*>(this)->IgnoreParens();
833 }
834
835 const Expr *IgnoreParenCasts() const LLVM_READONLY {
836 return const_cast<Expr*>(this)->IgnoreParenCasts();
837 }
838
839 /// Strip off casts, but keep parentheses.
840 const Expr *IgnoreCasts() const LLVM_READONLY {
841 return const_cast<Expr*>(this)->IgnoreCasts();
842 }
843
844 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
845 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
846 }
847
848 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
849
850 /// \brief For an expression of class type or pointer to class type,
851 /// return the most derived class decl the expression is known to refer to.
852 ///
853 /// If this expression is a cast, this method looks through it to find the
854 /// most derived decl that can be inferred from the expression.
855 /// This is valid because derived-to-base conversions have undefined
856 /// behavior if the object isn't dynamically of the derived type.
857 const CXXRecordDecl *getBestDynamicClassType() const;
858
859 /// \brief Get the inner expression that determines the best dynamic class.
860 /// If this is a prvalue, we guarantee that it is of the most-derived type
861 /// for the object itself.
862 const Expr *getBestDynamicClassTypeExpr() const;
863
864 /// Walk outwards from an expression we want to bind a reference to and
865 /// find the expression whose lifetime needs to be extended. Record
866 /// the LHSs of comma expressions and adjustments needed along the path.
867 const Expr *skipRValueSubobjectAdjustments(
868 SmallVectorImpl<const Expr *> &CommaLHS,
869 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
870 const Expr *skipRValueSubobjectAdjustments() const {
871 SmallVector<const Expr *, 8> CommaLHSs;
872 SmallVector<SubobjectAdjustment, 8> Adjustments;
873 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
874 }
875
876 static bool classof(const Stmt *T) {
877 return T->getStmtClass() >= firstExprConstant &&
878 T->getStmtClass() <= lastExprConstant;
879 }
880};
881
882//===----------------------------------------------------------------------===//
883// Primary Expressions.
884//===----------------------------------------------------------------------===//
885
886/// OpaqueValueExpr - An expression referring to an opaque object of a
887/// fixed type and value class. These don't correspond to concrete
888/// syntax; instead they're used to express operations (usually copy
889/// operations) on values whose source is generally obvious from
890/// context.
891class OpaqueValueExpr : public Expr {
892 friend class ASTStmtReader;
893
894 Expr *SourceExpr;
895 SourceLocation Loc;
896
897public:
898 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
899 ExprObjectKind OK = OK_Ordinary,
900 Expr *SourceExpr = nullptr)
901 : Expr(OpaqueValueExprClass, T, VK, OK,
902 T->isDependentType() ||
903 (SourceExpr && SourceExpr->isTypeDependent()),
904 T->isDependentType() ||
905 (SourceExpr && SourceExpr->isValueDependent()),
906 T->isInstantiationDependentType() ||
907 (SourceExpr && SourceExpr->isInstantiationDependent()),
908 false),
909 SourceExpr(SourceExpr), Loc(Loc) {
910 }
911
912 /// Given an expression which invokes a copy constructor --- i.e. a
913 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
914 /// find the OpaqueValueExpr that's the source of the construction.
915 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
916
917 explicit OpaqueValueExpr(EmptyShell Empty)
918 : Expr(OpaqueValueExprClass, Empty) {}
919
920 /// \brief Retrieve the location of this expression.
921 SourceLocation getLocation() const { return Loc; }
922
923 SourceLocation getLocStart() const LLVM_READONLY {
924 return SourceExpr ? SourceExpr->getLocStart() : Loc;
925 }
926
927 SourceLocation getLocEnd() const LLVM_READONLY {
928 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
929 }
930
931 SourceLocation getExprLoc() const LLVM_READONLY {
932 if (SourceExpr) return SourceExpr->getExprLoc();
933 return Loc;
934 }
935
936 child_range children() {
937 return child_range(child_iterator(), child_iterator());
938 }
939
940 const_child_range children() const {
941 return const_child_range(const_child_iterator(), const_child_iterator());
942 }
943
944 /// The source expression of an opaque value expression is the
945 /// expression which originally generated the value. This is
946 /// provided as a convenience for analyses that don't wish to
947 /// precisely model the execution behavior of the program.
948 ///
949 /// The source expression is typically set when building the
950 /// expression which binds the opaque value expression in the first
951 /// place.
952 Expr *getSourceExpr() const { return SourceExpr; }
953
954 static bool classof(const Stmt *T) {
955 return T->getStmtClass() == OpaqueValueExprClass;
956 }
957};
958
959/// \brief A reference to a declared variable, function, enum, etc.
960/// [C99 6.5.1p2]
961///
962/// This encodes all the information about how a declaration is referenced
963/// within an expression.
964///
965/// There are several optional constructs attached to DeclRefExprs only when
966/// they apply in order to conserve memory. These are laid out past the end of
967/// the object, and flags in the DeclRefExprBitfield track whether they exist:
968///
969/// DeclRefExprBits.HasQualifier:
970/// Specifies when this declaration reference expression has a C++
971/// nested-name-specifier.
972/// DeclRefExprBits.HasFoundDecl:
973/// Specifies when this declaration reference expression has a record of
974/// a NamedDecl (different from the referenced ValueDecl) which was found
975/// during name lookup and/or overload resolution.
976/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
977/// Specifies when this declaration reference expression has an explicit
978/// C++ template keyword and/or template argument list.
979/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
980/// Specifies when this declaration reference expression (validly)
981/// refers to an enclosed local or a captured variable.
982class DeclRefExpr final
983 : public Expr,
984 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
985 NamedDecl *, ASTTemplateKWAndArgsInfo,
986 TemplateArgumentLoc> {
987 /// \brief The declaration that we are referencing.
988 ValueDecl *D;
989
990 /// \brief The location of the declaration name itself.
991 SourceLocation Loc;
992
993 /// \brief Provides source/type location info for the declaration name
994 /// embedded in D.
995 DeclarationNameLoc DNLoc;
996
997 DeclRefExpr(const ASTContext &Ctx,
998 NestedNameSpecifierLoc QualifierLoc,
999 SourceLocation TemplateKWLoc,
1000 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
1001 const DeclarationNameInfo &NameInfo,
1002 NamedDecl *FoundD,
1003 const TemplateArgumentListInfo *TemplateArgs,
1004 QualType T, ExprValueKind VK);
1005
1006 /// \brief Construct an empty declaration reference expression.
1007 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1008
1009 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1010 return hasQualifier() ? 1 : 0;
1011 }
1012
1013 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1014 return hasFoundDecl() ? 1 : 0;
1015 }
1016
1017 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1018 return hasTemplateKWAndArgsInfo() ? 1 : 0;
1019 }
1020
1021 /// \brief Test whether there is a distinct FoundDecl attached to the end of
1022 /// this DRE.
1023 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1024
1025 /// \brief Computes the type- and value-dependence flags for this
1026 /// declaration reference expression.
1027 void computeDependence(const ASTContext &C);
1028
1029public:
1030 friend class ASTStmtReader;
1031 friend class ASTStmtWriter;
1032 friend TrailingObjects;
1033
1034 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1035 ExprValueKind VK, SourceLocation L,
1036 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1037 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1038 D(D), Loc(L), DNLoc(LocInfo) {
1039 DeclRefExprBits.HasQualifier = 0;
1040 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1041 DeclRefExprBits.HasFoundDecl = 0;
1042 DeclRefExprBits.HadMultipleCandidates = 0;
1043 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1044 RefersToEnclosingVariableOrCapture;
1045 computeDependence(D->getASTContext());
1046 }
1047
1048 static DeclRefExpr *
1049 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1050 SourceLocation TemplateKWLoc, ValueDecl *D,
1051 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1052 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1053 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1054
1055 static DeclRefExpr *
1056 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1057 SourceLocation TemplateKWLoc, ValueDecl *D,
1058 bool RefersToEnclosingVariableOrCapture,
1059 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1060 NamedDecl *FoundD = nullptr,
1061 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1062
1063 /// \brief Construct an empty declaration reference expression.
1064 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1065 bool HasQualifier,
1066 bool HasFoundDecl,
1067 bool HasTemplateKWAndArgsInfo,
1068 unsigned NumTemplateArgs);
1069
1070 ValueDecl *getDecl() { return D; }
1071 const ValueDecl *getDecl() const { return D; }
1072 void setDecl(ValueDecl *NewD) { D = NewD; }
1073
1074 DeclarationNameInfo getNameInfo() const {
1075 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1076 }
1077
1078 SourceLocation getLocation() const { return Loc; }
1079 void setLocation(SourceLocation L) { Loc = L; }
1080 SourceLocation getLocStart() const LLVM_READONLY;
1081 SourceLocation getLocEnd() const LLVM_READONLY;
1082
1083 /// \brief Determine whether this declaration reference was preceded by a
1084 /// C++ nested-name-specifier, e.g., \c N::foo.
1085 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1086
1087 /// \brief If the name was qualified, retrieves the nested-name-specifier
1088 /// that precedes the name, with source-location information.
1089 NestedNameSpecifierLoc getQualifierLoc() const {
1090 if (!hasQualifier())
1091 return NestedNameSpecifierLoc();
1092 return *getTrailingObjects<NestedNameSpecifierLoc>();
1093 }
1094
1095 /// \brief If the name was qualified, retrieves the nested-name-specifier
1096 /// that precedes the name. Otherwise, returns NULL.
1097 NestedNameSpecifier *getQualifier() const {
1098 return getQualifierLoc().getNestedNameSpecifier();
1099 }
1100
1101 /// \brief Get the NamedDecl through which this reference occurred.
1102 ///
1103 /// This Decl may be different from the ValueDecl actually referred to in the
1104 /// presence of using declarations, etc. It always returns non-NULL, and may
1105 /// simple return the ValueDecl when appropriate.
1106 NamedDecl *getFoundDecl() {
1107 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1108 }
1109
1110 /// \brief Get the NamedDecl through which this reference occurred.
1111 /// See non-const variant.
1112 const NamedDecl *getFoundDecl() const {
1113 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1114 }
1115
1116 bool hasTemplateKWAndArgsInfo() const {
1117 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1118 }
1119
1120 /// \brief Retrieve the location of the template keyword preceding
1121 /// this name, if any.
1122 SourceLocation getTemplateKeywordLoc() const {
1123 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1124 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1125 }
1126
1127 /// \brief Retrieve the location of the left angle bracket starting the
1128 /// explicit template argument list following the name, if any.
1129 SourceLocation getLAngleLoc() const {
1130 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1131 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1132 }
1133
1134 /// \brief Retrieve the location of the right angle bracket ending the
1135 /// explicit template argument list following the name, if any.
1136 SourceLocation getRAngleLoc() const {
1137 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1138 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1139 }
1140
1141 /// \brief Determines whether the name in this declaration reference
1142 /// was preceded by the template keyword.
1143 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1144
1145 /// \brief Determines whether this declaration reference was followed by an
1146 /// explicit template argument list.
1147 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1148
1149 /// \brief Copies the template arguments (if present) into the given
1150 /// structure.
1151 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1152 if (hasExplicitTemplateArgs())
1153 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1154 getTrailingObjects<TemplateArgumentLoc>(), List);
1155 }
1156
1157 /// \brief Retrieve the template arguments provided as part of this
1158 /// template-id.
1159 const TemplateArgumentLoc *getTemplateArgs() const {
1160 if (!hasExplicitTemplateArgs())
1161 return nullptr;
1162
1163 return getTrailingObjects<TemplateArgumentLoc>();
1164 }
1165
1166 /// \brief Retrieve the number of template arguments provided as part of this
1167 /// template-id.
1168 unsigned getNumTemplateArgs() const {
1169 if (!hasExplicitTemplateArgs())
1170 return 0;
1171
1172 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1173 }
1174
1175 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1176 return {getTemplateArgs(), getNumTemplateArgs()};
1177 }
1178
1179 /// \brief Returns true if this expression refers to a function that
1180 /// was resolved from an overloaded set having size greater than 1.
1181 bool hadMultipleCandidates() const {
1182 return DeclRefExprBits.HadMultipleCandidates;
1183 }
1184
1185 /// \brief Sets the flag telling whether this expression refers to
1186 /// a function that was resolved from an overloaded set having size
1187 /// greater than 1.
1188 void setHadMultipleCandidates(bool V = true) {
1189 DeclRefExprBits.HadMultipleCandidates = V;
1190 }
1191
1192 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1193 /// variable?
1194 bool refersToEnclosingVariableOrCapture() const {
1195 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1196 }
1197
1198 static bool classof(const Stmt *T) {
1199 return T->getStmtClass() == DeclRefExprClass;
1200 }
1201
1202 // Iterators
1203 child_range children() {
1204 return child_range(child_iterator(), child_iterator());
1205 }
1206
1207 const_child_range children() const {
1208 return const_child_range(const_child_iterator(), const_child_iterator());
1209 }
1210};
1211
1212/// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1213class PredefinedExpr : public Expr {
1214public:
1215 enum IdentType {
1216 Func,
1217 Function,
1218
1219 // Same as Function, but as wide string.
1220 LFunction,
1221 FuncDName,
1222 FuncSig,
1223 PrettyFunction,
1224
1225 /// \brief The same as PrettyFunction, except that the
1226 /// 'virtual' keyword is omitted for virtual member functions.
1227 PrettyFunctionNoVirtual
1228 };
1229
1230private:
1231 SourceLocation Loc;
1232 IdentType Type;
1233 Stmt *FnName = nullptr;
1234
1235public:
1236 friend class ASTStmtReader;
1237
1238 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1239 StringLiteral *SL);
1240
1241 /// \brief Construct an empty predefined expression.
1242 explicit PredefinedExpr(EmptyShell Empty)
1243 : Expr(PredefinedExprClass, Empty), Type(Func) {}
1244
1245 IdentType getIdentType() const { return Type; }
1246
1247 SourceLocation getLocation() const { return Loc; }
1248 void setLocation(SourceLocation L) { Loc = L; }
1249
1250 StringLiteral *getFunctionName();
1251 const StringLiteral *getFunctionName() const {
1252 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1253 }
1254
1255 static StringRef getIdentTypeName(IdentType IT);
1256 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1257
1258 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1259 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1260
1261 static bool classof(const Stmt *T) {
1262 return T->getStmtClass() == PredefinedExprClass;
1263 }
1264
1265 // Iterators
1266 child_range children() { return child_range(&FnName, &FnName + 1); }
1267
1268 const_child_range children() const {
1269 return const_child_range(&FnName, &FnName + 1);
1270 }
1271};
1272
1273/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1274/// leaking memory.
1275///
1276/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1277/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1278/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1279/// the APFloat/APInt values will never get freed. APNumericStorage uses
1280/// ASTContext's allocator for memory allocation.
1281class APNumericStorage {
1282 union {
1283 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1284 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1285 };
1286 unsigned BitWidth = 0;
1287
1288 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1289
1290protected:
1291 APNumericStorage() : VAL(0) {}
1292
1293 llvm::APInt getIntValue() const {
1294 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1295 if (NumWords > 1)
1296 return llvm::APInt(BitWidth, NumWords, pVal);
1297 else
1298 return llvm::APInt(BitWidth, VAL);
1299 }
1300
1301 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1302
1303public:
1304 APNumericStorage(const APNumericStorage &) = delete;
1305 APNumericStorage &operator=(const APNumericStorage &) = delete;
1306};
1307
1308class APIntStorage : private APNumericStorage {
1309public:
1310 llvm::APInt getValue() const { return getIntValue(); }
1311
1312 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1313 setIntValue(C, Val);
1314 }
1315};
1316
1317class APFloatStorage : private APNumericStorage {
1318public:
1319 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1320 return llvm::APFloat(Semantics, getIntValue());
1321 }
1322
1323 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1324 setIntValue(C, Val.bitcastToAPInt());
1325 }
1326};
1327
1328class IntegerLiteral : public Expr, public APIntStorage {
1329 SourceLocation Loc;
1330
1331 /// \brief Construct an empty integer literal.
1332 explicit IntegerLiteral(EmptyShell Empty)
1333 : Expr(IntegerLiteralClass, Empty) {}
1334
1335public:
1336 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1337 // or UnsignedLongLongTy
1338 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1339 SourceLocation l);
1340
1341 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1342 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1343 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1344 /// \param V - the value that the returned integer literal contains.
1345 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1346 QualType type, SourceLocation l);
1347
1348 /// \brief Returns a new empty integer literal.
1349 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1350
1351 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1352 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1353
1354 /// \brief Retrieve the location of the literal.
1355 SourceLocation getLocation() const { return Loc; }
1356
1357 void setLocation(SourceLocation Location) { Loc = Location; }
1358
1359 static bool classof(const Stmt *T) {
1360 return T->getStmtClass() == IntegerLiteralClass;
1361 }
1362
1363 // Iterators
1364 child_range children() {
1365 return child_range(child_iterator(), child_iterator());
1366 }
1367
1368 const_child_range children() const {
1369 return const_child_range(const_child_iterator(), const_child_iterator());
1370 }
1371};
1372
1373class CharacterLiteral : public Expr {
1374public:
1375 enum CharacterKind {
1376 Ascii,
1377 Wide,
1378 UTF8,
1379 UTF16,
1380 UTF32
1381 };
1382
1383private:
1384 unsigned Value;
1385 SourceLocation Loc;
1386
1387public:
1388 // type should be IntTy
1389 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1390 SourceLocation l)
1391 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1392 false, false),
1393 Value(value), Loc(l) {
1394 CharacterLiteralBits.Kind = kind;
1395 }
1396
1397 /// \brief Construct an empty character literal.
1398 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) {}
1399
1400 SourceLocation getLocation() const { return Loc; }
1401
1402 CharacterKind getKind() const {
1403 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1404 }
1405
1406 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1407 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1408
1409 unsigned getValue() const { return Value; }
1410
1411 void setLocation(SourceLocation Location) { Loc = Location; }
1412 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1413 void setValue(unsigned Val) { Value = Val; }
1414
1415 static bool classof(const Stmt *T) {
1416 return T->getStmtClass() == CharacterLiteralClass;
1417 }
1418
1419 // Iterators
1420 child_range children() {
1421 return child_range(child_iterator(), child_iterator());
1422 }
1423
1424 const_child_range children() const {
1425 return const_child_range(const_child_iterator(), const_child_iterator());
1426 }
1427};
1428
1429class FloatingLiteral : public Expr, private APFloatStorage {
1430 SourceLocation Loc;
1431
1432 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1433 QualType Type, SourceLocation L);
1434
1435 /// \brief Construct an empty floating-point literal.
1436 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1437
1438public:
1439 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1440 bool isexact, QualType Type, SourceLocation L);
1441 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1442
1443 llvm::APFloat getValue() const {
1444 return APFloatStorage::getValue(getSemantics());
1445 }
1446
1447 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1448 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1449 APFloatStorage::setValue(C, Val);
1450 }
1451
1452 /// Get a raw enumeration value representing the floating-point semantics of
1453 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1454 APFloatSemantics getRawSemantics() const {
1455 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1456 }
1457
1458 /// Set the raw enumeration value representing the floating-point semantics of
1459 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1460 void setRawSemantics(APFloatSemantics Sem) {
1461 FloatingLiteralBits.Semantics = Sem;
1462 }
1463
1464 /// Return the APFloat semantics this literal uses.
1465 const llvm::fltSemantics &getSemantics() const;
1466
1467 /// Set the APFloat semantics this literal uses.
1468 void setSemantics(const llvm::fltSemantics &Sem);
1469
1470 bool isExact() const { return FloatingLiteralBits.IsExact; }
1471 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1472
1473 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1474 /// double. Note that this may cause loss of precision, but is useful for
1475 /// debugging dumps, etc.
1476 double getValueAsApproximateDouble() const;
1477
1478 SourceLocation getLocation() const { return Loc; }
1479 void setLocation(SourceLocation L) { Loc = L; }
1480
1481 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1482 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1483
1484 static bool classof(const Stmt *T) {
1485 return T->getStmtClass() == FloatingLiteralClass;
1486 }
1487
1488 // Iterators
1489 child_range children() {
1490 return child_range(child_iterator(), child_iterator());
1491 }
1492
1493 const_child_range children() const {
1494 return const_child_range(const_child_iterator(), const_child_iterator());
1495 }
1496};
1497
1498/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1499/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1500/// IntegerLiteral classes. Instances of this class always have a Complex type
1501/// whose element type matches the subexpression.
1502class ImaginaryLiteral : public Expr {
1503 Stmt *Val;
1504
1505public:
1506 ImaginaryLiteral(Expr *val, QualType Ty)
1507 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1508 false, false),
1509 Val(val) {}
1510
1511 /// \brief Build an empty imaginary literal.
1512 explicit ImaginaryLiteral(EmptyShell Empty)
1513 : Expr(ImaginaryLiteralClass, Empty) {}
1514
1515 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1516 Expr *getSubExpr() { return cast<Expr>(Val); }
1517 void setSubExpr(Expr *E) { Val = E; }
1518
1519 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1520 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1521
1522 static bool classof(const Stmt *T) {
1523 return T->getStmtClass() == ImaginaryLiteralClass;
1524 }
1525
1526 // Iterators
1527 child_range children() { return child_range(&Val, &Val+1); }
1528
1529 const_child_range children() const {
1530 return const_child_range(&Val, &Val + 1);
1531 }
1532};
1533
1534/// StringLiteral - This represents a string literal expression, e.g. "foo"
1535/// or L"bar" (wide strings). The actual string is returned by getBytes()
1536/// is NOT null-terminated, and the length of the string is determined by
1537/// calling getByteLength(). The C type for a string is always a
1538/// ConstantArrayType. In C++, the char type is const qualified, in C it is
1539/// not.
1540///
1541/// Note that strings in C can be formed by concatenation of multiple string
1542/// literal pptokens in translation phase #6. This keeps track of the locations
1543/// of each of these pieces.
1544///
1545/// Strings in C can also be truncated and extended by assigning into arrays,
1546/// e.g. with constructs like:
1547/// char X[2] = "foobar";
1548/// In this case, getByteLength() will return 6, but the string literal will
1549/// have type "char[2]".
1550class StringLiteral : public Expr {
1551public:
1552 enum StringKind {
1553 Ascii,
1554 Wide,
1555 UTF8,
1556 UTF16,
1557 UTF32
1558 };
1559
1560private:
1561 friend class ASTStmtReader;
1562
1563 union {
1564 const char *asChar;
1565 const uint16_t *asUInt16;
1566 const uint32_t *asUInt32;
1567 } StrData;
1568 unsigned Length;
1569 unsigned CharByteWidth : 4;
1570 unsigned Kind : 3;
1571 unsigned IsPascal : 1;
1572 unsigned NumConcatenated;
1573 SourceLocation TokLocs[1];
1574
1575 StringLiteral(QualType Ty)
1576 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false,
1577 false, false) {}
1578
1579 static int mapCharByteWidth(TargetInfo const &target, StringKind k);
1580
1581public:
1582 /// This is the "fully general" constructor that allows representation of
1583 /// strings formed from multiple concatenated tokens.
1584 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1585 StringKind Kind, bool Pascal, QualType Ty,
1586 const SourceLocation *Loc, unsigned NumStrs);
1587
1588 /// Simple constructor for string literals made from one token.
1589 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1590 StringKind Kind, bool Pascal, QualType Ty,
1591 SourceLocation Loc) {
1592 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1593 }
1594
1595 /// \brief Construct an empty string literal.
1596 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1597
1598 StringRef getString() const {
1599 assert(CharByteWidth==1
1600 && "This function is used in places that assume strings use char");
1601 return StringRef(StrData.asChar, getByteLength());
1602 }
1603
1604 /// Allow access to clients that need the byte representation, such as
1605 /// ASTWriterStmt::VisitStringLiteral().
1606 StringRef getBytes() const {
1607 // FIXME: StringRef may not be the right type to use as a result for this.
1608 if (CharByteWidth == 1)
1609 return StringRef(StrData.asChar, getByteLength());
1610 if (CharByteWidth == 4)
1611 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1612 getByteLength());
1613 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1614 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1615 getByteLength());
1616 }
1617
1618 void outputString(raw_ostream &OS) const;
1619
1620 uint32_t getCodeUnit(size_t i) const {
1621 assert(i < Length && "out of bounds access");
1622 if (CharByteWidth == 1)
1623 return static_cast<unsigned char>(StrData.asChar[i]);
1624 if (CharByteWidth == 4)
1625 return StrData.asUInt32[i];
1626 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1627 return StrData.asUInt16[i];
1628 }
1629
1630 unsigned getByteLength() const { return CharByteWidth*Length; }
1631 unsigned getLength() const { return Length; }
1632 unsigned getCharByteWidth() const { return CharByteWidth; }
1633
1634 /// \brief Sets the string data to the given string data.
1635 void setString(const ASTContext &C, StringRef Str,
1636 StringKind Kind, bool IsPascal);
1637
1638 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1639
1640 bool isAscii() const { return Kind == Ascii; }
1641 bool isWide() const { return Kind == Wide; }
1642 bool isUTF8() const { return Kind == UTF8; }
1643 bool isUTF16() const { return Kind == UTF16; }
1644 bool isUTF32() const { return Kind == UTF32; }
1645 bool isPascal() const { return IsPascal; }
1646
1647 bool containsNonAsciiOrNull() const {
1648 StringRef Str = getString();
1649 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1650 if (!isASCII(Str[i]) || !Str[i])
1651 return true;
1652 return false;
1653 }
1654
1655 /// getNumConcatenated - Get the number of string literal tokens that were
1656 /// concatenated in translation phase #6 to form this string literal.
1657 unsigned getNumConcatenated() const { return NumConcatenated; }
1658
1659 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1660 assert(TokNum < NumConcatenated && "Invalid tok number");
1661 return TokLocs[TokNum];
1662 }
1663 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1664 assert(TokNum < NumConcatenated && "Invalid tok number");
1665 TokLocs[TokNum] = L;
1666 }
1667
1668 /// getLocationOfByte - Return a source location that points to the specified
1669 /// byte of this string literal.
1670 ///
1671 /// Strings are amazingly complex. They can be formed from multiple tokens
1672 /// and can have escape sequences in them in addition to the usual trigraph
1673 /// and escaped newline business. This routine handles this complexity.
1674 ///
1675 SourceLocation
1676 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1677 const LangOptions &Features, const TargetInfo &Target,
1678 unsigned *StartToken = nullptr,
1679 unsigned *StartTokenByteOffset = nullptr) const;
1680
1681 using tokloc_iterator = const SourceLocation *;
1682
1683 tokloc_iterator tokloc_begin() const { return TokLocs; }
1684 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1685
1686 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1687
1688 SourceLocation getLocEnd() const LLVM_READONLY {
1689 return TokLocs[NumConcatenated - 1];
1690 }
1691
1692 static bool classof(const Stmt *T) {
1693 return T->getStmtClass() == StringLiteralClass;
1694 }
1695
1696 // Iterators
1697 child_range children() {
1698 return child_range(child_iterator(), child_iterator());
1699 }
1700
1701 const_child_range children() const {
1702 return const_child_range(const_child_iterator(), const_child_iterator());
1703 }
1704};
1705
1706/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1707/// AST node is only formed if full location information is requested.
1708class ParenExpr : public Expr {
1709 SourceLocation L, R;
1710 Stmt *Val;
1711
1712public:
1713 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1714 : Expr(ParenExprClass, val->getType(),
1715 val->getValueKind(), val->getObjectKind(),
1716 val->isTypeDependent(), val->isValueDependent(),
1717 val->isInstantiationDependent(),
1718 val->containsUnexpandedParameterPack()),
1719 L(l), R(r), Val(val) {}
1720
1721 /// \brief Construct an empty parenthesized expression.
1722 explicit ParenExpr(EmptyShell Empty) : Expr(ParenExprClass, Empty) {}
1723
1724 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1725 Expr *getSubExpr() { return cast<Expr>(Val); }
1726 void setSubExpr(Expr *E) { Val = E; }
1727
1728 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1729 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1730
1731 /// \brief Get the location of the left parentheses '('.
1732 SourceLocation getLParen() const { return L; }
1733 void setLParen(SourceLocation Loc) { L = Loc; }
1734
1735 /// \brief Get the location of the right parentheses ')'.
1736 SourceLocation getRParen() const { return R; }
1737 void setRParen(SourceLocation Loc) { R = Loc; }
1738
1739 static bool classof(const Stmt *T) {
1740 return T->getStmtClass() == ParenExprClass;
1741 }
1742
1743 // Iterators
1744 child_range children() { return child_range(&Val, &Val+1); }
1745
1746 const_child_range children() const {
1747 return const_child_range(&Val, &Val + 1);
1748 }
1749};
1750
1751/// UnaryOperator - This represents the unary-expression's (except sizeof and
1752/// alignof), the postinc/postdec operators from postfix-expression, and various
1753/// extensions.
1754///
1755/// Notes on various nodes:
1756///
1757/// Real/Imag - These return the real/imag part of a complex operand. If
1758/// applied to a non-complex value, the former returns its operand and the
1759/// later returns zero in the type of the operand.
1760class UnaryOperator : public Expr {
1761public:
1762 using Opcode = UnaryOperatorKind;
1763
1764private:
1765 unsigned Opc : 5;
1766 SourceLocation Loc;
1767 Stmt *Val;
1768
1769public:
1770 UnaryOperator(Expr *input, Opcode opc, QualType type,
1771 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1772 : Expr(UnaryOperatorClass, type, VK, OK,
1773 input->isTypeDependent() || type->isDependentType(),
1774 input->isValueDependent(),
1775 (input->isInstantiationDependent() ||
1776 type->isInstantiationDependentType()),
1777 input->containsUnexpandedParameterPack()),
1778 Opc(opc), Loc(l), Val(input) {}
1779
1780 /// \brief Build an empty unary operator.
1781 explicit UnaryOperator(EmptyShell Empty)
1782 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) {}
1783
1784 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1785 void setOpcode(Opcode O) { Opc = O; }
1786
1787 Expr *getSubExpr() const { return cast<Expr>(Val); }
1788 void setSubExpr(Expr *E) { Val = E; }
1789
1790 /// getOperatorLoc - Return the location of the operator.
1791 SourceLocation getOperatorLoc() const { return Loc; }
1792 void setOperatorLoc(SourceLocation L) { Loc = L; }
1793
1794 /// isPostfix - Return true if this is a postfix operation, like x++.
1795 static bool isPostfix(Opcode Op) {
1796 return Op == UO_PostInc || Op == UO_PostDec;
1797 }
1798
1799 /// isPrefix - Return true if this is a prefix operation, like --x.
1800 static bool isPrefix(Opcode Op) {
1801 return Op == UO_PreInc || Op == UO_PreDec;
1802 }
1803
1804 bool isPrefix() const { return isPrefix(getOpcode()); }
1805 bool isPostfix() const { return isPostfix(getOpcode()); }
1806
1807 static bool isIncrementOp(Opcode Op) {
1808 return Op == UO_PreInc || Op == UO_PostInc;
1809 }
1810 bool isIncrementOp() const {
1811 return isIncrementOp(getOpcode());
1812 }
1813
1814 static bool isDecrementOp(Opcode Op) {
1815 return Op == UO_PreDec || Op == UO_PostDec;
1816 }
1817 bool isDecrementOp() const {
1818 return isDecrementOp(getOpcode());
1819 }
1820
1821 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1822 bool isIncrementDecrementOp() const {
1823 return isIncrementDecrementOp(getOpcode());
1824 }
1825
1826 static bool isArithmeticOp(Opcode Op) {
1827 return Op >= UO_Plus && Op <= UO_LNot;
1828 }
1829 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1830
1831 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1832 /// corresponds to, e.g. "sizeof" or "[pre]++"
1833 static StringRef getOpcodeStr(Opcode Op);
1834
1835 /// \brief Retrieve the unary opcode that corresponds to the given
1836 /// overloaded operator.
1837 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1838
1839 /// \brief Retrieve the overloaded operator kind that corresponds to
1840 /// the given unary opcode.
1841 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1842
1843 SourceLocation getLocStart() const LLVM_READONLY {
1844 return isPostfix() ? Val->getLocStart() : Loc;
1845 }
1846
1847 SourceLocation getLocEnd() const LLVM_READONLY {
1848 return isPostfix() ? Loc : Val->getLocEnd();
1849 }
1850
1851 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1852
1853 static bool classof(const Stmt *T) {
1854 return T->getStmtClass() == UnaryOperatorClass;
1855 }
1856
1857 // Iterators
1858 child_range children() { return child_range(&Val, &Val+1); }
1859
1860 const_child_range children() const {
1861 return const_child_range(&Val, &Val + 1);
1862 }
1863};
1864
1865/// Helper class for OffsetOfExpr.
1866
1867// __builtin_offsetof(type, identifier(.identifier|[expr])*)
1868class OffsetOfNode {
1869public:
1870 /// \brief The kind of offsetof node we have.
1871 enum Kind {
1872 /// \brief An index into an array.
1873 Array = 0x00,
1874
1875 /// \brief A field.
1876 Field = 0x01,
1877
1878 /// \brief A field in a dependent type, known only by its name.
1879 Identifier = 0x02,
1880
1881 /// \brief An implicit indirection through a C++ base class, when the
1882 /// field found is in a base class.
1883 Base = 0x03
1884 };
1885
1886private:
1887 enum { MaskBits = 2, Mask = 0x03 };
1888
1889 /// \brief The source range that covers this part of the designator.
1890 SourceRange Range;
1891
1892 /// \brief The data describing the designator, which comes in three
1893 /// different forms, depending on the lower two bits.
1894 /// - An unsigned index into the array of Expr*'s stored after this node
1895 /// in memory, for [constant-expression] designators.
1896 /// - A FieldDecl*, for references to a known field.
1897 /// - An IdentifierInfo*, for references to a field with a given name
1898 /// when the class type is dependent.
1899 /// - A CXXBaseSpecifier*, for references that look at a field in a
1900 /// base class.
1901 uintptr_t Data;
1902
1903public:
1904 /// \brief Create an offsetof node that refers to an array element.
1905 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1906 SourceLocation RBracketLoc)
1907 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1908
1909 /// \brief Create an offsetof node that refers to a field.
1910 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1911 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1912 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1913
1914 /// \brief Create an offsetof node that refers to an identifier.
1915 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1916 SourceLocation NameLoc)
1917 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1918 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1919
1920 /// \brief Create an offsetof node that refers into a C++ base class.
1921 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1922 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1923
1924 /// \brief Determine what kind of offsetof node this is.
1925 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1926
1927 /// \brief For an array element node, returns the index into the array
1928 /// of expressions.
1929 unsigned getArrayExprIndex() const {
1930 assert(getKind() == Array);
1931 return Data >> 2;
1932 }
1933
1934 /// \brief For a field offsetof node, returns the field.
1935 FieldDecl *getField() const {
1936 assert(getKind() == Field);
1937 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1938 }
1939
1940 /// \brief For a field or identifier offsetof node, returns the name of
1941 /// the field.
1942 IdentifierInfo *getFieldName() const;
1943
1944 /// \brief For a base class node, returns the base specifier.
1945 CXXBaseSpecifier *getBase() const {
1946 assert(getKind() == Base);
1947 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1948 }
1949
1950 /// \brief Retrieve the source range that covers this offsetof node.
1951 ///
1952 /// For an array element node, the source range contains the locations of
1953 /// the square brackets. For a field or identifier node, the source range
1954 /// contains the location of the period (if there is one) and the
1955 /// identifier.
1956 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1957 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1958 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1959};
1960
1961/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1962/// offsetof(record-type, member-designator). For example, given:
1963/// @code
1964/// struct S {
1965/// float f;
1966/// double d;
1967/// };
1968/// struct T {
1969/// int i;
1970/// struct S s[10];
1971/// };
1972/// @endcode
1973/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1974class OffsetOfExpr final
1975 : public Expr,
1976 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1977 SourceLocation OperatorLoc, RParenLoc;
1978
1979 // Base type;
1980 TypeSourceInfo *TSInfo = nullptr;
1981
1982 // Number of sub-components (i.e. instances of OffsetOfNode).
1983 unsigned NumComps;
1984
1985 // Number of sub-expressions (i.e. array subscript expressions).
1986 unsigned NumExprs;
1987
1988 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1989 return NumComps;
1990 }
1991
1992 OffsetOfExpr(const ASTContext &C, QualType type,
1993 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1994 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1995 SourceLocation RParenLoc);
1996
1997 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1998 : Expr(OffsetOfExprClass, EmptyShell()), NumComps(numComps),
1999 NumExprs(numExprs) {}
2000
2001public:
2002 friend TrailingObjects;
2003
2004 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2005 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2006 ArrayRef<OffsetOfNode> comps,
2007 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2008
2009 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2010 unsigned NumComps, unsigned NumExprs);
2011
2012 /// getOperatorLoc - Return the location of the operator.
2013 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2014 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2015
2016 /// \brief Return the location of the right parentheses.
2017 SourceLocation getRParenLoc() const { return RParenLoc; }
2018 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2019
2020 TypeSourceInfo *getTypeSourceInfo() const {
2021 return TSInfo;
2022 }
2023
2024 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2025 TSInfo = tsi;
2026 }
2027
2028 const OffsetOfNode &getComponent(unsigned Idx) const {
2029 assert(Idx < NumComps && "Subscript out of range");
2030 return getTrailingObjects<OffsetOfNode>()[Idx];
2031 }
2032
2033 void setComponent(unsigned Idx, OffsetOfNode ON) {
2034 assert(Idx < NumComps && "Subscript out of range");
2035 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2036 }
2037
2038 unsigned getNumComponents() const {
2039 return NumComps;
2040 }
2041
2042 Expr* getIndexExpr(unsigned Idx) {
2043 assert(Idx < NumExprs && "Subscript out of range");
2044 return getTrailingObjects<Expr *>()[Idx];
2045 }
2046
2047 const Expr *getIndexExpr(unsigned Idx) const {
2048 assert(Idx < NumExprs && "Subscript out of range");
2049 return getTrailingObjects<Expr *>()[Idx];
2050 }
2051
2052 void setIndexExpr(unsigned Idx, Expr* E) {
2053 assert(Idx < NumComps && "Subscript out of range");
2054 getTrailingObjects<Expr *>()[Idx] = E;
2055 }
2056
2057 unsigned getNumExpressions() const {
2058 return NumExprs;
2059 }
2060
2061 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
2062 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2063
2064 static bool classof(const Stmt *T) {
2065 return T->getStmtClass() == OffsetOfExprClass;
2066 }
2067
2068 // Iterators
2069 child_range children() {
2070 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2071 return child_range(begin, begin + NumExprs);
2072 }
2073
2074 const_child_range children() const {
2075 Stmt *const *begin =
2076 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2077 return const_child_range(begin, begin + NumExprs);
2078 }
2079};
2080
2081/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2082/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2083/// vec_step (OpenCL 1.1 6.11.12).
2084class UnaryExprOrTypeTraitExpr : public Expr {
2085 union {
2086 TypeSourceInfo *Ty;
2087 Stmt *Ex;
2088 } Argument;
2089 SourceLocation OpLoc, RParenLoc;
2090
2091public:
2092 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2093 QualType resultType, SourceLocation op,
2094 SourceLocation rp) :
2095 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2096 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2097 // Value-dependent if the argument is type-dependent.
2098 TInfo->getType()->isDependentType(),
2099 TInfo->getType()->isInstantiationDependentType(),
2100 TInfo->getType()->containsUnexpandedParameterPack()),
2101 OpLoc(op), RParenLoc(rp) {
2102 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2103 UnaryExprOrTypeTraitExprBits.IsType = true;
2104 Argument.Ty = TInfo;
2105 }
2106
2107 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2108 QualType resultType, SourceLocation op,
2109 SourceLocation rp);
2110
2111 /// \brief Construct an empty sizeof/alignof expression.
2112 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2113 : Expr(UnaryExprOrTypeTraitExprClass, Empty) {}
2114
2115 UnaryExprOrTypeTrait getKind() const {
2116 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2117 }
2118
2119 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2120
2121 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2122
2123 QualType getArgumentType() const {
2124 return getArgumentTypeInfo()->getType();
2125 }
2126
2127 TypeSourceInfo *getArgumentTypeInfo() const {
2128 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2129 return Argument.Ty;
2130 }
2131
2132 Expr *getArgumentExpr() {
2133 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2134 return static_cast<Expr*>(Argument.Ex);
2135 }
2136 const Expr *getArgumentExpr() const {
2137 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2138 }
2139
2140 void setArgument(Expr *E) {
2141 Argument.Ex = E;
2142 UnaryExprOrTypeTraitExprBits.IsType = false;
2143 }
2144 void setArgument(TypeSourceInfo *TInfo) {
2145 Argument.Ty = TInfo;
2146 UnaryExprOrTypeTraitExprBits.IsType = true;
2147 }
2148
2149 /// Gets the argument type, or the type of the argument expression, whichever
2150 /// is appropriate.
2151 QualType getTypeOfArgument() const {
2152 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2153 }
2154
2155 SourceLocation getOperatorLoc() const { return OpLoc; }
2156 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2157
2158 SourceLocation getRParenLoc() const { return RParenLoc; }
2159 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2160
2161 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2162 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2163
2164 static bool classof(const Stmt *T) {
2165 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2166 }
2167
2168 // Iterators
2169 child_range children();
2170 const_child_range children() const;
2171};
2172
2173//===----------------------------------------------------------------------===//
2174// Postfix Operators.
2175//===----------------------------------------------------------------------===//
2176
2177/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2178class ArraySubscriptExpr : public Expr {
2179 enum { LHS, RHS, END_EXPR=2 };
2180
2181 Stmt* SubExprs[END_EXPR];
2182 SourceLocation RBracketLoc;
2183
2184public:
2185 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2186 ExprValueKind VK, ExprObjectKind OK,
2187 SourceLocation rbracketloc)
2188 : Expr(ArraySubscriptExprClass, t, VK, OK,
2189 lhs->isTypeDependent() || rhs->isTypeDependent(),
2190 lhs->isValueDependent() || rhs->isValueDependent(),
2191 (lhs->isInstantiationDependent() ||
2192 rhs->isInstantiationDependent()),
2193 (lhs->containsUnexpandedParameterPack() ||
2194 rhs->containsUnexpandedParameterPack())),
2195 RBracketLoc(rbracketloc) {
2196 SubExprs[LHS] = lhs;
2197 SubExprs[RHS] = rhs;
2198 }
2199
2200 /// \brief Create an empty array subscript expression.
2201 explicit ArraySubscriptExpr(EmptyShell Shell)
2202 : Expr(ArraySubscriptExprClass, Shell) {}
2203
2204 /// An array access can be written A[4] or 4[A] (both are equivalent).
2205 /// - getBase() and getIdx() always present the normalized view: A[4].
2206 /// In this case getBase() returns "A" and getIdx() returns "4".
2207 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2208 /// 4[A] getLHS() returns "4".
2209 /// Note: Because vector element access is also written A[4] we must
2210 /// predicate the format conversion in getBase and getIdx only on the
2211 /// the type of the RHS, as it is possible for the LHS to be a vector of
2212 /// integer type
2213 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2214 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2215 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2216
2217 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2218 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2219 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2220
2221 Expr *getBase() {
2222 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2223 }
2224
2225 const Expr *getBase() const {
2226 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2227 }
2228
2229 Expr *getIdx() {
2230 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2231 }
2232
2233 const Expr *getIdx() const {
2234 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2235 }
2236
2237 SourceLocation getLocStart() const LLVM_READONLY {
2238 return getLHS()->getLocStart();
2239 }
2240
2241 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2242
2243 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2244 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2245
2246 SourceLocation getExprLoc() const LLVM_READONLY {
2247 return getBase()->getExprLoc();
2248 }
2249
2250 static bool classof(const Stmt *T) {
2251 return T->getStmtClass() == ArraySubscriptExprClass;
2252 }
2253
2254 // Iterators
2255 child_range children() {
2256 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2257 }
2258
2259 const_child_range children() const {
2260 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2261 }
2262};
2263
2264/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2265/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2266/// while its subclasses may represent alternative syntax that (semantically)
2267/// results in a function call. For example, CXXOperatorCallExpr is
2268/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2269/// "str1 + str2" to resolve to a function call.
2270class CallExpr : public Expr {
2271 enum { FN=0, PREARGS_START=1 };
2272
2273 Stmt **SubExprs = nullptr;
2274 unsigned NumArgs = 0;
2275 SourceLocation RParenLoc;
2276
2277 void updateDependenciesFromArg(Expr *Arg);
2278
2279protected:
2280 // These versions of the constructor are for derived classes.
2281 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2282 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2283 ExprValueKind VK, SourceLocation rparenloc);
2284 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2285 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2286 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2287 EmptyShell Empty);
2288
2289 Stmt *getPreArg(unsigned i) {
2290 assert(i < getNumPreArgs() && "Prearg access out of range!");
2291 return SubExprs[PREARGS_START+i];
2292 }
2293 const Stmt *getPreArg(unsigned i) const {
2294 assert(i < getNumPreArgs() && "Prearg access out of range!");
2295 return SubExprs[PREARGS_START+i];
2296 }
2297 void setPreArg(unsigned i, Stmt *PreArg) {
2298 assert(i < getNumPreArgs() && "Prearg access out of range!");
2299 SubExprs[PREARGS_START+i] = PreArg;
2300 }
2301
2302 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2303
2304public:
2305 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2306 ExprValueKind VK, SourceLocation rparenloc);
2307
2308 /// \brief Build an empty call expression.
2309 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2310
2311 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2312 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2313 void setCallee(Expr *F) { SubExprs[FN] = F; }
2314
2315 Decl *getCalleeDecl();
2316 const Decl *getCalleeDecl() const {
2317 return const_cast<CallExpr*>(this)->getCalleeDecl();
2318 }
2319
2320 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2321 FunctionDecl *getDirectCallee();
2322 const FunctionDecl *getDirectCallee() const {
2323 return const_cast<CallExpr*>(this)->getDirectCallee();
2324 }
2325
2326 /// getNumArgs - Return the number of actual arguments to this call.
2327 unsigned getNumArgs() const { return NumArgs; }
2328
2329 /// \brief Retrieve the call arguments.
2330 Expr **getArgs() {
2331 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2332 }
2333 const Expr *const *getArgs() const {
2334 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2335 PREARGS_START);
2336 }
2337
2338 /// getArg - Return the specified argument.
2339 Expr *getArg(unsigned Arg) {
2340 assert(Arg < NumArgs && "Arg access out of range!");
2341 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2342 }
2343 const Expr *getArg(unsigned Arg) const {
2344 assert(Arg < NumArgs && "Arg access out of range!");
2345 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2346 }
2347
2348 /// setArg - Set the specified argument.
2349 void setArg(unsigned Arg, Expr *ArgExpr) {
2350 assert(Arg < NumArgs && "Arg access out of range!");
2351 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2352 }
2353
2354 /// setNumArgs - This changes the number of arguments present in this call.
2355 /// Any orphaned expressions are deleted by this, and any new operands are set
2356 /// to null.
2357 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2358
2359 using arg_iterator = ExprIterator;
2360 using const_arg_iterator = ConstExprIterator;
2361 using arg_range = llvm::iterator_range<arg_iterator>;
2362 using arg_const_range = llvm::iterator_range<const_arg_iterator>;
2363
2364 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2365 arg_const_range arguments() const {
2366 return arg_const_range(arg_begin(), arg_end());
2367 }
2368
2369 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2370
2371 arg_iterator arg_end() {
2372 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2373 }
2374
2375 const_arg_iterator arg_begin() const {
2376 return SubExprs+PREARGS_START+getNumPreArgs();
2377 }
2378
2379 const_arg_iterator arg_end() const {
2380 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2381 }
2382
2383 /// This method provides fast access to all the subexpressions of
2384 /// a CallExpr without going through the slower virtual child_iterator
2385 /// interface. This provides efficient reverse iteration of the
2386 /// subexpressions. This is currently used for CFG construction.
2387 ArrayRef<Stmt*> getRawSubExprs() {
2388 return llvm::makeArrayRef(SubExprs,
2389 getNumPreArgs() + PREARGS_START + getNumArgs());
2390 }
2391
2392 /// getNumCommas - Return the number of commas that must have been present in
2393 /// this function call.
2394 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2395
2396 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2397 /// of the callee. If not, return 0.
2398 unsigned getBuiltinCallee() const;
2399
2400 /// \brief Returns \c true if this is a call to a builtin which does not
2401 /// evaluate side-effects within its arguments.
2402 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2403
2404 /// getCallReturnType - Get the return type of the call expr. This is not
2405 /// always the type of the expr itself, if the return type is a reference
2406 /// type.
2407 QualType getCallReturnType(const ASTContext &Ctx) const;
2408
2409 SourceLocation getRParenLoc() const { return RParenLoc; }
2410 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2411
2412 SourceLocation getLocStart() const LLVM_READONLY;
2413 SourceLocation getLocEnd() const LLVM_READONLY;
2414
2415 bool isCallToStdMove() const {
2416 const FunctionDecl* FD = getDirectCallee();
2417 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2418 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2419 }
2420
2421 static bool classof(const Stmt *T) {
2422 return T->getStmtClass() >= firstCallExprConstant &&
2423 T->getStmtClass() <= lastCallExprConstant;
2424 }
2425
2426 // Iterators
2427 child_range children() {
2428 return child_range(&SubExprs[0],
2429 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2430 }
2431
2432 const_child_range children() const {
2433 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2434 getNumPreArgs() + PREARGS_START);
2435 }
2436};
2437
2438/// Extra data stored in some MemberExpr objects.
2439struct MemberExprNameQualifier {
2440 /// \brief The nested-name-specifier that qualifies the name, including
2441 /// source-location information.
2442 NestedNameSpecifierLoc QualifierLoc;
2443
2444 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2445 /// name qualifiers.
2446 DeclAccessPair FoundDecl;
2447};
2448
2449/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2450///
2451class MemberExpr final
2452 : public Expr,
2453 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2454 ASTTemplateKWAndArgsInfo,
2455 TemplateArgumentLoc> {
2456 /// Base - the expression for the base pointer or structure references. In
2457 /// X.F, this is "X".
2458 Stmt *Base;
2459
2460 /// MemberDecl - This is the decl being referenced by the field/member name.
2461 /// In X.F, this is the decl referenced by F.
2462 ValueDecl *MemberDecl;
2463
2464 /// MemberDNLoc - Provides source/type location info for the
2465 /// declaration name embedded in MemberDecl.
2466 DeclarationNameLoc MemberDNLoc;
2467
2468 /// MemberLoc - This is the location of the member name.
2469 SourceLocation MemberLoc;
2470
2471 /// This is the location of the -> or . in the expression.
2472 SourceLocation OperatorLoc;
2473
2474 /// IsArrow - True if this is "X->F", false if this is "X.F".
2475 bool IsArrow : 1;
2476
2477 /// \brief True if this member expression used a nested-name-specifier to
2478 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2479 /// declaration. When true, a MemberExprNameQualifier
2480 /// structure is allocated immediately after the MemberExpr.
2481 bool HasQualifierOrFoundDecl : 1;
2482
2483 /// \brief True if this member expression specified a template keyword
2484 /// and/or a template argument list explicitly, e.g., x->f<int>,
2485 /// x->template f, x->template f<int>.
2486 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2487 /// TemplateArguments (if any) are present.
2488 bool HasTemplateKWAndArgsInfo : 1;
2489
2490 /// \brief True if this member expression refers to a method that
2491 /// was resolved from an overloaded set having size greater than 1.
2492 bool HadMultipleCandidates : 1;
2493
2494 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2495 return HasQualifierOrFoundDecl ? 1 : 0;
2496 }
2497
2498 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2499 return HasTemplateKWAndArgsInfo ? 1 : 0;
2500 }
2501
2502public:
2503 friend class ASTReader;
2504 friend class ASTStmtWriter;
2505 friend TrailingObjects;
2506
2507 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2508 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2509 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2510 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2511 base->isValueDependent(), base->isInstantiationDependent(),
2512 base->containsUnexpandedParameterPack()),
2513 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2514 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2515 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2516 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2517 assert(memberdecl->getDeclName() == NameInfo.getName());
2518 }
2519
2520 // NOTE: this constructor should be used only when it is known that
2521 // the member name can not provide additional syntactic info
2522 // (i.e., source locations for C++ operator names or type source info
2523 // for constructors, destructors and conversion operators).
2524 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2525 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2526 ExprValueKind VK, ExprObjectKind OK)
2527 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2528 base->isValueDependent(), base->isInstantiationDependent(),
2529 base->containsUnexpandedParameterPack()),
2530 Base(base), MemberDecl(memberdecl), MemberLoc(l),
2531 OperatorLoc(operatorloc), IsArrow(isarrow),
2532 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2533 HadMultipleCandidates(false) {}
2534
2535 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2536 SourceLocation OperatorLoc,
2537 NestedNameSpecifierLoc QualifierLoc,
2538 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2539 DeclAccessPair founddecl,
2540 DeclarationNameInfo MemberNameInfo,
2541 const TemplateArgumentListInfo *targs, QualType ty,
2542 ExprValueKind VK, ExprObjectKind OK);
2543
2544 void setBase(Expr *E) { Base = E; }
2545 Expr *getBase() const { return cast<Expr>(Base); }
2546
2547 /// \brief Retrieve the member declaration to which this expression refers.
2548 ///
2549 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2550 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2551 ValueDecl *getMemberDecl() const { return MemberDecl; }
2552 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2553
2554 /// \brief Retrieves the declaration found by lookup.
2555 DeclAccessPair getFoundDecl() const {
2556 if (!HasQualifierOrFoundDecl)
2557 return DeclAccessPair::make(getMemberDecl(),
2558 getMemberDecl()->getAccess());
2559 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2560 }
2561
2562 /// \brief Determines whether this member expression actually had
2563 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2564 /// x->Base::foo.
2565 bool hasQualifier() const { return getQualifier() != nullptr; }
2566
2567 /// \brief If the member name was qualified, retrieves the
2568 /// nested-name-specifier that precedes the member name, with source-location
2569 /// information.
2570 NestedNameSpecifierLoc getQualifierLoc() const {
2571 if (!HasQualifierOrFoundDecl)
2572 return NestedNameSpecifierLoc();
2573
2574 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2575 }
2576
2577 /// \brief If the member name was qualified, retrieves the
2578 /// nested-name-specifier that precedes the member name. Otherwise, returns
2579 /// NULL.
2580 NestedNameSpecifier *getQualifier() const {
2581 return getQualifierLoc().getNestedNameSpecifier();
2582 }
2583
2584 /// \brief Retrieve the location of the template keyword preceding
2585 /// the member name, if any.
2586 SourceLocation getTemplateKeywordLoc() const {
2587 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2588 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2589 }
2590
2591 /// \brief Retrieve the location of the left angle bracket starting the
2592 /// explicit template argument list following the member name, if any.
2593 SourceLocation getLAngleLoc() const {
2594 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2595 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2596 }
2597
2598 /// \brief Retrieve the location of the right angle bracket ending the
2599 /// explicit template argument list following the member name, if any.
2600 SourceLocation getRAngleLoc() const {
2601 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2602 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2603 }
2604
2605 /// Determines whether the member name was preceded by the template keyword.
2606 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2607
2608 /// \brief Determines whether the member name was followed by an
2609 /// explicit template argument list.
2610 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2611
2612 /// \brief Copies the template arguments (if present) into the given
2613 /// structure.
2614 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2615 if (hasExplicitTemplateArgs())
2616 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2617 getTrailingObjects<TemplateArgumentLoc>(), List);
2618 }
2619
2620 /// \brief Retrieve the template arguments provided as part of this
2621 /// template-id.
2622 const TemplateArgumentLoc *getTemplateArgs() const {
2623 if (!hasExplicitTemplateArgs())
2624 return nullptr;
2625
2626 return getTrailingObjects<TemplateArgumentLoc>();
2627 }
2628
2629 /// \brief Retrieve the number of template arguments provided as part of this
2630 /// template-id.
2631 unsigned getNumTemplateArgs() const {
2632 if (!hasExplicitTemplateArgs())
2633 return 0;
2634
2635 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2636 }
2637
2638 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2639 return {getTemplateArgs(), getNumTemplateArgs()};
2640 }
2641
2642 /// \brief Retrieve the member declaration name info.
2643 DeclarationNameInfo getMemberNameInfo() const {
2644 return DeclarationNameInfo(MemberDecl->getDeclName(),
2645 MemberLoc, MemberDNLoc);
2646 }
2647
2648 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2649
2650 bool isArrow() const { return IsArrow; }
2651 void setArrow(bool A) { IsArrow = A; }
2652
2653 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2654 /// location of 'F'.
2655 SourceLocation getMemberLoc() const { return MemberLoc; }
2656 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2657
2658 SourceLocation getLocStart() const LLVM_READONLY;
2659 SourceLocation getLocEnd() const LLVM_READONLY;
2660
2661 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2662
2663 /// \brief Determine whether the base of this explicit is implicit.
2664 bool isImplicitAccess() const {
2665 return getBase() && getBase()->isImplicitCXXThis();
2666 }
2667
2668 /// \brief Returns true if this member expression refers to a method that
2669 /// was resolved from an overloaded set having size greater than 1.
2670 bool hadMultipleCandidates() const {
2671 return HadMultipleCandidates;
2672 }
2673
2674 /// \brief Sets the flag telling whether this expression refers to
2675 /// a method that was resolved from an overloaded set having size
2676 /// greater than 1.
2677 void setHadMultipleCandidates(bool V = true) {
2678 HadMultipleCandidates = V;
2679 }
2680
2681 /// \brief Returns true if virtual dispatch is performed.
2682 /// If the member access is fully qualified, (i.e. X::f()), virtual
2683 /// dispatching is not performed. In -fapple-kext mode qualified
2684 /// calls to virtual method will still go through the vtable.
2685 bool performsVirtualDispatch(const LangOptions &LO) const {
2686 return LO.AppleKext || !hasQualifier();
2687 }
2688
2689 static bool classof(const Stmt *T) {
2690 return T->getStmtClass() == MemberExprClass;
2691 }
2692
2693 // Iterators
2694 child_range children() { return child_range(&Base, &Base+1); }
2695
2696 const_child_range children() const {
2697 return const_child_range(&Base, &Base + 1);
2698 }
2699};
2700
2701/// CompoundLiteralExpr - [C99 6.5.2.5]
2702class CompoundLiteralExpr : public Expr {
2703 /// LParenLoc - If non-null, this is the location of the left paren in a
2704 /// compound literal like "(int){4}". This can be null if this is a
2705 /// synthesized compound expression.
2706 SourceLocation LParenLoc;
2707
2708 /// The type as written. This can be an incomplete array type, in
2709 /// which case the actual expression type will be different.
2710 /// The int part of the pair stores whether this expr is file scope.
2711 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2712 Stmt *Init;
2713
2714public:
2715 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2716 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2717 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2718 tinfo->getType()->isDependentType(),
2719 init->isValueDependent(),
2720 (init->isInstantiationDependent() ||
2721 tinfo->getType()->isInstantiationDependentType()),
2722 init->containsUnexpandedParameterPack()),
2723 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2724
2725 /// \brief Construct an empty compound literal.
2726 explicit CompoundLiteralExpr(EmptyShell Empty)
2727 : Expr(CompoundLiteralExprClass, Empty) {}
2728
2729 const Expr *getInitializer() const { return cast<Expr>(Init); }
2730 Expr *getInitializer() { return cast<Expr>(Init); }
2731 void setInitializer(Expr *E) { Init = E; }
2732
2733 bool isFileScope() const { return TInfoAndScope.getInt(); }
2734 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2735
2736 SourceLocation getLParenLoc() const { return LParenLoc; }
2737 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2738
2739 TypeSourceInfo *getTypeSourceInfo() const {
2740 return TInfoAndScope.getPointer();
2741 }
2742
2743 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2744 TInfoAndScope.setPointer(tinfo);
2745 }
2746
2747 SourceLocation getLocStart() const LLVM_READONLY {
2748 // FIXME: Init should never be null.
2749 if (!Init)
2750 return SourceLocation();
2751 if (LParenLoc.isInvalid())
2752 return Init->getLocStart();
2753 return LParenLoc;
2754 }
2755
2756 SourceLocation getLocEnd() const LLVM_READONLY {
2757 // FIXME: Init should never be null.
2758 if (!Init)
2759 return SourceLocation();
2760 return Init->getLocEnd();
2761 }
2762
2763 static bool classof(const Stmt *T) {
2764 return T->getStmtClass() == CompoundLiteralExprClass;
2765 }
2766
2767 // Iterators
2768 child_range children() { return child_range(&Init, &Init+1); }
2769
2770 const_child_range children() const {
2771 return const_child_range(&Init, &Init + 1);
2772 }
2773};
2774
2775/// CastExpr - Base class for type casts, including both implicit
2776/// casts (ImplicitCastExpr) and explicit casts that have some
2777/// representation in the source code (ExplicitCastExpr's derived
2778/// classes).
2779class CastExpr : public Expr {
2780private:
2781 Stmt *Op;
2782
2783 bool CastConsistency() const;
2784
2785 const CXXBaseSpecifier * const *path_buffer() const {
2786 return const_cast<CastExpr*>(this)->path_buffer();
2787 }
2788
2789 CXXBaseSpecifier **path_buffer();
2790
2791 void setBasePathSize(unsigned basePathSize) {
2792 CastExprBits.BasePathSize = basePathSize;
2793 assert(CastExprBits.BasePathSize == basePathSize &&
2794 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2795 }
2796
2797protected:
2798 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2799 Expr *op, unsigned BasePathSize)
2800 : Expr(SC, ty, VK, OK_Ordinary,
2801 // Cast expressions are type-dependent if the type is
2802 // dependent (C++ [temp.dep.expr]p3).
2803 ty->isDependentType(),
2804 // Cast expressions are value-dependent if the type is
2805 // dependent or if the subexpression is value-dependent.
2806 ty->isDependentType() || (op && op->isValueDependent()),
2807 (ty->isInstantiationDependentType() ||
2808 (op && op->isInstantiationDependent())),
2809 // An implicit cast expression doesn't (lexically) contain an
2810 // unexpanded pack, even if its target type does.
2811 ((SC != ImplicitCastExprClass &&
2812 ty->containsUnexpandedParameterPack()) ||
2813 (op && op->containsUnexpandedParameterPack()))),
2814 Op(op) {
2815 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2816 CastExprBits.Kind = kind;
2817 setBasePathSize(BasePathSize);
2818 assert(CastConsistency());
2819 }
2820
2821 /// \brief Construct an empty cast.
2822 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2823 : Expr(SC, Empty) {
2824 setBasePathSize(BasePathSize);
2825 }
2826
2827public:
2828 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2829 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2830 const char *getCastKindName() const;
2831
2832 Expr *getSubExpr() { return cast<Expr>(Op); }
2833 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2834 void setSubExpr(Expr *E) { Op = E; }
2835
2836 /// \brief Retrieve the cast subexpression as it was written in the source
2837 /// code, looking through any implicit casts or other intermediate nodes
2838 /// introduced by semantic analysis.
2839 Expr *getSubExprAsWritten();
2840 const Expr *getSubExprAsWritten() const {
2841 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2842 }
2843
2844 using path_iterator = CXXBaseSpecifier **;
2845 using path_const_iterator = const CXXBaseSpecifier * const *;
2846
2847 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2848 unsigned path_size() const { return CastExprBits.BasePathSize; }
2849 path_iterator path_begin() { return path_buffer(); }
2850 path_iterator path_end() { return path_buffer() + path_size(); }
2851 path_const_iterator path_begin() const { return path_buffer(); }
2852 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2853
2854 const FieldDecl *getTargetUnionField() const {
2855 assert(getCastKind() == CK_ToUnion);
2856 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2857 }
2858
2859 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2860 QualType opType);
2861 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2862 QualType opType);
2863
2864 static bool classof(const Stmt *T) {
2865 return T->getStmtClass() >= firstCastExprConstant &&
2866 T->getStmtClass() <= lastCastExprConstant;
2867 }
2868
2869 // Iterators
2870 child_range children() { return child_range(&Op, &Op+1); }
2871 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2872};
2873
2874/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2875/// conversions, which have no direct representation in the original
2876/// source code. For example: converting T[]->T*, void f()->void
2877/// (*f)(), float->double, short->int, etc.
2878///
2879/// In C, implicit casts always produce rvalues. However, in C++, an
2880/// implicit cast whose result is being bound to a reference will be
2881/// an lvalue or xvalue. For example:
2882///
2883/// @code
2884/// class Base { };
2885/// class Derived : public Base { };
2886/// Derived &&ref();
2887/// void f(Derived d) {
2888/// Base& b = d; // initializer is an ImplicitCastExpr
2889/// // to an lvalue of type Base
2890/// Base&& r = ref(); // initializer is an ImplicitCastExpr
2891/// // to an xvalue of type Base
2892/// }
2893/// @endcode
2894class ImplicitCastExpr final
2895 : public CastExpr,
2896 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2897private:
2898 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2899 unsigned BasePathLength, ExprValueKind VK)
2900 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {}
2901
2902 /// \brief Construct an empty implicit cast.
2903 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2904 : CastExpr(ImplicitCastExprClass, Shell, PathSize) {}
2905
2906public:
2907 friend class CastExpr;
2908 friend TrailingObjects;
2909
2910 enum OnStack_t { OnStack };
2911
2912 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2913 ExprValueKind VK)
2914 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {}
2915
2916 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2917 CastKind Kind, Expr *Operand,
2918 const CXXCastPath *BasePath,
2919 ExprValueKind Cat);
2920
2921 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2922 unsigned PathSize);
2923
2924 SourceLocation getLocStart() const LLVM_READONLY {
2925 return getSubExpr()->getLocStart();
2926 }
2927
2928 SourceLocation getLocEnd() const LLVM_READONLY {
2929 return getSubExpr()->getLocEnd();
2930 }
2931
2932 static bool classof(const Stmt *T) {
2933 return T->getStmtClass() == ImplicitCastExprClass;
2934 }
2935};
2936
2937inline Expr *Expr::IgnoreImpCasts() {
2938 Expr *e = this;
2939 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2940 e = ice->getSubExpr();
2941 return e;
2942}
2943
2944/// ExplicitCastExpr - An explicit cast written in the source
2945/// code.
2946///
2947/// This class is effectively an abstract class, because it provides
2948/// the basic representation of an explicitly-written cast without
2949/// specifying which kind of cast (C cast, functional cast, static
2950/// cast, etc.) was written; specific derived classes represent the
2951/// particular style of cast and its location information.
2952///
2953/// Unlike implicit casts, explicit cast nodes have two different
2954/// types: the type that was written into the source code, and the
2955/// actual type of the expression as determined by semantic
2956/// analysis. These types may differ slightly. For example, in C++ one
2957/// can cast to a reference type, which indicates that the resulting
2958/// expression will be an lvalue or xvalue. The reference type, however,
2959/// will not be used as the type of the expression.
2960class ExplicitCastExpr : public CastExpr {
2961 /// TInfo - Source type info for the (written) type
2962 /// this expression is casting to.
2963 TypeSourceInfo *TInfo;
2964
2965protected:
2966 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2967 CastKind kind, Expr *op, unsigned PathSize,
2968 TypeSourceInfo *writtenTy)
2969 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2970
2971 /// \brief Construct an empty explicit cast.
2972 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2973 : CastExpr(SC, Shell, PathSize) {}
2974
2975public:
2976 /// getTypeInfoAsWritten - Returns the type source info for the type
2977 /// that this expression is casting to.
2978 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2979 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2980
2981 /// getTypeAsWritten - Returns the type that this expression is
2982 /// casting to, as written in the source code.
2983 QualType getTypeAsWritten() const { return TInfo->getType(); }
2984
2985 static bool classof(const Stmt *T) {
2986 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2987 T->getStmtClass() <= lastExplicitCastExprConstant;
2988 }
2989};
2990
2991/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2992/// cast in C++ (C++ [expr.cast]), which uses the syntax
2993/// (Type)expr. For example: @c (int)f.
2994class CStyleCastExpr final
2995 : public ExplicitCastExpr,
2996 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2997 // the location of the left paren
2998 SourceLocation LPLoc;
2999
3000 // the location of the right paren
3001 SourceLocation RPLoc;
3002
3003 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3004 unsigned PathSize, TypeSourceInfo *writtenTy,
3005 SourceLocation l, SourceLocation r)
3006 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3007 writtenTy), LPLoc(l), RPLoc(r) {}
3008
3009 /// \brief Construct an empty C-style explicit cast.
3010 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3011 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) {}
3012
3013public:
3014 friend class CastExpr;
3015 friend TrailingObjects;
3016
3017 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3018 ExprValueKind VK, CastKind K,
3019 Expr *Op, const CXXCastPath *BasePath,
3020 TypeSourceInfo *WrittenTy, SourceLocation L,
3021 SourceLocation R);
3022
3023 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3024 unsigned PathSize);
3025
3026 SourceLocation getLParenLoc() const { return LPLoc; }
3027 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3028
3029 SourceLocation getRParenLoc() const { return RPLoc; }
3030 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3031
3032 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
3033
3034 SourceLocation getLocEnd() const LLVM_READONLY {
3035 return getSubExpr()->getLocEnd();
3036 }
3037
3038 static bool classof(const Stmt *T) {
3039 return T->getStmtClass() == CStyleCastExprClass;
3040 }
3041};
3042
3043/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
3044///
3045/// This expression node kind describes a builtin binary operation,
3046/// such as "x + y" for integer values "x" and "y". The operands will
3047/// already have been converted to appropriate types (e.g., by
3048/// performing promotions or conversions).
3049///
3050/// In C++, where operators may be overloaded, a different kind of
3051/// expression node (CXXOperatorCallExpr) is used to express the
3052/// invocation of an overloaded operator with operator syntax. Within
3053/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3054/// used to store an expression "x + y" depends on the subexpressions
3055/// for x and y. If neither x or y is type-dependent, and the "+"
3056/// operator resolves to a built-in operation, BinaryOperator will be
3057/// used to express the computation (x and y may still be
3058/// value-dependent). If either x or y is type-dependent, or if the
3059/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3060/// be used to express the computation.
3061class BinaryOperator : public Expr {
3062public:
3063 using Opcode = BinaryOperatorKind;
3064
3065private:
3066 unsigned Opc : 6;
3067
3068 // This is only meaningful for operations on floating point types and 0
3069 // otherwise.
3070 unsigned FPFeatures : 2;
3071
3072 SourceLocation OpLoc;
3073
3074 enum { LHS, RHS, END_EXPR };
3075 Stmt* SubExprs[END_EXPR];
3076
3077public:
3078 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3079 ExprValueKind VK, ExprObjectKind OK,
3080 SourceLocation opLoc, FPOptions FPFeatures)
3081 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3082 lhs->isTypeDependent() || rhs->isTypeDependent(),
3083 lhs->isValueDependent() || rhs->isValueDependent(),
3084 (lhs->isInstantiationDependent() ||
3085 rhs->isInstantiationDependent()),
3086 (lhs->containsUnexpandedParameterPack() ||
3087 rhs->containsUnexpandedParameterPack())),
3088 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3089 SubExprs[LHS] = lhs;
3090 SubExprs[RHS] = rhs;
3091 assert(!isCompoundAssignmentOp() &&
3092 "Use CompoundAssignOperator for compound assignments");
3093 }
3094
3095 /// \brief Construct an empty binary operator.
3096 explicit BinaryOperator(EmptyShell Empty)
3097 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) {}
3098
3099 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3100 SourceLocation getOperatorLoc() const { return OpLoc; }
3101 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3102
3103 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3104 void setOpcode(Opcode O) { Opc = O; }
3105
3106 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3107 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3108 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3109 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3110
3111 SourceLocation getLocStart() const LLVM_READONLY {
3112 return getLHS()->getLocStart();
3113 }
3114
3115 SourceLocation getLocEnd() const LLVM_READONLY {
3116 return getRHS()->getLocEnd();
3117 }
3118
3119 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3120 /// corresponds to, e.g. "<<=".
3121 static StringRef getOpcodeStr(Opcode Op);
3122
3123 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3124
3125 /// \brief Retrieve the binary opcode that corresponds to the given
3126 /// overloaded operator.
3127 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3128
3129 /// \brief Retrieve the overloaded operator kind that corresponds to
3130 /// the given binary opcode.
3131 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3132
3133 /// predicates to categorize the respective opcodes.
3134 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3135 static bool isMultiplicativeOp(Opcode Opc) {
3136 return Opc >= BO_Mul && Opc <= BO_Rem;
3137 }
3138 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3139 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3140 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3141 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3142 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3143
3144 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3145 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3146
3147 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3148 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3149
3150 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3151 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3152
3153 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3154 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3155
3156 static Opcode negateComparisonOp(Opcode Opc) {
3157 switch (Opc) {
3158 default:
3159 llvm_unreachable("Not a comparsion operator.");
3160 case BO_LT: return BO_GE;
3161 case BO_GT: return BO_LE;
3162 case BO_LE: return BO_GT;
3163 case BO_GE: return BO_LT;
3164 case BO_EQ: return BO_NE;
3165 case BO_NE: return BO_EQ;
3166 }
3167 }
3168
3169 static Opcode reverseComparisonOp(Opcode Opc) {
3170 switch (Opc) {
3171 default:
3172 llvm_unreachable("Not a comparsion operator.");
3173 case BO_LT: return BO_GT;
3174 case BO_GT: return BO_LT;
3175 case BO_LE: return BO_GE;
3176 case BO_GE: return BO_LE;
3177 case BO_EQ:
3178 case BO_NE:
3179 return Opc;
3180 }
3181 }
3182
3183 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3184 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3185
3186 static bool isAssignmentOp(Opcode Opc) {
3187 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3188 }
3189 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3190
3191 static bool isCompoundAssignmentOp(Opcode Opc) {
3192 return Opc > BO_Assign && Opc <= BO_OrAssign;
3193 }
3194 bool isCompoundAssignmentOp() const {
3195 return isCompoundAssignmentOp(getOpcode());
3196 }
3197
3198 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3199 assert(isCompoundAssignmentOp(Opc));
3200 if (Opc >= BO_AndAssign)
3201 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3202 else
3203 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3204 }
3205
3206 static bool isShiftAssignOp(Opcode Opc) {
3207 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3208 }
3209 bool isShiftAssignOp() const {
3210 return isShiftAssignOp(getOpcode());
3211 }
3212
3213 // Return true if a binary operator using the specified opcode and operands
3214 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3215 // integer to a pointer.
3216 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3217 Expr *LHS, Expr *RHS);
3218
3219 static bool classof(const Stmt *S) {
3220 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3221 S->getStmtClass() <= lastBinaryOperatorConstant;
3222 }
3223
3224 // Iterators
3225 child_range children() {
3226 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3227 }
3228
3229 const_child_range children() const {
3230 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3231 }
3232
3233 // Set the FP contractability status of this operator. Only meaningful for
3234 // operations on floating point types.
3235 void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3236
3237 FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3238
3239 // Get the FP contractability status of this operator. Only meaningful for
3240 // operations on floating point types.
3241 bool isFPContractableWithinStatement() const {
3242 return FPOptions(FPFeatures).allowFPContractWithinStatement();
3243 }
3244
3245protected:
3246 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3247 ExprValueKind VK, ExprObjectKind OK,
3248 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3249 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3250 lhs->isTypeDependent() || rhs->isTypeDependent(),
3251 lhs->isValueDependent() || rhs->isValueDependent(),
3252 (lhs->isInstantiationDependent() ||
3253 rhs->isInstantiationDependent()),
3254 (lhs->containsUnexpandedParameterPack() ||
3255 rhs->containsUnexpandedParameterPack())),
3256 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3257 SubExprs[LHS] = lhs;
3258 SubExprs[RHS] = rhs;
3259 }
3260
3261 BinaryOperator(StmtClass SC, EmptyShell Empty)
3262 : Expr(SC, Empty), Opc(BO_MulAssign) {}
3263};
3264
3265/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3266/// track of the type the operation is performed in. Due to the semantics of
3267/// these operators, the operands are promoted, the arithmetic performed, an
3268/// implicit conversion back to the result type done, then the assignment takes
3269/// place. This captures the intermediate type which the computation is done
3270/// in.
3271class CompoundAssignOperator : public BinaryOperator {
3272 QualType ComputationLHSType;
3273 QualType ComputationResultType;
3274
3275public:
3276 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3277 ExprValueKind VK, ExprObjectKind OK,
3278 QualType CompLHSType, QualType CompResultType,
3279 SourceLocation OpLoc, FPOptions FPFeatures)
3280 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3281 true),
3282 ComputationLHSType(CompLHSType),
3283 ComputationResultType(CompResultType) {
3284 assert(isCompoundAssignmentOp() &&
3285 "Only should be used for compound assignments");
3286 }
3287
3288 /// \brief Build an empty compound assignment operator expression.
3289 explicit CompoundAssignOperator(EmptyShell Empty)
3290 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
3291
3292 // The two computation types are the type the LHS is converted
3293 // to for the computation and the type of the result; the two are
3294 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3295 QualType getComputationLHSType() const { return ComputationLHSType; }
3296 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3297
3298 QualType getComputationResultType() const { return ComputationResultType; }
3299 void setComputationResultType(QualType T) { ComputationResultType = T; }
3300
3301 static bool classof(const Stmt *S) {
3302 return S->getStmtClass() == CompoundAssignOperatorClass;
3303 }
3304};
3305
3306/// AbstractConditionalOperator - An abstract base class for
3307/// ConditionalOperator and BinaryConditionalOperator.
3308class AbstractConditionalOperator : public Expr {
3309 friend class ASTStmtReader;
3310
3311 SourceLocation QuestionLoc, ColonLoc;
3312
3313protected:
3314 AbstractConditionalOperator(StmtClass SC, QualType T,
3315 ExprValueKind VK, ExprObjectKind OK,
3316 bool TD, bool VD, bool ID,
3317 bool ContainsUnexpandedParameterPack,
3318 SourceLocation qloc,
3319 SourceLocation cloc)
3320 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3321 QuestionLoc(qloc), ColonLoc(cloc) {}
3322
3323 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3324 : Expr(SC, Empty) {}
3325
3326public:
3327 // getCond - Return the expression representing the condition for
3328 // the ?: operator.
3329 Expr *getCond() const;
3330
3331 // getTrueExpr - Return the subexpression representing the value of
3332 // the expression if the condition evaluates to true.
3333 Expr *getTrueExpr() const;
3334
3335 // getFalseExpr - Return the subexpression representing the value of
3336 // the expression if the condition evaluates to false. This is
3337 // the same as getRHS.
3338 Expr *getFalseExpr() const;
3339
3340 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3341 SourceLocation getColonLoc() const { return ColonLoc; }
3342
3343 static bool classof(const Stmt *T) {
3344 return T->getStmtClass() == ConditionalOperatorClass ||
3345 T->getStmtClass() == BinaryConditionalOperatorClass;
3346 }
3347};
3348
3349/// ConditionalOperator - The ?: ternary operator. The GNU "missing
3350/// middle" extension is a BinaryConditionalOperator.
3351class ConditionalOperator : public AbstractConditionalOperator {
3352 friend class ASTStmtReader;
3353
3354 enum { COND, LHS, RHS, END_EXPR };
3355
3356 // Left/Middle/Right hand sides.
3357 Stmt* SubExprs[END_EXPR];
3358
3359public:
3360 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3361 SourceLocation CLoc, Expr *rhs,
3362 QualType t, ExprValueKind VK, ExprObjectKind OK)
3363 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3364 // FIXME: the type of the conditional operator doesn't
3365 // depend on the type of the conditional, but the standard
3366 // seems to imply that it could. File a bug!
3367 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3368 (cond->isValueDependent() || lhs->isValueDependent() ||
3369 rhs->isValueDependent()),
3370 (cond->isInstantiationDependent() ||
3371 lhs->isInstantiationDependent() ||
3372 rhs->isInstantiationDependent()),
3373 (cond->containsUnexpandedParameterPack() ||
3374 lhs->containsUnexpandedParameterPack() ||
3375 rhs->containsUnexpandedParameterPack()),
3376 QLoc, CLoc) {
3377 SubExprs[COND] = cond;
3378 SubExprs[LHS] = lhs;
3379 SubExprs[RHS] = rhs;
3380 }
3381
3382 /// \brief Build an empty conditional operator.
3383 explicit ConditionalOperator(EmptyShell Empty)
3384 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) {}
3385
3386 // getCond - Return the expression representing the condition for
3387 // the ?: operator.
3388 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3389
3390 // getTrueExpr - Return the subexpression representing the value of
3391 // the expression if the condition evaluates to true.
3392 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3393
3394 // getFalseExpr - Return the subexpression representing the value of
3395 // the expression if the condition evaluates to false. This is
3396 // the same as getRHS.
3397 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3398
3399 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3400 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3401
3402 SourceLocation getLocStart() const LLVM_READONLY {
3403 return getCond()->getLocStart();
3404 }
3405
3406 SourceLocation getLocEnd() const LLVM_READONLY {
3407 return getRHS()->getLocEnd();
3408 }
3409
3410 static bool classof(const Stmt *T) {
3411 return T->getStmtClass() == ConditionalOperatorClass;
3412 }
3413
3414 // Iterators
3415 child_range children() {
3416 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3417 }
3418
3419 const_child_range children() const {
3420 return const_child_range(