1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Expr interface and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CLANG_AST_EXPR_H
14 #define LLVM_CLANG_AST_EXPR_H
15
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTVector.h"
18 #include "clang/AST/ComputeDependence.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/DependenceFlags.h"
22 #include "clang/AST/OperationKinds.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/TemplateBase.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/SyncScope.h"
29 #include "clang/Basic/TypeTraits.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APSInt.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/iterator.h"
35 #include "llvm/ADT/iterator_range.h"
36 #include "llvm/Support/AtomicOrdering.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/TrailingObjects.h"
39
40 namespace clang {
41 class APValue;
42 class ASTContext;
43 class BlockDecl;
44 class CXXBaseSpecifier;
45 class CXXMemberCallExpr;
46 class CXXOperatorCallExpr;
47 class CastExpr;
48 class Decl;
49 class IdentifierInfo;
50 class MaterializeTemporaryExpr;
51 class NamedDecl;
52 class ObjCPropertyRefExpr;
53 class OpaqueValueExpr;
54 class ParmVarDecl;
55 class StringLiteral;
56 class TargetInfo;
57 class ValueDecl;
58
59 /// A simple array of base specifiers.
60 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
61
62 /// An adjustment to be made to the temporary created when emitting a
63 /// reference binding, which accesses a particular subobject of that temporary.
64 struct SubobjectAdjustment {
65 enum {
66 DerivedToBaseAdjustment,
67 FieldAdjustment,
68 MemberPointerAdjustment
69 } Kind;
70
71 struct DTB {
72 const CastExpr *BasePath;
73 const CXXRecordDecl *DerivedClass;
74 };
75
76 struct P {
77 const MemberPointerType *MPT;
78 Expr *RHS;
79 };
80
81 union {
82 struct DTB DerivedToBase;
83 FieldDecl *Field;
84 struct P Ptr;
85 };
86
SubobjectAdjustmentSubobjectAdjustment87 SubobjectAdjustment(const CastExpr *BasePath,
88 const CXXRecordDecl *DerivedClass)
89 : Kind(DerivedToBaseAdjustment) {
90 DerivedToBase.BasePath = BasePath;
91 DerivedToBase.DerivedClass = DerivedClass;
92 }
93
SubobjectAdjustmentSubobjectAdjustment94 SubobjectAdjustment(FieldDecl *Field)
95 : Kind(FieldAdjustment) {
96 this->Field = Field;
97 }
98
SubobjectAdjustmentSubobjectAdjustment99 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
100 : Kind(MemberPointerAdjustment) {
101 this->Ptr.MPT = MPT;
102 this->Ptr.RHS = RHS;
103 }
104 };
105
106 /// This represents one expression. Note that Expr's are subclasses of Stmt.
107 /// This allows an expression to be transparently used any place a Stmt is
108 /// required.
109 class Expr : public ValueStmt {
110 QualType TR;
111
112 public:
113 Expr() = delete;
114 Expr(const Expr&) = delete;
115 Expr(Expr &&) = delete;
116 Expr &operator=(const Expr&) = delete;
117 Expr &operator=(Expr&&) = delete;
118
119 protected:
Expr(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK)120 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
121 : ValueStmt(SC) {
122 ExprBits.Dependent = 0;
123 ExprBits.ValueKind = VK;
124 ExprBits.ObjectKind = OK;
125 assert(ExprBits.ObjectKind == OK && "truncated kind");
126 setType(T);
127 }
128
129 /// Construct an empty expression.
Expr(StmtClass SC,EmptyShell)130 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
131
132 /// Each concrete expr subclass is expected to compute its dependence and call
133 /// this in the constructor.
setDependence(ExprDependence Deps)134 void setDependence(ExprDependence Deps) {
135 ExprBits.Dependent = static_cast<unsigned>(Deps);
136 }
137 friend class ASTImporter; // Sets dependence dircetly.
138 friend class ASTStmtReader; // Sets dependence dircetly.
139
140 public:
getType()141 QualType getType() const { return TR; }
setType(QualType t)142 void setType(QualType t) {
143 // In C++, the type of an expression is always adjusted so that it
144 // will not have reference type (C++ [expr]p6). Use
145 // QualType::getNonReferenceType() to retrieve the non-reference
146 // type. Additionally, inspect Expr::isLvalue to determine whether
147 // an expression that is adjusted in this manner should be
148 // considered an lvalue.
149 assert((t.isNull() || !t->isReferenceType()) &&
150 "Expressions can't have reference type");
151
152 TR = t;
153 }
154
getDependence()155 ExprDependence getDependence() const {
156 return static_cast<ExprDependence>(ExprBits.Dependent);
157 }
158
159 /// Determines whether the value of this expression depends on
160 /// - a template parameter (C++ [temp.dep.constexpr])
161 /// - or an error, whose resolution is unknown
162 ///
163 /// For example, the array bound of "Chars" in the following example is
164 /// value-dependent.
165 /// @code
166 /// template<int Size, char (&Chars)[Size]> struct meta_string;
167 /// @endcode
isValueDependent()168 bool isValueDependent() const {
169 return static_cast<bool>(getDependence() & ExprDependence::Value);
170 }
171
172 /// Determines whether the type of this expression depends on
173 /// - a template paramter (C++ [temp.dep.expr], which means that its type
174 /// could change from one template instantiation to the next)
175 /// - or an error
176 ///
177 /// For example, the expressions "x" and "x + y" are type-dependent in
178 /// the following code, but "y" is not type-dependent:
179 /// @code
180 /// template<typename T>
181 /// void add(T x, int y) {
182 /// x + y;
183 /// }
184 /// @endcode
isTypeDependent()185 bool isTypeDependent() const {
186 return static_cast<bool>(getDependence() & ExprDependence::Type);
187 }
188
189 /// Whether this expression is instantiation-dependent, meaning that
190 /// it depends in some way on
191 /// - a template parameter (even if neither its type nor (constant) value
192 /// can change due to the template instantiation)
193 /// - or an error
194 ///
195 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
196 /// instantiation-dependent (since it involves a template parameter \c T), but
197 /// is neither type- nor value-dependent, since the type of the inner
198 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
199 /// \c sizeof is known.
200 ///
201 /// \code
202 /// template<typename T>
203 /// void f(T x, T y) {
204 /// sizeof(sizeof(T() + T());
205 /// }
206 /// \endcode
207 ///
208 /// \code
209 /// void func(int) {
210 /// func(); // the expression is instantiation-dependent, because it depends
211 /// // on an error.
212 /// }
213 /// \endcode
isInstantiationDependent()214 bool isInstantiationDependent() const {
215 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
216 }
217
218 /// Whether this expression contains an unexpanded parameter
219 /// pack (for C++11 variadic templates).
220 ///
221 /// Given the following function template:
222 ///
223 /// \code
224 /// template<typename F, typename ...Types>
225 /// void forward(const F &f, Types &&...args) {
226 /// f(static_cast<Types&&>(args)...);
227 /// }
228 /// \endcode
229 ///
230 /// The expressions \c args and \c static_cast<Types&&>(args) both
231 /// contain parameter packs.
containsUnexpandedParameterPack()232 bool containsUnexpandedParameterPack() const {
233 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
234 }
235
236 /// Whether this expression contains subexpressions which had errors, e.g. a
237 /// TypoExpr.
containsErrors()238 bool containsErrors() const {
239 return static_cast<bool>(getDependence() & ExprDependence::Error);
240 }
241
242 /// getExprLoc - Return the preferred location for the arrow when diagnosing
243 /// a problem with a generic expression.
244 SourceLocation getExprLoc() const LLVM_READONLY;
245
246 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
247 /// applied to this expression if it appears as a discarded-value expression
248 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
249 bool isReadIfDiscardedInCPlusPlus11() const;
250
251 /// isUnusedResultAWarning - Return true if this immediate expression should
252 /// be warned about if the result is unused. If so, fill in expr, location,
253 /// and ranges with expr to warn on and source locations/ranges appropriate
254 /// for a warning.
255 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
256 SourceRange &R1, SourceRange &R2,
257 ASTContext &Ctx) const;
258
259 /// isLValue - True if this expression is an "l-value" according to
260 /// the rules of the current language. C and C++ give somewhat
261 /// different rules for this concept, but in general, the result of
262 /// an l-value expression identifies a specific object whereas the
263 /// result of an r-value expression is a value detached from any
264 /// specific storage.
265 ///
266 /// C++11 divides the concept of "r-value" into pure r-values
267 /// ("pr-values") and so-called expiring values ("x-values"), which
268 /// identify specific objects that can be safely cannibalized for
269 /// their resources. This is an unfortunate abuse of terminology on
270 /// the part of the C++ committee. In Clang, when we say "r-value",
271 /// we generally mean a pr-value.
isLValue()272 bool isLValue() const { return getValueKind() == VK_LValue; }
isRValue()273 bool isRValue() const { return getValueKind() == VK_RValue; }
isXValue()274 bool isXValue() const { return getValueKind() == VK_XValue; }
isGLValue()275 bool isGLValue() const { return getValueKind() != VK_RValue; }
276
277 enum LValueClassification {
278 LV_Valid,
279 LV_NotObjectType,
280 LV_IncompleteVoidType,
281 LV_DuplicateVectorComponents,
282 LV_InvalidExpression,
283 LV_InvalidMessageExpression,
284 LV_MemberFunction,
285 LV_SubObjCPropertySetting,
286 LV_ClassTemporary,
287 LV_ArrayTemporary
288 };
289 /// Reasons why an expression might not be an l-value.
290 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
291
292 enum isModifiableLvalueResult {
293 MLV_Valid,
294 MLV_NotObjectType,
295 MLV_IncompleteVoidType,
296 MLV_DuplicateVectorComponents,
297 MLV_InvalidExpression,
298 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
299 MLV_IncompleteType,
300 MLV_ConstQualified,
301 MLV_ConstQualifiedField,
302 MLV_ConstAddrSpace,
303 MLV_ArrayType,
304 MLV_NoSetterProperty,
305 MLV_MemberFunction,
306 MLV_SubObjCPropertySetting,
307 MLV_InvalidMessageExpression,
308 MLV_ClassTemporary,
309 MLV_ArrayTemporary
310 };
311 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
312 /// does not have an incomplete type, does not have a const-qualified type,
313 /// and if it is a structure or union, does not have any member (including,
314 /// recursively, any member or element of all contained aggregates or unions)
315 /// with a const-qualified type.
316 ///
317 /// \param Loc [in,out] - A source location which *may* be filled
318 /// in with the location of the expression making this a
319 /// non-modifiable lvalue, if specified.
320 isModifiableLvalueResult
321 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
322
323 /// The return type of classify(). Represents the C++11 expression
324 /// taxonomy.
325 class Classification {
326 public:
327 /// The various classification results. Most of these mean prvalue.
328 enum Kinds {
329 CL_LValue,
330 CL_XValue,
331 CL_Function, // Functions cannot be lvalues in C.
332 CL_Void, // Void cannot be an lvalue in C.
333 CL_AddressableVoid, // Void expression whose address can be taken in C.
334 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
335 CL_MemberFunction, // An expression referring to a member function
336 CL_SubObjCPropertySetting,
337 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
338 CL_ArrayTemporary, // A temporary of array type.
339 CL_ObjCMessageRValue, // ObjC message is an rvalue
340 CL_PRValue // A prvalue for any other reason, of any other type
341 };
342 /// The results of modification testing.
343 enum ModifiableType {
344 CM_Untested, // testModifiable was false.
345 CM_Modifiable,
346 CM_RValue, // Not modifiable because it's an rvalue
347 CM_Function, // Not modifiable because it's a function; C++ only
348 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
349 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
350 CM_ConstQualified,
351 CM_ConstQualifiedField,
352 CM_ConstAddrSpace,
353 CM_ArrayType,
354 CM_IncompleteType
355 };
356
357 private:
358 friend class Expr;
359
360 unsigned short Kind;
361 unsigned short Modifiable;
362
Classification(Kinds k,ModifiableType m)363 explicit Classification(Kinds k, ModifiableType m)
364 : Kind(k), Modifiable(m)
365 {}
366
367 public:
Classification()368 Classification() {}
369
getKind()370 Kinds getKind() const { return static_cast<Kinds>(Kind); }
getModifiable()371 ModifiableType getModifiable() const {
372 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
373 return static_cast<ModifiableType>(Modifiable);
374 }
isLValue()375 bool isLValue() const { return Kind == CL_LValue; }
isXValue()376 bool isXValue() const { return Kind == CL_XValue; }
isGLValue()377 bool isGLValue() const { return Kind <= CL_XValue; }
isPRValue()378 bool isPRValue() const { return Kind >= CL_Function; }
isRValue()379 bool isRValue() const { return Kind >= CL_XValue; }
isModifiable()380 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
381
382 /// Create a simple, modifiably lvalue
makeSimpleLValue()383 static Classification makeSimpleLValue() {
384 return Classification(CL_LValue, CM_Modifiable);
385 }
386
387 };
388 /// Classify - Classify this expression according to the C++11
389 /// expression taxonomy.
390 ///
391 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
392 /// old lvalue vs rvalue. This function determines the type of expression this
393 /// is. There are three expression types:
394 /// - lvalues are classical lvalues as in C++03.
395 /// - prvalues are equivalent to rvalues in C++03.
396 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
397 /// function returning an rvalue reference.
398 /// lvalues and xvalues are collectively referred to as glvalues, while
399 /// prvalues and xvalues together form rvalues.
Classify(ASTContext & Ctx)400 Classification Classify(ASTContext &Ctx) const {
401 return ClassifyImpl(Ctx, nullptr);
402 }
403
404 /// ClassifyModifiable - Classify this expression according to the
405 /// C++11 expression taxonomy, and see if it is valid on the left side
406 /// of an assignment.
407 ///
408 /// This function extends classify in that it also tests whether the
409 /// expression is modifiable (C99 6.3.2.1p1).
410 /// \param Loc A source location that might be filled with a relevant location
411 /// if the expression is not modifiable.
ClassifyModifiable(ASTContext & Ctx,SourceLocation & Loc)412 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
413 return ClassifyImpl(Ctx, &Loc);
414 }
415
416 /// Returns the set of floating point options that apply to this expression.
417 /// Only meaningful for operations on floating point values.
418 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
419
420 /// getValueKindForType - Given a formal return or parameter type,
421 /// give its value kind.
getValueKindForType(QualType T)422 static ExprValueKind getValueKindForType(QualType T) {
423 if (const ReferenceType *RT = T->getAs<ReferenceType>())
424 return (isa<LValueReferenceType>(RT)
425 ? VK_LValue
426 : (RT->getPointeeType()->isFunctionType()
427 ? VK_LValue : VK_XValue));
428 return VK_RValue;
429 }
430
431 /// getValueKind - The value kind that this expression produces.
getValueKind()432 ExprValueKind getValueKind() const {
433 return static_cast<ExprValueKind>(ExprBits.ValueKind);
434 }
435
436 /// getObjectKind - The object kind that this expression produces.
437 /// Object kinds are meaningful only for expressions that yield an
438 /// l-value or x-value.
getObjectKind()439 ExprObjectKind getObjectKind() const {
440 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
441 }
442
isOrdinaryOrBitFieldObject()443 bool isOrdinaryOrBitFieldObject() const {
444 ExprObjectKind OK = getObjectKind();
445 return (OK == OK_Ordinary || OK == OK_BitField);
446 }
447
448 /// setValueKind - Set the value kind produced by this expression.
setValueKind(ExprValueKind Cat)449 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
450
451 /// setObjectKind - Set the object kind produced by this expression.
setObjectKind(ExprObjectKind Cat)452 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
453
454 private:
455 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
456
457 public:
458
459 /// Returns true if this expression is a gl-value that
460 /// potentially refers to a bit-field.
461 ///
462 /// In C++, whether a gl-value refers to a bitfield is essentially
463 /// an aspect of the value-kind type system.
refersToBitField()464 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
465
466 /// If this expression refers to a bit-field, retrieve the
467 /// declaration of that bit-field.
468 ///
469 /// Note that this returns a non-null pointer in subtly different
470 /// places than refersToBitField returns true. In particular, this can
471 /// return a non-null pointer even for r-values loaded from
472 /// bit-fields, but it will return null for a conditional bit-field.
473 FieldDecl *getSourceBitField();
474
getSourceBitField()475 const FieldDecl *getSourceBitField() const {
476 return const_cast<Expr*>(this)->getSourceBitField();
477 }
478
479 Decl *getReferencedDeclOfCallee();
getReferencedDeclOfCallee()480 const Decl *getReferencedDeclOfCallee() const {
481 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
482 }
483
484 /// If this expression is an l-value for an Objective C
485 /// property, find the underlying property reference expression.
486 const ObjCPropertyRefExpr *getObjCProperty() const;
487
488 /// Check if this expression is the ObjC 'self' implicit parameter.
489 bool isObjCSelfExpr() const;
490
491 /// Returns whether this expression refers to a vector element.
492 bool refersToVectorElement() const;
493
494 /// Returns whether this expression refers to a matrix element.
refersToMatrixElement()495 bool refersToMatrixElement() const {
496 return getObjectKind() == OK_MatrixComponent;
497 }
498
499 /// Returns whether this expression refers to a global register
500 /// variable.
501 bool refersToGlobalRegisterVar() const;
502
503 /// Returns whether this expression has a placeholder type.
hasPlaceholderType()504 bool hasPlaceholderType() const {
505 return getType()->isPlaceholderType();
506 }
507
508 /// Returns whether this expression has a specific placeholder type.
hasPlaceholderType(BuiltinType::Kind K)509 bool hasPlaceholderType(BuiltinType::Kind K) const {
510 assert(BuiltinType::isPlaceholderTypeKind(K));
511 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
512 return BT->getKind() == K;
513 return false;
514 }
515
516 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
517 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
518 /// but also int expressions which are produced by things like comparisons in
519 /// C.
520 ///
521 /// \param Semantic If true, only return true for expressions that are known
522 /// to be semantically boolean, which might not be true even for expressions
523 /// that are known to evaluate to 0/1. For instance, reading an unsigned
524 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
525 /// semantically correspond to a bool.
526 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
527
528 /// isIntegerConstantExpr - Return the value if this expression is a valid
529 /// integer constant expression. If not a valid i-c-e, return None and fill
530 /// in Loc (if specified) with the location of the invalid expression.
531 ///
532 /// Note: This does not perform the implicit conversions required by C++11
533 /// [expr.const]p5.
534 Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx,
535 SourceLocation *Loc = nullptr,
536 bool isEvaluated = true) const;
537 bool isIntegerConstantExpr(const ASTContext &Ctx,
538 SourceLocation *Loc = nullptr) const;
539
540 /// isCXX98IntegralConstantExpr - Return true if this expression is an
541 /// integral constant expression in C++98. Can only be used in C++.
542 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
543
544 /// isCXX11ConstantExpr - Return true if this expression is a constant
545 /// expression in C++11. Can only be used in C++.
546 ///
547 /// Note: This does not perform the implicit conversions required by C++11
548 /// [expr.const]p5.
549 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
550 SourceLocation *Loc = nullptr) const;
551
552 /// isPotentialConstantExpr - Return true if this function's definition
553 /// might be usable in a constant expression in C++11, if it were marked
554 /// constexpr. Return false if the function can never produce a constant
555 /// expression, along with diagnostics describing why not.
556 static bool isPotentialConstantExpr(const FunctionDecl *FD,
557 SmallVectorImpl<
558 PartialDiagnosticAt> &Diags);
559
560 /// isPotentialConstantExprUnevaluted - Return true if this expression might
561 /// be usable in a constant expression in C++11 in an unevaluated context, if
562 /// it were in function FD marked constexpr. Return false if the function can
563 /// never produce a constant expression, along with diagnostics describing
564 /// why not.
565 static bool isPotentialConstantExprUnevaluated(Expr *E,
566 const FunctionDecl *FD,
567 SmallVectorImpl<
568 PartialDiagnosticAt> &Diags);
569
570 /// isConstantInitializer - Returns true if this expression can be emitted to
571 /// IR as a constant, and thus can be used as a constant initializer in C.
572 /// If this expression is not constant and Culprit is non-null,
573 /// it is used to store the address of first non constant expr.
574 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
575 const Expr **Culprit = nullptr) const;
576
577 /// EvalStatus is a struct with detailed info about an evaluation in progress.
578 struct EvalStatus {
579 /// Whether the evaluated expression has side effects.
580 /// For example, (f() && 0) can be folded, but it still has side effects.
581 bool HasSideEffects;
582
583 /// Whether the evaluation hit undefined behavior.
584 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
585 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
586 bool HasUndefinedBehavior;
587
588 /// Diag - If this is non-null, it will be filled in with a stack of notes
589 /// indicating why evaluation failed (or why it failed to produce a constant
590 /// expression).
591 /// If the expression is unfoldable, the notes will indicate why it's not
592 /// foldable. If the expression is foldable, but not a constant expression,
593 /// the notes will describes why it isn't a constant expression. If the
594 /// expression *is* a constant expression, no notes will be produced.
595 SmallVectorImpl<PartialDiagnosticAt> *Diag;
596
EvalStatusEvalStatus597 EvalStatus()
598 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
599
600 // hasSideEffects - Return true if the evaluated expression has
601 // side effects.
hasSideEffectsEvalStatus602 bool hasSideEffects() const {
603 return HasSideEffects;
604 }
605 };
606
607 /// EvalResult is a struct with detailed info about an evaluated expression.
608 struct EvalResult : EvalStatus {
609 /// Val - This is the value the expression can be folded to.
610 APValue Val;
611
612 // isGlobalLValue - Return true if the evaluated lvalue expression
613 // is global.
614 bool isGlobalLValue() const;
615 };
616
617 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
618 /// an rvalue using any crazy technique (that has nothing to do with language
619 /// standards) that we want to, even if the expression has side-effects. If
620 /// this function returns true, it returns the folded constant in Result. If
621 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
622 /// applied.
623 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
624 bool InConstantContext = false) const;
625
626 /// EvaluateAsBooleanCondition - Return true if this is a constant
627 /// which we can fold and convert to a boolean condition using
628 /// any crazy technique that we want to, even if the expression has
629 /// side-effects.
630 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
631 bool InConstantContext = false) const;
632
633 enum SideEffectsKind {
634 SE_NoSideEffects, ///< Strictly evaluate the expression.
635 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
636 ///< arbitrary unmodeled side effects.
637 SE_AllowSideEffects ///< Allow any unmodeled side effect.
638 };
639
640 /// EvaluateAsInt - Return true if this is a constant which we can fold and
641 /// convert to an integer, using any crazy technique that we want to.
642 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
643 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
644 bool InConstantContext = false) const;
645
646 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
647 /// convert to a floating point value, using any crazy technique that we
648 /// want to.
649 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
650 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
651 bool InConstantContext = false) const;
652
653 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
654 /// convert to a fixed point value.
655 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
656 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
657 bool InConstantContext = false) const;
658
659 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
660 /// constant folded without side-effects, but discard the result.
661 bool isEvaluatable(const ASTContext &Ctx,
662 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
663
664 /// HasSideEffects - This routine returns true for all those expressions
665 /// which have any effect other than producing a value. Example is a function
666 /// call, volatile variable read, or throwing an exception. If
667 /// IncludePossibleEffects is false, this call treats certain expressions with
668 /// potential side effects (such as function call-like expressions,
669 /// instantiation-dependent expressions, or invocations from a macro) as not
670 /// having side effects.
671 bool HasSideEffects(const ASTContext &Ctx,
672 bool IncludePossibleEffects = true) const;
673
674 /// Determine whether this expression involves a call to any function
675 /// that is not trivial.
676 bool hasNonTrivialCall(const ASTContext &Ctx) const;
677
678 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
679 /// integer. This must be called on an expression that constant folds to an
680 /// integer.
681 llvm::APSInt EvaluateKnownConstInt(
682 const ASTContext &Ctx,
683 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
684
685 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
686 const ASTContext &Ctx,
687 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
688
689 void EvaluateForOverflow(const ASTContext &Ctx) const;
690
691 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
692 /// lvalue with link time known address, with no side-effects.
693 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
694 bool InConstantContext = false) const;
695
696 /// EvaluateAsInitializer - Evaluate an expression as if it were the
697 /// initializer of the given declaration. Returns true if the initializer
698 /// can be folded to a constant, and produces any relevant notes. In C++11,
699 /// notes will be produced if the expression is not a constant expression.
700 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
701 const VarDecl *VD,
702 SmallVectorImpl<PartialDiagnosticAt> &Notes,
703 bool IsConstantInitializer) const;
704
705 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
706 /// of a call to the given function with the given arguments, inside an
707 /// unevaluated context. Returns true if the expression could be folded to a
708 /// constant.
709 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
710 const FunctionDecl *Callee,
711 ArrayRef<const Expr*> Args,
712 const Expr *This = nullptr) const;
713
714 enum class ConstantExprKind {
715 /// An integer constant expression (an array bound, enumerator, case value,
716 /// bit-field width, or similar) or similar.
717 Normal,
718 /// A non-class template argument. Such a value is only used for mangling,
719 /// not for code generation, so can refer to dllimported functions.
720 NonClassTemplateArgument,
721 /// A class template argument. Such a value is used for code generation.
722 ClassTemplateArgument,
723 /// An immediate invocation. The destruction of the end result of this
724 /// evaluation is not part of the evaluation, but all other temporaries
725 /// are destroyed.
726 ImmediateInvocation,
727 };
728
729 /// Evaluate an expression that is required to be a constant expression. Does
730 /// not check the syntactic constraints for C and C++98 constant expressions.
731 bool EvaluateAsConstantExpr(
732 EvalResult &Result, const ASTContext &Ctx,
733 ConstantExprKind Kind = ConstantExprKind::Normal) const;
734
735 /// If the current Expr is a pointer, this will try to statically
736 /// determine the number of bytes available where the pointer is pointing.
737 /// Returns true if all of the above holds and we were able to figure out the
738 /// size, false otherwise.
739 ///
740 /// \param Type - How to evaluate the size of the Expr, as defined by the
741 /// "type" parameter of __builtin_object_size
742 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
743 unsigned Type) const;
744
745 /// Enumeration used to describe the kind of Null pointer constant
746 /// returned from \c isNullPointerConstant().
747 enum NullPointerConstantKind {
748 /// Expression is not a Null pointer constant.
749 NPCK_NotNull = 0,
750
751 /// Expression is a Null pointer constant built from a zero integer
752 /// expression that is not a simple, possibly parenthesized, zero literal.
753 /// C++ Core Issue 903 will classify these expressions as "not pointers"
754 /// once it is adopted.
755 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
756 NPCK_ZeroExpression,
757
758 /// Expression is a Null pointer constant built from a literal zero.
759 NPCK_ZeroLiteral,
760
761 /// Expression is a C++11 nullptr.
762 NPCK_CXX11_nullptr,
763
764 /// Expression is a GNU-style __null constant.
765 NPCK_GNUNull
766 };
767
768 /// Enumeration used to describe how \c isNullPointerConstant()
769 /// should cope with value-dependent expressions.
770 enum NullPointerConstantValueDependence {
771 /// Specifies that the expression should never be value-dependent.
772 NPC_NeverValueDependent = 0,
773
774 /// Specifies that a value-dependent expression of integral or
775 /// dependent type should be considered a null pointer constant.
776 NPC_ValueDependentIsNull,
777
778 /// Specifies that a value-dependent expression should be considered
779 /// to never be a null pointer constant.
780 NPC_ValueDependentIsNotNull
781 };
782
783 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
784 /// a Null pointer constant. The return value can further distinguish the
785 /// kind of NULL pointer constant that was detected.
786 NullPointerConstantKind isNullPointerConstant(
787 ASTContext &Ctx,
788 NullPointerConstantValueDependence NPC) const;
789
790 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
791 /// write barrier.
792 bool isOBJCGCCandidate(ASTContext &Ctx) const;
793
794 /// Returns true if this expression is a bound member function.
795 bool isBoundMemberFunction(ASTContext &Ctx) const;
796
797 /// Given an expression of bound-member type, find the type
798 /// of the member. Returns null if this is an *overloaded* bound
799 /// member expression.
800 static QualType findBoundMemberType(const Expr *expr);
801
802 /// Skip past any invisble AST nodes which might surround this
803 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
804 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
805 /// implicit conversions.
806 Expr *IgnoreUnlessSpelledInSource();
IgnoreUnlessSpelledInSource()807 const Expr *IgnoreUnlessSpelledInSource() const {
808 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
809 }
810
811 /// Skip past any implicit casts which might surround this expression until
812 /// reaching a fixed point. Skips:
813 /// * ImplicitCastExpr
814 /// * FullExpr
815 Expr *IgnoreImpCasts() LLVM_READONLY;
IgnoreImpCasts()816 const Expr *IgnoreImpCasts() const {
817 return const_cast<Expr *>(this)->IgnoreImpCasts();
818 }
819
820 /// Skip past any casts which might surround this expression until reaching
821 /// a fixed point. Skips:
822 /// * CastExpr
823 /// * FullExpr
824 /// * MaterializeTemporaryExpr
825 /// * SubstNonTypeTemplateParmExpr
826 Expr *IgnoreCasts() LLVM_READONLY;
IgnoreCasts()827 const Expr *IgnoreCasts() const {
828 return const_cast<Expr *>(this)->IgnoreCasts();
829 }
830
831 /// Skip past any implicit AST nodes which might surround this expression
832 /// until reaching a fixed point. Skips:
833 /// * What IgnoreImpCasts() skips
834 /// * MaterializeTemporaryExpr
835 /// * CXXBindTemporaryExpr
836 Expr *IgnoreImplicit() LLVM_READONLY;
IgnoreImplicit()837 const Expr *IgnoreImplicit() const {
838 return const_cast<Expr *>(this)->IgnoreImplicit();
839 }
840
841 /// Skip past any implicit AST nodes which might surround this expression
842 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
843 /// also skips over implicit calls to constructors and conversion functions.
844 ///
845 /// FIXME: Should IgnoreImplicit do this?
846 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
IgnoreImplicitAsWritten()847 const Expr *IgnoreImplicitAsWritten() const {
848 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
849 }
850
851 /// Skip past any parentheses which might surround this expression until
852 /// reaching a fixed point. Skips:
853 /// * ParenExpr
854 /// * UnaryOperator if `UO_Extension`
855 /// * GenericSelectionExpr if `!isResultDependent()`
856 /// * ChooseExpr if `!isConditionDependent()`
857 /// * ConstantExpr
858 Expr *IgnoreParens() LLVM_READONLY;
IgnoreParens()859 const Expr *IgnoreParens() const {
860 return const_cast<Expr *>(this)->IgnoreParens();
861 }
862
863 /// Skip past any parentheses and implicit casts which might surround this
864 /// expression until reaching a fixed point.
865 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
866 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
867 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
868 /// * What IgnoreParens() skips
869 /// * What IgnoreImpCasts() skips
870 /// * MaterializeTemporaryExpr
871 /// * SubstNonTypeTemplateParmExpr
872 Expr *IgnoreParenImpCasts() LLVM_READONLY;
IgnoreParenImpCasts()873 const Expr *IgnoreParenImpCasts() const {
874 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
875 }
876
877 /// Skip past any parentheses and casts which might surround this expression
878 /// until reaching a fixed point. Skips:
879 /// * What IgnoreParens() skips
880 /// * What IgnoreCasts() skips
881 Expr *IgnoreParenCasts() LLVM_READONLY;
IgnoreParenCasts()882 const Expr *IgnoreParenCasts() const {
883 return const_cast<Expr *>(this)->IgnoreParenCasts();
884 }
885
886 /// Skip conversion operators. If this Expr is a call to a conversion
887 /// operator, return the argument.
888 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
IgnoreConversionOperatorSingleStep()889 const Expr *IgnoreConversionOperatorSingleStep() const {
890 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
891 }
892
893 /// Skip past any parentheses and lvalue casts which might surround this
894 /// expression until reaching a fixed point. Skips:
895 /// * What IgnoreParens() skips
896 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
897 /// casts are skipped
898 /// FIXME: This is intended purely as a temporary workaround for code
899 /// that hasn't yet been rewritten to do the right thing about those
900 /// casts, and may disappear along with the last internal use.
901 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
IgnoreParenLValueCasts()902 const Expr *IgnoreParenLValueCasts() const {
903 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
904 }
905
906 /// Skip past any parenthese and casts which do not change the value
907 /// (including ptr->int casts of the same size) until reaching a fixed point.
908 /// Skips:
909 /// * What IgnoreParens() skips
910 /// * CastExpr which do not change the value
911 /// * SubstNonTypeTemplateParmExpr
912 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
IgnoreParenNoopCasts(const ASTContext & Ctx)913 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
914 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
915 }
916
917 /// Skip past any parentheses and derived-to-base casts until reaching a
918 /// fixed point. Skips:
919 /// * What IgnoreParens() skips
920 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
921 /// CK_UncheckedDerivedToBase and CK_NoOp)
922 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
IgnoreParenBaseCasts()923 const Expr *IgnoreParenBaseCasts() const {
924 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
925 }
926
927 /// Determine whether this expression is a default function argument.
928 ///
929 /// Default arguments are implicitly generated in the abstract syntax tree
930 /// by semantic analysis for function calls, object constructions, etc. in
931 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
932 /// this routine also looks through any implicit casts to determine whether
933 /// the expression is a default argument.
934 bool isDefaultArgument() const;
935
936 /// Determine whether the result of this expression is a
937 /// temporary object of the given class type.
938 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
939
940 /// Whether this expression is an implicit reference to 'this' in C++.
941 bool isImplicitCXXThis() const;
942
943 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
944
945 /// For an expression of class type or pointer to class type,
946 /// return the most derived class decl the expression is known to refer to.
947 ///
948 /// If this expression is a cast, this method looks through it to find the
949 /// most derived decl that can be inferred from the expression.
950 /// This is valid because derived-to-base conversions have undefined
951 /// behavior if the object isn't dynamically of the derived type.
952 const CXXRecordDecl *getBestDynamicClassType() const;
953
954 /// Get the inner expression that determines the best dynamic class.
955 /// If this is a prvalue, we guarantee that it is of the most-derived type
956 /// for the object itself.
957 const Expr *getBestDynamicClassTypeExpr() const;
958
959 /// Walk outwards from an expression we want to bind a reference to and
960 /// find the expression whose lifetime needs to be extended. Record
961 /// the LHSs of comma expressions and adjustments needed along the path.
962 const Expr *skipRValueSubobjectAdjustments(
963 SmallVectorImpl<const Expr *> &CommaLHS,
964 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
skipRValueSubobjectAdjustments()965 const Expr *skipRValueSubobjectAdjustments() const {
966 SmallVector<const Expr *, 8> CommaLHSs;
967 SmallVector<SubobjectAdjustment, 8> Adjustments;
968 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
969 }
970
971 /// Checks that the two Expr's will refer to the same value as a comparison
972 /// operand. The caller must ensure that the values referenced by the Expr's
973 /// are not modified between E1 and E2 or the result my be invalid.
974 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
975
classof(const Stmt * T)976 static bool classof(const Stmt *T) {
977 return T->getStmtClass() >= firstExprConstant &&
978 T->getStmtClass() <= lastExprConstant;
979 }
980 };
981 // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
982 // Expr. Verify that we got it right.
983 static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
984 llvm::detail::ConstantLog2<alignof(Expr)>::value,
985 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
986
987 using ConstantExprKind = Expr::ConstantExprKind;
988
989 //===----------------------------------------------------------------------===//
990 // Wrapper Expressions.
991 //===----------------------------------------------------------------------===//
992
993 /// FullExpr - Represents a "full-expression" node.
994 class FullExpr : public Expr {
995 protected:
996 Stmt *SubExpr;
997
FullExpr(StmtClass SC,Expr * subexpr)998 FullExpr(StmtClass SC, Expr *subexpr)
999 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1000 subexpr->getObjectKind()),
1001 SubExpr(subexpr) {
1002 setDependence(computeDependence(this));
1003 }
FullExpr(StmtClass SC,EmptyShell Empty)1004 FullExpr(StmtClass SC, EmptyShell Empty)
1005 : Expr(SC, Empty) {}
1006 public:
getSubExpr()1007 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
getSubExpr()1008 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1009
1010 /// As with any mutator of the AST, be very careful when modifying an
1011 /// existing AST to preserve its invariants.
setSubExpr(Expr * E)1012 void setSubExpr(Expr *E) { SubExpr = E; }
1013
classof(const Stmt * T)1014 static bool classof(const Stmt *T) {
1015 return T->getStmtClass() >= firstFullExprConstant &&
1016 T->getStmtClass() <= lastFullExprConstant;
1017 }
1018 };
1019
1020 /// ConstantExpr - An expression that occurs in a constant context and
1021 /// optionally the result of evaluating the expression.
1022 class ConstantExpr final
1023 : public FullExpr,
1024 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1025 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1026 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1027 "for tail-allocated storage");
1028 friend TrailingObjects;
1029 friend class ASTStmtReader;
1030 friend class ASTStmtWriter;
1031
1032 public:
1033 /// Describes the kind of result that can be tail-allocated.
1034 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
1035
1036 private:
numTrailingObjects(OverloadToken<APValue>)1037 size_t numTrailingObjects(OverloadToken<APValue>) const {
1038 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
1039 }
numTrailingObjects(OverloadToken<uint64_t>)1040 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1041 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
1042 }
1043
Int64Result()1044 uint64_t &Int64Result() {
1045 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
1046 "invalid accessor");
1047 return *getTrailingObjects<uint64_t>();
1048 }
Int64Result()1049 const uint64_t &Int64Result() const {
1050 return const_cast<ConstantExpr *>(this)->Int64Result();
1051 }
APValueResult()1052 APValue &APValueResult() {
1053 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
1054 "invalid accessor");
1055 return *getTrailingObjects<APValue>();
1056 }
APValueResult()1057 APValue &APValueResult() const {
1058 return const_cast<ConstantExpr *>(this)->APValueResult();
1059 }
1060
1061 ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
1062 bool IsImmediateInvocation);
1063 ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
1064
1065 public:
1066 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1067 const APValue &Result);
1068 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1069 ResultStorageKind Storage = RSK_None,
1070 bool IsImmediateInvocation = false);
1071 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1072 ResultStorageKind StorageKind);
1073
1074 static ResultStorageKind getStorageKind(const APValue &Value);
1075 static ResultStorageKind getStorageKind(const Type *T,
1076 const ASTContext &Context);
1077
getBeginLoc()1078 SourceLocation getBeginLoc() const LLVM_READONLY {
1079 return SubExpr->getBeginLoc();
1080 }
getEndLoc()1081 SourceLocation getEndLoc() const LLVM_READONLY {
1082 return SubExpr->getEndLoc();
1083 }
1084
classof(const Stmt * T)1085 static bool classof(const Stmt *T) {
1086 return T->getStmtClass() == ConstantExprClass;
1087 }
1088
SetResult(APValue Value,const ASTContext & Context)1089 void SetResult(APValue Value, const ASTContext &Context) {
1090 MoveIntoResult(Value, Context);
1091 }
1092 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1093
getResultAPValueKind()1094 APValue::ValueKind getResultAPValueKind() const {
1095 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1096 }
getResultStorageKind()1097 ResultStorageKind getResultStorageKind() const {
1098 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1099 }
isImmediateInvocation()1100 bool isImmediateInvocation() const {
1101 return ConstantExprBits.IsImmediateInvocation;
1102 }
hasAPValueResult()1103 bool hasAPValueResult() const {
1104 return ConstantExprBits.APValueKind != APValue::None;
1105 }
1106 APValue getAPValueResult() const;
getResultAsAPValue()1107 APValue &getResultAsAPValue() const { return APValueResult(); }
1108 llvm::APSInt getResultAsAPSInt() const;
1109 // Iterators
children()1110 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
children()1111 const_child_range children() const {
1112 return const_child_range(&SubExpr, &SubExpr + 1);
1113 }
1114 };
1115
1116 //===----------------------------------------------------------------------===//
1117 // Primary Expressions.
1118 //===----------------------------------------------------------------------===//
1119
1120 /// OpaqueValueExpr - An expression referring to an opaque object of a
1121 /// fixed type and value class. These don't correspond to concrete
1122 /// syntax; instead they're used to express operations (usually copy
1123 /// operations) on values whose source is generally obvious from
1124 /// context.
1125 class OpaqueValueExpr : public Expr {
1126 friend class ASTStmtReader;
1127 Expr *SourceExpr;
1128
1129 public:
1130 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1131 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
Expr(OpaqueValueExprClass,T,VK,OK)1132 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1133 setIsUnique(false);
1134 OpaqueValueExprBits.Loc = Loc;
1135 setDependence(computeDependence(this));
1136 }
1137
1138 /// Given an expression which invokes a copy constructor --- i.e. a
1139 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1140 /// find the OpaqueValueExpr that's the source of the construction.
1141 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1142
OpaqueValueExpr(EmptyShell Empty)1143 explicit OpaqueValueExpr(EmptyShell Empty)
1144 : Expr(OpaqueValueExprClass, Empty) {}
1145
1146 /// Retrieve the location of this expression.
getLocation()1147 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1148
getBeginLoc()1149 SourceLocation getBeginLoc() const LLVM_READONLY {
1150 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1151 }
getEndLoc()1152 SourceLocation getEndLoc() const LLVM_READONLY {
1153 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1154 }
getExprLoc()1155 SourceLocation getExprLoc() const LLVM_READONLY {
1156 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1157 }
1158
children()1159 child_range children() {
1160 return child_range(child_iterator(), child_iterator());
1161 }
1162
children()1163 const_child_range children() const {
1164 return const_child_range(const_child_iterator(), const_child_iterator());
1165 }
1166
1167 /// The source expression of an opaque value expression is the
1168 /// expression which originally generated the value. This is
1169 /// provided as a convenience for analyses that don't wish to
1170 /// precisely model the execution behavior of the program.
1171 ///
1172 /// The source expression is typically set when building the
1173 /// expression which binds the opaque value expression in the first
1174 /// place.
getSourceExpr()1175 Expr *getSourceExpr() const { return SourceExpr; }
1176
setIsUnique(bool V)1177 void setIsUnique(bool V) {
1178 assert((!V || SourceExpr) &&
1179 "unique OVEs are expected to have source expressions");
1180 OpaqueValueExprBits.IsUnique = V;
1181 }
1182
isUnique()1183 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1184
classof(const Stmt * T)1185 static bool classof(const Stmt *T) {
1186 return T->getStmtClass() == OpaqueValueExprClass;
1187 }
1188 };
1189
1190 /// A reference to a declared variable, function, enum, etc.
1191 /// [C99 6.5.1p2]
1192 ///
1193 /// This encodes all the information about how a declaration is referenced
1194 /// within an expression.
1195 ///
1196 /// There are several optional constructs attached to DeclRefExprs only when
1197 /// they apply in order to conserve memory. These are laid out past the end of
1198 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
1199 ///
1200 /// DeclRefExprBits.HasQualifier:
1201 /// Specifies when this declaration reference expression has a C++
1202 /// nested-name-specifier.
1203 /// DeclRefExprBits.HasFoundDecl:
1204 /// Specifies when this declaration reference expression has a record of
1205 /// a NamedDecl (different from the referenced ValueDecl) which was found
1206 /// during name lookup and/or overload resolution.
1207 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1208 /// Specifies when this declaration reference expression has an explicit
1209 /// C++ template keyword and/or template argument list.
1210 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1211 /// Specifies when this declaration reference expression (validly)
1212 /// refers to an enclosed local or a captured variable.
1213 class DeclRefExpr final
1214 : public Expr,
1215 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1216 NamedDecl *, ASTTemplateKWAndArgsInfo,
1217 TemplateArgumentLoc> {
1218 friend class ASTStmtReader;
1219 friend class ASTStmtWriter;
1220 friend TrailingObjects;
1221
1222 /// The declaration that we are referencing.
1223 ValueDecl *D;
1224
1225 /// Provides source/type location info for the declaration name
1226 /// embedded in D.
1227 DeclarationNameLoc DNLoc;
1228
numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>)1229 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1230 return hasQualifier();
1231 }
1232
numTrailingObjects(OverloadToken<NamedDecl * >)1233 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1234 return hasFoundDecl();
1235 }
1236
numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>)1237 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1238 return hasTemplateKWAndArgsInfo();
1239 }
1240
1241 /// Test whether there is a distinct FoundDecl attached to the end of
1242 /// this DRE.
hasFoundDecl()1243 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1244
1245 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1246 SourceLocation TemplateKWLoc, ValueDecl *D,
1247 bool RefersToEnlosingVariableOrCapture,
1248 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1249 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1250 ExprValueKind VK, NonOdrUseReason NOUR);
1251
1252 /// Construct an empty declaration reference expression.
DeclRefExpr(EmptyShell Empty)1253 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1254
1255 public:
1256 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1257 bool RefersToEnclosingVariableOrCapture, QualType T,
1258 ExprValueKind VK, SourceLocation L,
1259 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1260 NonOdrUseReason NOUR = NOUR_None);
1261
1262 static DeclRefExpr *
1263 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1264 SourceLocation TemplateKWLoc, ValueDecl *D,
1265 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1266 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1267 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1268 NonOdrUseReason NOUR = NOUR_None);
1269
1270 static DeclRefExpr *
1271 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1272 SourceLocation TemplateKWLoc, ValueDecl *D,
1273 bool RefersToEnclosingVariableOrCapture,
1274 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1275 NamedDecl *FoundD = nullptr,
1276 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1277 NonOdrUseReason NOUR = NOUR_None);
1278
1279 /// Construct an empty declaration reference expression.
1280 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1281 bool HasFoundDecl,
1282 bool HasTemplateKWAndArgsInfo,
1283 unsigned NumTemplateArgs);
1284
getDecl()1285 ValueDecl *getDecl() { return D; }
getDecl()1286 const ValueDecl *getDecl() const { return D; }
1287 void setDecl(ValueDecl *NewD);
1288
getNameInfo()1289 DeclarationNameInfo getNameInfo() const {
1290 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1291 }
1292
getLocation()1293 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
setLocation(SourceLocation L)1294 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1295 SourceLocation getBeginLoc() const LLVM_READONLY;
1296 SourceLocation getEndLoc() const LLVM_READONLY;
1297
1298 /// Determine whether this declaration reference was preceded by a
1299 /// C++ nested-name-specifier, e.g., \c N::foo.
hasQualifier()1300 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1301
1302 /// If the name was qualified, retrieves the nested-name-specifier
1303 /// that precedes the name, with source-location information.
getQualifierLoc()1304 NestedNameSpecifierLoc getQualifierLoc() const {
1305 if (!hasQualifier())
1306 return NestedNameSpecifierLoc();
1307 return *getTrailingObjects<NestedNameSpecifierLoc>();
1308 }
1309
1310 /// If the name was qualified, retrieves the nested-name-specifier
1311 /// that precedes the name. Otherwise, returns NULL.
getQualifier()1312 NestedNameSpecifier *getQualifier() const {
1313 return getQualifierLoc().getNestedNameSpecifier();
1314 }
1315
1316 /// Get the NamedDecl through which this reference occurred.
1317 ///
1318 /// This Decl may be different from the ValueDecl actually referred to in the
1319 /// presence of using declarations, etc. It always returns non-NULL, and may
1320 /// simple return the ValueDecl when appropriate.
1321
getFoundDecl()1322 NamedDecl *getFoundDecl() {
1323 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1324 }
1325
1326 /// Get the NamedDecl through which this reference occurred.
1327 /// See non-const variant.
getFoundDecl()1328 const NamedDecl *getFoundDecl() const {
1329 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1330 }
1331
hasTemplateKWAndArgsInfo()1332 bool hasTemplateKWAndArgsInfo() const {
1333 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1334 }
1335
1336 /// Retrieve the location of the template keyword preceding
1337 /// this name, if any.
getTemplateKeywordLoc()1338 SourceLocation getTemplateKeywordLoc() const {
1339 if (!hasTemplateKWAndArgsInfo())
1340 return SourceLocation();
1341 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1342 }
1343
1344 /// Retrieve the location of the left angle bracket starting the
1345 /// explicit template argument list following the name, if any.
getLAngleLoc()1346 SourceLocation getLAngleLoc() const {
1347 if (!hasTemplateKWAndArgsInfo())
1348 return SourceLocation();
1349 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1350 }
1351
1352 /// Retrieve the location of the right angle bracket ending the
1353 /// explicit template argument list following the name, if any.
getRAngleLoc()1354 SourceLocation getRAngleLoc() const {
1355 if (!hasTemplateKWAndArgsInfo())
1356 return SourceLocation();
1357 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1358 }
1359
1360 /// Determines whether the name in this declaration reference
1361 /// was preceded by the template keyword.
hasTemplateKeyword()1362 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1363
1364 /// Determines whether this declaration reference was followed by an
1365 /// explicit template argument list.
hasExplicitTemplateArgs()1366 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1367
1368 /// Copies the template arguments (if present) into the given
1369 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)1370 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1371 if (hasExplicitTemplateArgs())
1372 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1373 getTrailingObjects<TemplateArgumentLoc>(), List);
1374 }
1375
1376 /// Retrieve the template arguments provided as part of this
1377 /// template-id.
getTemplateArgs()1378 const TemplateArgumentLoc *getTemplateArgs() const {
1379 if (!hasExplicitTemplateArgs())
1380 return nullptr;
1381 return getTrailingObjects<TemplateArgumentLoc>();
1382 }
1383
1384 /// Retrieve the number of template arguments provided as part of this
1385 /// template-id.
getNumTemplateArgs()1386 unsigned getNumTemplateArgs() const {
1387 if (!hasExplicitTemplateArgs())
1388 return 0;
1389 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1390 }
1391
template_arguments()1392 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1393 return {getTemplateArgs(), getNumTemplateArgs()};
1394 }
1395
1396 /// Returns true if this expression refers to a function that
1397 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()1398 bool hadMultipleCandidates() const {
1399 return DeclRefExprBits.HadMultipleCandidates;
1400 }
1401 /// Sets the flag telling whether this expression refers to
1402 /// a function that was resolved from an overloaded set having size
1403 /// greater than 1.
1404 void setHadMultipleCandidates(bool V = true) {
1405 DeclRefExprBits.HadMultipleCandidates = V;
1406 }
1407
1408 /// Is this expression a non-odr-use reference, and if so, why?
isNonOdrUse()1409 NonOdrUseReason isNonOdrUse() const {
1410 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1411 }
1412
1413 /// Does this DeclRefExpr refer to an enclosing local or a captured
1414 /// variable?
refersToEnclosingVariableOrCapture()1415 bool refersToEnclosingVariableOrCapture() const {
1416 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1417 }
1418
classof(const Stmt * T)1419 static bool classof(const Stmt *T) {
1420 return T->getStmtClass() == DeclRefExprClass;
1421 }
1422
1423 // Iterators
children()1424 child_range children() {
1425 return child_range(child_iterator(), child_iterator());
1426 }
1427
children()1428 const_child_range children() const {
1429 return const_child_range(const_child_iterator(), const_child_iterator());
1430 }
1431 };
1432
1433 /// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1434 /// leaking memory.
1435 ///
1436 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1437 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1438 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1439 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1440 /// ASTContext's allocator for memory allocation.
1441 class APNumericStorage {
1442 union {
1443 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1444 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1445 };
1446 unsigned BitWidth;
1447
hasAllocation()1448 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1449
1450 APNumericStorage(const APNumericStorage &) = delete;
1451 void operator=(const APNumericStorage &) = delete;
1452
1453 protected:
APNumericStorage()1454 APNumericStorage() : VAL(0), BitWidth(0) { }
1455
getIntValue()1456 llvm::APInt getIntValue() const {
1457 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1458 if (NumWords > 1)
1459 return llvm::APInt(BitWidth, NumWords, pVal);
1460 else
1461 return llvm::APInt(BitWidth, VAL);
1462 }
1463 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1464 };
1465
1466 class APIntStorage : private APNumericStorage {
1467 public:
getValue()1468 llvm::APInt getValue() const { return getIntValue(); }
setValue(const ASTContext & C,const llvm::APInt & Val)1469 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1470 setIntValue(C, Val);
1471 }
1472 };
1473
1474 class APFloatStorage : private APNumericStorage {
1475 public:
getValue(const llvm::fltSemantics & Semantics)1476 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1477 return llvm::APFloat(Semantics, getIntValue());
1478 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1479 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1480 setIntValue(C, Val.bitcastToAPInt());
1481 }
1482 };
1483
1484 class IntegerLiteral : public Expr, public APIntStorage {
1485 SourceLocation Loc;
1486
1487 /// Construct an empty integer literal.
IntegerLiteral(EmptyShell Empty)1488 explicit IntegerLiteral(EmptyShell Empty)
1489 : Expr(IntegerLiteralClass, Empty) { }
1490
1491 public:
1492 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1493 // or UnsignedLongLongTy
1494 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1495 SourceLocation l);
1496
1497 /// Returns a new integer literal with value 'V' and type 'type'.
1498 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1499 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1500 /// \param V - the value that the returned integer literal contains.
1501 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1502 QualType type, SourceLocation l);
1503 /// Returns a new empty integer literal.
1504 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1505
getBeginLoc()1506 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1507 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1508
1509 /// Retrieve the location of the literal.
getLocation()1510 SourceLocation getLocation() const { return Loc; }
1511
setLocation(SourceLocation Location)1512 void setLocation(SourceLocation Location) { Loc = Location; }
1513
classof(const Stmt * T)1514 static bool classof(const Stmt *T) {
1515 return T->getStmtClass() == IntegerLiteralClass;
1516 }
1517
1518 // Iterators
children()1519 child_range children() {
1520 return child_range(child_iterator(), child_iterator());
1521 }
children()1522 const_child_range children() const {
1523 return const_child_range(const_child_iterator(), const_child_iterator());
1524 }
1525 };
1526
1527 class FixedPointLiteral : public Expr, public APIntStorage {
1528 SourceLocation Loc;
1529 unsigned Scale;
1530
1531 /// \brief Construct an empty fixed-point literal.
FixedPointLiteral(EmptyShell Empty)1532 explicit FixedPointLiteral(EmptyShell Empty)
1533 : Expr(FixedPointLiteralClass, Empty) {}
1534
1535 public:
1536 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1537 SourceLocation l, unsigned Scale);
1538
1539 // Store the int as is without any bit shifting.
1540 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1541 const llvm::APInt &V,
1542 QualType type, SourceLocation l,
1543 unsigned Scale);
1544
1545 /// Returns an empty fixed-point literal.
1546 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1547
getBeginLoc()1548 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1549 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1550
1551 /// \brief Retrieve the location of the literal.
getLocation()1552 SourceLocation getLocation() const { return Loc; }
1553
setLocation(SourceLocation Location)1554 void setLocation(SourceLocation Location) { Loc = Location; }
1555
getScale()1556 unsigned getScale() const { return Scale; }
setScale(unsigned S)1557 void setScale(unsigned S) { Scale = S; }
1558
classof(const Stmt * T)1559 static bool classof(const Stmt *T) {
1560 return T->getStmtClass() == FixedPointLiteralClass;
1561 }
1562
1563 std::string getValueAsString(unsigned Radix) const;
1564
1565 // Iterators
children()1566 child_range children() {
1567 return child_range(child_iterator(), child_iterator());
1568 }
children()1569 const_child_range children() const {
1570 return const_child_range(const_child_iterator(), const_child_iterator());
1571 }
1572 };
1573
1574 class CharacterLiteral : public Expr {
1575 public:
1576 enum CharacterKind {
1577 Ascii,
1578 Wide,
1579 UTF8,
1580 UTF16,
1581 UTF32
1582 };
1583
1584 private:
1585 unsigned Value;
1586 SourceLocation Loc;
1587 public:
1588 // type should be IntTy
CharacterLiteral(unsigned value,CharacterKind kind,QualType type,SourceLocation l)1589 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1590 SourceLocation l)
1591 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary), Value(value),
1592 Loc(l) {
1593 CharacterLiteralBits.Kind = kind;
1594 setDependence(ExprDependence::None);
1595 }
1596
1597 /// Construct an empty character literal.
CharacterLiteral(EmptyShell Empty)1598 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1599
getLocation()1600 SourceLocation getLocation() const { return Loc; }
getKind()1601 CharacterKind getKind() const {
1602 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1603 }
1604
getBeginLoc()1605 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1606 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1607
getValue()1608 unsigned getValue() const { return Value; }
1609
setLocation(SourceLocation Location)1610 void setLocation(SourceLocation Location) { Loc = Location; }
setKind(CharacterKind kind)1611 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
setValue(unsigned Val)1612 void setValue(unsigned Val) { Value = Val; }
1613
classof(const Stmt * T)1614 static bool classof(const Stmt *T) {
1615 return T->getStmtClass() == CharacterLiteralClass;
1616 }
1617
1618 static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
1619
1620 // Iterators
children()1621 child_range children() {
1622 return child_range(child_iterator(), child_iterator());
1623 }
children()1624 const_child_range children() const {
1625 return const_child_range(const_child_iterator(), const_child_iterator());
1626 }
1627 };
1628
1629 class FloatingLiteral : public Expr, private APFloatStorage {
1630 SourceLocation Loc;
1631
1632 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1633 QualType Type, SourceLocation L);
1634
1635 /// Construct an empty floating-point literal.
1636 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1637
1638 public:
1639 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1640 bool isexact, QualType Type, SourceLocation L);
1641 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1642
getValue()1643 llvm::APFloat getValue() const {
1644 return APFloatStorage::getValue(getSemantics());
1645 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1646 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1647 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1648 APFloatStorage::setValue(C, Val);
1649 }
1650
1651 /// Get a raw enumeration value representing the floating-point semantics of
1652 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
getRawSemantics()1653 llvm::APFloatBase::Semantics getRawSemantics() const {
1654 return static_cast<llvm::APFloatBase::Semantics>(
1655 FloatingLiteralBits.Semantics);
1656 }
1657
1658 /// Set the raw enumeration value representing the floating-point semantics of
1659 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
setRawSemantics(llvm::APFloatBase::Semantics Sem)1660 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1661 FloatingLiteralBits.Semantics = Sem;
1662 }
1663
1664 /// Return the APFloat semantics this literal uses.
getSemantics()1665 const llvm::fltSemantics &getSemantics() const {
1666 return llvm::APFloatBase::EnumToSemantics(
1667 static_cast<llvm::APFloatBase::Semantics>(
1668 FloatingLiteralBits.Semantics));
1669 }
1670
1671 /// Set the APFloat semantics this literal uses.
setSemantics(const llvm::fltSemantics & Sem)1672 void setSemantics(const llvm::fltSemantics &Sem) {
1673 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1674 }
1675
isExact()1676 bool isExact() const { return FloatingLiteralBits.IsExact; }
setExact(bool E)1677 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1678
1679 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1680 /// double. Note that this may cause loss of precision, but is useful for
1681 /// debugging dumps, etc.
1682 double getValueAsApproximateDouble() const;
1683
getLocation()1684 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1685 void setLocation(SourceLocation L) { Loc = L; }
1686
getBeginLoc()1687 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1688 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1689
classof(const Stmt * T)1690 static bool classof(const Stmt *T) {
1691 return T->getStmtClass() == FloatingLiteralClass;
1692 }
1693
1694 // Iterators
children()1695 child_range children() {
1696 return child_range(child_iterator(), child_iterator());
1697 }
children()1698 const_child_range children() const {
1699 return const_child_range(const_child_iterator(), const_child_iterator());
1700 }
1701 };
1702
1703 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1704 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1705 /// IntegerLiteral classes. Instances of this class always have a Complex type
1706 /// whose element type matches the subexpression.
1707 ///
1708 class ImaginaryLiteral : public Expr {
1709 Stmt *Val;
1710 public:
ImaginaryLiteral(Expr * val,QualType Ty)1711 ImaginaryLiteral(Expr *val, QualType Ty)
1712 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary), Val(val) {
1713 setDependence(ExprDependence::None);
1714 }
1715
1716 /// Build an empty imaginary literal.
ImaginaryLiteral(EmptyShell Empty)1717 explicit ImaginaryLiteral(EmptyShell Empty)
1718 : Expr(ImaginaryLiteralClass, Empty) { }
1719
getSubExpr()1720 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()1721 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)1722 void setSubExpr(Expr *E) { Val = E; }
1723
getBeginLoc()1724 SourceLocation getBeginLoc() const LLVM_READONLY {
1725 return Val->getBeginLoc();
1726 }
getEndLoc()1727 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1728
classof(const Stmt * T)1729 static bool classof(const Stmt *T) {
1730 return T->getStmtClass() == ImaginaryLiteralClass;
1731 }
1732
1733 // Iterators
children()1734 child_range children() { return child_range(&Val, &Val+1); }
children()1735 const_child_range children() const {
1736 return const_child_range(&Val, &Val + 1);
1737 }
1738 };
1739
1740 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1741 /// or L"bar" (wide strings). The actual string data can be obtained with
1742 /// getBytes() and is NOT null-terminated. The length of the string data is
1743 /// determined by calling getByteLength().
1744 ///
1745 /// The C type for a string is always a ConstantArrayType. In C++, the char
1746 /// type is const qualified, in C it is not.
1747 ///
1748 /// Note that strings in C can be formed by concatenation of multiple string
1749 /// literal pptokens in translation phase #6. This keeps track of the locations
1750 /// of each of these pieces.
1751 ///
1752 /// Strings in C can also be truncated and extended by assigning into arrays,
1753 /// e.g. with constructs like:
1754 /// char X[2] = "foobar";
1755 /// In this case, getByteLength() will return 6, but the string literal will
1756 /// have type "char[2]".
1757 class StringLiteral final
1758 : public Expr,
1759 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1760 char> {
1761 friend class ASTStmtReader;
1762 friend TrailingObjects;
1763
1764 /// StringLiteral is followed by several trailing objects. They are in order:
1765 ///
1766 /// * A single unsigned storing the length in characters of this string. The
1767 /// length in bytes is this length times the width of a single character.
1768 /// Always present and stored as a trailing objects because storing it in
1769 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1770 /// due to alignment requirements. If you add some data to StringLiteral,
1771 /// consider moving it inside StringLiteral.
1772 ///
1773 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1774 /// token this string is made of.
1775 ///
1776 /// * An array of getByteLength() char used to store the string data.
1777
1778 public:
1779 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1780
1781 private:
numTrailingObjects(OverloadToken<unsigned>)1782 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
numTrailingObjects(OverloadToken<SourceLocation>)1783 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1784 return getNumConcatenated();
1785 }
1786
numTrailingObjects(OverloadToken<char>)1787 unsigned numTrailingObjects(OverloadToken<char>) const {
1788 return getByteLength();
1789 }
1790
getStrDataAsChar()1791 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
getStrDataAsChar()1792 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1793
getStrDataAsUInt16()1794 const uint16_t *getStrDataAsUInt16() const {
1795 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1796 }
1797
getStrDataAsUInt32()1798 const uint32_t *getStrDataAsUInt32() const {
1799 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1800 }
1801
1802 /// Build a string literal.
1803 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1804 bool Pascal, QualType Ty, const SourceLocation *Loc,
1805 unsigned NumConcatenated);
1806
1807 /// Build an empty string literal.
1808 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1809 unsigned CharByteWidth);
1810
1811 /// Map a target and string kind to the appropriate character width.
1812 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1813
1814 /// Set one of the string literal token.
setStrTokenLoc(unsigned TokNum,SourceLocation L)1815 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1816 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1817 getTrailingObjects<SourceLocation>()[TokNum] = L;
1818 }
1819
1820 public:
1821 /// This is the "fully general" constructor that allows representation of
1822 /// strings formed from multiple concatenated tokens.
1823 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1824 StringKind Kind, bool Pascal, QualType Ty,
1825 const SourceLocation *Loc,
1826 unsigned NumConcatenated);
1827
1828 /// Simple constructor for string literals made from one token.
Create(const ASTContext & Ctx,StringRef Str,StringKind Kind,bool Pascal,QualType Ty,SourceLocation Loc)1829 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1830 StringKind Kind, bool Pascal, QualType Ty,
1831 SourceLocation Loc) {
1832 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1833 }
1834
1835 /// Construct an empty string literal.
1836 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1837 unsigned NumConcatenated, unsigned Length,
1838 unsigned CharByteWidth);
1839
getString()1840 StringRef getString() const {
1841 assert(getCharByteWidth() == 1 &&
1842 "This function is used in places that assume strings use char");
1843 return StringRef(getStrDataAsChar(), getByteLength());
1844 }
1845
1846 /// Allow access to clients that need the byte representation, such as
1847 /// ASTWriterStmt::VisitStringLiteral().
getBytes()1848 StringRef getBytes() const {
1849 // FIXME: StringRef may not be the right type to use as a result for this.
1850 return StringRef(getStrDataAsChar(), getByteLength());
1851 }
1852
1853 void outputString(raw_ostream &OS) const;
1854
getCodeUnit(size_t i)1855 uint32_t getCodeUnit(size_t i) const {
1856 assert(i < getLength() && "out of bounds access");
1857 switch (getCharByteWidth()) {
1858 case 1:
1859 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1860 case 2:
1861 return getStrDataAsUInt16()[i];
1862 case 4:
1863 return getStrDataAsUInt32()[i];
1864 }
1865 llvm_unreachable("Unsupported character width!");
1866 }
1867
getByteLength()1868 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
getLength()1869 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
getCharByteWidth()1870 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1871
getKind()1872 StringKind getKind() const {
1873 return static_cast<StringKind>(StringLiteralBits.Kind);
1874 }
1875
isAscii()1876 bool isAscii() const { return getKind() == Ascii; }
isWide()1877 bool isWide() const { return getKind() == Wide; }
isUTF8()1878 bool isUTF8() const { return getKind() == UTF8; }
isUTF16()1879 bool isUTF16() const { return getKind() == UTF16; }
isUTF32()1880 bool isUTF32() const { return getKind() == UTF32; }
isPascal()1881 bool isPascal() const { return StringLiteralBits.IsPascal; }
1882
containsNonAscii()1883 bool containsNonAscii() const {
1884 for (auto c : getString())
1885 if (!isASCII(c))
1886 return true;
1887 return false;
1888 }
1889
containsNonAsciiOrNull()1890 bool containsNonAsciiOrNull() const {
1891 for (auto c : getString())
1892 if (!isASCII(c) || !c)
1893 return true;
1894 return false;
1895 }
1896
1897 /// getNumConcatenated - Get the number of string literal tokens that were
1898 /// concatenated in translation phase #6 to form this string literal.
getNumConcatenated()1899 unsigned getNumConcatenated() const {
1900 return StringLiteralBits.NumConcatenated;
1901 }
1902
1903 /// Get one of the string literal token.
getStrTokenLoc(unsigned TokNum)1904 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1905 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1906 return getTrailingObjects<SourceLocation>()[TokNum];
1907 }
1908
1909 /// getLocationOfByte - Return a source location that points to the specified
1910 /// byte of this string literal.
1911 ///
1912 /// Strings are amazingly complex. They can be formed from multiple tokens
1913 /// and can have escape sequences in them in addition to the usual trigraph
1914 /// and escaped newline business. This routine handles this complexity.
1915 ///
1916 SourceLocation
1917 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1918 const LangOptions &Features, const TargetInfo &Target,
1919 unsigned *StartToken = nullptr,
1920 unsigned *StartTokenByteOffset = nullptr) const;
1921
1922 typedef const SourceLocation *tokloc_iterator;
1923
tokloc_begin()1924 tokloc_iterator tokloc_begin() const {
1925 return getTrailingObjects<SourceLocation>();
1926 }
1927
tokloc_end()1928 tokloc_iterator tokloc_end() const {
1929 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1930 }
1931
getBeginLoc()1932 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
getEndLoc()1933 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1934
classof(const Stmt * T)1935 static bool classof(const Stmt *T) {
1936 return T->getStmtClass() == StringLiteralClass;
1937 }
1938
1939 // Iterators
children()1940 child_range children() {
1941 return child_range(child_iterator(), child_iterator());
1942 }
children()1943 const_child_range children() const {
1944 return const_child_range(const_child_iterator(), const_child_iterator());
1945 }
1946 };
1947
1948 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1949 class PredefinedExpr final
1950 : public Expr,
1951 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1952 friend class ASTStmtReader;
1953 friend TrailingObjects;
1954
1955 // PredefinedExpr is optionally followed by a single trailing
1956 // "Stmt *" for the predefined identifier. It is present if and only if
1957 // hasFunctionName() is true and is always a "StringLiteral *".
1958
1959 public:
1960 enum IdentKind {
1961 Func,
1962 Function,
1963 LFunction, // Same as Function, but as wide string.
1964 FuncDName,
1965 FuncSig,
1966 LFuncSig, // Same as FuncSig, but as as wide string
1967 PrettyFunction,
1968 /// The same as PrettyFunction, except that the
1969 /// 'virtual' keyword is omitted for virtual member functions.
1970 PrettyFunctionNoVirtual
1971 };
1972
1973 private:
1974 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1975 StringLiteral *SL);
1976
1977 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1978
1979 /// True if this PredefinedExpr has storage for a function name.
hasFunctionName()1980 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1981
setFunctionName(StringLiteral * SL)1982 void setFunctionName(StringLiteral *SL) {
1983 assert(hasFunctionName() &&
1984 "This PredefinedExpr has no storage for a function name!");
1985 *getTrailingObjects<Stmt *>() = SL;
1986 }
1987
1988 public:
1989 /// Create a PredefinedExpr.
1990 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1991 QualType FNTy, IdentKind IK, StringLiteral *SL);
1992
1993 /// Create an empty PredefinedExpr.
1994 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1995 bool HasFunctionName);
1996
getIdentKind()1997 IdentKind getIdentKind() const {
1998 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1999 }
2000
getLocation()2001 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
setLocation(SourceLocation L)2002 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2003
getFunctionName()2004 StringLiteral *getFunctionName() {
2005 return hasFunctionName()
2006 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2007 : nullptr;
2008 }
2009
getFunctionName()2010 const StringLiteral *getFunctionName() const {
2011 return hasFunctionName()
2012 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2013 : nullptr;
2014 }
2015
2016 static StringRef getIdentKindName(IdentKind IK);
getIdentKindName()2017 StringRef getIdentKindName() const {
2018 return getIdentKindName(getIdentKind());
2019 }
2020
2021 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
2022
getBeginLoc()2023 SourceLocation getBeginLoc() const { return getLocation(); }
getEndLoc()2024 SourceLocation getEndLoc() const { return getLocation(); }
2025
classof(const Stmt * T)2026 static bool classof(const Stmt *T) {
2027 return T->getStmtClass() == PredefinedExprClass;
2028 }
2029
2030 // Iterators
children()2031 child_range children() {
2032 return child_range(getTrailingObjects<Stmt *>(),
2033 getTrailingObjects<Stmt *>() + hasFunctionName());
2034 }
2035
children()2036 const_child_range children() const {
2037 return const_child_range(getTrailingObjects<Stmt *>(),
2038 getTrailingObjects<Stmt *>() + hasFunctionName());
2039 }
2040 };
2041
2042 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2043 /// AST node is only formed if full location information is requested.
2044 class ParenExpr : public Expr {
2045 SourceLocation L, R;
2046 Stmt *Val;
2047 public:
ParenExpr(SourceLocation l,SourceLocation r,Expr * val)2048 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2049 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2050 val->getObjectKind()),
2051 L(l), R(r), Val(val) {
2052 setDependence(computeDependence(this));
2053 }
2054
2055 /// Construct an empty parenthesized expression.
ParenExpr(EmptyShell Empty)2056 explicit ParenExpr(EmptyShell Empty)
2057 : Expr(ParenExprClass, Empty) { }
2058
getSubExpr()2059 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()2060 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)2061 void setSubExpr(Expr *E) { Val = E; }
2062
getBeginLoc()2063 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
getEndLoc()2064 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2065
2066 /// Get the location of the left parentheses '('.
getLParen()2067 SourceLocation getLParen() const { return L; }
setLParen(SourceLocation Loc)2068 void setLParen(SourceLocation Loc) { L = Loc; }
2069
2070 /// Get the location of the right parentheses ')'.
getRParen()2071 SourceLocation getRParen() const { return R; }
setRParen(SourceLocation Loc)2072 void setRParen(SourceLocation Loc) { R = Loc; }
2073
classof(const Stmt * T)2074 static bool classof(const Stmt *T) {
2075 return T->getStmtClass() == ParenExprClass;
2076 }
2077
2078 // Iterators
children()2079 child_range children() { return child_range(&Val, &Val+1); }
children()2080 const_child_range children() const {
2081 return const_child_range(&Val, &Val + 1);
2082 }
2083 };
2084
2085 /// UnaryOperator - This represents the unary-expression's (except sizeof and
2086 /// alignof), the postinc/postdec operators from postfix-expression, and various
2087 /// extensions.
2088 ///
2089 /// Notes on various nodes:
2090 ///
2091 /// Real/Imag - These return the real/imag part of a complex operand. If
2092 /// applied to a non-complex value, the former returns its operand and the
2093 /// later returns zero in the type of the operand.
2094 ///
2095 class UnaryOperator final
2096 : public Expr,
2097 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2098 Stmt *Val;
2099
numTrailingObjects(OverloadToken<FPOptionsOverride>)2100 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2101 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2102 }
2103
getTrailingFPFeatures()2104 FPOptionsOverride &getTrailingFPFeatures() {
2105 assert(UnaryOperatorBits.HasFPFeatures);
2106 return *getTrailingObjects<FPOptionsOverride>();
2107 }
2108
getTrailingFPFeatures()2109 const FPOptionsOverride &getTrailingFPFeatures() const {
2110 assert(UnaryOperatorBits.HasFPFeatures);
2111 return *getTrailingObjects<FPOptionsOverride>();
2112 }
2113
2114 public:
2115 typedef UnaryOperatorKind Opcode;
2116
2117 protected:
2118 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2119 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2120 bool CanOverflow, FPOptionsOverride FPFeatures);
2121
2122 /// Build an empty unary operator.
UnaryOperator(bool HasFPFeatures,EmptyShell Empty)2123 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2124 : Expr(UnaryOperatorClass, Empty) {
2125 UnaryOperatorBits.Opc = UO_AddrOf;
2126 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2127 }
2128
2129 public:
2130 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2131
2132 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2133 QualType type, ExprValueKind VK,
2134 ExprObjectKind OK, SourceLocation l,
2135 bool CanOverflow, FPOptionsOverride FPFeatures);
2136
getOpcode()2137 Opcode getOpcode() const {
2138 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2139 }
setOpcode(Opcode Opc)2140 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2141
getSubExpr()2142 Expr *getSubExpr() const { return cast<Expr>(Val); }
setSubExpr(Expr * E)2143 void setSubExpr(Expr *E) { Val = E; }
2144
2145 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2146 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
setOperatorLoc(SourceLocation L)2147 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2148
2149 /// Returns true if the unary operator can cause an overflow. For instance,
2150 /// signed int i = INT_MAX; i++;
2151 /// signed char c = CHAR_MAX; c++;
2152 /// Due to integer promotions, c++ is promoted to an int before the postfix
2153 /// increment, and the result is an int that cannot overflow. However, i++
2154 /// can overflow.
canOverflow()2155 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
setCanOverflow(bool C)2156 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2157
2158 // Get the FP contractability status of this operator. Only meaningful for
2159 // operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)2160 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2161 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2162 }
2163
2164 // Get the FENV_ACCESS status of this operator. Only meaningful for
2165 // operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)2166 bool isFEnvAccessOn(const LangOptions &LO) const {
2167 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2168 }
2169
2170 /// isPostfix - Return true if this is a postfix operation, like x++.
isPostfix(Opcode Op)2171 static bool isPostfix(Opcode Op) {
2172 return Op == UO_PostInc || Op == UO_PostDec;
2173 }
2174
2175 /// isPrefix - Return true if this is a prefix operation, like --x.
isPrefix(Opcode Op)2176 static bool isPrefix(Opcode Op) {
2177 return Op == UO_PreInc || Op == UO_PreDec;
2178 }
2179
isPrefix()2180 bool isPrefix() const { return isPrefix(getOpcode()); }
isPostfix()2181 bool isPostfix() const { return isPostfix(getOpcode()); }
2182
isIncrementOp(Opcode Op)2183 static bool isIncrementOp(Opcode Op) {
2184 return Op == UO_PreInc || Op == UO_PostInc;
2185 }
isIncrementOp()2186 bool isIncrementOp() const {
2187 return isIncrementOp(getOpcode());
2188 }
2189
isDecrementOp(Opcode Op)2190 static bool isDecrementOp(Opcode Op) {
2191 return Op == UO_PreDec || Op == UO_PostDec;
2192 }
isDecrementOp()2193 bool isDecrementOp() const {
2194 return isDecrementOp(getOpcode());
2195 }
2196
isIncrementDecrementOp(Opcode Op)2197 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
isIncrementDecrementOp()2198 bool isIncrementDecrementOp() const {
2199 return isIncrementDecrementOp(getOpcode());
2200 }
2201
isArithmeticOp(Opcode Op)2202 static bool isArithmeticOp(Opcode Op) {
2203 return Op >= UO_Plus && Op <= UO_LNot;
2204 }
isArithmeticOp()2205 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2206
2207 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2208 /// corresponds to, e.g. "sizeof" or "[pre]++"
2209 static StringRef getOpcodeStr(Opcode Op);
2210
2211 /// Retrieve the unary opcode that corresponds to the given
2212 /// overloaded operator.
2213 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2214
2215 /// Retrieve the overloaded operator kind that corresponds to
2216 /// the given unary opcode.
2217 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2218
getBeginLoc()2219 SourceLocation getBeginLoc() const LLVM_READONLY {
2220 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2221 }
getEndLoc()2222 SourceLocation getEndLoc() const LLVM_READONLY {
2223 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2224 }
getExprLoc()2225 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2226
classof(const Stmt * T)2227 static bool classof(const Stmt *T) {
2228 return T->getStmtClass() == UnaryOperatorClass;
2229 }
2230
2231 // Iterators
children()2232 child_range children() { return child_range(&Val, &Val+1); }
children()2233 const_child_range children() const {
2234 return const_child_range(&Val, &Val + 1);
2235 }
2236
2237 /// Is FPFeatures in Trailing Storage?
hasStoredFPFeatures()2238 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2239
2240 /// Get FPFeatures from trailing storage.
getStoredFPFeatures()2241 FPOptionsOverride getStoredFPFeatures() const {
2242 return getTrailingFPFeatures();
2243 }
2244
2245 protected:
2246 /// Set FPFeatures in trailing storage, used only by Serialization
setStoredFPFeatures(FPOptionsOverride F)2247 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2248
2249 public:
2250 // Get the FP features status of this operator. Only meaningful for
2251 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)2252 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2253 if (UnaryOperatorBits.HasFPFeatures)
2254 return getStoredFPFeatures().applyOverrides(LO);
2255 return FPOptions::defaultWithoutTrailingStorage(LO);
2256 }
getFPOptionsOverride()2257 FPOptionsOverride getFPOptionsOverride() const {
2258 if (UnaryOperatorBits.HasFPFeatures)
2259 return getStoredFPFeatures();
2260 return FPOptionsOverride();
2261 }
2262
2263 friend TrailingObjects;
2264 friend class ASTReader;
2265 friend class ASTStmtReader;
2266 friend class ASTStmtWriter;
2267 };
2268
2269 /// Helper class for OffsetOfExpr.
2270
2271 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2272 class OffsetOfNode {
2273 public:
2274 /// The kind of offsetof node we have.
2275 enum Kind {
2276 /// An index into an array.
2277 Array = 0x00,
2278 /// A field.
2279 Field = 0x01,
2280 /// A field in a dependent type, known only by its name.
2281 Identifier = 0x02,
2282 /// An implicit indirection through a C++ base class, when the
2283 /// field found is in a base class.
2284 Base = 0x03
2285 };
2286
2287 private:
2288 enum { MaskBits = 2, Mask = 0x03 };
2289
2290 /// The source range that covers this part of the designator.
2291 SourceRange Range;
2292
2293 /// The data describing the designator, which comes in three
2294 /// different forms, depending on the lower two bits.
2295 /// - An unsigned index into the array of Expr*'s stored after this node
2296 /// in memory, for [constant-expression] designators.
2297 /// - A FieldDecl*, for references to a known field.
2298 /// - An IdentifierInfo*, for references to a field with a given name
2299 /// when the class type is dependent.
2300 /// - A CXXBaseSpecifier*, for references that look at a field in a
2301 /// base class.
2302 uintptr_t Data;
2303
2304 public:
2305 /// Create an offsetof node that refers to an array element.
OffsetOfNode(SourceLocation LBracketLoc,unsigned Index,SourceLocation RBracketLoc)2306 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2307 SourceLocation RBracketLoc)
2308 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2309
2310 /// Create an offsetof node that refers to a field.
OffsetOfNode(SourceLocation DotLoc,FieldDecl * Field,SourceLocation NameLoc)2311 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2312 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2313 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2314
2315 /// Create an offsetof node that refers to an identifier.
OffsetOfNode(SourceLocation DotLoc,IdentifierInfo * Name,SourceLocation NameLoc)2316 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2317 SourceLocation NameLoc)
2318 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2319 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2320
2321 /// Create an offsetof node that refers into a C++ base class.
OffsetOfNode(const CXXBaseSpecifier * Base)2322 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2323 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2324
2325 /// Determine what kind of offsetof node this is.
getKind()2326 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2327
2328 /// For an array element node, returns the index into the array
2329 /// of expressions.
getArrayExprIndex()2330 unsigned getArrayExprIndex() const {
2331 assert(getKind() == Array);
2332 return Data >> 2;
2333 }
2334
2335 /// For a field offsetof node, returns the field.
getField()2336 FieldDecl *getField() const {
2337 assert(getKind() == Field);
2338 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2339 }
2340
2341 /// For a field or identifier offsetof node, returns the name of
2342 /// the field.
2343 IdentifierInfo *getFieldName() const;
2344
2345 /// For a base class node, returns the base specifier.
getBase()2346 CXXBaseSpecifier *getBase() const {
2347 assert(getKind() == Base);
2348 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2349 }
2350
2351 /// Retrieve the source range that covers this offsetof node.
2352 ///
2353 /// For an array element node, the source range contains the locations of
2354 /// the square brackets. For a field or identifier node, the source range
2355 /// contains the location of the period (if there is one) and the
2356 /// identifier.
getSourceRange()2357 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getBeginLoc()2358 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
getEndLoc()2359 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2360 };
2361
2362 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2363 /// offsetof(record-type, member-designator). For example, given:
2364 /// @code
2365 /// struct S {
2366 /// float f;
2367 /// double d;
2368 /// };
2369 /// struct T {
2370 /// int i;
2371 /// struct S s[10];
2372 /// };
2373 /// @endcode
2374 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2375
2376 class OffsetOfExpr final
2377 : public Expr,
2378 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2379 SourceLocation OperatorLoc, RParenLoc;
2380 // Base type;
2381 TypeSourceInfo *TSInfo;
2382 // Number of sub-components (i.e. instances of OffsetOfNode).
2383 unsigned NumComps;
2384 // Number of sub-expressions (i.e. array subscript expressions).
2385 unsigned NumExprs;
2386
numTrailingObjects(OverloadToken<OffsetOfNode>)2387 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2388 return NumComps;
2389 }
2390
2391 OffsetOfExpr(const ASTContext &C, QualType type,
2392 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2393 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2394 SourceLocation RParenLoc);
2395
OffsetOfExpr(unsigned numComps,unsigned numExprs)2396 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2397 : Expr(OffsetOfExprClass, EmptyShell()),
2398 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2399
2400 public:
2401
2402 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2403 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2404 ArrayRef<OffsetOfNode> comps,
2405 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2406
2407 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2408 unsigned NumComps, unsigned NumExprs);
2409
2410 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2411 SourceLocation getOperatorLoc() const { return OperatorLoc; }
setOperatorLoc(SourceLocation L)2412 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2413
2414 /// Return the location of the right parentheses.
getRParenLoc()2415 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation R)2416 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2417
getTypeSourceInfo()2418 TypeSourceInfo *getTypeSourceInfo() const {
2419 return TSInfo;
2420 }
setTypeSourceInfo(TypeSourceInfo * tsi)2421 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2422 TSInfo = tsi;
2423 }
2424
getComponent(unsigned Idx)2425 const OffsetOfNode &getComponent(unsigned Idx) const {
2426 assert(Idx < NumComps && "Subscript out of range");
2427 return getTrailingObjects<OffsetOfNode>()[Idx];
2428 }
2429
setComponent(unsigned Idx,OffsetOfNode ON)2430 void setComponent(unsigned Idx, OffsetOfNode ON) {
2431 assert(Idx < NumComps && "Subscript out of range");
2432 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2433 }
2434
getNumComponents()2435 unsigned getNumComponents() const {
2436 return NumComps;
2437 }
2438
getIndexExpr(unsigned Idx)2439 Expr* getIndexExpr(unsigned Idx) {
2440 assert(Idx < NumExprs && "Subscript out of range");
2441 return getTrailingObjects<Expr *>()[Idx];
2442 }
2443
getIndexExpr(unsigned Idx)2444 const Expr *getIndexExpr(unsigned Idx) const {
2445 assert(Idx < NumExprs && "Subscript out of range");
2446 return getTrailingObjects<Expr *>()[Idx];
2447 }
2448
setIndexExpr(unsigned Idx,Expr * E)2449 void setIndexExpr(unsigned Idx, Expr* E) {
2450 assert(Idx < NumComps && "Subscript out of range");
2451 getTrailingObjects<Expr *>()[Idx] = E;
2452 }
2453
getNumExpressions()2454 unsigned getNumExpressions() const {
2455 return NumExprs;
2456 }
2457
getBeginLoc()2458 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
getEndLoc()2459 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2460
classof(const Stmt * T)2461 static bool classof(const Stmt *T) {
2462 return T->getStmtClass() == OffsetOfExprClass;
2463 }
2464
2465 // Iterators
children()2466 child_range children() {
2467 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2468 return child_range(begin, begin + NumExprs);
2469 }
children()2470 const_child_range children() const {
2471 Stmt *const *begin =
2472 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2473 return const_child_range(begin, begin + NumExprs);
2474 }
2475 friend TrailingObjects;
2476 };
2477
2478 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2479 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2480 /// vec_step (OpenCL 1.1 6.11.12).
2481 class UnaryExprOrTypeTraitExpr : public Expr {
2482 union {
2483 TypeSourceInfo *Ty;
2484 Stmt *Ex;
2485 } Argument;
2486 SourceLocation OpLoc, RParenLoc;
2487
2488 public:
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,TypeSourceInfo * TInfo,QualType resultType,SourceLocation op,SourceLocation rp)2489 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2490 QualType resultType, SourceLocation op,
2491 SourceLocation rp)
2492 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary),
2493 OpLoc(op), RParenLoc(rp) {
2494 assert(ExprKind <= UETT_Last && "invalid enum value!");
2495 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2496 assert(static_cast<unsigned>(ExprKind) ==
2497 UnaryExprOrTypeTraitExprBits.Kind &&
2498 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2499 UnaryExprOrTypeTraitExprBits.IsType = true;
2500 Argument.Ty = TInfo;
2501 setDependence(computeDependence(this));
2502 }
2503
2504 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2505 QualType resultType, SourceLocation op,
2506 SourceLocation rp);
2507
2508 /// Construct an empty sizeof/alignof expression.
UnaryExprOrTypeTraitExpr(EmptyShell Empty)2509 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2510 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2511
getKind()2512 UnaryExprOrTypeTrait getKind() const {
2513 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2514 }
setKind(UnaryExprOrTypeTrait K)2515 void setKind(UnaryExprOrTypeTrait K) {
2516 assert(K <= UETT_Last && "invalid enum value!");
2517 UnaryExprOrTypeTraitExprBits.Kind = K;
2518 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2519 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2520 }
2521
isArgumentType()2522 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
getArgumentType()2523 QualType getArgumentType() const {
2524 return getArgumentTypeInfo()->getType();
2525 }
getArgumentTypeInfo()2526 TypeSourceInfo *getArgumentTypeInfo() const {
2527 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2528 return Argument.Ty;
2529 }
getArgumentExpr()2530 Expr *getArgumentExpr() {
2531 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2532 return static_cast<Expr*>(Argument.Ex);
2533 }
getArgumentExpr()2534 const Expr *getArgumentExpr() const {
2535 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2536 }
2537
setArgument(Expr * E)2538 void setArgument(Expr *E) {
2539 Argument.Ex = E;
2540 UnaryExprOrTypeTraitExprBits.IsType = false;
2541 }
setArgument(TypeSourceInfo * TInfo)2542 void setArgument(TypeSourceInfo *TInfo) {
2543 Argument.Ty = TInfo;
2544 UnaryExprOrTypeTraitExprBits.IsType = true;
2545 }
2546
2547 /// Gets the argument type, or the type of the argument expression, whichever
2548 /// is appropriate.
getTypeOfArgument()2549 QualType getTypeOfArgument() const {
2550 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2551 }
2552
getOperatorLoc()2553 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2554 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2555
getRParenLoc()2556 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2557 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2558
getBeginLoc()2559 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
getEndLoc()2560 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2561
classof(const Stmt * T)2562 static bool classof(const Stmt *T) {
2563 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2564 }
2565
2566 // Iterators
2567 child_range children();
2568 const_child_range children() const;
2569 };
2570
2571 //===----------------------------------------------------------------------===//
2572 // Postfix Operators.
2573 //===----------------------------------------------------------------------===//
2574
2575 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2576 class ArraySubscriptExpr : public Expr {
2577 enum { LHS, RHS, END_EXPR };
2578 Stmt *SubExprs[END_EXPR];
2579
lhsIsBase()2580 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2581
2582 public:
ArraySubscriptExpr(Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation rbracketloc)2583 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2584 ExprObjectKind OK, SourceLocation rbracketloc)
2585 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2586 SubExprs[LHS] = lhs;
2587 SubExprs[RHS] = rhs;
2588 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2589 setDependence(computeDependence(this));
2590 }
2591
2592 /// Create an empty array subscript expression.
ArraySubscriptExpr(EmptyShell Shell)2593 explicit ArraySubscriptExpr(EmptyShell Shell)
2594 : Expr(ArraySubscriptExprClass, Shell) { }
2595
2596 /// An array access can be written A[4] or 4[A] (both are equivalent).
2597 /// - getBase() and getIdx() always present the normalized view: A[4].
2598 /// In this case getBase() returns "A" and getIdx() returns "4".
2599 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2600 /// 4[A] getLHS() returns "4".
2601 /// Note: Because vector element access is also written A[4] we must
2602 /// predicate the format conversion in getBase and getIdx only on the
2603 /// the type of the RHS, as it is possible for the LHS to be a vector of
2604 /// integer type
getLHS()2605 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
getLHS()2606 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2607 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2608
getRHS()2609 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
getRHS()2610 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2611 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2612
getBase()2613 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
getBase()2614 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2615
getIdx()2616 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
getIdx()2617 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2618
getBeginLoc()2619 SourceLocation getBeginLoc() const LLVM_READONLY {
2620 return getLHS()->getBeginLoc();
2621 }
getEndLoc()2622 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2623
getRBracketLoc()2624 SourceLocation getRBracketLoc() const {
2625 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2626 }
setRBracketLoc(SourceLocation L)2627 void setRBracketLoc(SourceLocation L) {
2628 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2629 }
2630
getExprLoc()2631 SourceLocation getExprLoc() const LLVM_READONLY {
2632 return getBase()->getExprLoc();
2633 }
2634
classof(const Stmt * T)2635 static bool classof(const Stmt *T) {
2636 return T->getStmtClass() == ArraySubscriptExprClass;
2637 }
2638
2639 // Iterators
children()2640 child_range children() {
2641 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2642 }
children()2643 const_child_range children() const {
2644 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2645 }
2646 };
2647
2648 /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2649 /// extension.
2650 /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2651 /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2652 /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2653 /// exist during the initial construction of the AST.
2654 class MatrixSubscriptExpr : public Expr {
2655 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2656 Stmt *SubExprs[END_EXPR];
2657
2658 public:
MatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,QualType T,SourceLocation RBracketLoc)2659 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2660 SourceLocation RBracketLoc)
2661 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2662 OK_MatrixComponent) {
2663 SubExprs[BASE] = Base;
2664 SubExprs[ROW_IDX] = RowIdx;
2665 SubExprs[COLUMN_IDX] = ColumnIdx;
2666 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2667 setDependence(computeDependence(this));
2668 }
2669
2670 /// Create an empty matrix subscript expression.
MatrixSubscriptExpr(EmptyShell Shell)2671 explicit MatrixSubscriptExpr(EmptyShell Shell)
2672 : Expr(MatrixSubscriptExprClass, Shell) {}
2673
isIncomplete()2674 bool isIncomplete() const {
2675 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2676 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2677 "expressions without column index must be marked as incomplete");
2678 return IsIncomplete;
2679 }
getBase()2680 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
getBase()2681 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
setBase(Expr * E)2682 void setBase(Expr *E) { SubExprs[BASE] = E; }
2683
getRowIdx()2684 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
getRowIdx()2685 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
setRowIdx(Expr * E)2686 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2687
getColumnIdx()2688 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
getColumnIdx()2689 const Expr *getColumnIdx() const {
2690 assert(!isIncomplete() &&
2691 "cannot get the column index of an incomplete expression");
2692 return cast<Expr>(SubExprs[COLUMN_IDX]);
2693 }
setColumnIdx(Expr * E)2694 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2695
getBeginLoc()2696 SourceLocation getBeginLoc() const LLVM_READONLY {
2697 return getBase()->getBeginLoc();
2698 }
2699
getEndLoc()2700 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2701
getExprLoc()2702 SourceLocation getExprLoc() const LLVM_READONLY {
2703 return getBase()->getExprLoc();
2704 }
2705
getRBracketLoc()2706 SourceLocation getRBracketLoc() const {
2707 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2708 }
setRBracketLoc(SourceLocation L)2709 void setRBracketLoc(SourceLocation L) {
2710 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2711 }
2712
classof(const Stmt * T)2713 static bool classof(const Stmt *T) {
2714 return T->getStmtClass() == MatrixSubscriptExprClass;
2715 }
2716
2717 // Iterators
children()2718 child_range children() {
2719 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2720 }
children()2721 const_child_range children() const {
2722 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2723 }
2724 };
2725
2726 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2727 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2728 /// while its subclasses may represent alternative syntax that (semantically)
2729 /// results in a function call. For example, CXXOperatorCallExpr is
2730 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2731 /// "str1 + str2" to resolve to a function call.
2732 class CallExpr : public Expr {
2733 enum { FN = 0, PREARGS_START = 1 };
2734
2735 /// The number of arguments in the call expression.
2736 unsigned NumArgs;
2737
2738 /// The location of the right parenthese. This has a different meaning for
2739 /// the derived classes of CallExpr.
2740 SourceLocation RParenLoc;
2741
2742 // CallExpr store some data in trailing objects. However since CallExpr
2743 // is used a base of other expression classes we cannot use
2744 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2745 // and casts.
2746 //
2747 // The trailing objects are in order:
2748 //
2749 // * A single "Stmt *" for the callee expression.
2750 //
2751 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2752 //
2753 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2754 //
2755 // * An optional of type FPOptionsOverride.
2756 //
2757 // Note that we store the offset in bytes from the this pointer to the start
2758 // of the trailing objects. It would be perfectly possible to compute it
2759 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2760 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2761 // compute this once and then load the offset from the bit-fields of Stmt,
2762 // instead of re-computing the offset each time the trailing objects are
2763 // accessed.
2764
2765 /// Return a pointer to the start of the trailing array of "Stmt *".
getTrailingStmts()2766 Stmt **getTrailingStmts() {
2767 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2768 CallExprBits.OffsetToTrailingObjects);
2769 }
getTrailingStmts()2770 Stmt *const *getTrailingStmts() const {
2771 return const_cast<CallExpr *>(this)->getTrailingStmts();
2772 }
2773
2774 /// Map a statement class to the appropriate offset in bytes from the
2775 /// this pointer to the trailing objects.
2776 static unsigned offsetToTrailingObjects(StmtClass SC);
2777
getSizeOfTrailingStmts()2778 unsigned getSizeOfTrailingStmts() const {
2779 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2780 }
2781
getOffsetOfTrailingFPFeatures()2782 size_t getOffsetOfTrailingFPFeatures() const {
2783 assert(hasStoredFPFeatures());
2784 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2785 }
2786
2787 public:
2788 enum class ADLCallKind : bool { NotADL, UsesADL };
2789 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2790 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2791
2792 protected:
2793 /// Build a call expression, assuming that appropriate storage has been
2794 /// allocated for the trailing objects.
2795 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2796 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2797 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2798 unsigned MinNumArgs, ADLCallKind UsesADL);
2799
2800 /// Build an empty call expression, for deserialization.
2801 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2802 bool hasFPFeatures, EmptyShell Empty);
2803
2804 /// Return the size in bytes needed for the trailing objects.
2805 /// Used by the derived classes to allocate the right amount of storage.
sizeOfTrailingObjects(unsigned NumPreArgs,unsigned NumArgs,bool HasFPFeatures)2806 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2807 bool HasFPFeatures) {
2808 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2809 HasFPFeatures * sizeof(FPOptionsOverride);
2810 }
2811
getPreArg(unsigned I)2812 Stmt *getPreArg(unsigned I) {
2813 assert(I < getNumPreArgs() && "Prearg access out of range!");
2814 return getTrailingStmts()[PREARGS_START + I];
2815 }
getPreArg(unsigned I)2816 const Stmt *getPreArg(unsigned I) const {
2817 assert(I < getNumPreArgs() && "Prearg access out of range!");
2818 return getTrailingStmts()[PREARGS_START + I];
2819 }
setPreArg(unsigned I,Stmt * PreArg)2820 void setPreArg(unsigned I, Stmt *PreArg) {
2821 assert(I < getNumPreArgs() && "Prearg access out of range!");
2822 getTrailingStmts()[PREARGS_START + I] = PreArg;
2823 }
2824
getNumPreArgs()2825 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2826
2827 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()2828 FPOptionsOverride *getTrailingFPFeatures() {
2829 assert(hasStoredFPFeatures());
2830 return reinterpret_cast<FPOptionsOverride *>(
2831 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2832 getSizeOfTrailingStmts());
2833 }
getTrailingFPFeatures()2834 const FPOptionsOverride *getTrailingFPFeatures() const {
2835 assert(hasStoredFPFeatures());
2836 return reinterpret_cast<const FPOptionsOverride *>(
2837 reinterpret_cast<const char *>(this) +
2838 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2839 }
2840
2841 public:
2842 /// Create a call expression.
2843 /// \param Fn The callee expression,
2844 /// \param Args The argument array,
2845 /// \param Ty The type of the call expression (which is *not* the return
2846 /// type in general),
2847 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2848 /// \param RParenLoc The location of the right parenthesis in the call
2849 /// expression.
2850 /// \param FPFeatures Floating-point features associated with the call,
2851 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2852 /// number of arguments will be the greater of Args.size()
2853 /// and MinNumArgs. This is used in a few places to allocate
2854 /// enough storage for the default arguments.
2855 /// \param UsesADL Specifies whether the callee was found through
2856 /// argument-dependent lookup.
2857 ///
2858 /// Note that you can use CreateTemporary if you need a temporary call
2859 /// expression on the stack.
2860 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2861 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2862 SourceLocation RParenLoc,
2863 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2864 ADLCallKind UsesADL = NotADL);
2865
2866 /// Create a temporary call expression with no arguments in the memory
2867 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2868 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2869 ///
2870 /// \code{.cpp}
2871 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2872 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2873 /// \endcode
2874 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2875 ExprValueKind VK, SourceLocation RParenLoc,
2876 ADLCallKind UsesADL = NotADL);
2877
2878 /// Create an empty call expression, for deserialization.
2879 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2880 bool HasFPFeatures, EmptyShell Empty);
2881
getCallee()2882 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
getCallee()2883 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
setCallee(Expr * F)2884 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2885
getADLCallKind()2886 ADLCallKind getADLCallKind() const {
2887 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2888 }
2889 void setADLCallKind(ADLCallKind V = UsesADL) {
2890 CallExprBits.UsesADL = static_cast<bool>(V);
2891 }
usesADL()2892 bool usesADL() const { return getADLCallKind() == UsesADL; }
2893
hasStoredFPFeatures()2894 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2895
getCalleeDecl()2896 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
getCalleeDecl()2897 const Decl *getCalleeDecl() const {
2898 return getCallee()->getReferencedDeclOfCallee();
2899 }
2900
2901 /// If the callee is a FunctionDecl, return it. Otherwise return null.
getDirectCallee()2902 FunctionDecl *getDirectCallee() {
2903 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2904 }
getDirectCallee()2905 const FunctionDecl *getDirectCallee() const {
2906 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2907 }
2908
2909 /// getNumArgs - Return the number of actual arguments to this call.
getNumArgs()2910 unsigned getNumArgs() const { return NumArgs; }
2911
2912 /// Retrieve the call arguments.
getArgs()2913 Expr **getArgs() {
2914 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2915 getNumPreArgs());
2916 }
getArgs()2917 const Expr *const *getArgs() const {
2918 return reinterpret_cast<const Expr *const *>(
2919 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2920 }
2921
2922 /// getArg - Return the specified argument.
getArg(unsigned Arg)2923 Expr *getArg(unsigned Arg) {
2924 assert(Arg < getNumArgs() && "Arg access out of range!");
2925 return getArgs()[Arg];
2926 }
getArg(unsigned Arg)2927 const Expr *getArg(unsigned Arg) const {
2928 assert(Arg < getNumArgs() && "Arg access out of range!");
2929 return getArgs()[Arg];
2930 }
2931
2932 /// setArg - Set the specified argument.
setArg(unsigned Arg,Expr * ArgExpr)2933 void setArg(unsigned Arg, Expr *ArgExpr) {
2934 assert(Arg < getNumArgs() && "Arg access out of range!");
2935 getArgs()[Arg] = ArgExpr;
2936 }
2937
2938 /// Reduce the number of arguments in this call expression. This is used for
2939 /// example during error recovery to drop extra arguments. There is no way
2940 /// to perform the opposite because: 1.) We don't track how much storage
2941 /// we have for the argument array 2.) This would potentially require growing
2942 /// the argument array, something we cannot support since the arguments are
2943 /// stored in a trailing array.
shrinkNumArgs(unsigned NewNumArgs)2944 void shrinkNumArgs(unsigned NewNumArgs) {
2945 assert((NewNumArgs <= getNumArgs()) &&
2946 "shrinkNumArgs cannot increase the number of arguments!");
2947 NumArgs = NewNumArgs;
2948 }
2949
2950 /// Bluntly set a new number of arguments without doing any checks whatsoever.
2951 /// Only used during construction of a CallExpr in a few places in Sema.
2952 /// FIXME: Find a way to remove it.
setNumArgsUnsafe(unsigned NewNumArgs)2953 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
2954
2955 typedef ExprIterator arg_iterator;
2956 typedef ConstExprIterator const_arg_iterator;
2957 typedef llvm::iterator_range<arg_iterator> arg_range;
2958 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2959
arguments()2960 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arguments()2961 const_arg_range arguments() const {
2962 return const_arg_range(arg_begin(), arg_end());
2963 }
2964
arg_begin()2965 arg_iterator arg_begin() {
2966 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2967 }
arg_end()2968 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
2969
arg_begin()2970 const_arg_iterator arg_begin() const {
2971 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2972 }
arg_end()2973 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
2974
2975 /// This method provides fast access to all the subexpressions of
2976 /// a CallExpr without going through the slower virtual child_iterator
2977 /// interface. This provides efficient reverse iteration of the
2978 /// subexpressions. This is currently used for CFG construction.
getRawSubExprs()2979 ArrayRef<Stmt *> getRawSubExprs() {
2980 return llvm::makeArrayRef(getTrailingStmts(),
2981 PREARGS_START + getNumPreArgs() + getNumArgs());
2982 }
2983
2984 /// getNumCommas - Return the number of commas that must have been present in
2985 /// this function call.
getNumCommas()2986 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
2987
2988 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()2989 FPOptionsOverride getStoredFPFeatures() const {
2990 assert(hasStoredFPFeatures());
2991 return *getTrailingFPFeatures();
2992 }
2993 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
setStoredFPFeatures(FPOptionsOverride F)2994 void setStoredFPFeatures(FPOptionsOverride F) {
2995 assert(hasStoredFPFeatures());
2996 *getTrailingFPFeatures() = F;
2997 }
2998
2999 // Get the FP features status of this operator. Only meaningful for
3000 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3001 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3002 if (hasStoredFPFeatures())
3003 return getStoredFPFeatures().applyOverrides(LO);
3004 return FPOptions::defaultWithoutTrailingStorage(LO);
3005 }
3006
getFPFeatures()3007 FPOptionsOverride getFPFeatures() const {
3008 if (hasStoredFPFeatures())
3009 return getStoredFPFeatures();
3010 return FPOptionsOverride();
3011 }
3012
3013 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3014 /// of the callee. If not, return 0.
3015 unsigned getBuiltinCallee() const;
3016
3017 /// Returns \c true if this is a call to a builtin which does not
3018 /// evaluate side-effects within its arguments.
3019 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3020
3021 /// getCallReturnType - Get the return type of the call expr. This is not
3022 /// always the type of the expr itself, if the return type is a reference
3023 /// type.
3024 QualType getCallReturnType(const ASTContext &Ctx) const;
3025
3026 /// Returns the WarnUnusedResultAttr that is either declared on the called
3027 /// function, or its return type declaration.
3028 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3029
3030 /// Returns true if this call expression should warn on unused results.
hasUnusedResultAttr(const ASTContext & Ctx)3031 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3032 return getUnusedResultAttr(Ctx) != nullptr;
3033 }
3034
getRParenLoc()3035 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3036 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3037
3038 SourceLocation getBeginLoc() const LLVM_READONLY;
3039 SourceLocation getEndLoc() const LLVM_READONLY;
3040
3041 /// Return true if this is a call to __assume() or __builtin_assume() with
3042 /// a non-value-dependent constant parameter evaluating as false.
3043 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3044
3045 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3046 /// (Usually Exprs themselves should set dependence).
markDependentForPostponedNameLookup()3047 void markDependentForPostponedNameLookup() {
3048 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3049 }
3050
isCallToStdMove()3051 bool isCallToStdMove() const {
3052 const FunctionDecl *FD = getDirectCallee();
3053 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
3054 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
3055 }
3056
classof(const Stmt * T)3057 static bool classof(const Stmt *T) {
3058 return T->getStmtClass() >= firstCallExprConstant &&
3059 T->getStmtClass() <= lastCallExprConstant;
3060 }
3061
3062 // Iterators
children()3063 child_range children() {
3064 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3065 getNumPreArgs() + getNumArgs());
3066 }
3067
children()3068 const_child_range children() const {
3069 return const_child_range(getTrailingStmts(),
3070 getTrailingStmts() + PREARGS_START +
3071 getNumPreArgs() + getNumArgs());
3072 }
3073 };
3074
3075 /// Extra data stored in some MemberExpr objects.
3076 struct MemberExprNameQualifier {
3077 /// The nested-name-specifier that qualifies the name, including
3078 /// source-location information.
3079 NestedNameSpecifierLoc QualifierLoc;
3080
3081 /// The DeclAccessPair through which the MemberDecl was found due to
3082 /// name qualifiers.
3083 DeclAccessPair FoundDecl;
3084 };
3085
3086 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3087 ///
3088 class MemberExpr final
3089 : public Expr,
3090 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3091 ASTTemplateKWAndArgsInfo,
3092 TemplateArgumentLoc> {
3093 friend class ASTReader;
3094 friend class ASTStmtReader;
3095 friend class ASTStmtWriter;
3096 friend TrailingObjects;
3097
3098 /// Base - the expression for the base pointer or structure references. In
3099 /// X.F, this is "X".
3100 Stmt *Base;
3101
3102 /// MemberDecl - This is the decl being referenced by the field/member name.
3103 /// In X.F, this is the decl referenced by F.
3104 ValueDecl *MemberDecl;
3105
3106 /// MemberDNLoc - Provides source/type location info for the
3107 /// declaration name embedded in MemberDecl.
3108 DeclarationNameLoc MemberDNLoc;
3109
3110 /// MemberLoc - This is the location of the member name.
3111 SourceLocation MemberLoc;
3112
numTrailingObjects(OverloadToken<MemberExprNameQualifier>)3113 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3114 return hasQualifierOrFoundDecl();
3115 }
3116
numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>)3117 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3118 return hasTemplateKWAndArgsInfo();
3119 }
3120
hasQualifierOrFoundDecl()3121 bool hasQualifierOrFoundDecl() const {
3122 return MemberExprBits.HasQualifierOrFoundDecl;
3123 }
3124
hasTemplateKWAndArgsInfo()3125 bool hasTemplateKWAndArgsInfo() const {
3126 return MemberExprBits.HasTemplateKWAndArgsInfo;
3127 }
3128
3129 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3130 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3131 QualType T, ExprValueKind VK, ExprObjectKind OK,
3132 NonOdrUseReason NOUR);
MemberExpr(EmptyShell Empty)3133 MemberExpr(EmptyShell Empty)
3134 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3135
3136 public:
3137 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3138 SourceLocation OperatorLoc,
3139 NestedNameSpecifierLoc QualifierLoc,
3140 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3141 DeclAccessPair FoundDecl,
3142 DeclarationNameInfo MemberNameInfo,
3143 const TemplateArgumentListInfo *TemplateArgs,
3144 QualType T, ExprValueKind VK, ExprObjectKind OK,
3145 NonOdrUseReason NOUR);
3146
3147 /// Create an implicit MemberExpr, with no location, qualifier, template
3148 /// arguments, and so on. Suitable only for non-static member access.
CreateImplicit(const ASTContext & C,Expr * Base,bool IsArrow,ValueDecl * MemberDecl,QualType T,ExprValueKind VK,ExprObjectKind OK)3149 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3150 bool IsArrow, ValueDecl *MemberDecl,
3151 QualType T, ExprValueKind VK,
3152 ExprObjectKind OK) {
3153 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3154 SourceLocation(), MemberDecl,
3155 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3156 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3157 }
3158
3159 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3160 bool HasFoundDecl,
3161 bool HasTemplateKWAndArgsInfo,
3162 unsigned NumTemplateArgs);
3163
setBase(Expr * E)3164 void setBase(Expr *E) { Base = E; }
getBase()3165 Expr *getBase() const { return cast<Expr>(Base); }
3166
3167 /// Retrieve the member declaration to which this expression refers.
3168 ///
3169 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3170 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
getMemberDecl()3171 ValueDecl *getMemberDecl() const { return MemberDecl; }
3172 void setMemberDecl(ValueDecl *D);
3173
3174 /// Retrieves the declaration found by lookup.
getFoundDecl()3175 DeclAccessPair getFoundDecl() const {
3176 if (!hasQualifierOrFoundDecl())
3177 return DeclAccessPair::make(getMemberDecl(),
3178 getMemberDecl()->getAccess());
3179 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3180 }
3181
3182 /// Determines whether this member expression actually had
3183 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3184 /// x->Base::foo.
hasQualifier()3185 bool hasQualifier() const { return getQualifier() != nullptr; }
3186
3187 /// If the member name was qualified, retrieves the
3188 /// nested-name-specifier that precedes the member name, with source-location
3189 /// information.
getQualifierLoc()3190 NestedNameSpecifierLoc getQualifierLoc() const {
3191 if (!hasQualifierOrFoundDecl())
3192 return NestedNameSpecifierLoc();
3193 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3194 }
3195
3196 /// If the member name was qualified, retrieves the
3197 /// nested-name-specifier that precedes the member name. Otherwise, returns
3198 /// NULL.
getQualifier()3199 NestedNameSpecifier *getQualifier() const {
3200 return getQualifierLoc().getNestedNameSpecifier();
3201 }
3202
3203 /// Retrieve the location of the template keyword preceding
3204 /// the member name, if any.
getTemplateKeywordLoc()3205 SourceLocation getTemplateKeywordLoc() const {
3206 if (!hasTemplateKWAndArgsInfo())
3207 return SourceLocation();
3208 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3209 }
3210
3211 /// Retrieve the location of the left angle bracket starting the
3212 /// explicit template argument list following the member name, if any.
getLAngleLoc()3213 SourceLocation getLAngleLoc() const {
3214 if (!hasTemplateKWAndArgsInfo())
3215 return SourceLocation();
3216 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3217 }
3218
3219 /// Retrieve the location of the right angle bracket ending the
3220 /// explicit template argument list following the member name, if any.
getRAngleLoc()3221 SourceLocation getRAngleLoc() const {
3222 if (!hasTemplateKWAndArgsInfo())
3223 return SourceLocation();
3224 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3225 }
3226
3227 /// Determines whether the member name was preceded by the template keyword.
hasTemplateKeyword()3228 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3229
3230 /// Determines whether the member name was followed by an
3231 /// explicit template argument list.
hasExplicitTemplateArgs()3232 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3233
3234 /// Copies the template arguments (if present) into the given
3235 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)3236 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3237 if (hasExplicitTemplateArgs())
3238 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3239 getTrailingObjects<TemplateArgumentLoc>(), List);
3240 }
3241
3242 /// Retrieve the template arguments provided as part of this
3243 /// template-id.
getTemplateArgs()3244 const TemplateArgumentLoc *getTemplateArgs() const {
3245 if (!hasExplicitTemplateArgs())
3246 return nullptr;
3247
3248 return getTrailingObjects<TemplateArgumentLoc>();
3249 }
3250
3251 /// Retrieve the number of template arguments provided as part of this
3252 /// template-id.
getNumTemplateArgs()3253 unsigned getNumTemplateArgs() const {
3254 if (!hasExplicitTemplateArgs())
3255 return 0;
3256
3257 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3258 }
3259
template_arguments()3260 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3261 return {getTemplateArgs(), getNumTemplateArgs()};
3262 }
3263
3264 /// Retrieve the member declaration name info.
getMemberNameInfo()3265 DeclarationNameInfo getMemberNameInfo() const {
3266 return DeclarationNameInfo(MemberDecl->getDeclName(),
3267 MemberLoc, MemberDNLoc);
3268 }
3269
getOperatorLoc()3270 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3271
isArrow()3272 bool isArrow() const { return MemberExprBits.IsArrow; }
setArrow(bool A)3273 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3274
3275 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3276 /// location of 'F'.
getMemberLoc()3277 SourceLocation getMemberLoc() const { return MemberLoc; }
setMemberLoc(SourceLocation L)3278 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3279
3280 SourceLocation getBeginLoc() const LLVM_READONLY;
3281 SourceLocation getEndLoc() const LLVM_READONLY;
3282
getExprLoc()3283 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3284
3285 /// Determine whether the base of this explicit is implicit.
isImplicitAccess()3286 bool isImplicitAccess() const {
3287 return getBase() && getBase()->isImplicitCXXThis();
3288 }
3289
3290 /// Returns true if this member expression refers to a method that
3291 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()3292 bool hadMultipleCandidates() const {
3293 return MemberExprBits.HadMultipleCandidates;
3294 }
3295 /// Sets the flag telling whether this expression refers to
3296 /// a method that was resolved from an overloaded set having size
3297 /// greater than 1.
3298 void setHadMultipleCandidates(bool V = true) {
3299 MemberExprBits.HadMultipleCandidates = V;
3300 }
3301
3302 /// Returns true if virtual dispatch is performed.
3303 /// If the member access is fully qualified, (i.e. X::f()), virtual
3304 /// dispatching is not performed. In -fapple-kext mode qualified
3305 /// calls to virtual method will still go through the vtable.
performsVirtualDispatch(const LangOptions & LO)3306 bool performsVirtualDispatch(const LangOptions &LO) const {
3307 return LO.AppleKext || !hasQualifier();
3308 }
3309
3310 /// Is this expression a non-odr-use reference, and if so, why?
3311 /// This is only meaningful if the named member is a static member.
isNonOdrUse()3312 NonOdrUseReason isNonOdrUse() const {
3313 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3314 }
3315
classof(const Stmt * T)3316 static bool classof(const Stmt *T) {
3317 return T->getStmtClass() == MemberExprClass;
3318 }
3319
3320 // Iterators
children()3321 child_range children() { return child_range(&Base, &Base+1); }
children()3322 const_child_range children() const {
3323 return const_child_range(&Base, &Base + 1);
3324 }
3325 };
3326
3327 /// CompoundLiteralExpr - [C99 6.5.2.5]
3328 ///
3329 class CompoundLiteralExpr : public Expr {
3330 /// LParenLoc - If non-null, this is the location of the left paren in a
3331 /// compound literal like "(int){4}". This can be null if this is a
3332 /// synthesized compound expression.
3333 SourceLocation LParenLoc;
3334
3335 /// The type as written. This can be an incomplete array type, in
3336 /// which case the actual expression type will be different.
3337 /// The int part of the pair stores whether this expr is file scope.
3338 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3339 Stmt *Init;
3340 public:
CompoundLiteralExpr(SourceLocation lparenloc,TypeSourceInfo * tinfo,QualType T,ExprValueKind VK,Expr * init,bool fileScope)3341 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3342 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3343 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3344 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3345 setDependence(computeDependence(this));
3346 }
3347
3348 /// Construct an empty compound literal.
CompoundLiteralExpr(EmptyShell Empty)3349 explicit CompoundLiteralExpr(EmptyShell Empty)
3350 : Expr(CompoundLiteralExprClass, Empty) { }
3351
getInitializer()3352 const Expr *getInitializer() const { return cast<Expr>(Init); }
getInitializer()3353 Expr *getInitializer() { return cast<Expr>(Init); }
setInitializer(Expr * E)3354 void setInitializer(Expr *E) { Init = E; }
3355
isFileScope()3356 bool isFileScope() const { return TInfoAndScope.getInt(); }
setFileScope(bool FS)3357 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3358
getLParenLoc()3359 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)3360 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3361
getTypeSourceInfo()3362 TypeSourceInfo *getTypeSourceInfo() const {
3363 return TInfoAndScope.getPointer();
3364 }
setTypeSourceInfo(TypeSourceInfo * tinfo)3365 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3366 TInfoAndScope.setPointer(tinfo);
3367 }
3368
getBeginLoc()3369 SourceLocation getBeginLoc() const LLVM_READONLY {
3370 // FIXME: Init should never be null.
3371 if (!Init)
3372 return SourceLocation();
3373 if (LParenLoc.isInvalid())
3374 return Init->getBeginLoc();
3375 return LParenLoc;
3376 }
getEndLoc()3377 SourceLocation getEndLoc() const LLVM_READONLY {
3378 // FIXME: Init should never be null.
3379 if (!Init)
3380 return SourceLocation();
3381 return Init->getEndLoc();
3382 }
3383
classof(const Stmt * T)3384 static bool classof(const Stmt *T) {
3385 return T->getStmtClass() == CompoundLiteralExprClass;
3386 }
3387
3388 // Iterators
children()3389 child_range children() { return child_range(&Init, &Init+1); }
children()3390 const_child_range children() const {
3391 return const_child_range(&Init, &Init + 1);
3392 }
3393 };
3394
3395 /// CastExpr - Base class for type casts, including both implicit
3396 /// casts (ImplicitCastExpr) and explicit casts that have some
3397 /// representation in the source code (ExplicitCastExpr's derived
3398 /// classes).
3399 class CastExpr : public Expr {
3400 Stmt *Op;
3401
3402 bool CastConsistency() const;
3403
path_buffer()3404 const CXXBaseSpecifier * const *path_buffer() const {
3405 return const_cast<CastExpr*>(this)->path_buffer();
3406 }
3407 CXXBaseSpecifier **path_buffer();
3408
3409 friend class ASTStmtReader;
3410
3411 protected:
CastExpr(StmtClass SC,QualType ty,ExprValueKind VK,const CastKind kind,Expr * op,unsigned BasePathSize,bool HasFPFeatures)3412 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3413 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3414 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3415 CastExprBits.Kind = kind;
3416 CastExprBits.PartOfExplicitCast = false;
3417 CastExprBits.BasePathSize = BasePathSize;
3418 assert((CastExprBits.BasePathSize == BasePathSize) &&
3419 "BasePathSize overflow!");
3420 setDependence(computeDependence(this));
3421 assert(CastConsistency());
3422 CastExprBits.HasFPFeatures = HasFPFeatures;
3423 }
3424
3425 /// Construct an empty cast.
CastExpr(StmtClass SC,EmptyShell Empty,unsigned BasePathSize,bool HasFPFeatures)3426 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3427 bool HasFPFeatures)
3428 : Expr(SC, Empty) {
3429 CastExprBits.PartOfExplicitCast = false;
3430 CastExprBits.BasePathSize = BasePathSize;
3431 CastExprBits.HasFPFeatures = HasFPFeatures;
3432 assert((CastExprBits.BasePathSize == BasePathSize) &&
3433 "BasePathSize overflow!");
3434 }
3435
3436 /// Return a pointer to the trailing FPOptions.
3437 /// \pre hasStoredFPFeatures() == true
3438 FPOptionsOverride *getTrailingFPFeatures();
getTrailingFPFeatures()3439 const FPOptionsOverride *getTrailingFPFeatures() const {
3440 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3441 }
3442
3443 public:
getCastKind()3444 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
setCastKind(CastKind K)3445 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3446
3447 static const char *getCastKindName(CastKind CK);
getCastKindName()3448 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3449
getSubExpr()3450 Expr *getSubExpr() { return cast<Expr>(Op); }
getSubExpr()3451 const Expr *getSubExpr() const { return cast<Expr>(Op); }
setSubExpr(Expr * E)3452 void setSubExpr(Expr *E) { Op = E; }
3453
3454 /// Retrieve the cast subexpression as it was written in the source
3455 /// code, looking through any implicit casts or other intermediate nodes
3456 /// introduced by semantic analysis.
3457 Expr *getSubExprAsWritten();
getSubExprAsWritten()3458 const Expr *getSubExprAsWritten() const {
3459 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3460 }
3461
3462 /// If this cast applies a user-defined conversion, retrieve the conversion
3463 /// function that it invokes.
3464 NamedDecl *getConversionFunction() const;
3465
3466 typedef CXXBaseSpecifier **path_iterator;
3467 typedef const CXXBaseSpecifier *const *path_const_iterator;
path_empty()3468 bool path_empty() const { return path_size() == 0; }
path_size()3469 unsigned path_size() const { return CastExprBits.BasePathSize; }
path_begin()3470 path_iterator path_begin() { return path_buffer(); }
path_end()3471 path_iterator path_end() { return path_buffer() + path_size(); }
path_begin()3472 path_const_iterator path_begin() const { return path_buffer(); }
path_end()3473 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3474
path()3475 llvm::iterator_range<path_iterator> path() {
3476 return llvm::make_range(path_begin(), path_end());
3477 }
path()3478 llvm::iterator_range<path_const_iterator> path() const {
3479 return llvm::make_range(path_begin(), path_end());
3480 }
3481
getTargetUnionField()3482 const FieldDecl *getTargetUnionField() const {
3483 assert(getCastKind() == CK_ToUnion);
3484 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3485 }
3486
hasStoredFPFeatures()3487 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3488
3489 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()3490 FPOptionsOverride getStoredFPFeatures() const {
3491 assert(hasStoredFPFeatures());
3492 return *getTrailingFPFeatures();
3493 }
3494
3495 // Get the FP features status of this operation. Only meaningful for
3496 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3497 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3498 if (hasStoredFPFeatures())
3499 return getStoredFPFeatures().applyOverrides(LO);
3500 return FPOptions::defaultWithoutTrailingStorage(LO);
3501 }
3502
getFPFeatures()3503 FPOptionsOverride getFPFeatures() const {
3504 if (hasStoredFPFeatures())
3505 return getStoredFPFeatures();
3506 return FPOptionsOverride();
3507 }
3508
3509 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3510 QualType opType);
3511 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3512 QualType opType);
3513
classof(const Stmt * T)3514 static bool classof(const Stmt *T) {
3515 return T->getStmtClass() >= firstCastExprConstant &&
3516 T->getStmtClass() <= lastCastExprConstant;
3517 }
3518
3519 // Iterators
children()3520 child_range children() { return child_range(&Op, &Op+1); }
children()3521 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3522 };
3523
3524 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
3525 /// conversions, which have no direct representation in the original
3526 /// source code. For example: converting T[]->T*, void f()->void
3527 /// (*f)(), float->double, short->int, etc.
3528 ///
3529 /// In C, implicit casts always produce rvalues. However, in C++, an
3530 /// implicit cast whose result is being bound to a reference will be
3531 /// an lvalue or xvalue. For example:
3532 ///
3533 /// @code
3534 /// class Base { };
3535 /// class Derived : public Base { };
3536 /// Derived &&ref();
3537 /// void f(Derived d) {
3538 /// Base& b = d; // initializer is an ImplicitCastExpr
3539 /// // to an lvalue of type Base
3540 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
3541 /// // to an xvalue of type Base
3542 /// }
3543 /// @endcode
3544 class ImplicitCastExpr final
3545 : public CastExpr,
3546 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3547 FPOptionsOverride> {
3548
ImplicitCastExpr(QualType ty,CastKind kind,Expr * op,unsigned BasePathLength,FPOptionsOverride FPO,ExprValueKind VK)3549 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3550 unsigned BasePathLength, FPOptionsOverride FPO,
3551 ExprValueKind VK)
3552 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3553 FPO.requiresTrailingStorage()) {
3554 if (hasStoredFPFeatures())
3555 *getTrailingFPFeatures() = FPO;
3556 }
3557
3558 /// Construct an empty implicit cast.
ImplicitCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3559 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3560 bool HasFPFeatures)
3561 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3562
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3563 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3564 return path_size();
3565 }
3566
3567 public:
3568 enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _,QualType ty,CastKind kind,Expr * op,ExprValueKind VK,FPOptionsOverride FPO)3569 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3570 ExprValueKind VK, FPOptionsOverride FPO)
3571 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3572 FPO.requiresTrailingStorage()) {
3573 if (hasStoredFPFeatures())
3574 *getTrailingFPFeatures() = FPO;
3575 }
3576
isPartOfExplicitCast()3577 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
setIsPartOfExplicitCast(bool PartOfExplicitCast)3578 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3579 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3580 }
3581
3582 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3583 CastKind Kind, Expr *Operand,
3584 const CXXCastPath *BasePath,
3585 ExprValueKind Cat, FPOptionsOverride FPO);
3586
3587 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3588 unsigned PathSize, bool HasFPFeatures);
3589
getBeginLoc()3590 SourceLocation getBeginLoc() const LLVM_READONLY {
3591 return getSubExpr()->getBeginLoc();
3592 }
getEndLoc()3593 SourceLocation getEndLoc() const LLVM_READONLY {
3594 return getSubExpr()->getEndLoc();
3595 }
3596
classof(const Stmt * T)3597 static bool classof(const Stmt *T) {
3598 return T->getStmtClass() == ImplicitCastExprClass;
3599 }
3600
3601 friend TrailingObjects;
3602 friend class CastExpr;
3603 };
3604
3605 /// ExplicitCastExpr - An explicit cast written in the source
3606 /// code.
3607 ///
3608 /// This class is effectively an abstract class, because it provides
3609 /// the basic representation of an explicitly-written cast without
3610 /// specifying which kind of cast (C cast, functional cast, static
3611 /// cast, etc.) was written; specific derived classes represent the
3612 /// particular style of cast and its location information.
3613 ///
3614 /// Unlike implicit casts, explicit cast nodes have two different
3615 /// types: the type that was written into the source code, and the
3616 /// actual type of the expression as determined by semantic
3617 /// analysis. These types may differ slightly. For example, in C++ one
3618 /// can cast to a reference type, which indicates that the resulting
3619 /// expression will be an lvalue or xvalue. The reference type, however,
3620 /// will not be used as the type of the expression.
3621 class ExplicitCastExpr : public CastExpr {
3622 /// TInfo - Source type info for the (written) type
3623 /// this expression is casting to.
3624 TypeSourceInfo *TInfo;
3625
3626 protected:
ExplicitCastExpr(StmtClass SC,QualType exprTy,ExprValueKind VK,CastKind kind,Expr * op,unsigned PathSize,bool HasFPFeatures,TypeSourceInfo * writtenTy)3627 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3628 CastKind kind, Expr *op, unsigned PathSize,
3629 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3630 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3631 TInfo(writtenTy) {}
3632
3633 /// Construct an empty explicit cast.
ExplicitCastExpr(StmtClass SC,EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3634 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3635 bool HasFPFeatures)
3636 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3637
3638 public:
3639 /// getTypeInfoAsWritten - Returns the type source info for the type
3640 /// that this expression is casting to.
getTypeInfoAsWritten()3641 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
setTypeInfoAsWritten(TypeSourceInfo * writtenTy)3642 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3643
3644 /// getTypeAsWritten - Returns the type that this expression is
3645 /// casting to, as written in the source code.
getTypeAsWritten()3646 QualType getTypeAsWritten() const { return TInfo->getType(); }
3647
classof(const Stmt * T)3648 static bool classof(const Stmt *T) {
3649 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3650 T->getStmtClass() <= lastExplicitCastExprConstant;
3651 }
3652 };
3653
3654 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3655 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3656 /// (Type)expr. For example: @c (int)f.
3657 class CStyleCastExpr final
3658 : public ExplicitCastExpr,
3659 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3660 FPOptionsOverride> {
3661 SourceLocation LPLoc; // the location of the left paren
3662 SourceLocation RPLoc; // the location of the right paren
3663
CStyleCastExpr(QualType exprTy,ExprValueKind vk,CastKind kind,Expr * op,unsigned PathSize,FPOptionsOverride FPO,TypeSourceInfo * writtenTy,SourceLocation l,SourceLocation r)3664 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3665 unsigned PathSize, FPOptionsOverride FPO,
3666 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3667 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3668 FPO.requiresTrailingStorage(), writtenTy),
3669 LPLoc(l), RPLoc(r) {
3670 if (hasStoredFPFeatures())
3671 *getTrailingFPFeatures() = FPO;
3672 }
3673
3674 /// Construct an empty C-style explicit cast.
CStyleCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3675 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3676 bool HasFPFeatures)
3677 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3678
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3679 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3680 return path_size();
3681 }
3682
3683 public:
3684 static CStyleCastExpr *
3685 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3686 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3687 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3688
3689 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3690 unsigned PathSize, bool HasFPFeatures);
3691
getLParenLoc()3692 SourceLocation getLParenLoc() const { return LPLoc; }
setLParenLoc(SourceLocation L)3693 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3694
getRParenLoc()3695 SourceLocation getRParenLoc() const { return RPLoc; }
setRParenLoc(SourceLocation L)3696 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3697
getBeginLoc()3698 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
getEndLoc()3699 SourceLocation getEndLoc() const LLVM_READONLY {
3700 return getSubExpr()->getEndLoc();
3701 }
3702
classof(const Stmt * T)3703 static bool classof(const Stmt *T) {
3704 return T->getStmtClass() == CStyleCastExprClass;
3705 }
3706
3707 friend TrailingObjects;
3708 friend class CastExpr;
3709 };
3710
3711 /// A builtin binary operation expression such as "x + y" or "x <= y".
3712 ///
3713 /// This expression node kind describes a builtin binary operation,
3714 /// such as "x + y" for integer values "x" and "y". The operands will
3715 /// already have been converted to appropriate types (e.g., by
3716 /// performing promotions or conversions).
3717 ///
3718 /// In C++, where operators may be overloaded, a different kind of
3719 /// expression node (CXXOperatorCallExpr) is used to express the
3720 /// invocation of an overloaded operator with operator syntax. Within
3721 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3722 /// used to store an expression "x + y" depends on the subexpressions
3723 /// for x and y. If neither x or y is type-dependent, and the "+"
3724 /// operator resolves to a built-in operation, BinaryOperator will be
3725 /// used to express the computation (x and y may still be
3726 /// value-dependent). If either x or y is type-dependent, or if the
3727 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3728 /// be used to express the computation.
3729 class BinaryOperator : public Expr {
3730 enum { LHS, RHS, END_EXPR };
3731 Stmt *SubExprs[END_EXPR];
3732
3733 public:
3734 typedef BinaryOperatorKind Opcode;
3735
3736 protected:
3737 size_t offsetOfTrailingStorage() const;
3738
3739 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()3740 FPOptionsOverride *getTrailingFPFeatures() {
3741 assert(BinaryOperatorBits.HasFPFeatures);
3742 return reinterpret_cast<FPOptionsOverride *>(
3743 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3744 }
getTrailingFPFeatures()3745 const FPOptionsOverride *getTrailingFPFeatures() const {
3746 assert(BinaryOperatorBits.HasFPFeatures);
3747 return reinterpret_cast<const FPOptionsOverride *>(
3748 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3749 }
3750
3751 /// Build a binary operator, assuming that appropriate storage has been
3752 /// allocated for the trailing objects when needed.
3753 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3754 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3755 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3756
3757 /// Construct an empty binary operator.
BinaryOperator(EmptyShell Empty)3758 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3759 BinaryOperatorBits.Opc = BO_Comma;
3760 }
3761
3762 public:
3763 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3764
3765 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3766 Opcode opc, QualType ResTy, ExprValueKind VK,
3767 ExprObjectKind OK, SourceLocation opLoc,
3768 FPOptionsOverride FPFeatures);
getExprLoc()3769 SourceLocation getExprLoc() const { return getOperatorLoc(); }
getOperatorLoc()3770 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
setOperatorLoc(SourceLocation L)3771 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3772
getOpcode()3773 Opcode getOpcode() const {
3774 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3775 }
setOpcode(Opcode Opc)3776 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3777
getLHS()3778 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)3779 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()3780 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)3781 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3782
getBeginLoc()3783 SourceLocation getBeginLoc() const LLVM_READONLY {
3784 return getLHS()->getBeginLoc();
3785 }
getEndLoc()3786 SourceLocation getEndLoc() const LLVM_READONLY {
3787 return getRHS()->getEndLoc();
3788 }
3789
3790 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3791 /// corresponds to, e.g. "<<=".
3792 static StringRef getOpcodeStr(Opcode Op);
3793
getOpcodeStr()3794 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3795
3796 /// Retrieve the binary opcode that corresponds to the given
3797 /// overloaded operator.
3798 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3799
3800 /// Retrieve the overloaded operator kind that corresponds to
3801 /// the given binary opcode.
3802 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3803
3804 /// predicates to categorize the respective opcodes.
isPtrMemOp(Opcode Opc)3805 static bool isPtrMemOp(Opcode Opc) {
3806 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3807 }
isPtrMemOp()3808 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3809
isMultiplicativeOp(Opcode Opc)3810 static bool isMultiplicativeOp(Opcode Opc) {
3811 return Opc >= BO_Mul && Opc <= BO_Rem;
3812 }
isMultiplicativeOp()3813 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
isAdditiveOp(Opcode Opc)3814 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
isAdditiveOp()3815 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
isShiftOp(Opcode Opc)3816 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
isShiftOp()3817 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3818
isBitwiseOp(Opcode Opc)3819 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
isBitwiseOp()3820 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3821
isRelationalOp(Opcode Opc)3822 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
isRelationalOp()3823 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3824
isEqualityOp(Opcode Opc)3825 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
isEqualityOp()3826 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3827
isComparisonOp(Opcode Opc)3828 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
isComparisonOp()3829 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3830
isCommaOp(Opcode Opc)3831 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
isCommaOp()3832 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3833
negateComparisonOp(Opcode Opc)3834 static Opcode negateComparisonOp(Opcode Opc) {
3835 switch (Opc) {
3836 default:
3837 llvm_unreachable("Not a comparison operator.");
3838 case BO_LT: return BO_GE;
3839 case BO_GT: return BO_LE;
3840 case BO_LE: return BO_GT;
3841 case BO_GE: return BO_LT;
3842 case BO_EQ: return BO_NE;
3843 case BO_NE: return BO_EQ;
3844 }
3845 }
3846
reverseComparisonOp(Opcode Opc)3847 static Opcode reverseComparisonOp(Opcode Opc) {
3848 switch (Opc) {
3849 default:
3850 llvm_unreachable("Not a comparison operator.");
3851 case BO_LT: return BO_GT;
3852 case BO_GT: return BO_LT;
3853 case BO_LE: return BO_GE;
3854 case BO_GE: return BO_LE;
3855 case BO_EQ:
3856 case BO_NE:
3857 return Opc;
3858 }
3859 }
3860
isLogicalOp(Opcode Opc)3861 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
isLogicalOp()3862 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3863
isAssignmentOp(Opcode Opc)3864 static bool isAssignmentOp(Opcode Opc) {
3865 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3866 }
isAssignmentOp()3867 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3868
isCompoundAssignmentOp(Opcode Opc)3869 static bool isCompoundAssignmentOp(Opcode Opc) {
3870 return Opc > BO_Assign && Opc <= BO_OrAssign;
3871 }
isCompoundAssignmentOp()3872 bool isCompoundAssignmentOp() const {
3873 return isCompoundAssignmentOp(getOpcode());
3874 }
getOpForCompoundAssignment(Opcode Opc)3875 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3876 assert(isCompoundAssignmentOp(Opc));
3877 if (Opc >= BO_AndAssign)
3878 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3879 else
3880 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3881 }
3882
isShiftAssignOp(Opcode Opc)3883 static bool isShiftAssignOp(Opcode Opc) {
3884 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3885 }
isShiftAssignOp()3886 bool isShiftAssignOp() const {
3887 return isShiftAssignOp(getOpcode());
3888 }
3889
3890 // Return true if a binary operator using the specified opcode and operands
3891 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3892 // integer to a pointer.
3893 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3894 Expr *LHS, Expr *RHS);
3895
classof(const Stmt * S)3896 static bool classof(const Stmt *S) {
3897 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3898 S->getStmtClass() <= lastBinaryOperatorConstant;
3899 }
3900
3901 // Iterators
children()3902 child_range children() {
3903 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3904 }
children()3905 const_child_range children() const {
3906 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3907 }
3908
3909 /// Set and fetch the bit that shows whether FPFeatures needs to be
3910 /// allocated in Trailing Storage
setHasStoredFPFeatures(bool B)3911 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
hasStoredFPFeatures()3912 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3913
3914 /// Get FPFeatures from trailing storage
getStoredFPFeatures()3915 FPOptionsOverride getStoredFPFeatures() const {
3916 assert(hasStoredFPFeatures());
3917 return *getTrailingFPFeatures();
3918 }
3919 /// Set FPFeatures in trailing storage, used only by Serialization
setStoredFPFeatures(FPOptionsOverride F)3920 void setStoredFPFeatures(FPOptionsOverride F) {
3921 assert(BinaryOperatorBits.HasFPFeatures);
3922 *getTrailingFPFeatures() = F;
3923 }
3924
3925 // Get the FP features status of this operator. Only meaningful for
3926 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3927 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3928 if (BinaryOperatorBits.HasFPFeatures)
3929 return getStoredFPFeatures().applyOverrides(LO);
3930 return FPOptions::defaultWithoutTrailingStorage(LO);
3931 }
3932
3933 // This is used in ASTImporter
getFPFeatures(const LangOptions & LO)3934 FPOptionsOverride getFPFeatures(const LangOptions &LO) const {
3935 if (BinaryOperatorBits.HasFPFeatures)
3936 return getStoredFPFeatures();
3937 return FPOptionsOverride();
3938 }
3939
3940 // Get the FP contractability status of this operator. Only meaningful for
3941 // operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)3942 bool isFPContractableWithinStatement(const LangOptions &LO) const {
3943 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
3944 }
3945
3946 // Get the FENV_ACCESS status of this operator. Only meaningful for
3947 // operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)3948 bool isFEnvAccessOn(const LangOptions &LO) const {
3949 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
3950 }
3951
3952 protected:
3953 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3954 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3955 SourceLocation opLoc, FPOptionsOverride FPFeatures,
3956 bool dead2);
3957
3958 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
BinaryOperator(StmtClass SC,EmptyShell Empty)3959 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
3960 BinaryOperatorBits.Opc = BO_MulAssign;
3961 }
3962
3963 /// Return the size in bytes needed for the trailing objects.
3964 /// Used to allocate the right amount of storage.
sizeOfTrailingObjects(bool HasFPFeatures)3965 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
3966 return HasFPFeatures * sizeof(FPOptionsOverride);
3967 }
3968 };
3969
3970 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3971 /// track of the type the operation is performed in. Due to the semantics of
3972 /// these operators, the operands are promoted, the arithmetic performed, an
3973 /// implicit conversion back to the result type done, then the assignment takes
3974 /// place. This captures the intermediate type which the computation is done
3975 /// in.
3976 class CompoundAssignOperator : public BinaryOperator {
3977 QualType ComputationLHSType;
3978 QualType ComputationResultType;
3979
3980 /// Construct an empty CompoundAssignOperator.
CompoundAssignOperator(const ASTContext & C,EmptyShell Empty,bool hasFPFeatures)3981 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
3982 bool hasFPFeatures)
3983 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
3984
3985 protected:
CompoundAssignOperator(const ASTContext & C,Expr * lhs,Expr * rhs,Opcode opc,QualType ResType,ExprValueKind VK,ExprObjectKind OK,SourceLocation OpLoc,FPOptionsOverride FPFeatures,QualType CompLHSType,QualType CompResultType)3986 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
3987 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
3988 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
3989 QualType CompLHSType, QualType CompResultType)
3990 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3991 true),
3992 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
3993 assert(isCompoundAssignmentOp() &&
3994 "Only should be used for compound assignments");
3995 }
3996
3997 public:
3998 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
3999 bool hasFPFeatures);
4000
4001 static CompoundAssignOperator *
4002 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4003 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4004 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4005 QualType CompResultType = QualType());
4006
4007 // The two computation types are the type the LHS is converted
4008 // to for the computation and the type of the result; the two are
4009 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
getComputationLHSType()4010 QualType getComputationLHSType() const { return ComputationLHSType; }
setComputationLHSType(QualType T)4011 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4012
getComputationResultType()4013 QualType getComputationResultType() const { return ComputationResultType; }
setComputationResultType(QualType T)4014 void setComputationResultType(QualType T) { ComputationResultType = T; }
4015
classof(const Stmt * S)4016 static bool classof(const Stmt *S) {
4017 return S->getStmtClass() == CompoundAssignOperatorClass;
4018 }
4019 };
4020
offsetOfTrailingStorage()4021 inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4022 assert(BinaryOperatorBits.HasFPFeatures);
4023 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4024 : sizeof(BinaryOperator);
4025 }
4026
4027 /// AbstractConditionalOperator - An abstract base class for
4028 /// ConditionalOperator and BinaryConditionalOperator.
4029 class AbstractConditionalOperator : public Expr {
4030 SourceLocation QuestionLoc, ColonLoc;
4031 friend class ASTStmtReader;
4032
4033 protected:
AbstractConditionalOperator(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,SourceLocation qloc,SourceLocation cloc)4034 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4035 ExprObjectKind OK, SourceLocation qloc,
4036 SourceLocation cloc)
4037 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4038
AbstractConditionalOperator(StmtClass SC,EmptyShell Empty)4039 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4040 : Expr(SC, Empty) { }
4041
4042 public:
4043 // getCond - Return the expression representing the condition for
4044 // the ?: operator.
4045 Expr *getCond() const;
4046
4047 // getTrueExpr - Return the subexpression representing the value of
4048 // the expression if the condition evaluates to true.
4049 Expr *getTrueExpr() const;
4050
4051 // getFalseExpr - Return the subexpression representing the value of
4052 // the expression if the condition evaluates to false. This is
4053 // the same as getRHS.
4054 Expr *getFalseExpr() const;
4055
getQuestionLoc()4056 SourceLocation getQuestionLoc() const { return QuestionLoc; }
getColonLoc()4057 SourceLocation getColonLoc() const { return ColonLoc; }
4058
classof(const Stmt * T)4059 static bool classof(const Stmt *T) {
4060 return T->getStmtClass() == ConditionalOperatorClass ||
4061 T->getStmtClass() == BinaryConditionalOperatorClass;
4062 }
4063 };
4064
4065 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
4066 /// middle" extension is a BinaryConditionalOperator.
4067 class ConditionalOperator : public AbstractConditionalOperator {
4068 enum { COND, LHS, RHS, END_EXPR };
4069 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4070
4071 friend class ASTStmtReader;
4072 public:
ConditionalOperator(Expr * cond,SourceLocation QLoc,Expr * lhs,SourceLocation CLoc,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK)4073 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4074 SourceLocation CLoc, Expr *rhs, QualType t,
4075 ExprValueKind VK, ExprObjectKind OK)
4076 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4077 CLoc) {
4078 SubExprs[COND] = cond;
4079 SubExprs[LHS] = lhs;
4080 SubExprs[RHS] = rhs;
4081 setDependence(computeDependence(this));
4082 }
4083
4084 /// Build an empty conditional operator.
ConditionalOperator(EmptyShell Empty)4085 explicit ConditionalOperator(EmptyShell Empty)
4086 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4087
4088 // getCond - Return the expression representing the condition for
4089 // the ?: operator.
getCond()4090 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4091
4092 // getTrueExpr - Return the subexpression representing the value of
4093 // the expression if the condition evaluates to true.
getTrueExpr()4094 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4095
4096 // getFalseExpr - Return the subexpression representing the value of
4097 // the expression if the condition evaluates to false. This is
4098 // the same as getRHS.
getFalseExpr()4099 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4100
getLHS()4101 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
getRHS()4102 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4103
getBeginLoc()4104 SourceLocation getBeginLoc() const LLVM_READONLY {
4105 return getCond()->getBeginLoc();
4106 }
getEndLoc()4107 SourceLocation getEndLoc() const LLVM_READONLY {
4108 return getRHS()->getEndLoc();
4109 }
4110
classof(const Stmt * T)4111 static bool classof(const Stmt *T) {
4112 return T->getStmtClass() == ConditionalOperatorClass;
4113 }
4114
4115 // Iterators
children()4116 child_range children() {
4117 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4118 }
children()4119 const_child_range children() const {
4120 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4121 }
4122 };
4123
4124 /// BinaryConditionalOperator - The GNU extension to the conditional
4125 /// operator which allows the middle operand to be omitted.
4126 ///
4127 /// This is a different expression kind on the assumption that almost
4128 /// every client ends up needing to know that these are different.
4129 class BinaryConditionalOperator : public AbstractConditionalOperator {
4130 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4131
4132 /// - the common condition/left-hand-side expression, which will be
4133 /// evaluated as the opaque value
4134 /// - the condition, expressed in terms of the opaque value
4135 /// - the left-hand-side, expressed in terms of the opaque value
4136 /// - the right-hand-side
4137 Stmt *SubExprs[NUM_SUBEXPRS];
4138 OpaqueValueExpr *OpaqueValue;
4139
4140 friend class ASTStmtReader;
4141 public:
BinaryConditionalOperator(Expr * common,OpaqueValueExpr * opaqueValue,Expr * cond,Expr * lhs,Expr * rhs,SourceLocation qloc,SourceLocation cloc,QualType t,ExprValueKind VK,ExprObjectKind OK)4142 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4143 Expr *cond, Expr *lhs, Expr *rhs,
4144 SourceLocation qloc, SourceLocation cloc,
4145 QualType t, ExprValueKind VK, ExprObjectKind OK)
4146 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4147 qloc, cloc),
4148 OpaqueValue(opaqueValue) {
4149 SubExprs[COMMON] = common;
4150 SubExprs[COND] = cond;
4151 SubExprs[LHS] = lhs;
4152 SubExprs[RHS] = rhs;
4153 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4154 setDependence(computeDependence(this));
4155 }
4156
4157 /// Build an empty conditional operator.
BinaryConditionalOperator(EmptyShell Empty)4158 explicit BinaryConditionalOperator(EmptyShell Empty)
4159 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4160
4161 /// getCommon - Return the common expression, written to the
4162 /// left of the condition. The opaque value will be bound to the
4163 /// result of this expression.
getCommon()4164 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4165
4166 /// getOpaqueValue - Return the opaque value placeholder.
getOpaqueValue()4167 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4168
4169 /// getCond - Return the condition expression; this is defined
4170 /// in terms of the opaque value.
getCond()4171 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4172
4173 /// getTrueExpr - Return the subexpression which will be
4174 /// evaluated if the condition evaluates to true; this is defined
4175 /// in terms of the opaque value.
getTrueExpr()4176 Expr *getTrueExpr() const {
4177 return cast<Expr>(SubExprs[LHS]);
4178 }
4179
4180 /// getFalseExpr - Return the subexpression which will be
4181 /// evaluated if the condnition evaluates to false; this is
4182 /// defined in terms of the opaque value.
getFalseExpr()4183 Expr *getFalseExpr() const {
4184 return cast<Expr>(SubExprs[RHS]);
4185 }
4186
getBeginLoc()4187 SourceLocation getBeginLoc() const LLVM_READONLY {
4188 return getCommon()->getBeginLoc();
4189 }
getEndLoc()4190 SourceLocation getEndLoc() const LLVM_READONLY {
4191 return getFalseExpr()->getEndLoc();
4192 }
4193
classof(const Stmt * T)4194 static bool classof(const Stmt *T) {
4195 return T->getStmtClass() == BinaryConditionalOperatorClass;
4196 }
4197
4198 // Iterators
children()4199 child_range children() {
4200 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4201 }
children()4202 const_child_range children() const {
4203 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4204 }
4205 };
4206
getCond()4207 inline Expr *AbstractConditionalOperator::getCond() const {
4208 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4209 return co->getCond();
4210 return cast<BinaryConditionalOperator>(this)->getCond();
4211 }
4212
getTrueExpr()4213 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4214 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4215 return co->getTrueExpr();
4216 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4217 }
4218
getFalseExpr()4219 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4220 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4221 return co->getFalseExpr();
4222 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4223 }
4224
4225 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
4226 class AddrLabelExpr : public Expr {
4227 SourceLocation AmpAmpLoc, LabelLoc;
4228 LabelDecl *Label;
4229 public:
AddrLabelExpr(SourceLocation AALoc,SourceLocation LLoc,LabelDecl * L,QualType t)4230 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4231 QualType t)
4232 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary), AmpAmpLoc(AALoc),
4233 LabelLoc(LLoc), Label(L) {
4234 setDependence(ExprDependence::None);
4235 }
4236
4237 /// Build an empty address of a label expression.
AddrLabelExpr(EmptyShell Empty)4238 explicit AddrLabelExpr(EmptyShell Empty)
4239 : Expr(AddrLabelExprClass, Empty) { }
4240
getAmpAmpLoc()4241 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
setAmpAmpLoc(SourceLocation L)4242 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
getLabelLoc()4243 SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)4244 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4245
getBeginLoc()4246 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
getEndLoc()4247 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4248
getLabel()4249 LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * L)4250 void setLabel(LabelDecl *L) { Label = L; }
4251
classof(const Stmt * T)4252 static bool classof(const Stmt *T) {
4253 return T->getStmtClass() == AddrLabelExprClass;
4254 }
4255
4256 // Iterators
children()4257 child_range children() {
4258 return child_range(child_iterator(), child_iterator());
4259 }
children()4260 const_child_range children() const {
4261 return const_child_range(const_child_iterator(), const_child_iterator());
4262 }
4263 };
4264
4265 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4266 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4267 /// takes the value of the last subexpression.
4268 ///
4269 /// A StmtExpr is always an r-value; values "returned" out of a
4270 /// StmtExpr will be copied.
4271 class StmtExpr : public Expr {
4272 Stmt *SubStmt;
4273 SourceLocation LParenLoc, RParenLoc;
4274 public:
StmtExpr(CompoundStmt * SubStmt,QualType T,SourceLocation LParenLoc,SourceLocation RParenLoc,unsigned TemplateDepth)4275 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4276 SourceLocation RParenLoc, unsigned TemplateDepth)
4277 : Expr(StmtExprClass, T, VK_RValue, OK_Ordinary), SubStmt(SubStmt),
4278 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4279 setDependence(computeDependence(this, TemplateDepth));
4280 // FIXME: A templated statement expression should have an associated
4281 // DeclContext so that nested declarations always have a dependent context.
4282 StmtExprBits.TemplateDepth = TemplateDepth;
4283 }
4284
4285 /// Build an empty statement expression.
StmtExpr(EmptyShell Empty)4286 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4287
getSubStmt()4288 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
getSubStmt()4289 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
setSubStmt(CompoundStmt * S)4290 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4291
getBeginLoc()4292 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
getEndLoc()4293 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4294
getLParenLoc()4295 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)4296 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()4297 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4298 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4299
getTemplateDepth()4300 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4301
classof(const Stmt * T)4302 static bool classof(const Stmt *T) {
4303 return T->getStmtClass() == StmtExprClass;
4304 }
4305
4306 // Iterators
children()4307 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
children()4308 const_child_range children() const {
4309 return const_child_range(&SubStmt, &SubStmt + 1);
4310 }
4311 };
4312
4313 /// ShuffleVectorExpr - clang-specific builtin-in function
4314 /// __builtin_shufflevector.
4315 /// This AST node represents a operator that does a constant
4316 /// shuffle, similar to LLVM's shufflevector instruction. It takes
4317 /// two vectors and a variable number of constant indices,
4318 /// and returns the appropriately shuffled vector.
4319 class ShuffleVectorExpr : public Expr {
4320 SourceLocation BuiltinLoc, RParenLoc;
4321
4322 // SubExprs - the list of values passed to the __builtin_shufflevector
4323 // function. The first two are vectors, and the rest are constant
4324 // indices. The number of values in this list is always
4325 // 2+the number of indices in the vector type.
4326 Stmt **SubExprs;
4327 unsigned NumExprs;
4328
4329 public:
4330 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4331 SourceLocation BLoc, SourceLocation RP);
4332
4333 /// Build an empty vector-shuffle expression.
ShuffleVectorExpr(EmptyShell Empty)4334 explicit ShuffleVectorExpr(EmptyShell Empty)
4335 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4336
getBuiltinLoc()4337 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4338 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4339
getRParenLoc()4340 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4341 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4342
getBeginLoc()4343 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4344 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4345
classof(const Stmt * T)4346 static bool classof(const Stmt *T) {
4347 return T->getStmtClass() == ShuffleVectorExprClass;
4348 }
4349
4350 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4351 /// constant expression, the actual arguments passed in, and the function
4352 /// pointers.
getNumSubExprs()4353 unsigned getNumSubExprs() const { return NumExprs; }
4354
4355 /// Retrieve the array of expressions.
getSubExprs()4356 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4357
4358 /// getExpr - Return the Expr at the specified index.
getExpr(unsigned Index)4359 Expr *getExpr(unsigned Index) {
4360 assert((Index < NumExprs) && "Arg access out of range!");
4361 return cast<Expr>(SubExprs[Index]);
4362 }
getExpr(unsigned Index)4363 const Expr *getExpr(unsigned Index) const {
4364 assert((Index < NumExprs) && "Arg access out of range!");
4365 return cast<Expr>(SubExprs[Index]);
4366 }
4367
4368 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4369
getShuffleMaskIdx(const ASTContext & Ctx,unsigned N)4370 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4371 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4372 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4373 }
4374
4375 // Iterators
children()4376 child_range children() {
4377 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4378 }
children()4379 const_child_range children() const {
4380 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4381 }
4382 };
4383
4384 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4385 /// This AST node provides support for converting a vector type to another
4386 /// vector type of the same arity.
4387 class ConvertVectorExpr : public Expr {
4388 private:
4389 Stmt *SrcExpr;
4390 TypeSourceInfo *TInfo;
4391 SourceLocation BuiltinLoc, RParenLoc;
4392
4393 friend class ASTReader;
4394 friend class ASTStmtReader;
ConvertVectorExpr(EmptyShell Empty)4395 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4396
4397 public:
ConvertVectorExpr(Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4398 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4399 ExprValueKind VK, ExprObjectKind OK,
4400 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4401 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4402 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4403 setDependence(computeDependence(this));
4404 }
4405
4406 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()4407 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4408
4409 /// getTypeSourceInfo - Return the destination type.
getTypeSourceInfo()4410 TypeSourceInfo *getTypeSourceInfo() const {
4411 return TInfo;
4412 }
setTypeSourceInfo(TypeSourceInfo * ti)4413 void setTypeSourceInfo(TypeSourceInfo *ti) {
4414 TInfo = ti;
4415 }
4416
4417 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
getBuiltinLoc()4418 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4419
4420 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()4421 SourceLocation getRParenLoc() const { return RParenLoc; }
4422
getBeginLoc()4423 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4424 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4425
classof(const Stmt * T)4426 static bool classof(const Stmt *T) {
4427 return T->getStmtClass() == ConvertVectorExprClass;
4428 }
4429
4430 // Iterators
children()4431 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
children()4432 const_child_range children() const {
4433 return const_child_range(&SrcExpr, &SrcExpr + 1);
4434 }
4435 };
4436
4437 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4438 /// This AST node is similar to the conditional operator (?:) in C, with
4439 /// the following exceptions:
4440 /// - the test expression must be a integer constant expression.
4441 /// - the expression returned acts like the chosen subexpression in every
4442 /// visible way: the type is the same as that of the chosen subexpression,
4443 /// and all predicates (whether it's an l-value, whether it's an integer
4444 /// constant expression, etc.) return the same result as for the chosen
4445 /// sub-expression.
4446 class ChooseExpr : public Expr {
4447 enum { COND, LHS, RHS, END_EXPR };
4448 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4449 SourceLocation BuiltinLoc, RParenLoc;
4450 bool CondIsTrue;
4451 public:
ChooseExpr(SourceLocation BLoc,Expr * cond,Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation RP,bool condIsTrue)4452 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4453 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4454 bool condIsTrue)
4455 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4456 CondIsTrue(condIsTrue) {
4457 SubExprs[COND] = cond;
4458 SubExprs[LHS] = lhs;
4459 SubExprs[RHS] = rhs;
4460
4461 setDependence(computeDependence(this));
4462 }
4463
4464 /// Build an empty __builtin_choose_expr.
ChooseExpr(EmptyShell Empty)4465 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4466
4467 /// isConditionTrue - Return whether the condition is true (i.e. not
4468 /// equal to zero).
isConditionTrue()4469 bool isConditionTrue() const {
4470 assert(!isConditionDependent() &&
4471 "Dependent condition isn't true or false");
4472 return CondIsTrue;
4473 }
setIsConditionTrue(bool isTrue)4474 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4475
isConditionDependent()4476 bool isConditionDependent() const {
4477 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4478 }
4479
4480 /// getChosenSubExpr - Return the subexpression chosen according to the
4481 /// condition.
getChosenSubExpr()4482 Expr *getChosenSubExpr() const {
4483 return isConditionTrue() ? getLHS() : getRHS();
4484 }
4485
getCond()4486 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
setCond(Expr * E)4487 void setCond(Expr *E) { SubExprs[COND] = E; }
getLHS()4488 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)4489 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()4490 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)4491 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4492
getBuiltinLoc()4493 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4494 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4495
getRParenLoc()4496 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4497 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4498
getBeginLoc()4499 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4500 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4501
classof(const Stmt * T)4502 static bool classof(const Stmt *T) {
4503 return T->getStmtClass() == ChooseExprClass;
4504 }
4505
4506 // Iterators
children()4507 child_range children() {
4508 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4509 }
children()4510 const_child_range children() const {
4511 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4512 }
4513 };
4514
4515 /// GNUNullExpr - Implements the GNU __null extension, which is a name
4516 /// for a null pointer constant that has integral type (e.g., int or
4517 /// long) and is the same size and alignment as a pointer. The __null
4518 /// extension is typically only used by system headers, which define
4519 /// NULL as __null in C++ rather than using 0 (which is an integer
4520 /// that may not match the size of a pointer).
4521 class GNUNullExpr : public Expr {
4522 /// TokenLoc - The location of the __null keyword.
4523 SourceLocation TokenLoc;
4524
4525 public:
GNUNullExpr(QualType Ty,SourceLocation Loc)4526 GNUNullExpr(QualType Ty, SourceLocation Loc)
4527 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary), TokenLoc(Loc) {
4528 setDependence(ExprDependence::None);
4529 }
4530
4531 /// Build an empty GNU __null expression.
GNUNullExpr(EmptyShell Empty)4532 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4533
4534 /// getTokenLocation - The location of the __null token.
getTokenLocation()4535 SourceLocation getTokenLocation() const { return TokenLoc; }
setTokenLocation(SourceLocation L)4536 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4537
getBeginLoc()4538 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
getEndLoc()4539 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4540
classof(const Stmt * T)4541 static bool classof(const Stmt *T) {
4542 return T->getStmtClass() == GNUNullExprClass;
4543 }
4544
4545 // Iterators
children()4546 child_range children() {
4547 return child_range(child_iterator(), child_iterator());
4548 }
children()4549 const_child_range children() const {
4550 return const_child_range(const_child_iterator(), const_child_iterator());
4551 }
4552 };
4553
4554 /// Represents a call to the builtin function \c __builtin_va_arg.
4555 class VAArgExpr : public Expr {
4556 Stmt *Val;
4557 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4558 SourceLocation BuiltinLoc, RParenLoc;
4559 public:
VAArgExpr(SourceLocation BLoc,Expr * e,TypeSourceInfo * TInfo,SourceLocation RPLoc,QualType t,bool IsMS)4560 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4561 SourceLocation RPLoc, QualType t, bool IsMS)
4562 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary), Val(e),
4563 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4564 setDependence(computeDependence(this));
4565 }
4566
4567 /// Create an empty __builtin_va_arg expression.
VAArgExpr(EmptyShell Empty)4568 explicit VAArgExpr(EmptyShell Empty)
4569 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4570
getSubExpr()4571 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()4572 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)4573 void setSubExpr(Expr *E) { Val = E; }
4574
4575 /// Returns whether this is really a Win64 ABI va_arg expression.
isMicrosoftABI()4576 bool isMicrosoftABI() const { return TInfo.getInt(); }
setIsMicrosoftABI(bool IsMS)4577 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4578
getWrittenTypeInfo()4579 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
setWrittenTypeInfo(TypeSourceInfo * TI)4580 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4581
getBuiltinLoc()4582 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4583 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4584
getRParenLoc()4585 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4586 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4587
getBeginLoc()4588 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4589 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4590
classof(const Stmt * T)4591 static bool classof(const Stmt *T) {
4592 return T->getStmtClass() == VAArgExprClass;
4593 }
4594
4595 // Iterators
children()4596 child_range children() { return child_range(&Val, &Val+1); }
children()4597 const_child_range children() const {
4598 return const_child_range(&Val, &Val + 1);
4599 }
4600 };
4601
4602 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4603 /// __builtin_FUNCTION(), or __builtin_FILE().
4604 class SourceLocExpr final : public Expr {
4605 SourceLocation BuiltinLoc, RParenLoc;
4606 DeclContext *ParentContext;
4607
4608 public:
4609 enum IdentKind { Function, File, Line, Column };
4610
4611 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
4612 SourceLocation RParenLoc, DeclContext *Context);
4613
4614 /// Build an empty call expression.
SourceLocExpr(EmptyShell Empty)4615 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4616
4617 /// Return the result of evaluating this SourceLocExpr in the specified
4618 /// (and possibly null) default argument or initialization context.
4619 APValue EvaluateInContext(const ASTContext &Ctx,
4620 const Expr *DefaultExpr) const;
4621
4622 /// Return a string representing the name of the specific builtin function.
4623 StringRef getBuiltinStr() const;
4624
getIdentKind()4625 IdentKind getIdentKind() const {
4626 return static_cast<IdentKind>(SourceLocExprBits.Kind);
4627 }
4628
isStringType()4629 bool isStringType() const {
4630 switch (getIdentKind()) {
4631 case File:
4632 case Function:
4633 return true;
4634 case Line:
4635 case Column:
4636 return false;
4637 }
4638 llvm_unreachable("unknown source location expression kind");
4639 }
isIntType()4640 bool isIntType() const LLVM_READONLY { return !isStringType(); }
4641
4642 /// If the SourceLocExpr has been resolved return the subexpression
4643 /// representing the resolved value. Otherwise return null.
getParentContext()4644 const DeclContext *getParentContext() const { return ParentContext; }
getParentContext()4645 DeclContext *getParentContext() { return ParentContext; }
4646
getLocation()4647 SourceLocation getLocation() const { return BuiltinLoc; }
getBeginLoc()4648 SourceLocation getBeginLoc() const { return BuiltinLoc; }
getEndLoc()4649 SourceLocation getEndLoc() const { return RParenLoc; }
4650
children()4651 child_range children() {
4652 return child_range(child_iterator(), child_iterator());
4653 }
4654
children()4655 const_child_range children() const {
4656 return const_child_range(child_iterator(), child_iterator());
4657 }
4658
classof(const Stmt * T)4659 static bool classof(const Stmt *T) {
4660 return T->getStmtClass() == SourceLocExprClass;
4661 }
4662
4663 private:
4664 friend class ASTStmtReader;
4665 };
4666
4667 /// Describes an C or C++ initializer list.
4668 ///
4669 /// InitListExpr describes an initializer list, which can be used to
4670 /// initialize objects of different types, including
4671 /// struct/class/union types, arrays, and vectors. For example:
4672 ///
4673 /// @code
4674 /// struct foo x = { 1, { 2, 3 } };
4675 /// @endcode
4676 ///
4677 /// Prior to semantic analysis, an initializer list will represent the
4678 /// initializer list as written by the user, but will have the
4679 /// placeholder type "void". This initializer list is called the
4680 /// syntactic form of the initializer, and may contain C99 designated
4681 /// initializers (represented as DesignatedInitExprs), initializations
4682 /// of subobject members without explicit braces, and so on. Clients
4683 /// interested in the original syntax of the initializer list should
4684 /// use the syntactic form of the initializer list.
4685 ///
4686 /// After semantic analysis, the initializer list will represent the
4687 /// semantic form of the initializer, where the initializations of all
4688 /// subobjects are made explicit with nested InitListExpr nodes and
4689 /// C99 designators have been eliminated by placing the designated
4690 /// initializations into the subobject they initialize. Additionally,
4691 /// any "holes" in the initialization, where no initializer has been
4692 /// specified for a particular subobject, will be replaced with
4693 /// implicitly-generated ImplicitValueInitExpr expressions that
4694 /// value-initialize the subobjects. Note, however, that the
4695 /// initializer lists may still have fewer initializers than there are
4696 /// elements to initialize within the object.
4697 ///
4698 /// After semantic analysis has completed, given an initializer list,
4699 /// method isSemanticForm() returns true if and only if this is the
4700 /// semantic form of the initializer list (note: the same AST node
4701 /// may at the same time be the syntactic form).
4702 /// Given the semantic form of the initializer list, one can retrieve
4703 /// the syntactic form of that initializer list (when different)
4704 /// using method getSyntacticForm(); the method returns null if applied
4705 /// to a initializer list which is already in syntactic form.
4706 /// Similarly, given the syntactic form (i.e., an initializer list such
4707 /// that isSemanticForm() returns false), one can retrieve the semantic
4708 /// form using method getSemanticForm().
4709 /// Since many initializer lists have the same syntactic and semantic forms,
4710 /// getSyntacticForm() may return NULL, indicating that the current
4711 /// semantic initializer list also serves as its syntactic form.
4712 class InitListExpr : public Expr {
4713 // FIXME: Eliminate this vector in favor of ASTContext allocation
4714 typedef ASTVector<Stmt *> InitExprsTy;
4715 InitExprsTy InitExprs;
4716 SourceLocation LBraceLoc, RBraceLoc;
4717
4718 /// The alternative form of the initializer list (if it exists).
4719 /// The int part of the pair stores whether this initializer list is
4720 /// in semantic form. If not null, the pointer points to:
4721 /// - the syntactic form, if this is in semantic form;
4722 /// - the semantic form, if this is in syntactic form.
4723 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4724
4725 /// Either:
4726 /// If this initializer list initializes an array with more elements than
4727 /// there are initializers in the list, specifies an expression to be used
4728 /// for value initialization of the rest of the elements.
4729 /// Or
4730 /// If this initializer list initializes a union, specifies which
4731 /// field within the union will be initialized.
4732 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4733
4734 public:
4735 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4736 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4737
4738 /// Build an empty initializer list.
InitListExpr(EmptyShell Empty)4739 explicit InitListExpr(EmptyShell Empty)
4740 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4741
getNumInits()4742 unsigned getNumInits() const { return InitExprs.size(); }
4743
4744 /// Retrieve the set of initializers.
getInits()4745 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4746
4747 /// Retrieve the set of initializers.
getInits()4748 Expr * const *getInits() const {
4749 return reinterpret_cast<Expr * const *>(InitExprs.data());
4750 }
4751
inits()4752 ArrayRef<Expr *> inits() {
4753 return llvm::makeArrayRef(getInits(), getNumInits());
4754 }
4755
inits()4756 ArrayRef<Expr *> inits() const {
4757 return llvm::makeArrayRef(getInits(), getNumInits());
4758 }
4759
getInit(unsigned Init)4760 const Expr *getInit(unsigned Init) const {
4761 assert(Init < getNumInits() && "Initializer access out of range!");
4762 return cast_or_null<Expr>(InitExprs[Init]);
4763 }
4764
getInit(unsigned Init)4765 Expr *getInit(unsigned Init) {
4766 assert(Init < getNumInits() && "Initializer access out of range!");
4767 return cast_or_null<Expr>(InitExprs[Init]);
4768 }
4769
setInit(unsigned Init,Expr * expr)4770 void setInit(unsigned Init, Expr *expr) {
4771 assert(Init < getNumInits() && "Initializer access out of range!");
4772 InitExprs[Init] = expr;
4773
4774 if (expr)
4775 setDependence(getDependence() | expr->getDependence());
4776 }
4777
4778 /// Mark the semantic form of the InitListExpr as error when the semantic
4779 /// analysis fails.
markError()4780 void markError() {
4781 assert(isSemanticForm());
4782 setDependence(getDependence() | ExprDependence::ErrorDependent);
4783 }
4784
4785 /// Reserve space for some number of initializers.
4786 void reserveInits(const ASTContext &C, unsigned NumInits);
4787
4788 /// Specify the number of initializers
4789 ///
4790 /// If there are more than @p NumInits initializers, the remaining
4791 /// initializers will be destroyed. If there are fewer than @p
4792 /// NumInits initializers, NULL expressions will be added for the
4793 /// unknown initializers.
4794 void resizeInits(const ASTContext &Context, unsigned NumInits);
4795
4796 /// Updates the initializer at index @p Init with the new
4797 /// expression @p expr, and returns the old expression at that
4798 /// location.
4799 ///
4800 /// When @p Init is out of range for this initializer list, the
4801 /// initializer list will be extended with NULL expressions to
4802 /// accommodate the new entry.
4803 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4804
4805 /// If this initializer list initializes an array with more elements
4806 /// than there are initializers in the list, specifies an expression to be
4807 /// used for value initialization of the rest of the elements.
getArrayFiller()4808 Expr *getArrayFiller() {
4809 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4810 }
getArrayFiller()4811 const Expr *getArrayFiller() const {
4812 return const_cast<InitListExpr *>(this)->getArrayFiller();
4813 }
4814 void setArrayFiller(Expr *filler);
4815
4816 /// Return true if this is an array initializer and its array "filler"
4817 /// has been set.
hasArrayFiller()4818 bool hasArrayFiller() const { return getArrayFiller(); }
4819
4820 /// If this initializes a union, specifies which field in the
4821 /// union to initialize.
4822 ///
4823 /// Typically, this field is the first named field within the
4824 /// union. However, a designated initializer can specify the
4825 /// initialization of a different field within the union.
getInitializedFieldInUnion()4826 FieldDecl *getInitializedFieldInUnion() {
4827 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4828 }
getInitializedFieldInUnion()4829 const FieldDecl *getInitializedFieldInUnion() const {
4830 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4831 }
setInitializedFieldInUnion(FieldDecl * FD)4832 void setInitializedFieldInUnion(FieldDecl *FD) {
4833 assert((FD == nullptr
4834 || getInitializedFieldInUnion() == nullptr
4835 || getInitializedFieldInUnion() == FD)
4836 && "Only one field of a union may be initialized at a time!");
4837 ArrayFillerOrUnionFieldInit = FD;
4838 }
4839
4840 // Explicit InitListExpr's originate from source code (and have valid source
4841 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4842 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4843 // valid source locations too!
isExplicit()4844 bool isExplicit() const {
4845 return LBraceLoc.isValid() && RBraceLoc.isValid();
4846 }
4847
4848 // Is this an initializer for an array of characters, initialized by a string
4849 // literal or an @encode?
4850 bool isStringLiteralInit() const;
4851
4852 /// Is this a transparent initializer list (that is, an InitListExpr that is
4853 /// purely syntactic, and whose semantics are that of the sole contained
4854 /// initializer)?
4855 bool isTransparent() const;
4856
4857 /// Is this the zero initializer {0} in a language which considers it
4858 /// idiomatic?
4859 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4860
getLBraceLoc()4861 SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation Loc)4862 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
getRBraceLoc()4863 SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation Loc)4864 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4865
isSemanticForm()4866 bool isSemanticForm() const { return AltForm.getInt(); }
getSemanticForm()4867 InitListExpr *getSemanticForm() const {
4868 return isSemanticForm() ? nullptr : AltForm.getPointer();
4869 }
isSyntacticForm()4870 bool isSyntacticForm() const {
4871 return !AltForm.getInt() || !AltForm.getPointer();
4872 }
getSyntacticForm()4873 InitListExpr *getSyntacticForm() const {
4874 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4875 }
4876
setSyntacticForm(InitListExpr * Init)4877 void setSyntacticForm(InitListExpr *Init) {
4878 AltForm.setPointer(Init);
4879 AltForm.setInt(true);
4880 Init->AltForm.setPointer(this);
4881 Init->AltForm.setInt(false);
4882 }
4883
hadArrayRangeDesignator()4884 bool hadArrayRangeDesignator() const {
4885 return InitListExprBits.HadArrayRangeDesignator != 0;
4886 }
4887 void sawArrayRangeDesignator(bool ARD = true) {
4888 InitListExprBits.HadArrayRangeDesignator = ARD;
4889 }
4890
4891 SourceLocation getBeginLoc() const LLVM_READONLY;
4892 SourceLocation getEndLoc() const LLVM_READONLY;
4893
classof(const Stmt * T)4894 static bool classof(const Stmt *T) {
4895 return T->getStmtClass() == InitListExprClass;
4896 }
4897
4898 // Iterators
children()4899 child_range children() {
4900 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4901 return child_range(cast_away_const(CCR.begin()),
4902 cast_away_const(CCR.end()));
4903 }
4904
children()4905 const_child_range children() const {
4906 // FIXME: This does not include the array filler expression.
4907 if (InitExprs.empty())
4908 return const_child_range(const_child_iterator(), const_child_iterator());
4909 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4910 }
4911
4912 typedef InitExprsTy::iterator iterator;
4913 typedef InitExprsTy::const_iterator const_iterator;
4914 typedef InitExprsTy::reverse_iterator reverse_iterator;
4915 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4916
begin()4917 iterator begin() { return InitExprs.begin(); }
begin()4918 const_iterator begin() const { return InitExprs.begin(); }
end()4919 iterator end() { return InitExprs.end(); }
end()4920 const_iterator end() const { return InitExprs.end(); }
rbegin()4921 reverse_iterator rbegin() { return InitExprs.rbegin(); }
rbegin()4922 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
rend()4923