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