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