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