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