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