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 // Iterators
children()1619 child_range children() {
1620 return child_range(child_iterator(), child_iterator());
1621 }
children()1622 const_child_range children() const {
1623 return const_child_range(const_child_iterator(), const_child_iterator());
1624 }
1625 };
1626
1627 class FloatingLiteral : public Expr, private APFloatStorage {
1628 SourceLocation Loc;
1629
1630 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1631 QualType Type, SourceLocation L);
1632
1633 /// Construct an empty floating-point literal.
1634 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1635
1636 public:
1637 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1638 bool isexact, QualType Type, SourceLocation L);
1639 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1640
getValue()1641 llvm::APFloat getValue() const {
1642 return APFloatStorage::getValue(getSemantics());
1643 }
setValue(const ASTContext & C,const llvm::APFloat & Val)1644 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1645 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1646 APFloatStorage::setValue(C, Val);
1647 }
1648
1649 /// Get a raw enumeration value representing the floating-point semantics of
1650 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
getRawSemantics()1651 llvm::APFloatBase::Semantics getRawSemantics() const {
1652 return static_cast<llvm::APFloatBase::Semantics>(
1653 FloatingLiteralBits.Semantics);
1654 }
1655
1656 /// Set the raw enumeration value representing the floating-point semantics of
1657 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
setRawSemantics(llvm::APFloatBase::Semantics Sem)1658 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1659 FloatingLiteralBits.Semantics = Sem;
1660 }
1661
1662 /// Return the APFloat semantics this literal uses.
getSemantics()1663 const llvm::fltSemantics &getSemantics() const {
1664 return llvm::APFloatBase::EnumToSemantics(
1665 static_cast<llvm::APFloatBase::Semantics>(
1666 FloatingLiteralBits.Semantics));
1667 }
1668
1669 /// Set the APFloat semantics this literal uses.
setSemantics(const llvm::fltSemantics & Sem)1670 void setSemantics(const llvm::fltSemantics &Sem) {
1671 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1672 }
1673
isExact()1674 bool isExact() const { return FloatingLiteralBits.IsExact; }
setExact(bool E)1675 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1676
1677 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1678 /// double. Note that this may cause loss of precision, but is useful for
1679 /// debugging dumps, etc.
1680 double getValueAsApproximateDouble() const;
1681
getLocation()1682 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)1683 void setLocation(SourceLocation L) { Loc = L; }
1684
getBeginLoc()1685 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
getEndLoc()1686 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1687
classof(const Stmt * T)1688 static bool classof(const Stmt *T) {
1689 return T->getStmtClass() == FloatingLiteralClass;
1690 }
1691
1692 // Iterators
children()1693 child_range children() {
1694 return child_range(child_iterator(), child_iterator());
1695 }
children()1696 const_child_range children() const {
1697 return const_child_range(const_child_iterator(), const_child_iterator());
1698 }
1699 };
1700
1701 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1702 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1703 /// IntegerLiteral classes. Instances of this class always have a Complex type
1704 /// whose element type matches the subexpression.
1705 ///
1706 class ImaginaryLiteral : public Expr {
1707 Stmt *Val;
1708 public:
ImaginaryLiteral(Expr * val,QualType Ty)1709 ImaginaryLiteral(Expr *val, QualType Ty)
1710 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary), Val(val) {
1711 setDependence(ExprDependence::None);
1712 }
1713
1714 /// Build an empty imaginary literal.
ImaginaryLiteral(EmptyShell Empty)1715 explicit ImaginaryLiteral(EmptyShell Empty)
1716 : Expr(ImaginaryLiteralClass, Empty) { }
1717
getSubExpr()1718 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()1719 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)1720 void setSubExpr(Expr *E) { Val = E; }
1721
getBeginLoc()1722 SourceLocation getBeginLoc() const LLVM_READONLY {
1723 return Val->getBeginLoc();
1724 }
getEndLoc()1725 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1726
classof(const Stmt * T)1727 static bool classof(const Stmt *T) {
1728 return T->getStmtClass() == ImaginaryLiteralClass;
1729 }
1730
1731 // Iterators
children()1732 child_range children() { return child_range(&Val, &Val+1); }
children()1733 const_child_range children() const {
1734 return const_child_range(&Val, &Val + 1);
1735 }
1736 };
1737
1738 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1739 /// or L"bar" (wide strings). The actual string data can be obtained with
1740 /// getBytes() and is NOT null-terminated. The length of the string data is
1741 /// determined by calling getByteLength().
1742 ///
1743 /// The C type for a string is always a ConstantArrayType. In C++, the char
1744 /// type is const qualified, in C it is not.
1745 ///
1746 /// Note that strings in C can be formed by concatenation of multiple string
1747 /// literal pptokens in translation phase #6. This keeps track of the locations
1748 /// of each of these pieces.
1749 ///
1750 /// Strings in C can also be truncated and extended by assigning into arrays,
1751 /// e.g. with constructs like:
1752 /// char X[2] = "foobar";
1753 /// In this case, getByteLength() will return 6, but the string literal will
1754 /// have type "char[2]".
1755 class StringLiteral final
1756 : public Expr,
1757 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1758 char> {
1759 friend class ASTStmtReader;
1760 friend TrailingObjects;
1761
1762 /// StringLiteral is followed by several trailing objects. They are in order:
1763 ///
1764 /// * A single unsigned storing the length in characters of this string. The
1765 /// length in bytes is this length times the width of a single character.
1766 /// Always present and stored as a trailing objects because storing it in
1767 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1768 /// due to alignment requirements. If you add some data to StringLiteral,
1769 /// consider moving it inside StringLiteral.
1770 ///
1771 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1772 /// token this string is made of.
1773 ///
1774 /// * An array of getByteLength() char used to store the string data.
1775
1776 public:
1777 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1778
1779 private:
numTrailingObjects(OverloadToken<unsigned>)1780 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
numTrailingObjects(OverloadToken<SourceLocation>)1781 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1782 return getNumConcatenated();
1783 }
1784
numTrailingObjects(OverloadToken<char>)1785 unsigned numTrailingObjects(OverloadToken<char>) const {
1786 return getByteLength();
1787 }
1788
getStrDataAsChar()1789 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
getStrDataAsChar()1790 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1791
getStrDataAsUInt16()1792 const uint16_t *getStrDataAsUInt16() const {
1793 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1794 }
1795
getStrDataAsUInt32()1796 const uint32_t *getStrDataAsUInt32() const {
1797 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1798 }
1799
1800 /// Build a string literal.
1801 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1802 bool Pascal, QualType Ty, const SourceLocation *Loc,
1803 unsigned NumConcatenated);
1804
1805 /// Build an empty string literal.
1806 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1807 unsigned CharByteWidth);
1808
1809 /// Map a target and string kind to the appropriate character width.
1810 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1811
1812 /// Set one of the string literal token.
setStrTokenLoc(unsigned TokNum,SourceLocation L)1813 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1814 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1815 getTrailingObjects<SourceLocation>()[TokNum] = L;
1816 }
1817
1818 public:
1819 /// This is the "fully general" constructor that allows representation of
1820 /// strings formed from multiple concatenated tokens.
1821 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1822 StringKind Kind, bool Pascal, QualType Ty,
1823 const SourceLocation *Loc,
1824 unsigned NumConcatenated);
1825
1826 /// Simple constructor for string literals made from one token.
Create(const ASTContext & Ctx,StringRef Str,StringKind Kind,bool Pascal,QualType Ty,SourceLocation Loc)1827 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1828 StringKind Kind, bool Pascal, QualType Ty,
1829 SourceLocation Loc) {
1830 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1831 }
1832
1833 /// Construct an empty string literal.
1834 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1835 unsigned NumConcatenated, unsigned Length,
1836 unsigned CharByteWidth);
1837
getString()1838 StringRef getString() const {
1839 assert(getCharByteWidth() == 1 &&
1840 "This function is used in places that assume strings use char");
1841 return StringRef(getStrDataAsChar(), getByteLength());
1842 }
1843
1844 /// Allow access to clients that need the byte representation, such as
1845 /// ASTWriterStmt::VisitStringLiteral().
getBytes()1846 StringRef getBytes() const {
1847 // FIXME: StringRef may not be the right type to use as a result for this.
1848 return StringRef(getStrDataAsChar(), getByteLength());
1849 }
1850
1851 void outputString(raw_ostream &OS) const;
1852
getCodeUnit(size_t i)1853 uint32_t getCodeUnit(size_t i) const {
1854 assert(i < getLength() && "out of bounds access");
1855 switch (getCharByteWidth()) {
1856 case 1:
1857 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1858 case 2:
1859 return getStrDataAsUInt16()[i];
1860 case 4:
1861 return getStrDataAsUInt32()[i];
1862 }
1863 llvm_unreachable("Unsupported character width!");
1864 }
1865
getByteLength()1866 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
getLength()1867 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
getCharByteWidth()1868 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1869
getKind()1870 StringKind getKind() const {
1871 return static_cast<StringKind>(StringLiteralBits.Kind);
1872 }
1873
isAscii()1874 bool isAscii() const { return getKind() == Ascii; }
isWide()1875 bool isWide() const { return getKind() == Wide; }
isUTF8()1876 bool isUTF8() const { return getKind() == UTF8; }
isUTF16()1877 bool isUTF16() const { return getKind() == UTF16; }
isUTF32()1878 bool isUTF32() const { return getKind() == UTF32; }
isPascal()1879 bool isPascal() const { return StringLiteralBits.IsPascal; }
1880
containsNonAscii()1881 bool containsNonAscii() const {
1882 for (auto c : getString())
1883 if (!isASCII(c))
1884 return true;
1885 return false;
1886 }
1887
containsNonAsciiOrNull()1888 bool containsNonAsciiOrNull() const {
1889 for (auto c : getString())
1890 if (!isASCII(c) || !c)
1891 return true;
1892 return false;
1893 }
1894
1895 /// getNumConcatenated - Get the number of string literal tokens that were
1896 /// concatenated in translation phase #6 to form this string literal.
getNumConcatenated()1897 unsigned getNumConcatenated() const {
1898 return StringLiteralBits.NumConcatenated;
1899 }
1900
1901 /// Get one of the string literal token.
getStrTokenLoc(unsigned TokNum)1902 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1903 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1904 return getTrailingObjects<SourceLocation>()[TokNum];
1905 }
1906
1907 /// getLocationOfByte - Return a source location that points to the specified
1908 /// byte of this string literal.
1909 ///
1910 /// Strings are amazingly complex. They can be formed from multiple tokens
1911 /// and can have escape sequences in them in addition to the usual trigraph
1912 /// and escaped newline business. This routine handles this complexity.
1913 ///
1914 SourceLocation
1915 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1916 const LangOptions &Features, const TargetInfo &Target,
1917 unsigned *StartToken = nullptr,
1918 unsigned *StartTokenByteOffset = nullptr) const;
1919
1920 typedef const SourceLocation *tokloc_iterator;
1921
tokloc_begin()1922 tokloc_iterator tokloc_begin() const {
1923 return getTrailingObjects<SourceLocation>();
1924 }
1925
tokloc_end()1926 tokloc_iterator tokloc_end() const {
1927 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1928 }
1929
getBeginLoc()1930 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
getEndLoc()1931 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1932
classof(const Stmt * T)1933 static bool classof(const Stmt *T) {
1934 return T->getStmtClass() == StringLiteralClass;
1935 }
1936
1937 // Iterators
children()1938 child_range children() {
1939 return child_range(child_iterator(), child_iterator());
1940 }
children()1941 const_child_range children() const {
1942 return const_child_range(const_child_iterator(), const_child_iterator());
1943 }
1944 };
1945
1946 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1947 class PredefinedExpr final
1948 : public Expr,
1949 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1950 friend class ASTStmtReader;
1951 friend TrailingObjects;
1952
1953 // PredefinedExpr is optionally followed by a single trailing
1954 // "Stmt *" for the predefined identifier. It is present if and only if
1955 // hasFunctionName() is true and is always a "StringLiteral *".
1956
1957 public:
1958 enum IdentKind {
1959 Func,
1960 Function,
1961 LFunction, // Same as Function, but as wide string.
1962 FuncDName,
1963 FuncSig,
1964 LFuncSig, // Same as FuncSig, but as as wide string
1965 PrettyFunction,
1966 /// The same as PrettyFunction, except that the
1967 /// 'virtual' keyword is omitted for virtual member functions.
1968 PrettyFunctionNoVirtual
1969 };
1970
1971 private:
1972 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1973 StringLiteral *SL);
1974
1975 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1976
1977 /// True if this PredefinedExpr has storage for a function name.
hasFunctionName()1978 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1979
setFunctionName(StringLiteral * SL)1980 void setFunctionName(StringLiteral *SL) {
1981 assert(hasFunctionName() &&
1982 "This PredefinedExpr has no storage for a function name!");
1983 *getTrailingObjects<Stmt *>() = SL;
1984 }
1985
1986 public:
1987 /// Create a PredefinedExpr.
1988 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1989 QualType FNTy, IdentKind IK, StringLiteral *SL);
1990
1991 /// Create an empty PredefinedExpr.
1992 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1993 bool HasFunctionName);
1994
getIdentKind()1995 IdentKind getIdentKind() const {
1996 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1997 }
1998
getLocation()1999 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
setLocation(SourceLocation L)2000 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2001
getFunctionName()2002 StringLiteral *getFunctionName() {
2003 return hasFunctionName()
2004 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2005 : nullptr;
2006 }
2007
getFunctionName()2008 const StringLiteral *getFunctionName() const {
2009 return hasFunctionName()
2010 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2011 : nullptr;
2012 }
2013
2014 static StringRef getIdentKindName(IdentKind IK);
getIdentKindName()2015 StringRef getIdentKindName() const {
2016 return getIdentKindName(getIdentKind());
2017 }
2018
2019 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
2020
getBeginLoc()2021 SourceLocation getBeginLoc() const { return getLocation(); }
getEndLoc()2022 SourceLocation getEndLoc() const { return getLocation(); }
2023
classof(const Stmt * T)2024 static bool classof(const Stmt *T) {
2025 return T->getStmtClass() == PredefinedExprClass;
2026 }
2027
2028 // Iterators
children()2029 child_range children() {
2030 return child_range(getTrailingObjects<Stmt *>(),
2031 getTrailingObjects<Stmt *>() + hasFunctionName());
2032 }
2033
children()2034 const_child_range children() const {
2035 return const_child_range(getTrailingObjects<Stmt *>(),
2036 getTrailingObjects<Stmt *>() + hasFunctionName());
2037 }
2038 };
2039
2040 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2041 /// AST node is only formed if full location information is requested.
2042 class ParenExpr : public Expr {
2043 SourceLocation L, R;
2044 Stmt *Val;
2045 public:
ParenExpr(SourceLocation l,SourceLocation r,Expr * val)2046 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2047 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2048 val->getObjectKind()),
2049 L(l), R(r), Val(val) {
2050 setDependence(computeDependence(this));
2051 }
2052
2053 /// Construct an empty parenthesized expression.
ParenExpr(EmptyShell Empty)2054 explicit ParenExpr(EmptyShell Empty)
2055 : Expr(ParenExprClass, Empty) { }
2056
getSubExpr()2057 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()2058 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)2059 void setSubExpr(Expr *E) { Val = E; }
2060
getBeginLoc()2061 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
getEndLoc()2062 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2063
2064 /// Get the location of the left parentheses '('.
getLParen()2065 SourceLocation getLParen() const { return L; }
setLParen(SourceLocation Loc)2066 void setLParen(SourceLocation Loc) { L = Loc; }
2067
2068 /// Get the location of the right parentheses ')'.
getRParen()2069 SourceLocation getRParen() const { return R; }
setRParen(SourceLocation Loc)2070 void setRParen(SourceLocation Loc) { R = Loc; }
2071
classof(const Stmt * T)2072 static bool classof(const Stmt *T) {
2073 return T->getStmtClass() == ParenExprClass;
2074 }
2075
2076 // Iterators
children()2077 child_range children() { return child_range(&Val, &Val+1); }
children()2078 const_child_range children() const {
2079 return const_child_range(&Val, &Val + 1);
2080 }
2081 };
2082
2083 /// UnaryOperator - This represents the unary-expression's (except sizeof and
2084 /// alignof), the postinc/postdec operators from postfix-expression, and various
2085 /// extensions.
2086 ///
2087 /// Notes on various nodes:
2088 ///
2089 /// Real/Imag - These return the real/imag part of a complex operand. If
2090 /// applied to a non-complex value, the former returns its operand and the
2091 /// later returns zero in the type of the operand.
2092 ///
2093 class UnaryOperator final
2094 : public Expr,
2095 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2096 Stmt *Val;
2097
numTrailingObjects(OverloadToken<FPOptionsOverride>)2098 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2099 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2100 }
2101
getTrailingFPFeatures()2102 FPOptionsOverride &getTrailingFPFeatures() {
2103 assert(UnaryOperatorBits.HasFPFeatures);
2104 return *getTrailingObjects<FPOptionsOverride>();
2105 }
2106
getTrailingFPFeatures()2107 const FPOptionsOverride &getTrailingFPFeatures() const {
2108 assert(UnaryOperatorBits.HasFPFeatures);
2109 return *getTrailingObjects<FPOptionsOverride>();
2110 }
2111
2112 public:
2113 typedef UnaryOperatorKind Opcode;
2114
2115 protected:
2116 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2117 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2118 bool CanOverflow, FPOptionsOverride FPFeatures);
2119
2120 /// Build an empty unary operator.
UnaryOperator(bool HasFPFeatures,EmptyShell Empty)2121 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2122 : Expr(UnaryOperatorClass, Empty) {
2123 UnaryOperatorBits.Opc = UO_AddrOf;
2124 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2125 }
2126
2127 public:
2128 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2129
2130 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2131 QualType type, ExprValueKind VK,
2132 ExprObjectKind OK, SourceLocation l,
2133 bool CanOverflow, FPOptionsOverride FPFeatures);
2134
getOpcode()2135 Opcode getOpcode() const {
2136 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2137 }
setOpcode(Opcode Opc)2138 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2139
getSubExpr()2140 Expr *getSubExpr() const { return cast<Expr>(Val); }
setSubExpr(Expr * E)2141 void setSubExpr(Expr *E) { Val = E; }
2142
2143 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2144 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
setOperatorLoc(SourceLocation L)2145 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2146
2147 /// Returns true if the unary operator can cause an overflow. For instance,
2148 /// signed int i = INT_MAX; i++;
2149 /// signed char c = CHAR_MAX; c++;
2150 /// Due to integer promotions, c++ is promoted to an int before the postfix
2151 /// increment, and the result is an int that cannot overflow. However, i++
2152 /// can overflow.
canOverflow()2153 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
setCanOverflow(bool C)2154 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2155
2156 // Get the FP contractability status of this operator. Only meaningful for
2157 // operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)2158 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2159 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2160 }
2161
2162 // Get the FENV_ACCESS status of this operator. Only meaningful for
2163 // operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)2164 bool isFEnvAccessOn(const LangOptions &LO) const {
2165 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2166 }
2167
2168 /// isPostfix - Return true if this is a postfix operation, like x++.
isPostfix(Opcode Op)2169 static bool isPostfix(Opcode Op) {
2170 return Op == UO_PostInc || Op == UO_PostDec;
2171 }
2172
2173 /// isPrefix - Return true if this is a prefix operation, like --x.
isPrefix(Opcode Op)2174 static bool isPrefix(Opcode Op) {
2175 return Op == UO_PreInc || Op == UO_PreDec;
2176 }
2177
isPrefix()2178 bool isPrefix() const { return isPrefix(getOpcode()); }
isPostfix()2179 bool isPostfix() const { return isPostfix(getOpcode()); }
2180
isIncrementOp(Opcode Op)2181 static bool isIncrementOp(Opcode Op) {
2182 return Op == UO_PreInc || Op == UO_PostInc;
2183 }
isIncrementOp()2184 bool isIncrementOp() const {
2185 return isIncrementOp(getOpcode());
2186 }
2187
isDecrementOp(Opcode Op)2188 static bool isDecrementOp(Opcode Op) {
2189 return Op == UO_PreDec || Op == UO_PostDec;
2190 }
isDecrementOp()2191 bool isDecrementOp() const {
2192 return isDecrementOp(getOpcode());
2193 }
2194
isIncrementDecrementOp(Opcode Op)2195 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
isIncrementDecrementOp()2196 bool isIncrementDecrementOp() const {
2197 return isIncrementDecrementOp(getOpcode());
2198 }
2199
isArithmeticOp(Opcode Op)2200 static bool isArithmeticOp(Opcode Op) {
2201 return Op >= UO_Plus && Op <= UO_LNot;
2202 }
isArithmeticOp()2203 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2204
2205 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2206 /// corresponds to, e.g. "sizeof" or "[pre]++"
2207 static StringRef getOpcodeStr(Opcode Op);
2208
2209 /// Retrieve the unary opcode that corresponds to the given
2210 /// overloaded operator.
2211 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2212
2213 /// Retrieve the overloaded operator kind that corresponds to
2214 /// the given unary opcode.
2215 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2216
getBeginLoc()2217 SourceLocation getBeginLoc() const LLVM_READONLY {
2218 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2219 }
getEndLoc()2220 SourceLocation getEndLoc() const LLVM_READONLY {
2221 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2222 }
getExprLoc()2223 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2224
classof(const Stmt * T)2225 static bool classof(const Stmt *T) {
2226 return T->getStmtClass() == UnaryOperatorClass;
2227 }
2228
2229 // Iterators
children()2230 child_range children() { return child_range(&Val, &Val+1); }
children()2231 const_child_range children() const {
2232 return const_child_range(&Val, &Val + 1);
2233 }
2234
2235 /// Is FPFeatures in Trailing Storage?
hasStoredFPFeatures()2236 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2237
2238 /// Get FPFeatures from trailing storage.
getStoredFPFeatures()2239 FPOptionsOverride getStoredFPFeatures() const {
2240 return getTrailingFPFeatures();
2241 }
2242
2243 protected:
2244 /// Set FPFeatures in trailing storage, used only by Serialization
setStoredFPFeatures(FPOptionsOverride F)2245 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2246
2247 public:
2248 // Get the FP features status of this operator. Only meaningful for
2249 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)2250 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2251 if (UnaryOperatorBits.HasFPFeatures)
2252 return getStoredFPFeatures().applyOverrides(LO);
2253 return FPOptions::defaultWithoutTrailingStorage(LO);
2254 }
getFPOptionsOverride()2255 FPOptionsOverride getFPOptionsOverride() const {
2256 if (UnaryOperatorBits.HasFPFeatures)
2257 return getStoredFPFeatures();
2258 return FPOptionsOverride();
2259 }
2260
2261 friend TrailingObjects;
2262 friend class ASTReader;
2263 friend class ASTStmtReader;
2264 friend class ASTStmtWriter;
2265 };
2266
2267 /// Helper class for OffsetOfExpr.
2268
2269 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2270 class OffsetOfNode {
2271 public:
2272 /// The kind of offsetof node we have.
2273 enum Kind {
2274 /// An index into an array.
2275 Array = 0x00,
2276 /// A field.
2277 Field = 0x01,
2278 /// A field in a dependent type, known only by its name.
2279 Identifier = 0x02,
2280 /// An implicit indirection through a C++ base class, when the
2281 /// field found is in a base class.
2282 Base = 0x03
2283 };
2284
2285 private:
2286 enum { MaskBits = 2, Mask = 0x03 };
2287
2288 /// The source range that covers this part of the designator.
2289 SourceRange Range;
2290
2291 /// The data describing the designator, which comes in three
2292 /// different forms, depending on the lower two bits.
2293 /// - An unsigned index into the array of Expr*'s stored after this node
2294 /// in memory, for [constant-expression] designators.
2295 /// - A FieldDecl*, for references to a known field.
2296 /// - An IdentifierInfo*, for references to a field with a given name
2297 /// when the class type is dependent.
2298 /// - A CXXBaseSpecifier*, for references that look at a field in a
2299 /// base class.
2300 uintptr_t Data;
2301
2302 public:
2303 /// Create an offsetof node that refers to an array element.
OffsetOfNode(SourceLocation LBracketLoc,unsigned Index,SourceLocation RBracketLoc)2304 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2305 SourceLocation RBracketLoc)
2306 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2307
2308 /// Create an offsetof node that refers to a field.
OffsetOfNode(SourceLocation DotLoc,FieldDecl * Field,SourceLocation NameLoc)2309 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2310 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2311 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2312
2313 /// Create an offsetof node that refers to an identifier.
OffsetOfNode(SourceLocation DotLoc,IdentifierInfo * Name,SourceLocation NameLoc)2314 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2315 SourceLocation NameLoc)
2316 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2317 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2318
2319 /// Create an offsetof node that refers into a C++ base class.
OffsetOfNode(const CXXBaseSpecifier * Base)2320 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2321 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2322
2323 /// Determine what kind of offsetof node this is.
getKind()2324 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2325
2326 /// For an array element node, returns the index into the array
2327 /// of expressions.
getArrayExprIndex()2328 unsigned getArrayExprIndex() const {
2329 assert(getKind() == Array);
2330 return Data >> 2;
2331 }
2332
2333 /// For a field offsetof node, returns the field.
getField()2334 FieldDecl *getField() const {
2335 assert(getKind() == Field);
2336 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2337 }
2338
2339 /// For a field or identifier offsetof node, returns the name of
2340 /// the field.
2341 IdentifierInfo *getFieldName() const;
2342
2343 /// For a base class node, returns the base specifier.
getBase()2344 CXXBaseSpecifier *getBase() const {
2345 assert(getKind() == Base);
2346 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2347 }
2348
2349 /// Retrieve the source range that covers this offsetof node.
2350 ///
2351 /// For an array element node, the source range contains the locations of
2352 /// the square brackets. For a field or identifier node, the source range
2353 /// contains the location of the period (if there is one) and the
2354 /// identifier.
getSourceRange()2355 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getBeginLoc()2356 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
getEndLoc()2357 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2358 };
2359
2360 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2361 /// offsetof(record-type, member-designator). For example, given:
2362 /// @code
2363 /// struct S {
2364 /// float f;
2365 /// double d;
2366 /// };
2367 /// struct T {
2368 /// int i;
2369 /// struct S s[10];
2370 /// };
2371 /// @endcode
2372 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2373
2374 class OffsetOfExpr final
2375 : public Expr,
2376 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2377 SourceLocation OperatorLoc, RParenLoc;
2378 // Base type;
2379 TypeSourceInfo *TSInfo;
2380 // Number of sub-components (i.e. instances of OffsetOfNode).
2381 unsigned NumComps;
2382 // Number of sub-expressions (i.e. array subscript expressions).
2383 unsigned NumExprs;
2384
numTrailingObjects(OverloadToken<OffsetOfNode>)2385 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2386 return NumComps;
2387 }
2388
2389 OffsetOfExpr(const ASTContext &C, QualType type,
2390 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2391 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2392 SourceLocation RParenLoc);
2393
OffsetOfExpr(unsigned numComps,unsigned numExprs)2394 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2395 : Expr(OffsetOfExprClass, EmptyShell()),
2396 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2397
2398 public:
2399
2400 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2401 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2402 ArrayRef<OffsetOfNode> comps,
2403 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2404
2405 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2406 unsigned NumComps, unsigned NumExprs);
2407
2408 /// getOperatorLoc - Return the location of the operator.
getOperatorLoc()2409 SourceLocation getOperatorLoc() const { return OperatorLoc; }
setOperatorLoc(SourceLocation L)2410 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2411
2412 /// Return the location of the right parentheses.
getRParenLoc()2413 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation R)2414 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2415
getTypeSourceInfo()2416 TypeSourceInfo *getTypeSourceInfo() const {
2417 return TSInfo;
2418 }
setTypeSourceInfo(TypeSourceInfo * tsi)2419 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2420 TSInfo = tsi;
2421 }
2422
getComponent(unsigned Idx)2423 const OffsetOfNode &getComponent(unsigned Idx) const {
2424 assert(Idx < NumComps && "Subscript out of range");
2425 return getTrailingObjects<OffsetOfNode>()[Idx];
2426 }
2427
setComponent(unsigned Idx,OffsetOfNode ON)2428 void setComponent(unsigned Idx, OffsetOfNode ON) {
2429 assert(Idx < NumComps && "Subscript out of range");
2430 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2431 }
2432
getNumComponents()2433 unsigned getNumComponents() const {
2434 return NumComps;
2435 }
2436
getIndexExpr(unsigned Idx)2437 Expr* getIndexExpr(unsigned Idx) {
2438 assert(Idx < NumExprs && "Subscript out of range");
2439 return getTrailingObjects<Expr *>()[Idx];
2440 }
2441
getIndexExpr(unsigned Idx)2442 const Expr *getIndexExpr(unsigned Idx) const {
2443 assert(Idx < NumExprs && "Subscript out of range");
2444 return getTrailingObjects<Expr *>()[Idx];
2445 }
2446
setIndexExpr(unsigned Idx,Expr * E)2447 void setIndexExpr(unsigned Idx, Expr* E) {
2448 assert(Idx < NumComps && "Subscript out of range");
2449 getTrailingObjects<Expr *>()[Idx] = E;
2450 }
2451
getNumExpressions()2452 unsigned getNumExpressions() const {
2453 return NumExprs;
2454 }
2455
getBeginLoc()2456 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
getEndLoc()2457 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2458
classof(const Stmt * T)2459 static bool classof(const Stmt *T) {
2460 return T->getStmtClass() == OffsetOfExprClass;
2461 }
2462
2463 // Iterators
children()2464 child_range children() {
2465 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2466 return child_range(begin, begin + NumExprs);
2467 }
children()2468 const_child_range children() const {
2469 Stmt *const *begin =
2470 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2471 return const_child_range(begin, begin + NumExprs);
2472 }
2473 friend TrailingObjects;
2474 };
2475
2476 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2477 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2478 /// vec_step (OpenCL 1.1 6.11.12).
2479 class UnaryExprOrTypeTraitExpr : public Expr {
2480 union {
2481 TypeSourceInfo *Ty;
2482 Stmt *Ex;
2483 } Argument;
2484 SourceLocation OpLoc, RParenLoc;
2485
2486 public:
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,TypeSourceInfo * TInfo,QualType resultType,SourceLocation op,SourceLocation rp)2487 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2488 QualType resultType, SourceLocation op,
2489 SourceLocation rp)
2490 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary),
2491 OpLoc(op), RParenLoc(rp) {
2492 assert(ExprKind <= UETT_Last && "invalid enum value!");
2493 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2494 assert(static_cast<unsigned>(ExprKind) ==
2495 UnaryExprOrTypeTraitExprBits.Kind &&
2496 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2497 UnaryExprOrTypeTraitExprBits.IsType = true;
2498 Argument.Ty = TInfo;
2499 setDependence(computeDependence(this));
2500 }
2501
2502 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2503 QualType resultType, SourceLocation op,
2504 SourceLocation rp);
2505
2506 /// Construct an empty sizeof/alignof expression.
UnaryExprOrTypeTraitExpr(EmptyShell Empty)2507 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2508 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2509
getKind()2510 UnaryExprOrTypeTrait getKind() const {
2511 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2512 }
setKind(UnaryExprOrTypeTrait K)2513 void setKind(UnaryExprOrTypeTrait K) {
2514 assert(K <= UETT_Last && "invalid enum value!");
2515 UnaryExprOrTypeTraitExprBits.Kind = K;
2516 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2517 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2518 }
2519
isArgumentType()2520 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
getArgumentType()2521 QualType getArgumentType() const {
2522 return getArgumentTypeInfo()->getType();
2523 }
getArgumentTypeInfo()2524 TypeSourceInfo *getArgumentTypeInfo() const {
2525 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2526 return Argument.Ty;
2527 }
getArgumentExpr()2528 Expr *getArgumentExpr() {
2529 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2530 return static_cast<Expr*>(Argument.Ex);
2531 }
getArgumentExpr()2532 const Expr *getArgumentExpr() const {
2533 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2534 }
2535
setArgument(Expr * E)2536 void setArgument(Expr *E) {
2537 Argument.Ex = E;
2538 UnaryExprOrTypeTraitExprBits.IsType = false;
2539 }
setArgument(TypeSourceInfo * TInfo)2540 void setArgument(TypeSourceInfo *TInfo) {
2541 Argument.Ty = TInfo;
2542 UnaryExprOrTypeTraitExprBits.IsType = true;
2543 }
2544
2545 /// Gets the argument type, or the type of the argument expression, whichever
2546 /// is appropriate.
getTypeOfArgument()2547 QualType getTypeOfArgument() const {
2548 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2549 }
2550
getOperatorLoc()2551 SourceLocation getOperatorLoc() const { return OpLoc; }
setOperatorLoc(SourceLocation L)2552 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2553
getRParenLoc()2554 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)2555 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2556
getBeginLoc()2557 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
getEndLoc()2558 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2559
classof(const Stmt * T)2560 static bool classof(const Stmt *T) {
2561 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2562 }
2563
2564 // Iterators
2565 child_range children();
2566 const_child_range children() const;
2567 };
2568
2569 //===----------------------------------------------------------------------===//
2570 // Postfix Operators.
2571 //===----------------------------------------------------------------------===//
2572
2573 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2574 class ArraySubscriptExpr : public Expr {
2575 enum { LHS, RHS, END_EXPR };
2576 Stmt *SubExprs[END_EXPR];
2577
lhsIsBase()2578 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2579
2580 public:
ArraySubscriptExpr(Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation rbracketloc)2581 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2582 ExprObjectKind OK, SourceLocation rbracketloc)
2583 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2584 SubExprs[LHS] = lhs;
2585 SubExprs[RHS] = rhs;
2586 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2587 setDependence(computeDependence(this));
2588 }
2589
2590 /// Create an empty array subscript expression.
ArraySubscriptExpr(EmptyShell Shell)2591 explicit ArraySubscriptExpr(EmptyShell Shell)
2592 : Expr(ArraySubscriptExprClass, Shell) { }
2593
2594 /// An array access can be written A[4] or 4[A] (both are equivalent).
2595 /// - getBase() and getIdx() always present the normalized view: A[4].
2596 /// In this case getBase() returns "A" and getIdx() returns "4".
2597 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2598 /// 4[A] getLHS() returns "4".
2599 /// Note: Because vector element access is also written A[4] we must
2600 /// predicate the format conversion in getBase and getIdx only on the
2601 /// the type of the RHS, as it is possible for the LHS to be a vector of
2602 /// integer type
getLHS()2603 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
getLHS()2604 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)2605 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2606
getRHS()2607 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
getRHS()2608 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)2609 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2610
getBase()2611 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
getBase()2612 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2613
getIdx()2614 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
getIdx()2615 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2616
getBeginLoc()2617 SourceLocation getBeginLoc() const LLVM_READONLY {
2618 return getLHS()->getBeginLoc();
2619 }
getEndLoc()2620 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2621
getRBracketLoc()2622 SourceLocation getRBracketLoc() const {
2623 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2624 }
setRBracketLoc(SourceLocation L)2625 void setRBracketLoc(SourceLocation L) {
2626 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2627 }
2628
getExprLoc()2629 SourceLocation getExprLoc() const LLVM_READONLY {
2630 return getBase()->getExprLoc();
2631 }
2632
classof(const Stmt * T)2633 static bool classof(const Stmt *T) {
2634 return T->getStmtClass() == ArraySubscriptExprClass;
2635 }
2636
2637 // Iterators
children()2638 child_range children() {
2639 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2640 }
children()2641 const_child_range children() const {
2642 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2643 }
2644 };
2645
2646 /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2647 /// extension.
2648 /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2649 /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2650 /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2651 /// exist during the initial construction of the AST.
2652 class MatrixSubscriptExpr : public Expr {
2653 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2654 Stmt *SubExprs[END_EXPR];
2655
2656 public:
MatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,QualType T,SourceLocation RBracketLoc)2657 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2658 SourceLocation RBracketLoc)
2659 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2660 OK_MatrixComponent) {
2661 SubExprs[BASE] = Base;
2662 SubExprs[ROW_IDX] = RowIdx;
2663 SubExprs[COLUMN_IDX] = ColumnIdx;
2664 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2665 setDependence(computeDependence(this));
2666 }
2667
2668 /// Create an empty matrix subscript expression.
MatrixSubscriptExpr(EmptyShell Shell)2669 explicit MatrixSubscriptExpr(EmptyShell Shell)
2670 : Expr(MatrixSubscriptExprClass, Shell) {}
2671
isIncomplete()2672 bool isIncomplete() const {
2673 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2674 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2675 "expressions without column index must be marked as incomplete");
2676 return IsIncomplete;
2677 }
getBase()2678 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
getBase()2679 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
setBase(Expr * E)2680 void setBase(Expr *E) { SubExprs[BASE] = E; }
2681
getRowIdx()2682 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
getRowIdx()2683 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
setRowIdx(Expr * E)2684 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2685
getColumnIdx()2686 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
getColumnIdx()2687 const Expr *getColumnIdx() const {
2688 assert(!isIncomplete() &&
2689 "cannot get the column index of an incomplete expression");
2690 return cast<Expr>(SubExprs[COLUMN_IDX]);
2691 }
setColumnIdx(Expr * E)2692 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2693
getBeginLoc()2694 SourceLocation getBeginLoc() const LLVM_READONLY {
2695 return getBase()->getBeginLoc();
2696 }
2697
getEndLoc()2698 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2699
getExprLoc()2700 SourceLocation getExprLoc() const LLVM_READONLY {
2701 return getBase()->getExprLoc();
2702 }
2703
getRBracketLoc()2704 SourceLocation getRBracketLoc() const {
2705 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2706 }
setRBracketLoc(SourceLocation L)2707 void setRBracketLoc(SourceLocation L) {
2708 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2709 }
2710
classof(const Stmt * T)2711 static bool classof(const Stmt *T) {
2712 return T->getStmtClass() == MatrixSubscriptExprClass;
2713 }
2714
2715 // Iterators
children()2716 child_range children() {
2717 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2718 }
children()2719 const_child_range children() const {
2720 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2721 }
2722 };
2723
2724 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2725 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2726 /// while its subclasses may represent alternative syntax that (semantically)
2727 /// results in a function call. For example, CXXOperatorCallExpr is
2728 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2729 /// "str1 + str2" to resolve to a function call.
2730 class CallExpr : public Expr {
2731 enum { FN = 0, PREARGS_START = 1 };
2732
2733 /// The number of arguments in the call expression.
2734 unsigned NumArgs;
2735
2736 /// The location of the right parenthese. This has a different meaning for
2737 /// the derived classes of CallExpr.
2738 SourceLocation RParenLoc;
2739
2740 // CallExpr store some data in trailing objects. However since CallExpr
2741 // is used a base of other expression classes we cannot use
2742 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2743 // and casts.
2744 //
2745 // The trailing objects are in order:
2746 //
2747 // * A single "Stmt *" for the callee expression.
2748 //
2749 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2750 //
2751 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2752 //
2753 // * An optional of type FPOptionsOverride.
2754 //
2755 // Note that we store the offset in bytes from the this pointer to the start
2756 // of the trailing objects. It would be perfectly possible to compute it
2757 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2758 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2759 // compute this once and then load the offset from the bit-fields of Stmt,
2760 // instead of re-computing the offset each time the trailing objects are
2761 // accessed.
2762
2763 /// Return a pointer to the start of the trailing array of "Stmt *".
getTrailingStmts()2764 Stmt **getTrailingStmts() {
2765 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2766 CallExprBits.OffsetToTrailingObjects);
2767 }
getTrailingStmts()2768 Stmt *const *getTrailingStmts() const {
2769 return const_cast<CallExpr *>(this)->getTrailingStmts();
2770 }
2771
2772 /// Map a statement class to the appropriate offset in bytes from the
2773 /// this pointer to the trailing objects.
2774 static unsigned offsetToTrailingObjects(StmtClass SC);
2775
getSizeOfTrailingStmts()2776 unsigned getSizeOfTrailingStmts() const {
2777 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2778 }
2779
getOffsetOfTrailingFPFeatures()2780 size_t getOffsetOfTrailingFPFeatures() const {
2781 assert(hasStoredFPFeatures());
2782 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2783 }
2784
2785 public:
2786 enum class ADLCallKind : bool { NotADL, UsesADL };
2787 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2788 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2789
2790 protected:
2791 /// Build a call expression, assuming that appropriate storage has been
2792 /// allocated for the trailing objects.
2793 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2794 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2795 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2796 unsigned MinNumArgs, ADLCallKind UsesADL);
2797
2798 /// Build an empty call expression, for deserialization.
2799 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2800 bool hasFPFeatures, EmptyShell Empty);
2801
2802 /// Return the size in bytes needed for the trailing objects.
2803 /// Used by the derived classes to allocate the right amount of storage.
sizeOfTrailingObjects(unsigned NumPreArgs,unsigned NumArgs,bool HasFPFeatures)2804 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2805 bool HasFPFeatures) {
2806 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2807 HasFPFeatures * sizeof(FPOptionsOverride);
2808 }
2809
getPreArg(unsigned I)2810 Stmt *getPreArg(unsigned I) {
2811 assert(I < getNumPreArgs() && "Prearg access out of range!");
2812 return getTrailingStmts()[PREARGS_START + I];
2813 }
getPreArg(unsigned I)2814 const Stmt *getPreArg(unsigned I) const {
2815 assert(I < getNumPreArgs() && "Prearg access out of range!");
2816 return getTrailingStmts()[PREARGS_START + I];
2817 }
setPreArg(unsigned I,Stmt * PreArg)2818 void setPreArg(unsigned I, Stmt *PreArg) {
2819 assert(I < getNumPreArgs() && "Prearg access out of range!");
2820 getTrailingStmts()[PREARGS_START + I] = PreArg;
2821 }
2822
getNumPreArgs()2823 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2824
2825 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()2826 FPOptionsOverride *getTrailingFPFeatures() {
2827 assert(hasStoredFPFeatures());
2828 return reinterpret_cast<FPOptionsOverride *>(
2829 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2830 getSizeOfTrailingStmts());
2831 }
getTrailingFPFeatures()2832 const FPOptionsOverride *getTrailingFPFeatures() const {
2833 assert(hasStoredFPFeatures());
2834 return reinterpret_cast<const FPOptionsOverride *>(
2835 reinterpret_cast<const char *>(this) +
2836 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2837 }
2838
2839 public:
2840 /// Create a call expression.
2841 /// \param Fn The callee expression,
2842 /// \param Args The argument array,
2843 /// \param Ty The type of the call expression (which is *not* the return
2844 /// type in general),
2845 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2846 /// \param RParenLoc The location of the right parenthesis in the call
2847 /// expression.
2848 /// \param FPFeatures Floating-point features associated with the call,
2849 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2850 /// number of arguments will be the greater of Args.size()
2851 /// and MinNumArgs. This is used in a few places to allocate
2852 /// enough storage for the default arguments.
2853 /// \param UsesADL Specifies whether the callee was found through
2854 /// argument-dependent lookup.
2855 ///
2856 /// Note that you can use CreateTemporary if you need a temporary call
2857 /// expression on the stack.
2858 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2859 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2860 SourceLocation RParenLoc,
2861 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2862 ADLCallKind UsesADL = NotADL);
2863
2864 /// Create a temporary call expression with no arguments in the memory
2865 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2866 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2867 ///
2868 /// \code{.cpp}
2869 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2870 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2871 /// \endcode
2872 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2873 ExprValueKind VK, SourceLocation RParenLoc,
2874 ADLCallKind UsesADL = NotADL);
2875
2876 /// Create an empty call expression, for deserialization.
2877 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2878 bool HasFPFeatures, EmptyShell Empty);
2879
getCallee()2880 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
getCallee()2881 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
setCallee(Expr * F)2882 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2883
getADLCallKind()2884 ADLCallKind getADLCallKind() const {
2885 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2886 }
2887 void setADLCallKind(ADLCallKind V = UsesADL) {
2888 CallExprBits.UsesADL = static_cast<bool>(V);
2889 }
usesADL()2890 bool usesADL() const { return getADLCallKind() == UsesADL; }
2891
hasStoredFPFeatures()2892 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2893
getCalleeDecl()2894 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
getCalleeDecl()2895 const Decl *getCalleeDecl() const {
2896 return getCallee()->getReferencedDeclOfCallee();
2897 }
2898
2899 /// If the callee is a FunctionDecl, return it. Otherwise return null.
getDirectCallee()2900 FunctionDecl *getDirectCallee() {
2901 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2902 }
getDirectCallee()2903 const FunctionDecl *getDirectCallee() const {
2904 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2905 }
2906
2907 /// getNumArgs - Return the number of actual arguments to this call.
getNumArgs()2908 unsigned getNumArgs() const { return NumArgs; }
2909
2910 /// Retrieve the call arguments.
getArgs()2911 Expr **getArgs() {
2912 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2913 getNumPreArgs());
2914 }
getArgs()2915 const Expr *const *getArgs() const {
2916 return reinterpret_cast<const Expr *const *>(
2917 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2918 }
2919
2920 /// getArg - Return the specified argument.
getArg(unsigned Arg)2921 Expr *getArg(unsigned Arg) {
2922 assert(Arg < getNumArgs() && "Arg access out of range!");
2923 return getArgs()[Arg];
2924 }
getArg(unsigned Arg)2925 const Expr *getArg(unsigned Arg) const {
2926 assert(Arg < getNumArgs() && "Arg access out of range!");
2927 return getArgs()[Arg];
2928 }
2929
2930 /// setArg - Set the specified argument.
setArg(unsigned Arg,Expr * ArgExpr)2931 void setArg(unsigned Arg, Expr *ArgExpr) {
2932 assert(Arg < getNumArgs() && "Arg access out of range!");
2933 getArgs()[Arg] = ArgExpr;
2934 }
2935
2936 /// Reduce the number of arguments in this call expression. This is used for
2937 /// example during error recovery to drop extra arguments. There is no way
2938 /// to perform the opposite because: 1.) We don't track how much storage
2939 /// we have for the argument array 2.) This would potentially require growing
2940 /// the argument array, something we cannot support since the arguments are
2941 /// stored in a trailing array.
shrinkNumArgs(unsigned NewNumArgs)2942 void shrinkNumArgs(unsigned NewNumArgs) {
2943 assert((NewNumArgs <= getNumArgs()) &&
2944 "shrinkNumArgs cannot increase the number of arguments!");
2945 NumArgs = NewNumArgs;
2946 }
2947
2948 /// Bluntly set a new number of arguments without doing any checks whatsoever.
2949 /// Only used during construction of a CallExpr in a few places in Sema.
2950 /// FIXME: Find a way to remove it.
setNumArgsUnsafe(unsigned NewNumArgs)2951 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
2952
2953 typedef ExprIterator arg_iterator;
2954 typedef ConstExprIterator const_arg_iterator;
2955 typedef llvm::iterator_range<arg_iterator> arg_range;
2956 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2957
arguments()2958 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arguments()2959 const_arg_range arguments() const {
2960 return const_arg_range(arg_begin(), arg_end());
2961 }
2962
arg_begin()2963 arg_iterator arg_begin() {
2964 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2965 }
arg_end()2966 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
2967
arg_begin()2968 const_arg_iterator arg_begin() const {
2969 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2970 }
arg_end()2971 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
2972
2973 /// This method provides fast access to all the subexpressions of
2974 /// a CallExpr without going through the slower virtual child_iterator
2975 /// interface. This provides efficient reverse iteration of the
2976 /// subexpressions. This is currently used for CFG construction.
getRawSubExprs()2977 ArrayRef<Stmt *> getRawSubExprs() {
2978 return llvm::makeArrayRef(getTrailingStmts(),
2979 PREARGS_START + getNumPreArgs() + getNumArgs());
2980 }
2981
2982 /// getNumCommas - Return the number of commas that must have been present in
2983 /// this function call.
getNumCommas()2984 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
2985
2986 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()2987 FPOptionsOverride getStoredFPFeatures() const {
2988 assert(hasStoredFPFeatures());
2989 return *getTrailingFPFeatures();
2990 }
2991 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
setStoredFPFeatures(FPOptionsOverride F)2992 void setStoredFPFeatures(FPOptionsOverride F) {
2993 assert(hasStoredFPFeatures());
2994 *getTrailingFPFeatures() = F;
2995 }
2996
2997 // Get the FP features status of this operator. Only meaningful for
2998 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)2999 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3000 if (hasStoredFPFeatures())
3001 return getStoredFPFeatures().applyOverrides(LO);
3002 return FPOptions::defaultWithoutTrailingStorage(LO);
3003 }
3004
getFPFeatures()3005 FPOptionsOverride getFPFeatures() const {
3006 if (hasStoredFPFeatures())
3007 return getStoredFPFeatures();
3008 return FPOptionsOverride();
3009 }
3010
3011 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3012 /// of the callee. If not, return 0.
3013 unsigned getBuiltinCallee() const;
3014
3015 /// Returns \c true if this is a call to a builtin which does not
3016 /// evaluate side-effects within its arguments.
3017 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3018
3019 /// getCallReturnType - Get the return type of the call expr. This is not
3020 /// always the type of the expr itself, if the return type is a reference
3021 /// type.
3022 QualType getCallReturnType(const ASTContext &Ctx) const;
3023
3024 /// Returns the WarnUnusedResultAttr that is either declared on the called
3025 /// function, or its return type declaration.
3026 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3027
3028 /// Returns true if this call expression should warn on unused results.
hasUnusedResultAttr(const ASTContext & Ctx)3029 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3030 return getUnusedResultAttr(Ctx) != nullptr;
3031 }
3032
getRParenLoc()3033 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3034 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3035
3036 SourceLocation getBeginLoc() const LLVM_READONLY;
3037 SourceLocation getEndLoc() const LLVM_READONLY;
3038
3039 /// Return true if this is a call to __assume() or __builtin_assume() with
3040 /// a non-value-dependent constant parameter evaluating as false.
3041 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3042
3043 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3044 /// (Usually Exprs themselves should set dependence).
markDependentForPostponedNameLookup()3045 void markDependentForPostponedNameLookup() {
3046 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3047 }
3048
isCallToStdMove()3049 bool isCallToStdMove() const {
3050 const FunctionDecl *FD = getDirectCallee();
3051 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
3052 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
3053 }
3054
classof(const Stmt * T)3055 static bool classof(const Stmt *T) {
3056 return T->getStmtClass() >= firstCallExprConstant &&
3057 T->getStmtClass() <= lastCallExprConstant;
3058 }
3059
3060 // Iterators
children()3061 child_range children() {
3062 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3063 getNumPreArgs() + getNumArgs());
3064 }
3065
children()3066 const_child_range children() const {
3067 return const_child_range(getTrailingStmts(),
3068 getTrailingStmts() + PREARGS_START +
3069 getNumPreArgs() + getNumArgs());
3070 }
3071 };
3072
3073 /// Extra data stored in some MemberExpr objects.
3074 struct MemberExprNameQualifier {
3075 /// The nested-name-specifier that qualifies the name, including
3076 /// source-location information.
3077 NestedNameSpecifierLoc QualifierLoc;
3078
3079 /// The DeclAccessPair through which the MemberDecl was found due to
3080 /// name qualifiers.
3081 DeclAccessPair FoundDecl;
3082 };
3083
3084 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3085 ///
3086 class MemberExpr final
3087 : public Expr,
3088 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3089 ASTTemplateKWAndArgsInfo,
3090 TemplateArgumentLoc> {
3091 friend class ASTReader;
3092 friend class ASTStmtReader;
3093 friend class ASTStmtWriter;
3094 friend TrailingObjects;
3095
3096 /// Base - the expression for the base pointer or structure references. In
3097 /// X.F, this is "X".
3098 Stmt *Base;
3099
3100 /// MemberDecl - This is the decl being referenced by the field/member name.
3101 /// In X.F, this is the decl referenced by F.
3102 ValueDecl *MemberDecl;
3103
3104 /// MemberDNLoc - Provides source/type location info for the
3105 /// declaration name embedded in MemberDecl.
3106 DeclarationNameLoc MemberDNLoc;
3107
3108 /// MemberLoc - This is the location of the member name.
3109 SourceLocation MemberLoc;
3110
numTrailingObjects(OverloadToken<MemberExprNameQualifier>)3111 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3112 return hasQualifierOrFoundDecl();
3113 }
3114
numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>)3115 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3116 return hasTemplateKWAndArgsInfo();
3117 }
3118
hasQualifierOrFoundDecl()3119 bool hasQualifierOrFoundDecl() const {
3120 return MemberExprBits.HasQualifierOrFoundDecl;
3121 }
3122
hasTemplateKWAndArgsInfo()3123 bool hasTemplateKWAndArgsInfo() const {
3124 return MemberExprBits.HasTemplateKWAndArgsInfo;
3125 }
3126
3127 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3128 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3129 QualType T, ExprValueKind VK, ExprObjectKind OK,
3130 NonOdrUseReason NOUR);
MemberExpr(EmptyShell Empty)3131 MemberExpr(EmptyShell Empty)
3132 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3133
3134 public:
3135 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3136 SourceLocation OperatorLoc,
3137 NestedNameSpecifierLoc QualifierLoc,
3138 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3139 DeclAccessPair FoundDecl,
3140 DeclarationNameInfo MemberNameInfo,
3141 const TemplateArgumentListInfo *TemplateArgs,
3142 QualType T, ExprValueKind VK, ExprObjectKind OK,
3143 NonOdrUseReason NOUR);
3144
3145 /// Create an implicit MemberExpr, with no location, qualifier, template
3146 /// 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)3147 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3148 bool IsArrow, ValueDecl *MemberDecl,
3149 QualType T, ExprValueKind VK,
3150 ExprObjectKind OK) {
3151 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3152 SourceLocation(), MemberDecl,
3153 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3154 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3155 }
3156
3157 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3158 bool HasFoundDecl,
3159 bool HasTemplateKWAndArgsInfo,
3160 unsigned NumTemplateArgs);
3161
setBase(Expr * E)3162 void setBase(Expr *E) { Base = E; }
getBase()3163 Expr *getBase() const { return cast<Expr>(Base); }
3164
3165 /// Retrieve the member declaration to which this expression refers.
3166 ///
3167 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3168 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
getMemberDecl()3169 ValueDecl *getMemberDecl() const { return MemberDecl; }
3170 void setMemberDecl(ValueDecl *D);
3171
3172 /// Retrieves the declaration found by lookup.
getFoundDecl()3173 DeclAccessPair getFoundDecl() const {
3174 if (!hasQualifierOrFoundDecl())
3175 return DeclAccessPair::make(getMemberDecl(),
3176 getMemberDecl()->getAccess());
3177 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3178 }
3179
3180 /// Determines whether this member expression actually had
3181 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3182 /// x->Base::foo.
hasQualifier()3183 bool hasQualifier() const { return getQualifier() != nullptr; }
3184
3185 /// If the member name was qualified, retrieves the
3186 /// nested-name-specifier that precedes the member name, with source-location
3187 /// information.
getQualifierLoc()3188 NestedNameSpecifierLoc getQualifierLoc() const {
3189 if (!hasQualifierOrFoundDecl())
3190 return NestedNameSpecifierLoc();
3191 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3192 }
3193
3194 /// If the member name was qualified, retrieves the
3195 /// nested-name-specifier that precedes the member name. Otherwise, returns
3196 /// NULL.
getQualifier()3197 NestedNameSpecifier *getQualifier() const {
3198 return getQualifierLoc().getNestedNameSpecifier();
3199 }
3200
3201 /// Retrieve the location of the template keyword preceding
3202 /// the member name, if any.
getTemplateKeywordLoc()3203 SourceLocation getTemplateKeywordLoc() const {
3204 if (!hasTemplateKWAndArgsInfo())
3205 return SourceLocation();
3206 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3207 }
3208
3209 /// Retrieve the location of the left angle bracket starting the
3210 /// explicit template argument list following the member name, if any.
getLAngleLoc()3211 SourceLocation getLAngleLoc() const {
3212 if (!hasTemplateKWAndArgsInfo())
3213 return SourceLocation();
3214 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3215 }
3216
3217 /// Retrieve the location of the right angle bracket ending the
3218 /// explicit template argument list following the member name, if any.
getRAngleLoc()3219 SourceLocation getRAngleLoc() const {
3220 if (!hasTemplateKWAndArgsInfo())
3221 return SourceLocation();
3222 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3223 }
3224
3225 /// Determines whether the member name was preceded by the template keyword.
hasTemplateKeyword()3226 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3227
3228 /// Determines whether the member name was followed by an
3229 /// explicit template argument list.
hasExplicitTemplateArgs()3230 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3231
3232 /// Copies the template arguments (if present) into the given
3233 /// structure.
copyTemplateArgumentsInto(TemplateArgumentListInfo & List)3234 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3235 if (hasExplicitTemplateArgs())
3236 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3237 getTrailingObjects<TemplateArgumentLoc>(), List);
3238 }
3239
3240 /// Retrieve the template arguments provided as part of this
3241 /// template-id.
getTemplateArgs()3242 const TemplateArgumentLoc *getTemplateArgs() const {
3243 if (!hasExplicitTemplateArgs())
3244 return nullptr;
3245
3246 return getTrailingObjects<TemplateArgumentLoc>();
3247 }
3248
3249 /// Retrieve the number of template arguments provided as part of this
3250 /// template-id.
getNumTemplateArgs()3251 unsigned getNumTemplateArgs() const {
3252 if (!hasExplicitTemplateArgs())
3253 return 0;
3254
3255 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3256 }
3257
template_arguments()3258 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3259 return {getTemplateArgs(), getNumTemplateArgs()};
3260 }
3261
3262 /// Retrieve the member declaration name info.
getMemberNameInfo()3263 DeclarationNameInfo getMemberNameInfo() const {
3264 return DeclarationNameInfo(MemberDecl->getDeclName(),
3265 MemberLoc, MemberDNLoc);
3266 }
3267
getOperatorLoc()3268 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3269
isArrow()3270 bool isArrow() const { return MemberExprBits.IsArrow; }
setArrow(bool A)3271 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3272
3273 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3274 /// location of 'F'.
getMemberLoc()3275 SourceLocation getMemberLoc() const { return MemberLoc; }
setMemberLoc(SourceLocation L)3276 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3277
3278 SourceLocation getBeginLoc() const LLVM_READONLY;
3279 SourceLocation getEndLoc() const LLVM_READONLY;
3280
getExprLoc()3281 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3282
3283 /// Determine whether the base of this explicit is implicit.
isImplicitAccess()3284 bool isImplicitAccess() const {
3285 return getBase() && getBase()->isImplicitCXXThis();
3286 }
3287
3288 /// Returns true if this member expression refers to a method that
3289 /// was resolved from an overloaded set having size greater than 1.
hadMultipleCandidates()3290 bool hadMultipleCandidates() const {
3291 return MemberExprBits.HadMultipleCandidates;
3292 }
3293 /// Sets the flag telling whether this expression refers to
3294 /// a method that was resolved from an overloaded set having size
3295 /// greater than 1.
3296 void setHadMultipleCandidates(bool V = true) {
3297 MemberExprBits.HadMultipleCandidates = V;
3298 }
3299
3300 /// Returns true if virtual dispatch is performed.
3301 /// If the member access is fully qualified, (i.e. X::f()), virtual
3302 /// dispatching is not performed. In -fapple-kext mode qualified
3303 /// calls to virtual method will still go through the vtable.
performsVirtualDispatch(const LangOptions & LO)3304 bool performsVirtualDispatch(const LangOptions &LO) const {
3305 return LO.AppleKext || !hasQualifier();
3306 }
3307
3308 /// Is this expression a non-odr-use reference, and if so, why?
3309 /// This is only meaningful if the named member is a static member.
isNonOdrUse()3310 NonOdrUseReason isNonOdrUse() const {
3311 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3312 }
3313
classof(const Stmt * T)3314 static bool classof(const Stmt *T) {
3315 return T->getStmtClass() == MemberExprClass;
3316 }
3317
3318 // Iterators
children()3319 child_range children() { return child_range(&Base, &Base+1); }
children()3320 const_child_range children() const {
3321 return const_child_range(&Base, &Base + 1);
3322 }
3323 };
3324
3325 /// CompoundLiteralExpr - [C99 6.5.2.5]
3326 ///
3327 class CompoundLiteralExpr : public Expr {
3328 /// LParenLoc - If non-null, this is the location of the left paren in a
3329 /// compound literal like "(int){4}". This can be null if this is a
3330 /// synthesized compound expression.
3331 SourceLocation LParenLoc;
3332
3333 /// The type as written. This can be an incomplete array type, in
3334 /// which case the actual expression type will be different.
3335 /// The int part of the pair stores whether this expr is file scope.
3336 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3337 Stmt *Init;
3338 public:
CompoundLiteralExpr(SourceLocation lparenloc,TypeSourceInfo * tinfo,QualType T,ExprValueKind VK,Expr * init,bool fileScope)3339 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3340 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3341 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3342 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3343 setDependence(computeDependence(this));
3344 }
3345
3346 /// Construct an empty compound literal.
CompoundLiteralExpr(EmptyShell Empty)3347 explicit CompoundLiteralExpr(EmptyShell Empty)
3348 : Expr(CompoundLiteralExprClass, Empty) { }
3349
getInitializer()3350 const Expr *getInitializer() const { return cast<Expr>(Init); }
getInitializer()3351 Expr *getInitializer() { return cast<Expr>(Init); }
setInitializer(Expr * E)3352 void setInitializer(Expr *E) { Init = E; }
3353
isFileScope()3354 bool isFileScope() const { return TInfoAndScope.getInt(); }
setFileScope(bool FS)3355 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3356
getLParenLoc()3357 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)3358 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3359
getTypeSourceInfo()3360 TypeSourceInfo *getTypeSourceInfo() const {
3361 return TInfoAndScope.getPointer();
3362 }
setTypeSourceInfo(TypeSourceInfo * tinfo)3363 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3364 TInfoAndScope.setPointer(tinfo);
3365 }
3366
getBeginLoc()3367 SourceLocation getBeginLoc() const LLVM_READONLY {
3368 // FIXME: Init should never be null.
3369 if (!Init)
3370 return SourceLocation();
3371 if (LParenLoc.isInvalid())
3372 return Init->getBeginLoc();
3373 return LParenLoc;
3374 }
getEndLoc()3375 SourceLocation getEndLoc() const LLVM_READONLY {
3376 // FIXME: Init should never be null.
3377 if (!Init)
3378 return SourceLocation();
3379 return Init->getEndLoc();
3380 }
3381
classof(const Stmt * T)3382 static bool classof(const Stmt *T) {
3383 return T->getStmtClass() == CompoundLiteralExprClass;
3384 }
3385
3386 // Iterators
children()3387 child_range children() { return child_range(&Init, &Init+1); }
children()3388 const_child_range children() const {
3389 return const_child_range(&Init, &Init + 1);
3390 }
3391 };
3392
3393 /// CastExpr - Base class for type casts, including both implicit
3394 /// casts (ImplicitCastExpr) and explicit casts that have some
3395 /// representation in the source code (ExplicitCastExpr's derived
3396 /// classes).
3397 class CastExpr : public Expr {
3398 Stmt *Op;
3399
3400 bool CastConsistency() const;
3401
path_buffer()3402 const CXXBaseSpecifier * const *path_buffer() const {
3403 return const_cast<CastExpr*>(this)->path_buffer();
3404 }
3405 CXXBaseSpecifier **path_buffer();
3406
3407 friend class ASTStmtReader;
3408
3409 protected:
CastExpr(StmtClass SC,QualType ty,ExprValueKind VK,const CastKind kind,Expr * op,unsigned BasePathSize,bool HasFPFeatures)3410 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3411 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3412 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3413 CastExprBits.Kind = kind;
3414 CastExprBits.PartOfExplicitCast = false;
3415 CastExprBits.BasePathSize = BasePathSize;
3416 assert((CastExprBits.BasePathSize == BasePathSize) &&
3417 "BasePathSize overflow!");
3418 setDependence(computeDependence(this));
3419 assert(CastConsistency());
3420 CastExprBits.HasFPFeatures = HasFPFeatures;
3421 }
3422
3423 /// Construct an empty cast.
CastExpr(StmtClass SC,EmptyShell Empty,unsigned BasePathSize,bool HasFPFeatures)3424 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3425 bool HasFPFeatures)
3426 : Expr(SC, Empty) {
3427 CastExprBits.PartOfExplicitCast = false;
3428 CastExprBits.BasePathSize = BasePathSize;
3429 CastExprBits.HasFPFeatures = HasFPFeatures;
3430 assert((CastExprBits.BasePathSize == BasePathSize) &&
3431 "BasePathSize overflow!");
3432 }
3433
3434 /// Return a pointer to the trailing FPOptions.
3435 /// \pre hasStoredFPFeatures() == true
3436 FPOptionsOverride *getTrailingFPFeatures();
getTrailingFPFeatures()3437 const FPOptionsOverride *getTrailingFPFeatures() const {
3438 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3439 }
3440
3441 public:
getCastKind()3442 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
setCastKind(CastKind K)3443 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3444
3445 static const char *getCastKindName(CastKind CK);
getCastKindName()3446 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3447
getSubExpr()3448 Expr *getSubExpr() { return cast<Expr>(Op); }
getSubExpr()3449 const Expr *getSubExpr() const { return cast<Expr>(Op); }
setSubExpr(Expr * E)3450 void setSubExpr(Expr *E) { Op = E; }
3451
3452 /// Retrieve the cast subexpression as it was written in the source
3453 /// code, looking through any implicit casts or other intermediate nodes
3454 /// introduced by semantic analysis.
3455 Expr *getSubExprAsWritten();
getSubExprAsWritten()3456 const Expr *getSubExprAsWritten() const {
3457 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3458 }
3459
3460 /// If this cast applies a user-defined conversion, retrieve the conversion
3461 /// function that it invokes.
3462 NamedDecl *getConversionFunction() const;
3463
3464 typedef CXXBaseSpecifier **path_iterator;
3465 typedef const CXXBaseSpecifier *const *path_const_iterator;
path_empty()3466 bool path_empty() const { return path_size() == 0; }
path_size()3467 unsigned path_size() const { return CastExprBits.BasePathSize; }
path_begin()3468 path_iterator path_begin() { return path_buffer(); }
path_end()3469 path_iterator path_end() { return path_buffer() + path_size(); }
path_begin()3470 path_const_iterator path_begin() const { return path_buffer(); }
path_end()3471 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3472
path()3473 llvm::iterator_range<path_iterator> path() {
3474 return llvm::make_range(path_begin(), path_end());
3475 }
path()3476 llvm::iterator_range<path_const_iterator> path() const {
3477 return llvm::make_range(path_begin(), path_end());
3478 }
3479
getTargetUnionField()3480 const FieldDecl *getTargetUnionField() const {
3481 assert(getCastKind() == CK_ToUnion);
3482 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3483 }
3484
hasStoredFPFeatures()3485 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3486
3487 /// Get FPOptionsOverride from trailing storage.
getStoredFPFeatures()3488 FPOptionsOverride getStoredFPFeatures() const {
3489 assert(hasStoredFPFeatures());
3490 return *getTrailingFPFeatures();
3491 }
3492
3493 // Get the FP features status of this operation. Only meaningful for
3494 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3495 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3496 if (hasStoredFPFeatures())
3497 return getStoredFPFeatures().applyOverrides(LO);
3498 return FPOptions::defaultWithoutTrailingStorage(LO);
3499 }
3500
getFPFeatures()3501 FPOptionsOverride getFPFeatures() const {
3502 if (hasStoredFPFeatures())
3503 return getStoredFPFeatures();
3504 return FPOptionsOverride();
3505 }
3506
3507 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3508 QualType opType);
3509 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3510 QualType opType);
3511
classof(const Stmt * T)3512 static bool classof(const Stmt *T) {
3513 return T->getStmtClass() >= firstCastExprConstant &&
3514 T->getStmtClass() <= lastCastExprConstant;
3515 }
3516
3517 // Iterators
children()3518 child_range children() { return child_range(&Op, &Op+1); }
children()3519 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3520 };
3521
3522 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
3523 /// conversions, which have no direct representation in the original
3524 /// source code. For example: converting T[]->T*, void f()->void
3525 /// (*f)(), float->double, short->int, etc.
3526 ///
3527 /// In C, implicit casts always produce rvalues. However, in C++, an
3528 /// implicit cast whose result is being bound to a reference will be
3529 /// an lvalue or xvalue. For example:
3530 ///
3531 /// @code
3532 /// class Base { };
3533 /// class Derived : public Base { };
3534 /// Derived &&ref();
3535 /// void f(Derived d) {
3536 /// Base& b = d; // initializer is an ImplicitCastExpr
3537 /// // to an lvalue of type Base
3538 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
3539 /// // to an xvalue of type Base
3540 /// }
3541 /// @endcode
3542 class ImplicitCastExpr final
3543 : public CastExpr,
3544 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3545 FPOptionsOverride> {
3546
ImplicitCastExpr(QualType ty,CastKind kind,Expr * op,unsigned BasePathLength,FPOptionsOverride FPO,ExprValueKind VK)3547 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3548 unsigned BasePathLength, FPOptionsOverride FPO,
3549 ExprValueKind VK)
3550 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3551 FPO.requiresTrailingStorage()) {
3552 if (hasStoredFPFeatures())
3553 *getTrailingFPFeatures() = FPO;
3554 }
3555
3556 /// Construct an empty implicit cast.
ImplicitCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3557 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3558 bool HasFPFeatures)
3559 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3560
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3561 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3562 return path_size();
3563 }
3564
3565 public:
3566 enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _,QualType ty,CastKind kind,Expr * op,ExprValueKind VK,FPOptionsOverride FPO)3567 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3568 ExprValueKind VK, FPOptionsOverride FPO)
3569 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3570 FPO.requiresTrailingStorage()) {
3571 if (hasStoredFPFeatures())
3572 *getTrailingFPFeatures() = FPO;
3573 }
3574
isPartOfExplicitCast()3575 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
setIsPartOfExplicitCast(bool PartOfExplicitCast)3576 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3577 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3578 }
3579
3580 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3581 CastKind Kind, Expr *Operand,
3582 const CXXCastPath *BasePath,
3583 ExprValueKind Cat, FPOptionsOverride FPO);
3584
3585 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3586 unsigned PathSize, bool HasFPFeatures);
3587
getBeginLoc()3588 SourceLocation getBeginLoc() const LLVM_READONLY {
3589 return getSubExpr()->getBeginLoc();
3590 }
getEndLoc()3591 SourceLocation getEndLoc() const LLVM_READONLY {
3592 return getSubExpr()->getEndLoc();
3593 }
3594
classof(const Stmt * T)3595 static bool classof(const Stmt *T) {
3596 return T->getStmtClass() == ImplicitCastExprClass;
3597 }
3598
3599 friend TrailingObjects;
3600 friend class CastExpr;
3601 };
3602
3603 /// ExplicitCastExpr - An explicit cast written in the source
3604 /// code.
3605 ///
3606 /// This class is effectively an abstract class, because it provides
3607 /// the basic representation of an explicitly-written cast without
3608 /// specifying which kind of cast (C cast, functional cast, static
3609 /// cast, etc.) was written; specific derived classes represent the
3610 /// particular style of cast and its location information.
3611 ///
3612 /// Unlike implicit casts, explicit cast nodes have two different
3613 /// types: the type that was written into the source code, and the
3614 /// actual type of the expression as determined by semantic
3615 /// analysis. These types may differ slightly. For example, in C++ one
3616 /// can cast to a reference type, which indicates that the resulting
3617 /// expression will be an lvalue or xvalue. The reference type, however,
3618 /// will not be used as the type of the expression.
3619 class ExplicitCastExpr : public CastExpr {
3620 /// TInfo - Source type info for the (written) type
3621 /// this expression is casting to.
3622 TypeSourceInfo *TInfo;
3623
3624 protected:
ExplicitCastExpr(StmtClass SC,QualType exprTy,ExprValueKind VK,CastKind kind,Expr * op,unsigned PathSize,bool HasFPFeatures,TypeSourceInfo * writtenTy)3625 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3626 CastKind kind, Expr *op, unsigned PathSize,
3627 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3628 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3629 TInfo(writtenTy) {}
3630
3631 /// Construct an empty explicit cast.
ExplicitCastExpr(StmtClass SC,EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3632 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3633 bool HasFPFeatures)
3634 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3635
3636 public:
3637 /// getTypeInfoAsWritten - Returns the type source info for the type
3638 /// that this expression is casting to.
getTypeInfoAsWritten()3639 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
setTypeInfoAsWritten(TypeSourceInfo * writtenTy)3640 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3641
3642 /// getTypeAsWritten - Returns the type that this expression is
3643 /// casting to, as written in the source code.
getTypeAsWritten()3644 QualType getTypeAsWritten() const { return TInfo->getType(); }
3645
classof(const Stmt * T)3646 static bool classof(const Stmt *T) {
3647 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3648 T->getStmtClass() <= lastExplicitCastExprConstant;
3649 }
3650 };
3651
3652 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3653 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3654 /// (Type)expr. For example: @c (int)f.
3655 class CStyleCastExpr final
3656 : public ExplicitCastExpr,
3657 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3658 FPOptionsOverride> {
3659 SourceLocation LPLoc; // the location of the left paren
3660 SourceLocation RPLoc; // the location of the right paren
3661
CStyleCastExpr(QualType exprTy,ExprValueKind vk,CastKind kind,Expr * op,unsigned PathSize,FPOptionsOverride FPO,TypeSourceInfo * writtenTy,SourceLocation l,SourceLocation r)3662 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3663 unsigned PathSize, FPOptionsOverride FPO,
3664 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3665 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3666 FPO.requiresTrailingStorage(), writtenTy),
3667 LPLoc(l), RPLoc(r) {
3668 if (hasStoredFPFeatures())
3669 *getTrailingFPFeatures() = FPO;
3670 }
3671
3672 /// Construct an empty C-style explicit cast.
CStyleCastExpr(EmptyShell Shell,unsigned PathSize,bool HasFPFeatures)3673 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3674 bool HasFPFeatures)
3675 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3676
numTrailingObjects(OverloadToken<CXXBaseSpecifier * >)3677 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3678 return path_size();
3679 }
3680
3681 public:
3682 static CStyleCastExpr *
3683 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3684 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3685 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3686
3687 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3688 unsigned PathSize, bool HasFPFeatures);
3689
getLParenLoc()3690 SourceLocation getLParenLoc() const { return LPLoc; }
setLParenLoc(SourceLocation L)3691 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3692
getRParenLoc()3693 SourceLocation getRParenLoc() const { return RPLoc; }
setRParenLoc(SourceLocation L)3694 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3695
getBeginLoc()3696 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
getEndLoc()3697 SourceLocation getEndLoc() const LLVM_READONLY {
3698 return getSubExpr()->getEndLoc();
3699 }
3700
classof(const Stmt * T)3701 static bool classof(const Stmt *T) {
3702 return T->getStmtClass() == CStyleCastExprClass;
3703 }
3704
3705 friend TrailingObjects;
3706 friend class CastExpr;
3707 };
3708
3709 /// A builtin binary operation expression such as "x + y" or "x <= y".
3710 ///
3711 /// This expression node kind describes a builtin binary operation,
3712 /// such as "x + y" for integer values "x" and "y". The operands will
3713 /// already have been converted to appropriate types (e.g., by
3714 /// performing promotions or conversions).
3715 ///
3716 /// In C++, where operators may be overloaded, a different kind of
3717 /// expression node (CXXOperatorCallExpr) is used to express the
3718 /// invocation of an overloaded operator with operator syntax. Within
3719 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3720 /// used to store an expression "x + y" depends on the subexpressions
3721 /// for x and y. If neither x or y is type-dependent, and the "+"
3722 /// operator resolves to a built-in operation, BinaryOperator will be
3723 /// used to express the computation (x and y may still be
3724 /// value-dependent). If either x or y is type-dependent, or if the
3725 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3726 /// be used to express the computation.
3727 class BinaryOperator : public Expr {
3728 enum { LHS, RHS, END_EXPR };
3729 Stmt *SubExprs[END_EXPR];
3730
3731 public:
3732 typedef BinaryOperatorKind Opcode;
3733
3734 protected:
3735 size_t offsetOfTrailingStorage() const;
3736
3737 /// Return a pointer to the trailing FPOptions
getTrailingFPFeatures()3738 FPOptionsOverride *getTrailingFPFeatures() {
3739 assert(BinaryOperatorBits.HasFPFeatures);
3740 return reinterpret_cast<FPOptionsOverride *>(
3741 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3742 }
getTrailingFPFeatures()3743 const FPOptionsOverride *getTrailingFPFeatures() const {
3744 assert(BinaryOperatorBits.HasFPFeatures);
3745 return reinterpret_cast<const FPOptionsOverride *>(
3746 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3747 }
3748
3749 /// Build a binary operator, assuming that appropriate storage has been
3750 /// allocated for the trailing objects when needed.
3751 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3752 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3753 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3754
3755 /// Construct an empty binary operator.
BinaryOperator(EmptyShell Empty)3756 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3757 BinaryOperatorBits.Opc = BO_Comma;
3758 }
3759
3760 public:
3761 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3762
3763 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3764 Opcode opc, QualType ResTy, ExprValueKind VK,
3765 ExprObjectKind OK, SourceLocation opLoc,
3766 FPOptionsOverride FPFeatures);
getExprLoc()3767 SourceLocation getExprLoc() const { return getOperatorLoc(); }
getOperatorLoc()3768 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
setOperatorLoc(SourceLocation L)3769 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3770
getOpcode()3771 Opcode getOpcode() const {
3772 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3773 }
setOpcode(Opcode Opc)3774 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3775
getLHS()3776 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)3777 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()3778 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)3779 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3780
getBeginLoc()3781 SourceLocation getBeginLoc() const LLVM_READONLY {
3782 return getLHS()->getBeginLoc();
3783 }
getEndLoc()3784 SourceLocation getEndLoc() const LLVM_READONLY {
3785 return getRHS()->getEndLoc();
3786 }
3787
3788 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3789 /// corresponds to, e.g. "<<=".
3790 static StringRef getOpcodeStr(Opcode Op);
3791
getOpcodeStr()3792 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3793
3794 /// Retrieve the binary opcode that corresponds to the given
3795 /// overloaded operator.
3796 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3797
3798 /// Retrieve the overloaded operator kind that corresponds to
3799 /// the given binary opcode.
3800 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3801
3802 /// predicates to categorize the respective opcodes.
isPtrMemOp(Opcode Opc)3803 static bool isPtrMemOp(Opcode Opc) {
3804 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3805 }
isPtrMemOp()3806 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3807
isMultiplicativeOp(Opcode Opc)3808 static bool isMultiplicativeOp(Opcode Opc) {
3809 return Opc >= BO_Mul && Opc <= BO_Rem;
3810 }
isMultiplicativeOp()3811 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
isAdditiveOp(Opcode Opc)3812 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
isAdditiveOp()3813 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
isShiftOp(Opcode Opc)3814 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
isShiftOp()3815 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3816
isBitwiseOp(Opcode Opc)3817 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
isBitwiseOp()3818 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3819
isRelationalOp(Opcode Opc)3820 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
isRelationalOp()3821 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3822
isEqualityOp(Opcode Opc)3823 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
isEqualityOp()3824 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3825
isComparisonOp(Opcode Opc)3826 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
isComparisonOp()3827 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3828
isCommaOp(Opcode Opc)3829 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
isCommaOp()3830 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3831
negateComparisonOp(Opcode Opc)3832 static Opcode negateComparisonOp(Opcode Opc) {
3833 switch (Opc) {
3834 default:
3835 llvm_unreachable("Not a comparison operator.");
3836 case BO_LT: return BO_GE;
3837 case BO_GT: return BO_LE;
3838 case BO_LE: return BO_GT;
3839 case BO_GE: return BO_LT;
3840 case BO_EQ: return BO_NE;
3841 case BO_NE: return BO_EQ;
3842 }
3843 }
3844
reverseComparisonOp(Opcode Opc)3845 static Opcode reverseComparisonOp(Opcode Opc) {
3846 switch (Opc) {
3847 default:
3848 llvm_unreachable("Not a comparison operator.");
3849 case BO_LT: return BO_GT;
3850 case BO_GT: return BO_LT;
3851 case BO_LE: return BO_GE;
3852 case BO_GE: return BO_LE;
3853 case BO_EQ:
3854 case BO_NE:
3855 return Opc;
3856 }
3857 }
3858
isLogicalOp(Opcode Opc)3859 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
isLogicalOp()3860 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3861
isAssignmentOp(Opcode Opc)3862 static bool isAssignmentOp(Opcode Opc) {
3863 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3864 }
isAssignmentOp()3865 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3866
isCompoundAssignmentOp(Opcode Opc)3867 static bool isCompoundAssignmentOp(Opcode Opc) {
3868 return Opc > BO_Assign && Opc <= BO_OrAssign;
3869 }
isCompoundAssignmentOp()3870 bool isCompoundAssignmentOp() const {
3871 return isCompoundAssignmentOp(getOpcode());
3872 }
getOpForCompoundAssignment(Opcode Opc)3873 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3874 assert(isCompoundAssignmentOp(Opc));
3875 if (Opc >= BO_AndAssign)
3876 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3877 else
3878 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3879 }
3880
isShiftAssignOp(Opcode Opc)3881 static bool isShiftAssignOp(Opcode Opc) {
3882 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3883 }
isShiftAssignOp()3884 bool isShiftAssignOp() const {
3885 return isShiftAssignOp(getOpcode());
3886 }
3887
3888 // Return true if a binary operator using the specified opcode and operands
3889 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3890 // integer to a pointer.
3891 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3892 Expr *LHS, Expr *RHS);
3893
classof(const Stmt * S)3894 static bool classof(const Stmt *S) {
3895 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3896 S->getStmtClass() <= lastBinaryOperatorConstant;
3897 }
3898
3899 // Iterators
children()3900 child_range children() {
3901 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3902 }
children()3903 const_child_range children() const {
3904 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3905 }
3906
3907 /// Set and fetch the bit that shows whether FPFeatures needs to be
3908 /// allocated in Trailing Storage
setHasStoredFPFeatures(bool B)3909 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
hasStoredFPFeatures()3910 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3911
3912 /// Get FPFeatures from trailing storage
getStoredFPFeatures()3913 FPOptionsOverride getStoredFPFeatures() const {
3914 assert(hasStoredFPFeatures());
3915 return *getTrailingFPFeatures();
3916 }
3917 /// Set FPFeatures in trailing storage, used only by Serialization
setStoredFPFeatures(FPOptionsOverride F)3918 void setStoredFPFeatures(FPOptionsOverride F) {
3919 assert(BinaryOperatorBits.HasFPFeatures);
3920 *getTrailingFPFeatures() = F;
3921 }
3922
3923 // Get the FP features status of this operator. Only meaningful for
3924 // operations on floating point types.
getFPFeaturesInEffect(const LangOptions & LO)3925 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3926 if (BinaryOperatorBits.HasFPFeatures)
3927 return getStoredFPFeatures().applyOverrides(LO);
3928 return FPOptions::defaultWithoutTrailingStorage(LO);
3929 }
3930
3931 // This is used in ASTImporter
getFPFeatures(const LangOptions & LO)3932 FPOptionsOverride getFPFeatures(const LangOptions &LO) const {
3933 if (BinaryOperatorBits.HasFPFeatures)
3934 return getStoredFPFeatures();
3935 return FPOptionsOverride();
3936 }
3937
3938 // Get the FP contractability status of this operator. Only meaningful for
3939 // operations on floating point types.
isFPContractableWithinStatement(const LangOptions & LO)3940 bool isFPContractableWithinStatement(const LangOptions &LO) const {
3941 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
3942 }
3943
3944 // Get the FENV_ACCESS status of this operator. Only meaningful for
3945 // operations on floating point types.
isFEnvAccessOn(const LangOptions & LO)3946 bool isFEnvAccessOn(const LangOptions &LO) const {
3947 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
3948 }
3949
3950 protected:
3951 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3952 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3953 SourceLocation opLoc, FPOptionsOverride FPFeatures,
3954 bool dead2);
3955
3956 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
BinaryOperator(StmtClass SC,EmptyShell Empty)3957 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
3958 BinaryOperatorBits.Opc = BO_MulAssign;
3959 }
3960
3961 /// Return the size in bytes needed for the trailing objects.
3962 /// Used to allocate the right amount of storage.
sizeOfTrailingObjects(bool HasFPFeatures)3963 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
3964 return HasFPFeatures * sizeof(FPOptionsOverride);
3965 }
3966 };
3967
3968 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3969 /// track of the type the operation is performed in. Due to the semantics of
3970 /// these operators, the operands are promoted, the arithmetic performed, an
3971 /// implicit conversion back to the result type done, then the assignment takes
3972 /// place. This captures the intermediate type which the computation is done
3973 /// in.
3974 class CompoundAssignOperator : public BinaryOperator {
3975 QualType ComputationLHSType;
3976 QualType ComputationResultType;
3977
3978 /// Construct an empty CompoundAssignOperator.
CompoundAssignOperator(const ASTContext & C,EmptyShell Empty,bool hasFPFeatures)3979 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
3980 bool hasFPFeatures)
3981 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
3982
3983 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)3984 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
3985 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
3986 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
3987 QualType CompLHSType, QualType CompResultType)
3988 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3989 true),
3990 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
3991 assert(isCompoundAssignmentOp() &&
3992 "Only should be used for compound assignments");
3993 }
3994
3995 public:
3996 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
3997 bool hasFPFeatures);
3998
3999 static CompoundAssignOperator *
4000 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4001 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4002 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4003 QualType CompResultType = QualType());
4004
4005 // The two computation types are the type the LHS is converted
4006 // to for the computation and the type of the result; the two are
4007 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
getComputationLHSType()4008 QualType getComputationLHSType() const { return ComputationLHSType; }
setComputationLHSType(QualType T)4009 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4010
getComputationResultType()4011 QualType getComputationResultType() const { return ComputationResultType; }
setComputationResultType(QualType T)4012 void setComputationResultType(QualType T) { ComputationResultType = T; }
4013
classof(const Stmt * S)4014 static bool classof(const Stmt *S) {
4015 return S->getStmtClass() == CompoundAssignOperatorClass;
4016 }
4017 };
4018
offsetOfTrailingStorage()4019 inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4020 assert(BinaryOperatorBits.HasFPFeatures);
4021 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4022 : sizeof(BinaryOperator);
4023 }
4024
4025 /// AbstractConditionalOperator - An abstract base class for
4026 /// ConditionalOperator and BinaryConditionalOperator.
4027 class AbstractConditionalOperator : public Expr {
4028 SourceLocation QuestionLoc, ColonLoc;
4029 friend class ASTStmtReader;
4030
4031 protected:
AbstractConditionalOperator(StmtClass SC,QualType T,ExprValueKind VK,ExprObjectKind OK,SourceLocation qloc,SourceLocation cloc)4032 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4033 ExprObjectKind OK, SourceLocation qloc,
4034 SourceLocation cloc)
4035 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4036
AbstractConditionalOperator(StmtClass SC,EmptyShell Empty)4037 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4038 : Expr(SC, Empty) { }
4039
4040 public:
4041 // getCond - Return the expression representing the condition for
4042 // the ?: operator.
4043 Expr *getCond() const;
4044
4045 // getTrueExpr - Return the subexpression representing the value of
4046 // the expression if the condition evaluates to true.
4047 Expr *getTrueExpr() const;
4048
4049 // getFalseExpr - Return the subexpression representing the value of
4050 // the expression if the condition evaluates to false. This is
4051 // the same as getRHS.
4052 Expr *getFalseExpr() const;
4053
getQuestionLoc()4054 SourceLocation getQuestionLoc() const { return QuestionLoc; }
getColonLoc()4055 SourceLocation getColonLoc() const { return ColonLoc; }
4056
classof(const Stmt * T)4057 static bool classof(const Stmt *T) {
4058 return T->getStmtClass() == ConditionalOperatorClass ||
4059 T->getStmtClass() == BinaryConditionalOperatorClass;
4060 }
4061 };
4062
4063 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
4064 /// middle" extension is a BinaryConditionalOperator.
4065 class ConditionalOperator : public AbstractConditionalOperator {
4066 enum { COND, LHS, RHS, END_EXPR };
4067 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4068
4069 friend class ASTStmtReader;
4070 public:
ConditionalOperator(Expr * cond,SourceLocation QLoc,Expr * lhs,SourceLocation CLoc,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK)4071 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4072 SourceLocation CLoc, Expr *rhs, QualType t,
4073 ExprValueKind VK, ExprObjectKind OK)
4074 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4075 CLoc) {
4076 SubExprs[COND] = cond;
4077 SubExprs[LHS] = lhs;
4078 SubExprs[RHS] = rhs;
4079 setDependence(computeDependence(this));
4080 }
4081
4082 /// Build an empty conditional operator.
ConditionalOperator(EmptyShell Empty)4083 explicit ConditionalOperator(EmptyShell Empty)
4084 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4085
4086 // getCond - Return the expression representing the condition for
4087 // the ?: operator.
getCond()4088 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4089
4090 // getTrueExpr - Return the subexpression representing the value of
4091 // the expression if the condition evaluates to true.
getTrueExpr()4092 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4093
4094 // getFalseExpr - Return the subexpression representing the value of
4095 // the expression if the condition evaluates to false. This is
4096 // the same as getRHS.
getFalseExpr()4097 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4098
getLHS()4099 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
getRHS()4100 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4101
getBeginLoc()4102 SourceLocation getBeginLoc() const LLVM_READONLY {
4103 return getCond()->getBeginLoc();
4104 }
getEndLoc()4105 SourceLocation getEndLoc() const LLVM_READONLY {
4106 return getRHS()->getEndLoc();
4107 }
4108
classof(const Stmt * T)4109 static bool classof(const Stmt *T) {
4110 return T->getStmtClass() == ConditionalOperatorClass;
4111 }
4112
4113 // Iterators
children()4114 child_range children() {
4115 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4116 }
children()4117 const_child_range children() const {
4118 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4119 }
4120 };
4121
4122 /// BinaryConditionalOperator - The GNU extension to the conditional
4123 /// operator which allows the middle operand to be omitted.
4124 ///
4125 /// This is a different expression kind on the assumption that almost
4126 /// every client ends up needing to know that these are different.
4127 class BinaryConditionalOperator : public AbstractConditionalOperator {
4128 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4129
4130 /// - the common condition/left-hand-side expression, which will be
4131 /// evaluated as the opaque value
4132 /// - the condition, expressed in terms of the opaque value
4133 /// - the left-hand-side, expressed in terms of the opaque value
4134 /// - the right-hand-side
4135 Stmt *SubExprs[NUM_SUBEXPRS];
4136 OpaqueValueExpr *OpaqueValue;
4137
4138 friend class ASTStmtReader;
4139 public:
BinaryConditionalOperator(Expr * common,OpaqueValueExpr * opaqueValue,Expr * cond,Expr * lhs,Expr * rhs,SourceLocation qloc,SourceLocation cloc,QualType t,ExprValueKind VK,ExprObjectKind OK)4140 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4141 Expr *cond, Expr *lhs, Expr *rhs,
4142 SourceLocation qloc, SourceLocation cloc,
4143 QualType t, ExprValueKind VK, ExprObjectKind OK)
4144 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4145 qloc, cloc),
4146 OpaqueValue(opaqueValue) {
4147 SubExprs[COMMON] = common;
4148 SubExprs[COND] = cond;
4149 SubExprs[LHS] = lhs;
4150 SubExprs[RHS] = rhs;
4151 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4152 setDependence(computeDependence(this));
4153 }
4154
4155 /// Build an empty conditional operator.
BinaryConditionalOperator(EmptyShell Empty)4156 explicit BinaryConditionalOperator(EmptyShell Empty)
4157 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4158
4159 /// getCommon - Return the common expression, written to the
4160 /// left of the condition. The opaque value will be bound to the
4161 /// result of this expression.
getCommon()4162 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4163
4164 /// getOpaqueValue - Return the opaque value placeholder.
getOpaqueValue()4165 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4166
4167 /// getCond - Return the condition expression; this is defined
4168 /// in terms of the opaque value.
getCond()4169 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4170
4171 /// getTrueExpr - Return the subexpression which will be
4172 /// evaluated if the condition evaluates to true; this is defined
4173 /// in terms of the opaque value.
getTrueExpr()4174 Expr *getTrueExpr() const {
4175 return cast<Expr>(SubExprs[LHS]);
4176 }
4177
4178 /// getFalseExpr - Return the subexpression which will be
4179 /// evaluated if the condnition evaluates to false; this is
4180 /// defined in terms of the opaque value.
getFalseExpr()4181 Expr *getFalseExpr() const {
4182 return cast<Expr>(SubExprs[RHS]);
4183 }
4184
getBeginLoc()4185 SourceLocation getBeginLoc() const LLVM_READONLY {
4186 return getCommon()->getBeginLoc();
4187 }
getEndLoc()4188 SourceLocation getEndLoc() const LLVM_READONLY {
4189 return getFalseExpr()->getEndLoc();
4190 }
4191
classof(const Stmt * T)4192 static bool classof(const Stmt *T) {
4193 return T->getStmtClass() == BinaryConditionalOperatorClass;
4194 }
4195
4196 // Iterators
children()4197 child_range children() {
4198 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4199 }
children()4200 const_child_range children() const {
4201 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4202 }
4203 };
4204
getCond()4205 inline Expr *AbstractConditionalOperator::getCond() const {
4206 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4207 return co->getCond();
4208 return cast<BinaryConditionalOperator>(this)->getCond();
4209 }
4210
getTrueExpr()4211 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4212 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4213 return co->getTrueExpr();
4214 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4215 }
4216
getFalseExpr()4217 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4218 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4219 return co->getFalseExpr();
4220 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4221 }
4222
4223 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
4224 class AddrLabelExpr : public Expr {
4225 SourceLocation AmpAmpLoc, LabelLoc;
4226 LabelDecl *Label;
4227 public:
AddrLabelExpr(SourceLocation AALoc,SourceLocation LLoc,LabelDecl * L,QualType t)4228 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4229 QualType t)
4230 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary), AmpAmpLoc(AALoc),
4231 LabelLoc(LLoc), Label(L) {
4232 setDependence(ExprDependence::None);
4233 }
4234
4235 /// Build an empty address of a label expression.
AddrLabelExpr(EmptyShell Empty)4236 explicit AddrLabelExpr(EmptyShell Empty)
4237 : Expr(AddrLabelExprClass, Empty) { }
4238
getAmpAmpLoc()4239 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
setAmpAmpLoc(SourceLocation L)4240 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
getLabelLoc()4241 SourceLocation getLabelLoc() const { return LabelLoc; }
setLabelLoc(SourceLocation L)4242 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4243
getBeginLoc()4244 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
getEndLoc()4245 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4246
getLabel()4247 LabelDecl *getLabel() const { return Label; }
setLabel(LabelDecl * L)4248 void setLabel(LabelDecl *L) { Label = L; }
4249
classof(const Stmt * T)4250 static bool classof(const Stmt *T) {
4251 return T->getStmtClass() == AddrLabelExprClass;
4252 }
4253
4254 // Iterators
children()4255 child_range children() {
4256 return child_range(child_iterator(), child_iterator());
4257 }
children()4258 const_child_range children() const {
4259 return const_child_range(const_child_iterator(), const_child_iterator());
4260 }
4261 };
4262
4263 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4264 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4265 /// takes the value of the last subexpression.
4266 ///
4267 /// A StmtExpr is always an r-value; values "returned" out of a
4268 /// StmtExpr will be copied.
4269 class StmtExpr : public Expr {
4270 Stmt *SubStmt;
4271 SourceLocation LParenLoc, RParenLoc;
4272 public:
StmtExpr(CompoundStmt * SubStmt,QualType T,SourceLocation LParenLoc,SourceLocation RParenLoc,unsigned TemplateDepth)4273 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4274 SourceLocation RParenLoc, unsigned TemplateDepth)
4275 : Expr(StmtExprClass, T, VK_RValue, OK_Ordinary), SubStmt(SubStmt),
4276 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4277 setDependence(computeDependence(this, TemplateDepth));
4278 // FIXME: A templated statement expression should have an associated
4279 // DeclContext so that nested declarations always have a dependent context.
4280 StmtExprBits.TemplateDepth = TemplateDepth;
4281 }
4282
4283 /// Build an empty statement expression.
StmtExpr(EmptyShell Empty)4284 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4285
getSubStmt()4286 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
getSubStmt()4287 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
setSubStmt(CompoundStmt * S)4288 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4289
getBeginLoc()4290 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
getEndLoc()4291 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4292
getLParenLoc()4293 SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)4294 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
getRParenLoc()4295 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4296 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4297
getTemplateDepth()4298 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4299
classof(const Stmt * T)4300 static bool classof(const Stmt *T) {
4301 return T->getStmtClass() == StmtExprClass;
4302 }
4303
4304 // Iterators
children()4305 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
children()4306 const_child_range children() const {
4307 return const_child_range(&SubStmt, &SubStmt + 1);
4308 }
4309 };
4310
4311 /// ShuffleVectorExpr - clang-specific builtin-in function
4312 /// __builtin_shufflevector.
4313 /// This AST node represents a operator that does a constant
4314 /// shuffle, similar to LLVM's shufflevector instruction. It takes
4315 /// two vectors and a variable number of constant indices,
4316 /// and returns the appropriately shuffled vector.
4317 class ShuffleVectorExpr : public Expr {
4318 SourceLocation BuiltinLoc, RParenLoc;
4319
4320 // SubExprs - the list of values passed to the __builtin_shufflevector
4321 // function. The first two are vectors, and the rest are constant
4322 // indices. The number of values in this list is always
4323 // 2+the number of indices in the vector type.
4324 Stmt **SubExprs;
4325 unsigned NumExprs;
4326
4327 public:
4328 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4329 SourceLocation BLoc, SourceLocation RP);
4330
4331 /// Build an empty vector-shuffle expression.
ShuffleVectorExpr(EmptyShell Empty)4332 explicit ShuffleVectorExpr(EmptyShell Empty)
4333 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4334
getBuiltinLoc()4335 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4336 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4337
getRParenLoc()4338 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4339 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4340
getBeginLoc()4341 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4342 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4343
classof(const Stmt * T)4344 static bool classof(const Stmt *T) {
4345 return T->getStmtClass() == ShuffleVectorExprClass;
4346 }
4347
4348 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4349 /// constant expression, the actual arguments passed in, and the function
4350 /// pointers.
getNumSubExprs()4351 unsigned getNumSubExprs() const { return NumExprs; }
4352
4353 /// Retrieve the array of expressions.
getSubExprs()4354 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4355
4356 /// getExpr - Return the Expr at the specified index.
getExpr(unsigned Index)4357 Expr *getExpr(unsigned Index) {
4358 assert((Index < NumExprs) && "Arg access out of range!");
4359 return cast<Expr>(SubExprs[Index]);
4360 }
getExpr(unsigned Index)4361 const Expr *getExpr(unsigned Index) const {
4362 assert((Index < NumExprs) && "Arg access out of range!");
4363 return cast<Expr>(SubExprs[Index]);
4364 }
4365
4366 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4367
getShuffleMaskIdx(const ASTContext & Ctx,unsigned N)4368 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4369 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4370 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4371 }
4372
4373 // Iterators
children()4374 child_range children() {
4375 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4376 }
children()4377 const_child_range children() const {
4378 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4379 }
4380 };
4381
4382 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4383 /// This AST node provides support for converting a vector type to another
4384 /// vector type of the same arity.
4385 class ConvertVectorExpr : public Expr {
4386 private:
4387 Stmt *SrcExpr;
4388 TypeSourceInfo *TInfo;
4389 SourceLocation BuiltinLoc, RParenLoc;
4390
4391 friend class ASTReader;
4392 friend class ASTStmtReader;
ConvertVectorExpr(EmptyShell Empty)4393 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4394
4395 public:
ConvertVectorExpr(Expr * SrcExpr,TypeSourceInfo * TI,QualType DstType,ExprValueKind VK,ExprObjectKind OK,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4396 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4397 ExprValueKind VK, ExprObjectKind OK,
4398 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4399 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4400 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4401 setDependence(computeDependence(this));
4402 }
4403
4404 /// getSrcExpr - Return the Expr to be converted.
getSrcExpr()4405 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4406
4407 /// getTypeSourceInfo - Return the destination type.
getTypeSourceInfo()4408 TypeSourceInfo *getTypeSourceInfo() const {
4409 return TInfo;
4410 }
setTypeSourceInfo(TypeSourceInfo * ti)4411 void setTypeSourceInfo(TypeSourceInfo *ti) {
4412 TInfo = ti;
4413 }
4414
4415 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
getBuiltinLoc()4416 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4417
4418 /// getRParenLoc - Return the location of final right parenthesis.
getRParenLoc()4419 SourceLocation getRParenLoc() const { return RParenLoc; }
4420
getBeginLoc()4421 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4422 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4423
classof(const Stmt * T)4424 static bool classof(const Stmt *T) {
4425 return T->getStmtClass() == ConvertVectorExprClass;
4426 }
4427
4428 // Iterators
children()4429 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
children()4430 const_child_range children() const {
4431 return const_child_range(&SrcExpr, &SrcExpr + 1);
4432 }
4433 };
4434
4435 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4436 /// This AST node is similar to the conditional operator (?:) in C, with
4437 /// the following exceptions:
4438 /// - the test expression must be a integer constant expression.
4439 /// - the expression returned acts like the chosen subexpression in every
4440 /// visible way: the type is the same as that of the chosen subexpression,
4441 /// and all predicates (whether it's an l-value, whether it's an integer
4442 /// constant expression, etc.) return the same result as for the chosen
4443 /// sub-expression.
4444 class ChooseExpr : public Expr {
4445 enum { COND, LHS, RHS, END_EXPR };
4446 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4447 SourceLocation BuiltinLoc, RParenLoc;
4448 bool CondIsTrue;
4449 public:
ChooseExpr(SourceLocation BLoc,Expr * cond,Expr * lhs,Expr * rhs,QualType t,ExprValueKind VK,ExprObjectKind OK,SourceLocation RP,bool condIsTrue)4450 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4451 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4452 bool condIsTrue)
4453 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4454 CondIsTrue(condIsTrue) {
4455 SubExprs[COND] = cond;
4456 SubExprs[LHS] = lhs;
4457 SubExprs[RHS] = rhs;
4458
4459 setDependence(computeDependence(this));
4460 }
4461
4462 /// Build an empty __builtin_choose_expr.
ChooseExpr(EmptyShell Empty)4463 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4464
4465 /// isConditionTrue - Return whether the condition is true (i.e. not
4466 /// equal to zero).
isConditionTrue()4467 bool isConditionTrue() const {
4468 assert(!isConditionDependent() &&
4469 "Dependent condition isn't true or false");
4470 return CondIsTrue;
4471 }
setIsConditionTrue(bool isTrue)4472 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4473
isConditionDependent()4474 bool isConditionDependent() const {
4475 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4476 }
4477
4478 /// getChosenSubExpr - Return the subexpression chosen according to the
4479 /// condition.
getChosenSubExpr()4480 Expr *getChosenSubExpr() const {
4481 return isConditionTrue() ? getLHS() : getRHS();
4482 }
4483
getCond()4484 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
setCond(Expr * E)4485 void setCond(Expr *E) { SubExprs[COND] = E; }
getLHS()4486 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
setLHS(Expr * E)4487 void setLHS(Expr *E) { SubExprs[LHS] = E; }
getRHS()4488 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
setRHS(Expr * E)4489 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4490
getBuiltinLoc()4491 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4492 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4493
getRParenLoc()4494 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4495 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4496
getBeginLoc()4497 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4498 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4499
classof(const Stmt * T)4500 static bool classof(const Stmt *T) {
4501 return T->getStmtClass() == ChooseExprClass;
4502 }
4503
4504 // Iterators
children()4505 child_range children() {
4506 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4507 }
children()4508 const_child_range children() const {
4509 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4510 }
4511 };
4512
4513 /// GNUNullExpr - Implements the GNU __null extension, which is a name
4514 /// for a null pointer constant that has integral type (e.g., int or
4515 /// long) and is the same size and alignment as a pointer. The __null
4516 /// extension is typically only used by system headers, which define
4517 /// NULL as __null in C++ rather than using 0 (which is an integer
4518 /// that may not match the size of a pointer).
4519 class GNUNullExpr : public Expr {
4520 /// TokenLoc - The location of the __null keyword.
4521 SourceLocation TokenLoc;
4522
4523 public:
GNUNullExpr(QualType Ty,SourceLocation Loc)4524 GNUNullExpr(QualType Ty, SourceLocation Loc)
4525 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary), TokenLoc(Loc) {
4526 setDependence(ExprDependence::None);
4527 }
4528
4529 /// Build an empty GNU __null expression.
GNUNullExpr(EmptyShell Empty)4530 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4531
4532 /// getTokenLocation - The location of the __null token.
getTokenLocation()4533 SourceLocation getTokenLocation() const { return TokenLoc; }
setTokenLocation(SourceLocation L)4534 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4535
getBeginLoc()4536 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
getEndLoc()4537 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4538
classof(const Stmt * T)4539 static bool classof(const Stmt *T) {
4540 return T->getStmtClass() == GNUNullExprClass;
4541 }
4542
4543 // Iterators
children()4544 child_range children() {
4545 return child_range(child_iterator(), child_iterator());
4546 }
children()4547 const_child_range children() const {
4548 return const_child_range(const_child_iterator(), const_child_iterator());
4549 }
4550 };
4551
4552 /// Represents a call to the builtin function \c __builtin_va_arg.
4553 class VAArgExpr : public Expr {
4554 Stmt *Val;
4555 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4556 SourceLocation BuiltinLoc, RParenLoc;
4557 public:
VAArgExpr(SourceLocation BLoc,Expr * e,TypeSourceInfo * TInfo,SourceLocation RPLoc,QualType t,bool IsMS)4558 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4559 SourceLocation RPLoc, QualType t, bool IsMS)
4560 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary), Val(e),
4561 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4562 setDependence(computeDependence(this));
4563 }
4564
4565 /// Create an empty __builtin_va_arg expression.
VAArgExpr(EmptyShell Empty)4566 explicit VAArgExpr(EmptyShell Empty)
4567 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4568
getSubExpr()4569 const Expr *getSubExpr() const { return cast<Expr>(Val); }
getSubExpr()4570 Expr *getSubExpr() { return cast<Expr>(Val); }
setSubExpr(Expr * E)4571 void setSubExpr(Expr *E) { Val = E; }
4572
4573 /// Returns whether this is really a Win64 ABI va_arg expression.
isMicrosoftABI()4574 bool isMicrosoftABI() const { return TInfo.getInt(); }
setIsMicrosoftABI(bool IsMS)4575 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4576
getWrittenTypeInfo()4577 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
setWrittenTypeInfo(TypeSourceInfo * TI)4578 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4579
getBuiltinLoc()4580 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
setBuiltinLoc(SourceLocation L)4581 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4582
getRParenLoc()4583 SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)4584 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4585
getBeginLoc()4586 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
getEndLoc()4587 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4588
classof(const Stmt * T)4589 static bool classof(const Stmt *T) {
4590 return T->getStmtClass() == VAArgExprClass;
4591 }
4592
4593 // Iterators
children()4594 child_range children() { return child_range(&Val, &Val+1); }
children()4595 const_child_range children() const {
4596 return const_child_range(&Val, &Val + 1);
4597 }
4598 };
4599
4600 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4601 /// __builtin_FUNCTION(), or __builtin_FILE().
4602 class SourceLocExpr final : public Expr {
4603 SourceLocation BuiltinLoc, RParenLoc;
4604 DeclContext *ParentContext;
4605
4606 public:
4607 enum IdentKind { Function, File, Line, Column };
4608
4609 SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
4610 SourceLocation RParenLoc, DeclContext *Context);
4611
4612 /// Build an empty call expression.
SourceLocExpr(EmptyShell Empty)4613 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4614
4615 /// Return the result of evaluating this SourceLocExpr in the specified
4616 /// (and possibly null) default argument or initialization context.
4617 APValue EvaluateInContext(const ASTContext &Ctx,
4618 const Expr *DefaultExpr) const;
4619
4620 /// Return a string representing the name of the specific builtin function.
4621 StringRef getBuiltinStr() const;
4622
getIdentKind()4623 IdentKind getIdentKind() const {
4624 return static_cast<IdentKind>(SourceLocExprBits.Kind);
4625 }
4626
isStringType()4627 bool isStringType() const {
4628 switch (getIdentKind()) {
4629 case File:
4630 case Function:
4631 return true;
4632 case Line:
4633 case Column:
4634 return false;
4635 }
4636 llvm_unreachable("unknown source location expression kind");
4637 }
isIntType()4638 bool isIntType() const LLVM_READONLY { return !isStringType(); }
4639
4640 /// If the SourceLocExpr has been resolved return the subexpression
4641 /// representing the resolved value. Otherwise return null.
getParentContext()4642 const DeclContext *getParentContext() const { return ParentContext; }
getParentContext()4643 DeclContext *getParentContext() { return ParentContext; }
4644
getLocation()4645 SourceLocation getLocation() const { return BuiltinLoc; }
getBeginLoc()4646 SourceLocation getBeginLoc() const { return BuiltinLoc; }
getEndLoc()4647 SourceLocation getEndLoc() const { return RParenLoc; }
4648
children()4649 child_range children() {
4650 return child_range(child_iterator(), child_iterator());
4651 }
4652
children()4653 const_child_range children() const {
4654 return const_child_range(child_iterator(), child_iterator());
4655 }
4656
classof(const Stmt * T)4657 static bool classof(const Stmt *T) {
4658 return T->getStmtClass() == SourceLocExprClass;
4659 }
4660
4661 private:
4662 friend class ASTStmtReader;
4663 };
4664
4665 /// Describes an C or C++ initializer list.
4666 ///
4667 /// InitListExpr describes an initializer list, which can be used to
4668 /// initialize objects of different types, including
4669 /// struct/class/union types, arrays, and vectors. For example:
4670 ///
4671 /// @code
4672 /// struct foo x = { 1, { 2, 3 } };
4673 /// @endcode
4674 ///
4675 /// Prior to semantic analysis, an initializer list will represent the
4676 /// initializer list as written by the user, but will have the
4677 /// placeholder type "void". This initializer list is called the
4678 /// syntactic form of the initializer, and may contain C99 designated
4679 /// initializers (represented as DesignatedInitExprs), initializations
4680 /// of subobject members without explicit braces, and so on. Clients
4681 /// interested in the original syntax of the initializer list should
4682 /// use the syntactic form of the initializer list.
4683 ///
4684 /// After semantic analysis, the initializer list will represent the
4685 /// semantic form of the initializer, where the initializations of all
4686 /// subobjects are made explicit with nested InitListExpr nodes and
4687 /// C99 designators have been eliminated by placing the designated
4688 /// initializations into the subobject they initialize. Additionally,
4689 /// any "holes" in the initialization, where no initializer has been
4690 /// specified for a particular subobject, will be replaced with
4691 /// implicitly-generated ImplicitValueInitExpr expressions that
4692 /// value-initialize the subobjects. Note, however, that the
4693 /// initializer lists may still have fewer initializers than there are
4694 /// elements to initialize within the object.
4695 ///
4696 /// After semantic analysis has completed, given an initializer list,
4697 /// method isSemanticForm() returns true if and only if this is the
4698 /// semantic form of the initializer list (note: the same AST node
4699 /// may at the same time be the syntactic form).
4700 /// Given the semantic form of the initializer list, one can retrieve
4701 /// the syntactic form of that initializer list (when different)
4702 /// using method getSyntacticForm(); the method returns null if applied
4703 /// to a initializer list which is already in syntactic form.
4704 /// Similarly, given the syntactic form (i.e., an initializer list such
4705 /// that isSemanticForm() returns false), one can retrieve the semantic
4706 /// form using method getSemanticForm().
4707 /// Since many initializer lists have the same syntactic and semantic forms,
4708 /// getSyntacticForm() may return NULL, indicating that the current
4709 /// semantic initializer list also serves as its syntactic form.
4710 class InitListExpr : public Expr {
4711 // FIXME: Eliminate this vector in favor of ASTContext allocation
4712 typedef ASTVector<Stmt *> InitExprsTy;
4713 InitExprsTy InitExprs;
4714 SourceLocation LBraceLoc, RBraceLoc;
4715
4716 /// The alternative form of the initializer list (if it exists).
4717 /// The int part of the pair stores whether this initializer list is
4718 /// in semantic form. If not null, the pointer points to:
4719 /// - the syntactic form, if this is in semantic form;
4720 /// - the semantic form, if this is in syntactic form.
4721 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4722
4723 /// Either:
4724 /// If this initializer list initializes an array with more elements than
4725 /// there are initializers in the list, specifies an expression to be used
4726 /// for value initialization of the rest of the elements.
4727 /// Or
4728 /// If this initializer list initializes a union, specifies which
4729 /// field within the union will be initialized.
4730 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4731
4732 public:
4733 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4734 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4735
4736 /// Build an empty initializer list.
InitListExpr(EmptyShell Empty)4737 explicit InitListExpr(EmptyShell Empty)
4738 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4739
getNumInits()4740 unsigned getNumInits() const { return InitExprs.size(); }
4741
4742 /// Retrieve the set of initializers.
getInits()4743 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4744
4745 /// Retrieve the set of initializers.
getInits()4746 Expr * const *getInits() const {
4747 return reinterpret_cast<Expr * const *>(InitExprs.data());
4748 }
4749
inits()4750 ArrayRef<Expr *> inits() {
4751 return llvm::makeArrayRef(getInits(), getNumInits());
4752 }
4753
inits()4754 ArrayRef<Expr *> inits() const {
4755 return llvm::makeArrayRef(getInits(), getNumInits());
4756 }
4757
getInit(unsigned Init)4758 const Expr *getInit(unsigned Init) const {
4759 assert(Init < getNumInits() && "Initializer access out of range!");
4760 return cast_or_null<Expr>(InitExprs[Init]);
4761 }
4762
getInit(unsigned Init)4763 Expr *getInit(unsigned Init) {
4764 assert(Init < getNumInits() && "Initializer access out of range!");
4765 return cast_or_null<Expr>(InitExprs[Init]);
4766 }
4767
setInit(unsigned Init,Expr * expr)4768 void setInit(unsigned Init, Expr *expr) {
4769 assert(Init < getNumInits() && "Initializer access out of range!");
4770 InitExprs[Init] = expr;
4771
4772 if (expr)
4773 setDependence(getDependence() | expr->getDependence());
4774 }
4775
4776 /// Mark the semantic form of the InitListExpr as error when the semantic
4777 /// analysis fails.
markError()4778 void markError() {
4779 assert(isSemanticForm());
4780 setDependence(getDependence() | ExprDependence::ErrorDependent);
4781 }
4782
4783 /// Reserve space for some number of initializers.
4784 void reserveInits(const ASTContext &C, unsigned NumInits);
4785
4786 /// Specify the number of initializers
4787 ///
4788 /// If there are more than @p NumInits initializers, the remaining
4789 /// initializers will be destroyed. If there are fewer than @p
4790 /// NumInits initializers, NULL expressions will be added for the
4791 /// unknown initializers.
4792 void resizeInits(const ASTContext &Context, unsigned NumInits);
4793
4794 /// Updates the initializer at index @p Init with the new
4795 /// expression @p expr, and returns the old expression at that
4796 /// location.
4797 ///
4798 /// When @p Init is out of range for this initializer list, the
4799 /// initializer list will be extended with NULL expressions to
4800 /// accommodate the new entry.
4801 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4802
4803 /// If this initializer list initializes an array with more elements
4804 /// than there are initializers in the list, specifies an expression to be
4805 /// used for value initialization of the rest of the elements.
getArrayFiller()4806 Expr *getArrayFiller() {
4807 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4808 }
getArrayFiller()4809 const Expr *getArrayFiller() const {
4810 return const_cast<InitListExpr *>(this)->getArrayFiller();
4811 }
4812 void setArrayFiller(Expr *filler);
4813
4814 /// Return true if this is an array initializer and its array "filler"
4815 /// has been set.
hasArrayFiller()4816 bool hasArrayFiller() const { return getArrayFiller(); }
4817
4818 /// If this initializes a union, specifies which field in the
4819 /// union to initialize.
4820 ///
4821 /// Typically, this field is the first named field within the
4822 /// union. However, a designated initializer can specify the
4823 /// initialization of a different field within the union.
getInitializedFieldInUnion()4824 FieldDecl *getInitializedFieldInUnion() {
4825 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4826 }
getInitializedFieldInUnion()4827 const FieldDecl *getInitializedFieldInUnion() const {
4828 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4829 }
setInitializedFieldInUnion(FieldDecl * FD)4830 void setInitializedFieldInUnion(FieldDecl *FD) {
4831 assert((FD == nullptr
4832 || getInitializedFieldInUnion() == nullptr
4833 || getInitializedFieldInUnion() == FD)
4834 && "Only one field of a union may be initialized at a time!");
4835 ArrayFillerOrUnionFieldInit = FD;
4836 }
4837
4838 // Explicit InitListExpr's originate from source code (and have valid source
4839 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4840 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4841 // valid source locations too!
isExplicit()4842 bool isExplicit() const {
4843 return LBraceLoc.isValid() && RBraceLoc.isValid();
4844 }
4845
4846 // Is this an initializer for an array of characters, initialized by a string
4847 // literal or an @encode?
4848 bool isStringLiteralInit() const;
4849
4850 /// Is this a transparent initializer list (that is, an InitListExpr that is
4851 /// purely syntactic, and whose semantics are that of the sole contained
4852 /// initializer)?
4853 bool isTransparent() const;
4854
4855 /// Is this the zero initializer {0} in a language which considers it
4856 /// idiomatic?
4857 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4858
getLBraceLoc()4859 SourceLocation getLBraceLoc() const { return LBraceLoc; }
setLBraceLoc(SourceLocation Loc)4860 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
getRBraceLoc()4861 SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation Loc)4862 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4863
isSemanticForm()4864 bool isSemanticForm() const { return AltForm.getInt(); }
getSemanticForm()4865 InitListExpr *getSemanticForm() const {
4866 return isSemanticForm() ? nullptr : AltForm.getPointer();
4867 }
isSyntacticForm()4868 bool isSyntacticForm() const {
4869 return !AltForm.getInt() || !AltForm.getPointer();
4870 }
getSyntacticForm()4871 InitListExpr *getSyntacticForm() const {
4872 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4873 }
4874
setSyntacticForm(InitListExpr * Init)4875 void setSyntacticForm(InitListExpr *Init) {
4876 AltForm.setPointer(Init);
4877 AltForm.setInt(true);
4878 Init->AltForm.setPointer(this);
4879 Init->AltForm.setInt(false);
4880 }
4881
hadArrayRangeDesignator()4882 bool hadArrayRangeDesignator() const {
4883 return InitListExprBits.HadArrayRangeDesignator != 0;
4884 }
4885 void sawArrayRangeDesignator(bool ARD = true) {
4886 InitListExprBits.HadArrayRangeDesignator = ARD;
4887 }
4888
4889 SourceLocation getBeginLoc() const LLVM_READONLY;
4890 SourceLocation getEndLoc() const LLVM_READONLY;
4891
classof(const Stmt * T)4892 static bool classof(const Stmt *T) {
4893 return T->getStmtClass() == InitListExprClass;
4894 }
4895
4896 // Iterators
children()4897 child_range children() {
4898 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4899 return child_range(cast_away_const(CCR.begin()),
4900 cast_away_const(CCR.end()));
4901 }
4902
children()4903 const_child_range children() const {
4904 // FIXME: This does not include the array filler expression.
4905 if (InitExprs.empty())
4906 return const_child_range(const_child_iterator(), const_child_iterator());
4907 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4908 }
4909
4910 typedef InitExprsTy::iterator iterator;
4911 typedef InitExprsTy::const_iterator const_iterator;
4912 typedef InitExprsTy::reverse_iterator reverse_iterator;
4913 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4914
begin()4915 iterator begin() { return InitExprs.begin(); }
begin()4916 const_iterator begin() const { return InitExprs.begin(); }
end()4917 iterator end() { return InitExprs.end(); }
end()4918 const_iterator end() const { return InitExprs.end(); }
rbegin()4919 reverse_iterator rbegin() { return InitExprs.rbegin(); }
rbegin()4920 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
rend()4921