Coverage Report

Created: 2019-02-23 12:57

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