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