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#include "llvm/Support/TrailingObjects.h"
36
37namespace clang {
38 class APValue;
39 class ASTContext;
40 class BlockDecl;
41 class CXXBaseSpecifier;
42 class CXXMemberCallExpr;
43 class CXXOperatorCallExpr;
44 class CastExpr;
45 class Decl;
46 class IdentifierInfo;
47 class MaterializeTemporaryExpr;
48 class NamedDecl;
49 class ObjCPropertyRefExpr;
50 class OpaqueValueExpr;
51 class ParmVarDecl;
52 class StringLiteral;
53 class TargetInfo;
54 class ValueDecl;
55
56/// A simple array of base specifiers.
57typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
58
59/// An adjustment to be made to the temporary created when emitting a
60/// reference binding, which accesses a particular subobject of that temporary.
61struct SubobjectAdjustment {
62 enum {
63 DerivedToBaseAdjustment,
64 FieldAdjustment,
65 MemberPointerAdjustment
66 } Kind;
67
68 struct DTB {
69 const CastExpr *BasePath;
70 const CXXRecordDecl *DerivedClass;
71 };
72
73 struct P {
74 const MemberPointerType *MPT;
75 Expr *RHS;
76 };
77
78 union {
79 struct DTB DerivedToBase;
80 FieldDecl *Field;
81 struct P Ptr;
82 };
83
84 SubobjectAdjustment(const CastExpr *BasePath,
85 const CXXRecordDecl *DerivedClass)
86 : Kind(DerivedToBaseAdjustment) {
87 DerivedToBase.BasePath = BasePath;
88 DerivedToBase.DerivedClass = DerivedClass;
89 }
90
91 SubobjectAdjustment(FieldDecl *Field)
92 : Kind(FieldAdjustment) {
93 this->Field = Field;
94 }
95
96 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
97 : Kind(MemberPointerAdjustment) {
98 this->Ptr.MPT = MPT;
99 this->Ptr.RHS = RHS;
100 }
101};
102
103/// This represents one expression. Note that Expr's are subclasses of Stmt.
104/// This allows an expression to be transparently used any place a Stmt is
105/// required.
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 /// 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 /// 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 /// Set whether this expression is type-dependent or not.
170 void setTypeDependent(bool TD) {
171 ExprBits.TypeDependent = TD;
172 }
173
174 /// 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 /// Set whether this expression is instantiation-dependent or not.
196 void setInstantiationDependent(bool ID) {
197 ExprBits.InstantiationDependent = ID;
198 }
199
200 /// 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 /// 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 /// The return type of classify(). Represents the C++11 expression
301 /// taxonomy.
302 class Classification {
303 public:
304 /// 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 /// 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 /// Create a simple, modifiably lvalue
360 static Classification makeSimpleLValue() {
361 return Classification(CL_LValue, CM_Modifiable);
362 }
363
364 };
365 /// 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 /// 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 /// 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 /// 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 /// 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 /// Check if this expression is the ObjC 'self' implicit parameter.
462 bool isObjCSelfExpr() const;
463
464 /// Returns whether this expression refers to a vector element.
465 bool refersToVectorElement() const;
466
467 /// Returns whether this expression refers to a global register
468 /// variable.
469 bool refersToGlobalRegisterVar() const;
470
471 /// Returns whether this expression has a placeholder type.
472 bool hasPlaceholderType() const {
473 return getType()->isPlaceholderType();
474 }
475
476 /// 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 /// 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 /// 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 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 /// 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(
636 const ASTContext &Ctx,
637 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
638
639 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
640 const ASTContext &Ctx,
641 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
642
643 void EvaluateForOverflow(const ASTContext &Ctx) const;
644
645 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
646 /// lvalue with link time known address, with no side-effects.
647 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
648
649 /// EvaluateAsInitializer - Evaluate an expression as if it were the
650 /// initializer of the given declaration. Returns true if the initializer
651 /// can be folded to a constant, and produces any relevant notes. In C++11,
652 /// notes will be produced if the expression is not a constant expression.
653 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
654 const VarDecl *VD,
655 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
656
657 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
658 /// of a call to the given function with the given arguments, inside an
659 /// unevaluated context. Returns true if the expression could be folded to a
660 /// constant.
661 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
662 const FunctionDecl *Callee,
663 ArrayRef<const Expr*> Args,
664 const Expr *This = nullptr) const;
665
666 /// Indicates how the constant expression will be used.
667 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
668
669 /// Evaluate an expression that is required to be a constant expression.
670 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
671 const ASTContext &Ctx) const;
672
673 /// If the current Expr is a pointer, this will try to statically
674 /// determine the number of bytes available where the pointer is pointing.
675 /// Returns true if all of the above holds and we were able to figure out the
676 /// size, false otherwise.
677 ///
678 /// \param Type - How to evaluate the size of the Expr, as defined by the
679 /// "type" parameter of __builtin_object_size
680 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
681 unsigned Type) const;
682
683 /// Enumeration used to describe the kind of Null pointer constant
684 /// returned from \c isNullPointerConstant().
685 enum NullPointerConstantKind {
686 /// Expression is not a Null pointer constant.
687 NPCK_NotNull = 0,
688
689 /// Expression is a Null pointer constant built from a zero integer
690 /// expression that is not a simple, possibly parenthesized, zero literal.
691 /// C++ Core Issue 903 will classify these expressions as "not pointers"
692 /// once it is adopted.
693 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
694 NPCK_ZeroExpression,
695
696 /// Expression is a Null pointer constant built from a literal zero.
697 NPCK_ZeroLiteral,
698
699 /// Expression is a C++11 nullptr.
700 NPCK_CXX11_nullptr,
701
702 /// Expression is a GNU-style __null constant.
703 NPCK_GNUNull
704 };
705
706 /// Enumeration used to describe how \c isNullPointerConstant()
707 /// should cope with value-dependent expressions.
708 enum NullPointerConstantValueDependence {
709 /// Specifies that the expression should never be value-dependent.
710 NPC_NeverValueDependent = 0,
711
712 /// Specifies that a value-dependent expression of integral or
713 /// dependent type should be considered a null pointer constant.
714 NPC_ValueDependentIsNull,
715
716 /// Specifies that a value-dependent expression should be considered
717 /// to never be a null pointer constant.
718 NPC_ValueDependentIsNotNull
719 };
720
721 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
722 /// a Null pointer constant. The return value can further distinguish the
723 /// kind of NULL pointer constant that was detected.
724 NullPointerConstantKind isNullPointerConstant(
725 ASTContext &Ctx,
726 NullPointerConstantValueDependence NPC) const;
727
728 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
729 /// write barrier.
730 bool isOBJCGCCandidate(ASTContext &Ctx) const;
731
732 /// Returns true if this expression is a bound member function.
733 bool isBoundMemberFunction(ASTContext &Ctx) const;
734
735 /// Given an expression of bound-member type, find the type
736 /// of the member. Returns null if this is an *overloaded* bound
737 /// member expression.
738 static QualType findBoundMemberType(const Expr *expr);
739
740 /// IgnoreImpCasts - Skip past any implicit casts which might
741 /// surround this expression. Only skips ImplicitCastExprs.
742 Expr *IgnoreImpCasts() LLVM_READONLY;
743
744 /// IgnoreImplicit - Skip past any implicit AST nodes which might
745 /// surround this expression.
746 Expr *IgnoreImplicit() LLVM_READONLY {
747 return cast<Expr>(Stmt::IgnoreImplicit());
748 }
749
750 const Expr *IgnoreImplicit() const LLVM_READONLY {
751 return const_cast<Expr*>(this)->IgnoreImplicit();
752 }
753
754 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
755 /// its subexpression. If that subexpression is also a ParenExpr,
756 /// then this method recursively returns its subexpression, and so forth.
757 /// Otherwise, the method returns the current Expr.
758 Expr *IgnoreParens() LLVM_READONLY;
759
760 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
761 /// or CastExprs, returning their operand.
762 Expr *IgnoreParenCasts() LLVM_READONLY;
763
764 /// Ignore casts. Strip off any CastExprs, returning their operand.
765 Expr *IgnoreCasts() LLVM_READONLY;
766
767 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
768 /// any ParenExpr or ImplicitCastExprs, returning their operand.
769 Expr *IgnoreParenImpCasts() LLVM_READONLY;
770
771 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
772 /// call to a conversion operator, return the argument.
773 Expr *IgnoreConversionOperator() LLVM_READONLY;
774
775 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
776 return const_cast<Expr*>(this)->IgnoreConversionOperator();
777 }
778
779 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
780 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
781 }
782
783 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
784 /// CastExprs that represent lvalue casts, returning their operand.
785 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
786
787 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
788 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
789 }
790
791 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
792 /// value (including ptr->int casts of the same size). Strip off any
793 /// ParenExpr or CastExprs, returning their operand.
794 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
795
796 /// Ignore parentheses and derived-to-base casts.
797 Expr *ignoreParenBaseCasts() LLVM_READONLY;
798
799 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
800 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
801 }
802
803 /// Determine whether this expression is a default function argument.
804 ///
805 /// Default arguments are implicitly generated in the abstract syntax tree
806 /// by semantic analysis for function calls, object constructions, etc. in
807 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
808 /// this routine also looks through any implicit casts to determine whether
809 /// the expression is a default argument.
810 bool isDefaultArgument() const;
811
812 /// Determine whether the result of this expression is a
813 /// temporary object of the given class type.
814 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
815
816 /// Whether this expression is an implicit reference to 'this' in C++.
817 bool isImplicitCXXThis() const;
818
819 const Expr *IgnoreImpCasts() const LLVM_READONLY {
820 return const_cast<Expr*>(this)->IgnoreImpCasts();
821 }
822 const Expr *IgnoreParens() const LLVM_READONLY {
823 return const_cast<Expr*>(this)->IgnoreParens();
824 }
825 const Expr *IgnoreParenCasts() const LLVM_READONLY {
826 return const_cast<Expr*>(this)->IgnoreParenCasts();
827 }
828 /// Strip off casts, but keep parentheses.
829 const Expr *IgnoreCasts() const LLVM_READONLY {
830 return const_cast<Expr*>(this)->IgnoreCasts();
831 }
832
833 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
834 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
835 }
836
837 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
838
839 /// For an expression of class type or pointer to class type,
840 /// return the most derived class decl the expression is known to refer to.
841 ///
842 /// If this expression is a cast, this method looks through it to find the
843 /// most derived decl that can be inferred from the expression.
844 /// This is valid because derived-to-base conversions have undefined
845 /// behavior if the object isn't dynamically of the derived type.
846 const CXXRecordDecl *getBestDynamicClassType() const;
847
848 /// Get the inner expression that determines the best dynamic class.
849 /// If this is a prvalue, we guarantee that it is of the most-derived type
850 /// for the object itself.
851 const Expr *getBestDynamicClassTypeExpr() const;
852
853 /// Walk outwards from an expression we want to bind a reference to and
854 /// find the expression whose lifetime needs to be extended. Record
855 /// the LHSs of comma expressions and adjustments needed along the path.
856 const Expr *skipRValueSubobjectAdjustments(
857 SmallVectorImpl<const Expr *> &CommaLHS,
858 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
859 const Expr *skipRValueSubobjectAdjustments() const {
860 SmallVector<const Expr *, 8> CommaLHSs;
861 SmallVector<SubobjectAdjustment, 8> Adjustments;
862 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
863 }
864
865 static bool classof(const Stmt *T) {
866 return T->getStmtClass() >= firstExprConstant &&
867 T->getStmtClass() <= lastExprConstant;
868 }
869};
870
871//===----------------------------------------------------------------------===//
872// Wrapper Expressions.
873//===----------------------------------------------------------------------===//
874
875/// FullExpr - Represents a "full-expression" node.
876class FullExpr : public Expr {
877protected:
878 Stmt *SubExpr;
879
880 FullExpr(StmtClass SC, Expr *subexpr)
881 : Expr(SC, subexpr->getType(),
882 subexpr->getValueKind(), subexpr->getObjectKind(),
883 subexpr->isTypeDependent(), subexpr->isValueDependent(),
884 subexpr->isInstantiationDependent(),
885 subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {}
886 FullExpr(StmtClass SC, EmptyShell Empty)
887 : Expr(SC, Empty) {}
888public:
889 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
890 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
891
892 /// As with any mutator of the AST, be very careful when modifying an
893 /// existing AST to preserve its invariants.
894 void setSubExpr(Expr *E) { SubExpr = E; }
895
896 static bool classof(const Stmt *T) {
897 return T->getStmtClass() >= firstFullExprConstant &&
898 T->getStmtClass() <= lastFullExprConstant;
899 }
900};
901
902/// ConstantExpr - An expression that occurs in a constant context.
903class ConstantExpr : public FullExpr {
904public:
905 ConstantExpr(Expr *subexpr)
906 : FullExpr(ConstantExprClass, subexpr) {}
907
908 /// Build an empty constant expression wrapper.
909 explicit ConstantExpr(EmptyShell Empty)
910 : FullExpr(ConstantExprClass, Empty) {}
911
912 SourceLocation getBeginLoc() const LLVM_READONLY {
913 return SubExpr->getBeginLoc();
914 }
915 SourceLocation getEndLoc() const LLVM_READONLY {
916 return SubExpr->getEndLoc();
917 }
918
919 static bool classof(const Stmt *T) {
920 return T->getStmtClass() == ConstantExprClass;
921 }
922
923 // Iterators
924 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
925 const_child_range children() const {
926 return const_child_range(&SubExpr, &SubExpr + 1);
927 }
928};
929
930//===----------------------------------------------------------------------===//
931// Primary Expressions.
932//===----------------------------------------------------------------------===//
933
934/// OpaqueValueExpr - An expression referring to an opaque object of a
935/// fixed type and value class. These don't correspond to concrete
936/// syntax; instead they're used to express operations (usually copy
937/// operations) on values whose source is generally obvious from
938/// context.
939class OpaqueValueExpr : public Expr {
940 friend class ASTStmtReader;
941 Expr *SourceExpr;
942 SourceLocation Loc;
943
944public:
945 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
946 ExprObjectKind OK = OK_Ordinary,
947 Expr *SourceExpr = nullptr)
948 : Expr(OpaqueValueExprClass, T, VK, OK,
949 T->isDependentType() ||
950 (SourceExpr && SourceExpr->isTypeDependent()),
951 T->isDependentType() ||
952 (SourceExpr && SourceExpr->isValueDependent()),
953 T->isInstantiationDependentType() ||
954 (SourceExpr && SourceExpr->isInstantiationDependent()),
955 false),
956 SourceExpr(SourceExpr), Loc(Loc) {
957 setIsUnique(false);
958 }
959
960 /// Given an expression which invokes a copy constructor --- i.e. a
961 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
962 /// find the OpaqueValueExpr that's the source of the construction.
963 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
964
965 explicit OpaqueValueExpr(EmptyShell Empty)
966 : Expr(OpaqueValueExprClass, Empty) { }
967
968 /// Retrieve the location of this expression.
969 SourceLocation getLocation() const { return Loc; }
970
971 SourceLocation getBeginLoc() const LLVM_READONLY {
972 return SourceExpr ? SourceExpr->getBeginLoc() : Loc;
973 }
974 SourceLocation getEndLoc() const LLVM_READONLY {
975 return SourceExpr ? SourceExpr->getEndLoc() : Loc;
976 }
977 SourceLocation getExprLoc() const LLVM_READONLY {
978 if (SourceExpr) return SourceExpr->getExprLoc();
979 return Loc;
980 }
981
982 child_range children() {
983 return child_range(child_iterator(), child_iterator());
984 }
985
986 const_child_range children() const {
987 return const_child_range(const_child_iterator(), const_child_iterator());
988 }
989
990 /// The source expression of an opaque value expression is the
991 /// expression which originally generated the value. This is
992 /// provided as a convenience for analyses that don't wish to
993 /// precisely model the execution behavior of the program.
994 ///
995 /// The source expression is typically set when building the
996 /// expression which binds the opaque value expression in the first
997 /// place.
998 Expr *getSourceExpr() const { return SourceExpr; }
999
1000 void setIsUnique(bool V) {
1001 assert((!V || SourceExpr) &&
1002 "unique OVEs are expected to have source expressions");
1003 OpaqueValueExprBits.IsUnique = V;
1004 }
1005
1006 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1007
1008 static bool classof(const Stmt *T) {
1009 return T->getStmtClass() == OpaqueValueExprClass;
1010 }
1011};
1012
1013/// A reference to a declared variable, function, enum, etc.
1014/// [C99 6.5.1p2]
1015///
1016/// This encodes all the information about how a declaration is referenced
1017/// within an expression.
1018///
1019/// There are several optional constructs attached to DeclRefExprs only when
1020/// they apply in order to conserve memory. These are laid out past the end of
1021/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1022///
1023/// DeclRefExprBits.HasQualifier:
1024/// Specifies when this declaration reference expression has a C++
1025/// nested-name-specifier.
1026/// DeclRefExprBits.HasFoundDecl:
1027/// Specifies when this declaration reference expression has a record of
1028/// a NamedDecl (different from the referenced ValueDecl) which was found
1029/// during name lookup and/or overload resolution.
1030/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1031/// Specifies when this declaration reference expression has an explicit
1032/// C++ template keyword and/or template argument list.
1033/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1034/// Specifies when this declaration reference expression (validly)
1035/// refers to an enclosed local or a captured variable.
1036class DeclRefExpr final
1037 : public Expr,
1038 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1039 NamedDecl *, ASTTemplateKWAndArgsInfo,
1040 TemplateArgumentLoc> {
1041 friend class ASTStmtReader;
1042 friend class ASTStmtWriter;
1043 friend TrailingObjects;
1044
1045 /// The declaration that we are referencing.
1046 ValueDecl *D;
1047
1048 /// Provides source/type location info for the declaration name
1049 /// embedded in D.
1050 DeclarationNameLoc DNLoc;
1051
1052 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1053 return hasQualifier();
1054 }
1055
1056 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1057 return hasFoundDecl();
1058 }
1059
1060 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1061 return hasTemplateKWAndArgsInfo();
1062 }
1063
1064 /// Test whether there is a distinct FoundDecl attached to the end of
1065 /// this DRE.
1066 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1067
1068 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1069 SourceLocation TemplateKWLoc, ValueDecl *D,
1070 bool RefersToEnlosingVariableOrCapture,
1071 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1072 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1073 ExprValueKind VK);
1074
1075 /// Construct an empty declaration reference expression.
1076 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1077
1078 /// Computes the type- and value-dependence flags for this
1079 /// declaration reference expression.
1080 void computeDependence(const ASTContext &Ctx);
1081
1082public:
1083 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1084 ExprValueKind VK, SourceLocation L,
1085 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1086 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1087 D(D), DNLoc(LocInfo) {
1088 DeclRefExprBits.HasQualifier = false;
1089 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
1090 DeclRefExprBits.HasFoundDecl = false;
1091 DeclRefExprBits.HadMultipleCandidates = false;
1092 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1093 RefersToEnclosingVariableOrCapture;
1094 DeclRefExprBits.Loc = L;
1095 computeDependence(D->getASTContext());
1096 }
1097
1098 static DeclRefExpr *
1099 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1100 SourceLocation TemplateKWLoc, ValueDecl *D,
1101 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1102 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1103 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1104
1105 static DeclRefExpr *
1106 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1107 SourceLocation TemplateKWLoc, ValueDecl *D,
1108 bool RefersToEnclosingVariableOrCapture,
1109 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1110 NamedDecl *FoundD = nullptr,
1111 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1112
1113 /// Construct an empty declaration reference expression.
1114 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1115 bool HasFoundDecl,
1116 bool HasTemplateKWAndArgsInfo,
1117 unsigned NumTemplateArgs);
1118
1119 ValueDecl *getDecl() { return D; }
1120 const ValueDecl *getDecl() const { return D; }
1121 void setDecl(ValueDecl *NewD) { D = NewD; }
1122
1123 DeclarationNameInfo getNameInfo() const {
1124 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1125 }
1126
1127 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1128 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1129 SourceLocation getBeginLoc() const LLVM_READONLY;
1130 SourceLocation getEndLoc() const LLVM_READONLY;
1131
1132 /// Determine whether this declaration reference was preceded by a
1133 /// C++ nested-name-specifier, e.g., \c N::foo.
1134 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1135
1136 /// If the name was qualified, retrieves the nested-name-specifier
1137 /// that precedes the name, with source-location information.
1138 NestedNameSpecifierLoc getQualifierLoc() const {
1139 if (!hasQualifier())
1140 return NestedNameSpecifierLoc();
1141 return *getTrailingObjects<NestedNameSpecifierLoc>();
1142 }
1143
1144 /// If the name was qualified, retrieves the nested-name-specifier
1145 /// that precedes the name. Otherwise, returns NULL.
1146 NestedNameSpecifier *getQualifier() const {
1147 return getQualifierLoc().getNestedNameSpecifier();
1148 }
1149
1150 /// Get the NamedDecl through which this reference occurred.
1151 ///
1152 /// This Decl may be different from the ValueDecl actually referred to in the
1153 /// presence of using declarations, etc. It always returns non-NULL, and may
1154 /// simple return the ValueDecl when appropriate.
1155
1156 NamedDecl *getFoundDecl() {
1157 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1158 }
1159
1160 /// Get the NamedDecl through which this reference occurred.
1161 /// See non-const variant.
1162 const NamedDecl *getFoundDecl() const {
1163 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1164 }
1165
1166 bool hasTemplateKWAndArgsInfo() const {
1167 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1168 }
1169
1170 /// Retrieve the location of the template keyword preceding
1171 /// this name, if any.
1172 SourceLocation getTemplateKeywordLoc() const {
1173 if (!hasTemplateKWAndArgsInfo())
1174 return SourceLocation();
1175 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1176 }
1177
1178 /// Retrieve the location of the left angle bracket starting the
1179 /// explicit template argument list following the name, if any.
1180 SourceLocation getLAngleLoc() const {
1181 if (!hasTemplateKWAndArgsInfo())
1182 return SourceLocation();
1183 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1184 }
1185
1186 /// Retrieve the location of the right angle bracket ending the
1187 /// explicit template argument list following the name, if any.
1188 SourceLocation getRAngleLoc() const {
1189 if (!hasTemplateKWAndArgsInfo())
1190 return SourceLocation();
1191 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1192 }
1193
1194 /// Determines whether the name in this declaration reference
1195 /// was preceded by the template keyword.
1196 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1197
1198 /// Determines whether this declaration reference was followed by an
1199 /// explicit template argument list.
1200 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1201
1202 /// Copies the template arguments (if present) into the given
1203 /// structure.
1204 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1205 if (hasExplicitTemplateArgs())
1206 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1207 getTrailingObjects<TemplateArgumentLoc>(), List);
1208 }
1209
1210 /// Retrieve the template arguments provided as part of this
1211 /// template-id.
1212 const TemplateArgumentLoc *getTemplateArgs() const {
1213 if (!hasExplicitTemplateArgs())
1214 return nullptr;
1215 return getTrailingObjects<TemplateArgumentLoc>();
1216 }
1217
1218 /// Retrieve the number of template arguments provided as part of this
1219 /// template-id.
1220 unsigned getNumTemplateArgs() const {
1221 if (!hasExplicitTemplateArgs())
1222 return 0;
1223 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1224 }
1225
1226 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1227 return {getTemplateArgs(), getNumTemplateArgs()};
1228 }
1229
1230 /// Returns true if this expression refers to a function that
1231 /// was resolved from an overloaded set having size greater than 1.
1232 bool hadMultipleCandidates() const {
1233 return DeclRefExprBits.HadMultipleCandidates;
1234 }
1235 /// Sets the flag telling whether this expression refers to
1236 /// a function that was resolved from an overloaded set having size
1237 /// greater than 1.
1238 void setHadMultipleCandidates(bool V = true) {
1239 DeclRefExprBits.HadMultipleCandidates = V;
1240 }
1241
1242 /// Does this DeclRefExpr refer to an enclosing local or a captured
1243 /// variable?
1244 bool refersToEnclosingVariableOrCapture() const {
1245 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1246 }
1247
1248 static bool classof(const Stmt *T) {
1249 return T->getStmtClass() == DeclRefExprClass;
1250 }
1251
1252 // Iterators
1253 child_range children() {
1254 return child_range(child_iterator(), child_iterator());
1255 }
1256
1257 const_child_range children() const {
1258 return const_child_range(const_child_iterator(), const_child_iterator());
1259 }
1260};
1261
1262/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1263/// leaking memory.
1264///
1265/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1266/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1267/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1268/// the APFloat/APInt values will never get freed. APNumericStorage uses
1269/// ASTContext's allocator for memory allocation.
1270class APNumericStorage {
1271 union {
1272 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1273 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1274 };
1275 unsigned BitWidth;
1276
1277 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1278
1279 APNumericStorage(const APNumericStorage &) = delete;
1280 void operator=(const APNumericStorage &) = delete;
1281
1282protected:
1283 APNumericStorage() : VAL(0), BitWidth(0) { }
1284
1285 llvm::APInt getIntValue() const {
1286 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1287 if (NumWords > 1)
1288 return llvm::APInt(BitWidth, NumWords, pVal);
1289 else
1290 return llvm::APInt(BitWidth, VAL);
1291 }
1292 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1293};
1294
1295class APIntStorage : private APNumericStorage {
1296public:
1297 llvm::APInt getValue() const { return getIntValue(); }
1298 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1299 setIntValue(C, Val);
1300 }
1301};
1302
1303class APFloatStorage : private APNumericStorage {
1304public:
1305 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1306 return llvm::APFloat(Semantics, getIntValue());
1307 }
1308 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1309 setIntValue(C, Val.bitcastToAPInt());
1310 }
1311};
1312
1313class IntegerLiteral : public Expr, public APIntStorage {
1314 SourceLocation Loc;
1315
1316 /// Construct an empty integer literal.
1317 explicit IntegerLiteral(EmptyShell Empty)
1318 : Expr(IntegerLiteralClass, Empty) { }
1319
1320public:
1321 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1322 // or UnsignedLongLongTy
1323 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1324 SourceLocation l);
1325
1326 /// Returns a new integer literal with value 'V' and type 'type'.
1327 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1328 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1329 /// \param V - the value that the returned integer literal contains.
1330 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1331 QualType type, SourceLocation l);
1332 /// Returns a new empty integer literal.
1333 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1334
1335 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1336 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1337
1338 /// Retrieve the location of the literal.
1339 SourceLocation getLocation() const { return Loc; }
1340
1341 void setLocation(SourceLocation Location) { Loc = Location; }
1342
1343 static bool classof(const Stmt *T) {
1344 return T->getStmtClass() == IntegerLiteralClass;
1345 }
1346
1347 // Iterators
1348 child_range children() {
1349 return child_range(child_iterator(), child_iterator());
1350 }
1351 const_child_range children() const {
1352 return const_child_range(const_child_iterator(), const_child_iterator());
1353 }
1354};
1355
1356class FixedPointLiteral : public Expr, public APIntStorage {
1357 SourceLocation Loc;
1358 unsigned Scale;
1359
1360 /// \brief Construct an empty integer literal.
1361 explicit FixedPointLiteral(EmptyShell Empty)
1362 : Expr(FixedPointLiteralClass, Empty) {}
1363
1364 public:
1365 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1366 SourceLocation l, unsigned Scale);
1367
1368 // Store the int as is without any bit shifting.
1369 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1370 const llvm::APInt &V,
1371 QualType type, SourceLocation l,
1372 unsigned Scale);
1373
1374 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1375 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1376
1377 /// \brief Retrieve the location of the literal.
1378 SourceLocation getLocation() const { return Loc; }
1379
1380 void setLocation(SourceLocation Location) { Loc = Location; }
1381
1382 static bool classof(const Stmt *T) {
1383 return T->getStmtClass() == FixedPointLiteralClass;
1384 }
1385
1386 std::string getValueAsString(unsigned Radix) const;
1387
1388 // Iterators
1389 child_range children() {
1390 return child_range(child_iterator(), child_iterator());
1391 }
1392 const_child_range children() const {
1393 return const_child_range(const_child_iterator(), const_child_iterator());
1394 }
1395};
1396
1397class CharacterLiteral : public Expr {
1398public:
1399 enum CharacterKind {
1400 Ascii,
1401 Wide,
1402 UTF8,
1403 UTF16,
1404 UTF32
1405 };
1406
1407private:
1408 unsigned Value;
1409 SourceLocation Loc;
1410public:
1411 // type should be IntTy
1412 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1413 SourceLocation l)
1414 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1415 false, false),
1416 Value(value), Loc(l) {
1417 CharacterLiteralBits.Kind = kind;
1418 }
1419
1420 /// Construct an empty character literal.
1421 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1422
1423 SourceLocation getLocation() const { return Loc; }
1424 CharacterKind getKind() const {
1425 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1426 }
1427
1428 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1429 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1430
1431 unsigned getValue() const { return Value; }
1432
1433 void setLocation(SourceLocation Location) { Loc = Location; }
1434 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1435 void setValue(unsigned Val) { Value = Val; }
1436
1437 static bool classof(const Stmt *T) {
1438 return T->getStmtClass() == CharacterLiteralClass;
1439 }
1440
1441 // Iterators
1442 child_range children() {
1443 return child_range(child_iterator(), child_iterator());
1444 }
1445 const_child_range children() const {
1446 return const_child_range(const_child_iterator(), const_child_iterator());
1447 }
1448};
1449
1450class FloatingLiteral : public Expr, private APFloatStorage {
1451 SourceLocation Loc;
1452
1453 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1454 QualType Type, SourceLocation L);
1455
1456 /// Construct an empty floating-point literal.
1457 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1458
1459public:
1460 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1461 bool isexact, QualType Type, SourceLocation L);
1462 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1463
1464 llvm::APFloat getValue() const {
1465 return APFloatStorage::getValue(getSemantics());
1466 }
1467 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1468 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1469 APFloatStorage::setValue(C, Val);
1470 }
1471
1472 /// Get a raw enumeration value representing the floating-point semantics of
1473 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1474 APFloatSemantics getRawSemantics() const {
1475 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1476 }
1477
1478 /// Set the raw enumeration value representing the floating-point semantics of
1479 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1480 void setRawSemantics(APFloatSemantics Sem) {
1481 FloatingLiteralBits.Semantics = Sem;
1482 }
1483
1484 /// Return the APFloat semantics this literal uses.
1485 const llvm::fltSemantics &getSemantics() const;
1486
1487 /// Set the APFloat semantics this literal uses.
1488 void setSemantics(const llvm::fltSemantics &Sem);
1489
1490 bool isExact() const { return FloatingLiteralBits.IsExact; }
1491 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1492
1493 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1494 /// double. Note that this may cause loss of precision, but is useful for
1495 /// debugging dumps, etc.
1496 double getValueAsApproximateDouble() const;
1497
1498 SourceLocation getLocation() const { return Loc; }
1499 void setLocation(SourceLocation L) { Loc = L; }
1500
1501 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1502 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1503
1504 static bool classof(const Stmt *T) {
1505 return T->getStmtClass() == FloatingLiteralClass;
1506 }
1507
1508 // Iterators
1509 child_range children() {
1510 return child_range(child_iterator(), child_iterator());
1511 }
1512 const_child_range children() const {
1513 return const_child_range(const_child_iterator(), const_child_iterator());
1514 }
1515};
1516
1517/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1518/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1519/// IntegerLiteral classes. Instances of this class always have a Complex type
1520/// whose element type matches the subexpression.
1521///
1522class ImaginaryLiteral : public Expr {
1523 Stmt *Val;
1524public:
1525 ImaginaryLiteral(Expr *val, QualType Ty)
1526 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1527 false, false),
1528 Val(val) {}
1529
1530 /// Build an empty imaginary literal.
1531 explicit ImaginaryLiteral(EmptyShell Empty)
1532 : Expr(ImaginaryLiteralClass, Empty) { }
1533
1534 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1535 Expr *getSubExpr() { return cast<Expr>(Val); }
1536 void setSubExpr(Expr *E) { Val = E; }
1537
1538 SourceLocation getBeginLoc() const LLVM_READONLY {
1539 return Val->getBeginLoc();
1540 }
1541 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1542
1543 static bool classof(const Stmt *T) {
1544 return T->getStmtClass() == ImaginaryLiteralClass;
1545 }
1546
1547 // Iterators
1548 child_range children() { return child_range(&Val, &Val+1); }
1549 const_child_range children() const {
1550 return const_child_range(&Val, &Val + 1);
1551 }
1552};
1553
1554/// StringLiteral - This represents a string literal expression, e.g. "foo"
1555/// or L"bar" (wide strings). The actual string is returned by getBytes()
1556/// is NOT null-terminated, and the length of the string is determined by
1557/// calling getByteLength(). The C type for a string is always a
1558/// ConstantArrayType. In C++, the char type is const qualified, in C it is
1559/// not.
1560///
1561/// Note that strings in C can be formed by concatenation of multiple string
1562/// literal pptokens in translation phase #6. This keeps track of the locations
1563/// of each of these pieces.
1564///
1565/// Strings in C can also be truncated and extended by assigning into arrays,
1566/// e.g. with constructs like:
1567/// char X[2] = "foobar";
1568/// In this case, getByteLength() will return 6, but the string literal will
1569/// have type "char[2]".
1570class StringLiteral : public Expr {
1571public:
1572 enum StringKind {
1573 Ascii,
1574 Wide,
1575 UTF8,
1576 UTF16,
1577 UTF32
1578 };
1579
1580private:
1581 friend class ASTStmtReader;
1582
1583 union {
1584 const char *asChar;
1585 const uint16_t *asUInt16;
1586 const uint32_t *asUInt32;
1587 } StrData;
1588 unsigned Length;
1589 unsigned CharByteWidth : 4;
1590 unsigned Kind : 3;
1591 unsigned IsPascal : 1;
1592 unsigned NumConcatenated;
1593 SourceLocation TokLocs[1];
1594
1595 StringLiteral(QualType Ty) :
1596 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1597 false) {}
1598
1599 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1600
1601public:
1602 /// This is the "fully general" constructor that allows representation of
1603 /// strings formed from multiple concatenated tokens.
1604 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1605 StringKind Kind, bool Pascal, QualType Ty,
1606 const SourceLocation *Loc, unsigned NumStrs);
1607
1608 /// Simple constructor for string literals made from one token.
1609 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1610 StringKind Kind, bool Pascal, QualType Ty,
1611 SourceLocation Loc) {
1612 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1613 }
1614
1615 /// Construct an empty string literal.
1616 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1617
1618 StringRef getString() const {
1619 assert(CharByteWidth==1
1620 && "This function is used in places that assume strings use char");
1621 return StringRef(StrData.asChar, getByteLength());
1622 }
1623
1624 /// Allow access to clients that need the byte representation, such as
1625 /// ASTWriterStmt::VisitStringLiteral().
1626 StringRef getBytes() const {
1627 // FIXME: StringRef may not be the right type to use as a result for this.
1628 if (CharByteWidth == 1)
1629 return StringRef(StrData.asChar, getByteLength());
1630 if (CharByteWidth == 4)
1631 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1632 getByteLength());
1633 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1634 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1635 getByteLength());
1636 }
1637
1638 void outputString(raw_ostream &OS) const;
1639
1640 uint32_t getCodeUnit(size_t i) const {
1641 assert(i < Length && "out of bounds access");
1642 if (CharByteWidth == 1)
1643 return static_cast<unsigned char>(StrData.asChar[i]);
1644 if (CharByteWidth == 4)
1645 return StrData.asUInt32[i];
1646 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1647 return StrData.asUInt16[i];
1648 }
1649
1650 unsigned getByteLength() const { return CharByteWidth*Length; }
1651 unsigned getLength() const { return Length; }
1652 unsigned getCharByteWidth() const { return CharByteWidth; }
1653
1654 /// Sets the string data to the given string data.
1655 void setString(const ASTContext &C, StringRef Str,
1656 StringKind Kind, bool IsPascal);
1657
1658 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1659
1660
1661 bool isAscii() const { return Kind == Ascii; }
1662 bool isWide() const { return Kind == Wide; }
1663 bool isUTF8() const { return Kind == UTF8; }
1664 bool isUTF16() const { return Kind == UTF16; }
1665 bool isUTF32() const { return Kind == UTF32; }
1666 bool isPascal() const { return IsPascal; }
1667
1668 bool containsNonAscii() const {
1669 StringRef Str = getString();
1670 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1671 if (!isASCII(Str[i]))
1672 return true;
1673 return false;
1674 }
1675
1676 bool containsNonAsciiOrNull() const {
1677 StringRef Str = getString();
1678 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1679 if (!isASCII(Str[i]) || !Str[i])
1680 return true;
1681 return false;
1682 }
1683
1684 /// getNumConcatenated - Get the number of string literal tokens that were
1685 /// concatenated in translation phase #6 to form this string literal.
1686 unsigned getNumConcatenated() const { return NumConcatenated; }
1687
1688 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1689 assert(TokNum < NumConcatenated && "Invalid tok number");
1690 return TokLocs[TokNum];
1691 }
1692 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1693 assert(TokNum < NumConcatenated && "Invalid tok number");
1694 TokLocs[TokNum] = L;
1695 }
1696
1697 /// getLocationOfByte - Return a source location that points to the specified
1698 /// byte of this string literal.
1699 ///
1700 /// Strings are amazingly complex. They can be formed from multiple tokens
1701 /// and can have escape sequences in them in addition to the usual trigraph
1702 /// and escaped newline business. This routine handles this complexity.
1703 ///
1704 SourceLocation
1705 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1706 const LangOptions &Features, const TargetInfo &Target,
1707 unsigned *StartToken = nullptr,
1708 unsigned *StartTokenByteOffset = nullptr) const;
1709
1710 typedef const SourceLocation *tokloc_iterator;
1711 tokloc_iterator tokloc_begin() const { return TokLocs; }
1712 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1713
1714 SourceLocation getBeginLoc() const LLVM_READONLY { return TokLocs[0]; }
1715 SourceLocation getEndLoc() const LLVM_READONLY {
1716 return TokLocs[NumConcatenated - 1];
1717 }
1718
1719 static bool classof(const Stmt *T) {
1720 return T->getStmtClass() == StringLiteralClass;
1721 }
1722
1723 // Iterators
1724 child_range children() {
1725 return child_range(child_iterator(), child_iterator());
1726 }
1727 const_child_range children() const {
1728 return const_child_range(const_child_iterator(), const_child_iterator());
1729 }
1730};
1731
1732/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1733class PredefinedExpr final
1734 : public Expr,
1735 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1736 friend class ASTStmtReader;
1737 friend TrailingObjects;
1738
1739 // PredefinedExpr is optionally followed by a single trailing
1740 // "Stmt *" for the predefined identifier. It is present if and only if
1741 // hasFunctionName() is true and is always a "StringLiteral *".
1742
1743public:
1744 enum IdentKind {
1745 Func,
1746 Function,
1747 LFunction, // Same as Function, but as wide string.
1748 FuncDName,
1749 FuncSig,
1750 LFuncSig, // Same as FuncSig, but as as wide string
1751 PrettyFunction,
1752 /// The same as PrettyFunction, except that the
1753 /// 'virtual' keyword is omitted for virtual member functions.
1754 PrettyFunctionNoVirtual
1755 };
1756
1757private:
1758 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1759 StringLiteral *SL);
1760
1761 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1762
1763 /// True if this PredefinedExpr has storage for a function name.
1764 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1765
1766 void setFunctionName(StringLiteral *SL) {
1767 assert(hasFunctionName() &&
1768 "This PredefinedExpr has no storage for a function name!");
1769 *getTrailingObjects<Stmt *>() = SL;
1770 }
1771
1772public:
1773 /// Create a PredefinedExpr.
1774 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1775 QualType FNTy, IdentKind IK, StringLiteral *SL);
1776
1777 /// Create an empty PredefinedExpr.
1778 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1779 bool HasFunctionName);
1780
1781 IdentKind getIdentKind() const {
1782 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1783 }
1784
1785 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
1786 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
1787
1788 StringLiteral *getFunctionName() {
1789 return hasFunctionName()
1790 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1791 : nullptr;
1792 }
1793
1794 const StringLiteral *getFunctionName() const {
1795 return hasFunctionName()
1796 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1797 : nullptr;
1798 }
1799
1800 static StringRef getIdentKindName(IdentKind IK);
1801 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
1802
1803 SourceLocation getBeginLoc() const { return getLocation(); }
1804 SourceLocation getEndLoc() const { return getLocation(); }
1805
1806 static bool classof(const Stmt *T) {
1807 return T->getStmtClass() == PredefinedExprClass;
1808 }
1809
1810 // Iterators
1811 child_range children() {
1812 return child_range(getTrailingObjects<Stmt *>(),
1813 getTrailingObjects<Stmt *>() + hasFunctionName());
1814 }
1815};
1816
1817/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1818/// AST node is only formed if full location information is requested.
1819class ParenExpr : public Expr {
1820 SourceLocation L, R;
1821 Stmt *Val;
1822public:
1823 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1824 : Expr(ParenExprClass, val->getType(),
1825 val->getValueKind(), val->getObjectKind(),
1826 val->isTypeDependent(), val->isValueDependent(),
1827 val->isInstantiationDependent(),
1828 val->containsUnexpandedParameterPack()),
1829 L(l), R(r), Val(val) {}
1830
1831 /// Construct an empty parenthesized expression.
1832 explicit ParenExpr(EmptyShell Empty)
1833 : Expr(ParenExprClass, Empty) { }
1834
1835 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1836 Expr *getSubExpr() { return cast<Expr>(Val); }
1837 void setSubExpr(Expr *E) { Val = E; }
1838
1839 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
1840 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
1841
1842 /// Get the location of the left parentheses '('.
1843 SourceLocation getLParen() const { return L; }
1844 void setLParen(SourceLocation Loc) { L = Loc; }
1845
1846 /// Get the location of the right parentheses ')'.
1847 SourceLocation getRParen() const { return R; }
1848 void setRParen(SourceLocation Loc) { R = Loc; }
1849
1850 static bool classof(const Stmt *T) {
1851 return T->getStmtClass() == ParenExprClass;
1852 }
1853
1854 // Iterators
1855 child_range children() { return child_range(&Val, &Val+1); }
1856 const_child_range children() const {
1857 return const_child_range(&Val, &Val + 1);
1858 }
1859};
1860
1861/// UnaryOperator - This represents the unary-expression's (except sizeof and
1862/// alignof), the postinc/postdec operators from postfix-expression, and various
1863/// extensions.
1864///
1865/// Notes on various nodes:
1866///
1867/// Real/Imag - These return the real/imag part of a complex operand. If
1868/// applied to a non-complex value, the former returns its operand and the
1869/// later returns zero in the type of the operand.
1870///
1871class UnaryOperator : public Expr {
1872public:
1873 typedef UnaryOperatorKind Opcode;
1874
1875private:
1876 unsigned Opc : 5;
1877 unsigned CanOverflow : 1;
1878 SourceLocation Loc;
1879 Stmt *Val;
1880public:
1881 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
1882 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
1883 : Expr(UnaryOperatorClass, type, VK, OK,
1884 input->isTypeDependent() || type->isDependentType(),
1885 input->isValueDependent(),
1886 (input->isInstantiationDependent() ||
1887 type->isInstantiationDependentType()),
1888 input->containsUnexpandedParameterPack()),
1889 Opc(opc), CanOverflow(CanOverflow), Loc(l), Val(input) {}
1890
1891 /// Build an empty unary operator.
1892 explicit UnaryOperator(EmptyShell Empty)
1893 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1894
1895 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1896 void setOpcode(Opcode O) { Opc = O; }
1897
1898 Expr *getSubExpr() const { return cast<Expr>(Val); }
1899 void setSubExpr(Expr *E) { Val = E; }
1900
1901 /// getOperatorLoc - Return the location of the operator.
1902 SourceLocation getOperatorLoc() const { return Loc; }
1903 void setOperatorLoc(SourceLocation L) { Loc = L; }
1904
1905 /// Returns true if the unary operator can cause an overflow. For instance,
1906 /// signed int i = INT_MAX; i++;
1907 /// signed char c = CHAR_MAX; c++;
1908 /// Due to integer promotions, c++ is promoted to an int before the postfix
1909 /// increment, and the result is an int that cannot overflow. However, i++
1910 /// can overflow.
1911 bool canOverflow() const { return CanOverflow; }
1912 void setCanOverflow(bool C) { CanOverflow = C; }
1913
1914 /// isPostfix - Return true if this is a postfix operation, like x++.
1915 static bool isPostfix(Opcode Op) {
1916 return Op == UO_PostInc || Op == UO_PostDec;
1917 }
1918
1919 /// isPrefix - Return true if this is a prefix operation, like --x.
1920 static bool isPrefix(Opcode Op) {
1921 return Op == UO_PreInc || Op == UO_PreDec;
1922 }
1923
1924 bool isPrefix() const { return isPrefix(getOpcode()); }
1925 bool isPostfix() const { return isPostfix(getOpcode()); }
1926
1927 static bool isIncrementOp(Opcode Op) {
1928 return Op == UO_PreInc || Op == UO_PostInc;
1929 }
1930 bool isIncrementOp() const {
1931 return isIncrementOp(getOpcode());
1932 }
1933
1934 static bool isDecrementOp(Opcode Op) {
1935 return Op == UO_PreDec || Op == UO_PostDec;
1936 }
1937 bool isDecrementOp() const {
1938 return isDecrementOp(getOpcode());
1939 }
1940
1941 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1942 bool isIncrementDecrementOp() const {
1943 return isIncrementDecrementOp(getOpcode());
1944 }
1945
1946 static bool isArithmeticOp(Opcode Op) {
1947 return Op >= UO_Plus && Op <= UO_LNot;
1948 }
1949 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1950
1951 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1952 /// corresponds to, e.g. "sizeof" or "[pre]++"
1953 static StringRef getOpcodeStr(Opcode Op);
1954
1955 /// Retrieve the unary opcode that corresponds to the given
1956 /// overloaded operator.
1957 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1958
1959 /// Retrieve the overloaded operator kind that corresponds to
1960 /// the given unary opcode.
1961 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1962
1963 SourceLocation getBeginLoc() const LLVM_READONLY {
1964 return isPostfix() ? Val->getBeginLoc() : Loc;
1965 }
1966 SourceLocation getEndLoc() const LLVM_READONLY {
1967 return isPostfix() ? Loc : Val->getEndLoc();
1968 }
1969 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1970
1971 static bool classof(const Stmt *T) {
1972 return T->getStmtClass() == UnaryOperatorClass;
1973 }
1974
1975 // Iterators
1976 child_range children() { return child_range(&Val, &Val+1); }
1977 const_child_range children() const {
1978 return const_child_range(&Val, &Val + 1);
1979 }
1980};
1981
1982/// Helper class for OffsetOfExpr.
1983
1984// __builtin_offsetof(type, identifier(.identifier|[expr])*)
1985class OffsetOfNode {
1986public:
1987 /// The kind of offsetof node we have.
1988 enum Kind {
1989 /// An index into an array.
1990 Array = 0x00,
1991 /// A field.
1992 Field = 0x01,
1993 /// A field in a dependent type, known only by its name.
1994 Identifier = 0x02,
1995 /// An implicit indirection through a C++ base class, when the
1996 /// field found is in a base class.
1997 Base = 0x03
1998 };
1999
2000private:
2001 enum { MaskBits = 2, Mask = 0x03 };
2002
2003 /// The source range that covers this part of the designator.
2004 SourceRange Range;
2005
2006 /// The data describing the designator, which comes in three
2007 /// different forms, depending on the lower two bits.
2008 /// - An unsigned index into the array of Expr*'s stored after this node
2009 /// in memory, for [constant-expression] designators.
2010 /// - A FieldDecl*, for references to a known field.
2011 /// - An IdentifierInfo*, for references to a field with a given name
2012 /// when the class type is dependent.
2013 /// - A CXXBaseSpecifier*, for references that look at a field in a
2014 /// base class.
2015 uintptr_t Data;
2016
2017public:
2018 /// Create an offsetof node that refers to an array element.
2019 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2020 SourceLocation RBracketLoc)
2021 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2022
2023 /// Create an offsetof node that refers to a field.
2024 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2025 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2026 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2027
2028 /// Create an offsetof node that refers to an identifier.
2029 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2030 SourceLocation NameLoc)
2031 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2032 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2033
2034 /// Create an offsetof node that refers into a C++ base class.
2035 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2036 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2037
2038 /// Determine what kind of offsetof node this is.
2039 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2040
2041 /// For an array element node, returns the index into the array
2042 /// of expressions.
2043 unsigned getArrayExprIndex() const {
2044 assert(getKind() == Array);
2045 return Data >> 2;
2046 }
2047
2048 /// For a field offsetof node, returns the field.
2049 FieldDecl *getField() const {
2050 assert(getKind() == Field);
2051 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2052 }
2053
2054 /// For a field or identifier offsetof node, returns the name of
2055 /// the field.
2056 IdentifierInfo *getFieldName() const;
2057
2058 /// For a base class node, returns the base specifier.
2059 CXXBaseSpecifier *getBase() const {
2060 assert(getKind() == Base);
2061 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2062 }
2063
2064 /// Retrieve the source range that covers this offsetof node.
2065 ///
2066 /// For an array element node, the source range contains the locations of
2067 /// the square brackets. For a field or identifier node, the source range
2068 /// contains the location of the period (if there is one) and the
2069 /// identifier.
2070 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2071 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2072 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2073};
2074
2075/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2076/// offsetof(record-type, member-designator). For example, given:
2077/// @code
2078/// struct S {
2079/// float f;
2080/// double d;
2081/// };
2082/// struct T {
2083/// int i;
2084/// struct S s[10];
2085/// };
2086/// @endcode
2087/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2088
2089class OffsetOfExpr final
2090 : public Expr,
2091 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2092 SourceLocation OperatorLoc, RParenLoc;
2093 // Base type;
2094 TypeSourceInfo *TSInfo;
2095 // Number of sub-components (i.e. instances of OffsetOfNode).
2096 unsigned NumComps;
2097 // Number of sub-expressions (i.e. array subscript expressions).
2098 unsigned NumExprs;
2099
2100 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2101 return NumComps;
2102 }
2103
2104 OffsetOfExpr(const ASTContext &C, QualType type,
2105 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2106 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2107 SourceLocation RParenLoc);
2108
2109 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2110 : Expr(OffsetOfExprClass, EmptyShell()),
2111 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2112
2113public:
2114
2115 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2116 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2117 ArrayRef<OffsetOfNode> comps,
2118 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2119
2120 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2121 unsigned NumComps, unsigned NumExprs);
2122
2123 /// getOperatorLoc - Return the location of the operator.
2124 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2125 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2126
2127 /// Return the location of the right parentheses.
2128 SourceLocation getRParenLoc() const { return RParenLoc; }
2129 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2130
2131 TypeSourceInfo *getTypeSourceInfo() const {
2132 return TSInfo;
2133 }
2134 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2135 TSInfo = tsi;
2136 }
2137
2138 const OffsetOfNode &getComponent(unsigned Idx) const {
2139 assert(Idx < NumComps && "Subscript out of range");
2140 return getTrailingObjects<OffsetOfNode>()[Idx];
2141 }
2142
2143 void setComponent(unsigned Idx, OffsetOfNode ON) {
2144 assert(Idx < NumComps && "Subscript out of range");
2145 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2146 }
2147
2148 unsigned getNumComponents() const {
2149 return NumComps;
2150 }
2151
2152 Expr* getIndexExpr(unsigned Idx) {
2153 assert(Idx < NumExprs && "Subscript out of range");
2154 return getTrailingObjects<Expr *>()[Idx];
2155 }
2156
2157 const Expr *getIndexExpr(unsigned Idx) const {
2158 assert(Idx < NumExprs && "Subscript out of range");
2159 return getTrailingObjects<Expr *>()[Idx];
2160 }
2161
2162 void setIndexExpr(unsigned Idx, Expr* E) {
2163 assert(Idx < NumComps && "Subscript out of range");
2164 getTrailingObjects<Expr *>()[Idx] = E;
2165 }
2166
2167 unsigned getNumExpressions() const {
2168 return NumExprs;
2169 }
2170
2171 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2172 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2173
2174 static bool classof(const Stmt *T) {
2175 return T->getStmtClass() == OffsetOfExprClass;
2176 }
2177
2178 // Iterators
2179 child_range children() {
2180 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2181 return child_range(begin, begin + NumExprs);
2182 }
2183 const_child_range children() const {
2184 Stmt *const *begin =
2185 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2186 return const_child_range(begin, begin + NumExprs);
2187 }
2188 friend TrailingObjects;
2189};
2190
2191/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2192/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2193/// vec_step (OpenCL 1.1 6.11.12).
2194class UnaryExprOrTypeTraitExpr : public Expr {
2195 union {
2196 TypeSourceInfo *Ty;
2197 Stmt *Ex;
2198 } Argument;
2199 SourceLocation OpLoc, RParenLoc;
2200
2201public:
2202 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2203 QualType resultType, SourceLocation op,
2204 SourceLocation rp) :
2205 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2206 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2207 // Value-dependent if the argument is type-dependent.
2208 TInfo->getType()->isDependentType(),
2209 TInfo->getType()->isInstantiationDependentType(),
2210 TInfo->getType()->containsUnexpandedParameterPack()),
2211 OpLoc(op), RParenLoc(rp) {
2212 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2213 UnaryExprOrTypeTraitExprBits.IsType = true;
2214 Argument.Ty = TInfo;
2215 }
2216
2217 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2218 QualType resultType, SourceLocation op,
2219 SourceLocation rp);
2220
2221 /// Construct an empty sizeof/alignof expression.
2222 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2223 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2224
2225 UnaryExprOrTypeTrait getKind() const {
2226 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2227 }
2228 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2229
2230 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2231 QualType getArgumentType() const {
2232 return getArgumentTypeInfo()->getType();
2233 }
2234 TypeSourceInfo *getArgumentTypeInfo() const {
2235 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2236 return Argument.Ty;
2237 }
2238 Expr *getArgumentExpr() {
2239 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2240 return static_cast<Expr*>(Argument.Ex);
2241 }
2242 const Expr *getArgumentExpr() const {
2243 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2244 }
2245
2246 void setArgument(Expr *E) {
2247 Argument.Ex = E;
2248 UnaryExprOrTypeTraitExprBits.IsType = false;
2249 }
2250 void setArgument(TypeSourceInfo *TInfo) {
2251 Argument.Ty = TInfo;
2252 UnaryExprOrTypeTraitExprBits.IsType = true;
2253 }
2254
2255 /// Gets the argument type, or the type of the argument expression, whichever
2256 /// is appropriate.
2257 QualType getTypeOfArgument() const {
2258 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2259 }
2260
2261 SourceLocation getOperatorLoc() const { return OpLoc; }
2262 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2263
2264 SourceLocation getRParenLoc() const { return RParenLoc; }
2265 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2266
2267 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2268 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2269
2270 static bool classof(const Stmt *T) {
2271 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2272 }
2273
2274 // Iterators
2275 child_range children();
2276 const_child_range children() const;
2277};
2278
2279//===----------------------------------------------------------------------===//
2280// Postfix Operators.
2281//===----------------------------------------------------------------------===//
2282
2283/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2284class ArraySubscriptExpr : public Expr {
2285 enum { LHS, RHS, END_EXPR=2 };
2286 Stmt* SubExprs[END_EXPR];
2287 SourceLocation RBracketLoc;
2288public:
2289 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2290 ExprValueKind VK, ExprObjectKind OK,
2291 SourceLocation rbracketloc)
2292 : Expr(ArraySubscriptExprClass, t, VK, OK,
2293 lhs->isTypeDependent() || rhs->isTypeDependent(),
2294 lhs->isValueDependent() || rhs->isValueDependent(),
2295 (lhs->isInstantiationDependent() ||
2296 rhs->isInstantiationDependent()),
2297 (lhs->containsUnexpandedParameterPack() ||
2298 rhs->containsUnexpandedParameterPack())),
2299 RBracketLoc(rbracketloc) {
2300 SubExprs[LHS] = lhs;
2301 SubExprs[RHS] = rhs;
2302 }
2303
2304 /// Create an empty array subscript expression.
2305 explicit ArraySubscriptExpr(EmptyShell Shell)
2306 : Expr(ArraySubscriptExprClass, Shell) { }
2307
2308 /// An array access can be written A[4] or 4[A] (both are equivalent).
2309 /// - getBase() and getIdx() always present the normalized view: A[4].
2310 /// In this case getBase() returns "A" and getIdx() returns "4".
2311 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2312 /// 4[A] getLHS() returns "4".
2313 /// Note: Because vector element access is also written A[4] we must
2314 /// predicate the format conversion in getBase and getIdx only on the
2315 /// the type of the RHS, as it is possible for the LHS to be a vector of
2316 /// integer type
2317 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2318 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2319 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2320
2321 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2322 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2323 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2324
2325 Expr *getBase() {
2326 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2327 }
2328
2329 const Expr *getBase() const {
2330 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2331 }
2332
2333 Expr *getIdx() {
2334 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2335 }
2336
2337 const Expr *getIdx() const {
2338 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2339 }
2340
2341 SourceLocation getBeginLoc() const LLVM_READONLY {
2342 return getLHS()->getBeginLoc();
2343 }
2344 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
2345
2346 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2347 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2348
2349 SourceLocation getExprLoc() const LLVM_READONLY {
2350 return getBase()->getExprLoc();
2351 }
2352
2353 static bool classof(const Stmt *T) {
2354 return T->getStmtClass() == ArraySubscriptExprClass;
2355 }
2356
2357 // Iterators
2358 child_range children() {
2359 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2360 }
2361 const_child_range children() const {
2362 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2363 }
2364};
2365
2366/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2367/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2368/// while its subclasses may represent alternative syntax that (semantically)
2369/// results in a function call. For example, CXXOperatorCallExpr is
2370/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2371/// "str1 + str2" to resolve to a function call.
2372class CallExpr : public Expr {
2373 enum { FN=0, PREARGS_START=1 };
2374 Stmt **SubExprs;
2375 unsigned NumArgs;
2376 SourceLocation RParenLoc;
2377
2378 void updateDependenciesFromArg(Expr *Arg);
2379
2380protected:
2381 // These versions of the constructor are for derived classes.
2382 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2383 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2384 ExprValueKind VK, SourceLocation rparenloc);
2385 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2386 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2387 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2388 EmptyShell Empty);
2389
2390 Stmt *getPreArg(unsigned i) {
2391 assert(i < getNumPreArgs() && "Prearg access out of range!");
2392 return SubExprs[PREARGS_START+i];
2393 }
2394 const Stmt *getPreArg(unsigned i) const {
2395 assert(i < getNumPreArgs() && "Prearg access out of range!");
2396 return SubExprs[PREARGS_START+i];
2397 }
2398 void setPreArg(unsigned i, Stmt *PreArg) {
2399 assert(i < getNumPreArgs() && "Prearg access out of range!");
2400 SubExprs[PREARGS_START+i] = PreArg;
2401 }
2402
2403 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2404
2405public:
2406 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2407 ExprValueKind VK, SourceLocation rparenloc);
2408
2409 /// Build an empty call expression.
2410 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2411
2412 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2413 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2414 void setCallee(Expr *F) { SubExprs[FN] = F; }
2415
2416 Decl *getCalleeDecl();
2417 const Decl *getCalleeDecl() const {
2418 return const_cast<CallExpr*>(this)->getCalleeDecl();
2419 }
2420
2421 /// If the callee is a FunctionDecl, return it. Otherwise return 0.
2422 FunctionDecl *getDirectCallee();
2423 const FunctionDecl *getDirectCallee() const {
2424 return const_cast<CallExpr*>(this)->getDirectCallee();
2425 }
2426
2427 /// getNumArgs - Return the number of actual arguments to this call.
2428 ///
2429 unsigned getNumArgs() const { return NumArgs; }
2430
2431 /// Retrieve the call arguments.
2432 Expr **getArgs() {
2433 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2434 }
2435 const Expr *const *getArgs() const {
2436 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2437 PREARGS_START);
2438 }
2439
2440 /// getArg - Return the specified argument.
2441 Expr *getArg(unsigned Arg) {
2442 assert(Arg < NumArgs && "Arg access out of range!");
2443 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2444 }
2445 const Expr *getArg(unsigned Arg) const {
2446 assert(Arg < NumArgs && "Arg access out of range!");
2447 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2448 }
2449
2450 /// setArg - Set the specified argument.
2451 void setArg(unsigned Arg, Expr *ArgExpr) {
2452 assert(Arg < NumArgs && "Arg access out of range!");
2453 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2454 }
2455
2456 /// setNumArgs - This changes the number of arguments present in this call.
2457 /// Any orphaned expressions are deleted by this, and any new operands are set
2458 /// to null.
2459 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2460
2461 typedef ExprIterator arg_iterator;
2462 typedef ConstExprIterator const_arg_iterator;
2463 typedef llvm::iterator_range<arg_iterator> arg_range;
2464 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2465
2466 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2467 const_arg_range arguments() const {
2468 return const_arg_range(arg_begin(), arg_end());
2469 }
2470
2471 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2472 arg_iterator arg_end() {
2473 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2474 }
2475 const_arg_iterator arg_begin() const {
2476 return SubExprs+PREARGS_START+getNumPreArgs();
2477 }
2478 const_arg_iterator arg_end() const {
2479 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2480 }
2481
2482 /// This method provides fast access to all the subexpressions of
2483 /// a CallExpr without going through the slower virtual child_iterator
2484 /// interface. This provides efficient reverse iteration of the
2485 /// subexpressions. This is currently used for CFG construction.
2486 ArrayRef<Stmt*> getRawSubExprs() {
2487 return llvm::makeArrayRef(SubExprs,
2488 getNumPreArgs() + PREARGS_START + getNumArgs());
2489 }
2490
2491 /// getNumCommas - Return the number of commas that must have been present in
2492 /// this function call.
2493 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2494
2495 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2496 /// of the callee. If not, return 0.
2497 unsigned getBuiltinCallee() const;
2498
2499 /// Returns \c true if this is a call to a builtin which does not
2500 /// evaluate side-effects within its arguments.
2501 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2502
2503 /// getCallReturnType - Get the return type of the call expr. This is not
2504 /// always the type of the expr itself, if the return type is a reference
2505 /// type.
2506 QualType getCallReturnType(const ASTContext &Ctx) const;
2507
2508 SourceLocation getRParenLoc() const { return RParenLoc; }
2509 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2510
2511 SourceLocation getBeginLoc() const LLVM_READONLY;
2512 SourceLocation getEndLoc() const LLVM_READONLY;
2513
2514 /// Return true if this is a call to __assume() or __builtin_assume() with
2515 /// a non-value-dependent constant parameter evaluating as false.
2516 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2517
2518 bool isCallToStdMove() const {
2519 const FunctionDecl* FD = getDirectCallee();
2520 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2521 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2522 }
2523
2524 static bool classof(const Stmt *T) {
2525 return T->getStmtClass() >= firstCallExprConstant &&
2526 T->getStmtClass() <= lastCallExprConstant;
2527 }
2528
2529 // Iterators
2530 child_range children() {
2531 return child_range(&SubExprs[0],
2532 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2533 }
2534
2535 const_child_range children() const {
2536 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2537 getNumPreArgs() + PREARGS_START);
2538 }
2539};
2540
2541/// Extra data stored in some MemberExpr objects.
2542struct MemberExprNameQualifier {
2543 /// The nested-name-specifier that qualifies the name, including
2544 /// source-location information.
2545 NestedNameSpecifierLoc QualifierLoc;
2546
2547 /// The DeclAccessPair through which the MemberDecl was found due to
2548 /// name qualifiers.
2549 DeclAccessPair FoundDecl;
2550};
2551
2552/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2553///
2554class MemberExpr final
2555 : public Expr,
2556 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2557 ASTTemplateKWAndArgsInfo,
2558 TemplateArgumentLoc> {
2559 /// Base - the expression for the base pointer or structure references. In
2560 /// X.F, this is "X".
2561 Stmt *Base;
2562
2563 /// MemberDecl - This is the decl being referenced by the field/member name.
2564 /// In X.F, this is the decl referenced by F.
2565 ValueDecl *MemberDecl;
2566
2567 /// MemberDNLoc - Provides source/type location info for the
2568 /// declaration name embedded in MemberDecl.
2569 DeclarationNameLoc MemberDNLoc;
2570
2571 /// MemberLoc - This is the location of the member name.
2572 SourceLocation MemberLoc;
2573
2574 /// This is the location of the -> or . in the expression.
2575 SourceLocation OperatorLoc;
2576
2577 /// IsArrow - True if this is "X->F", false if this is "X.F".
2578 bool IsArrow : 1;
2579
2580 /// True if this member expression used a nested-name-specifier to
2581 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2582 /// declaration. When true, a MemberExprNameQualifier
2583 /// structure is allocated immediately after the MemberExpr.
2584 bool HasQualifierOrFoundDecl : 1;
2585
2586 /// True if this member expression specified a template keyword
2587 /// and/or a template argument list explicitly, e.g., x->f<int>,
2588 /// x->template f, x->template f<int>.
2589 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2590 /// TemplateArguments (if any) are present.
2591 bool HasTemplateKWAndArgsInfo : 1;
2592
2593 /// True if this member expression refers to a method that
2594 /// was resolved from an overloaded set having size greater than 1.
2595 bool HadMultipleCandidates : 1;
2596
2597 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2598 return HasQualifierOrFoundDecl ? 1 : 0;
2599 }
2600
2601 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2602 return HasTemplateKWAndArgsInfo ? 1 : 0;
2603 }
2604
2605public:
2606 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2607 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2608 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2609 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2610 base->isValueDependent(), base->isInstantiationDependent(),
2611 base->containsUnexpandedParameterPack()),
2612 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2613 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2614 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2615 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2616 assert(memberdecl->getDeclName() == NameInfo.getName());
2617 }
2618
2619 // NOTE: this constructor should be used only when it is known that
2620 // the member name can not provide additional syntactic info
2621 // (i.e., source locations for C++ operator names or type source info
2622 // for constructors, destructors and conversion operators).
2623 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2624 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2625 ExprValueKind VK, ExprObjectKind OK)
2626 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2627 base->isValueDependent(), base->isInstantiationDependent(),
2628 base->containsUnexpandedParameterPack()),
2629 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2630 OperatorLoc(operatorloc), IsArrow(isarrow),
2631 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2632 HadMultipleCandidates(false) {}
2633
2634 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2635 SourceLocation OperatorLoc,
2636 NestedNameSpecifierLoc QualifierLoc,
2637 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2638 DeclAccessPair founddecl,
2639 DeclarationNameInfo MemberNameInfo,
2640 const TemplateArgumentListInfo *targs, QualType ty,
2641 ExprValueKind VK, ExprObjectKind OK);
2642
2643 void setBase(Expr *E) { Base = E; }
2644 Expr *getBase() const { return cast<Expr>(Base); }
2645
2646 /// Retrieve the member declaration to which this expression refers.
2647 ///
2648 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2649 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2650 ValueDecl *getMemberDecl() const { return MemberDecl; }
2651 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2652
2653 /// Retrieves the declaration found by lookup.
2654 DeclAccessPair getFoundDecl() const {
2655 if (!HasQualifierOrFoundDecl)
2656 return DeclAccessPair::make(getMemberDecl(),
2657 getMemberDecl()->getAccess());
2658 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2659 }
2660
2661 /// Determines whether this member expression actually had
2662 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2663 /// x->Base::foo.
2664 bool hasQualifier() const { return getQualifier() != nullptr; }
2665
2666 /// If the member name was qualified, retrieves the
2667 /// nested-name-specifier that precedes the member name, with source-location
2668 /// information.
2669 NestedNameSpecifierLoc getQualifierLoc() const {
2670 if (!HasQualifierOrFoundDecl)
2671 return NestedNameSpecifierLoc();
2672
2673 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2674 }
2675
2676 /// If the member name was qualified, retrieves the
2677 /// nested-name-specifier that precedes the member name. Otherwise, returns
2678 /// NULL.
2679 NestedNameSpecifier *getQualifier() const {
2680 return getQualifierLoc().getNestedNameSpecifier();
2681 }
2682
2683 /// Retrieve the location of the template keyword preceding
2684 /// the member name, if any.
2685 SourceLocation getTemplateKeywordLoc() const {
2686 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2687 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2688 }
2689
2690 /// Retrieve the location of the left angle bracket starting the
2691 /// explicit template argument list following the member name, if any.
2692 SourceLocation getLAngleLoc() const {
2693 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2694 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2695 }
2696
2697 /// Retrieve the location of the right angle bracket ending the
2698 /// explicit template argument list following the member name, if any.
2699 SourceLocation getRAngleLoc() const {
2700 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2701 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2702 }
2703
2704 /// Determines whether the member name was preceded by the template keyword.
2705 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2706
2707 /// Determines whether the member name was followed by an
2708 /// explicit template argument list.
2709 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2710
2711 /// Copies the template arguments (if present) into the given
2712 /// structure.
2713 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2714 if (hasExplicitTemplateArgs())
2715 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2716 getTrailingObjects<TemplateArgumentLoc>(), List);
2717 }
2718
2719 /// Retrieve the template arguments provided as part of this
2720 /// template-id.
2721 const TemplateArgumentLoc *getTemplateArgs() const {
2722 if (!hasExplicitTemplateArgs())
2723 return nullptr;
2724
2725 return getTrailingObjects<TemplateArgumentLoc>();
2726 }
2727
2728 /// Retrieve the number of template arguments provided as part of this
2729 /// template-id.
2730 unsigned getNumTemplateArgs() const {
2731 if (!hasExplicitTemplateArgs())
2732 return 0;
2733
2734 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2735 }
2736
2737 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2738 return {getTemplateArgs(), getNumTemplateArgs()};
2739 }
2740
2741 /// Retrieve the member declaration name info.
2742 DeclarationNameInfo getMemberNameInfo() const {
2743 return DeclarationNameInfo(MemberDecl->getDeclName(),
2744 MemberLoc, MemberDNLoc);
2745 }
2746
2747 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2748
2749 bool isArrow() const { return IsArrow; }
2750 void setArrow(bool A) { IsArrow = A; }
2751
2752 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2753 /// location of 'F'.
2754 SourceLocation getMemberLoc() const { return MemberLoc; }
2755 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2756
2757 SourceLocation getBeginLoc() const LLVM_READONLY;
2758 SourceLocation getEndLoc() const LLVM_READONLY;
2759
2760 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2761
2762 /// Determine whether the base of this explicit is implicit.
2763 bool isImplicitAccess() const {
2764 return getBase() && getBase()->isImplicitCXXThis();
2765 }
2766
2767 /// Returns true if this member expression refers to a method that
2768 /// was resolved from an overloaded set having size greater than 1.
2769 bool hadMultipleCandidates() const {
2770 return HadMultipleCandidates;
2771 }
2772 /// Sets the flag telling whether this expression refers to
2773 /// a method that was resolved from an overloaded set having size
2774 /// greater than 1.
2775 void setHadMultipleCandidates(bool V = true) {
2776 HadMultipleCandidates = V;
2777 }
2778
2779 /// Returns true if virtual dispatch is performed.
2780 /// If the member access is fully qualified, (i.e. X::f()), virtual
2781 /// dispatching is not performed. In -fapple-kext mode qualified
2782 /// calls to virtual method will still go through the vtable.
2783 bool performsVirtualDispatch(const LangOptions &LO) const {
2784 return LO.AppleKext || !hasQualifier();
2785 }
2786
2787 static bool classof(const Stmt *T) {
2788 return T->getStmtClass() == MemberExprClass;
2789 }
2790
2791 // Iterators
2792 child_range children() { return child_range(&Base, &Base+1); }
2793 const_child_range children() const {
2794 return const_child_range(&Base, &Base + 1);
2795 }
2796
2797 friend TrailingObjects;
2798 friend class ASTReader;
2799 friend class ASTStmtWriter;
2800};
2801
2802/// CompoundLiteralExpr - [C99 6.5.2.5]
2803///
2804class CompoundLiteralExpr : public Expr {
2805 /// LParenLoc - If non-null, this is the location of the left paren in a
2806 /// compound literal like "(int){4}". This can be null if this is a
2807 /// synthesized compound expression.
2808 SourceLocation LParenLoc;
2809
2810 /// The type as written. This can be an incomplete array type, in
2811 /// which case the actual expression type will be different.
2812 /// The int part of the pair stores whether this expr is file scope.
2813 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2814 Stmt *Init;
2815public:
2816 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2817 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2818 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2819 tinfo->getType()->isDependentType(),
2820 init->isValueDependent(),
2821 (init->isInstantiationDependent() ||
2822 tinfo->getType()->isInstantiationDependentType()),
2823 init->containsUnexpandedParameterPack()),
2824 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2825
2826 /// Construct an empty compound literal.
2827 explicit CompoundLiteralExpr(EmptyShell Empty)
2828 : Expr(CompoundLiteralExprClass, Empty) { }
2829
2830 const Expr *getInitializer() const { return cast<Expr>(Init); }
2831 Expr *getInitializer() { return cast<Expr>(Init); }
2832 void setInitializer(Expr *E) { Init = E; }
2833
2834 bool isFileScope() const { return TInfoAndScope.getInt(); }
2835 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2836
2837 SourceLocation getLParenLoc() const { return LParenLoc; }
2838 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2839
2840 TypeSourceInfo *getTypeSourceInfo() const {
2841 return TInfoAndScope.getPointer();
2842 }
2843 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2844 TInfoAndScope.setPointer(tinfo);
2845 }
2846
2847 SourceLocation getBeginLoc() const LLVM_READONLY {
2848 // FIXME: Init should never be null.
2849 if (!Init)
2850 return SourceLocation();
2851 if (LParenLoc.isInvalid())
2852 return Init->getBeginLoc();
2853 return LParenLoc;
2854 }
2855 SourceLocation getEndLoc() const LLVM_READONLY {
2856 // FIXME: Init should never be null.
2857 if (!Init)
2858 return SourceLocation();
2859 return Init->getEndLoc();
2860 }
2861
2862 static bool classof(const Stmt *T) {
2863 return T->getStmtClass() == CompoundLiteralExprClass;
2864 }
2865
2866 // Iterators
2867 child_range children() { return child_range(&Init, &Init+1); }
2868 const_child_range