Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/ExprConstant.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
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 implements the Expr constant evaluator.
10
//
11
// Constant expression evaluation produces four main results:
12
//
13
//  * A success/failure flag indicating whether constant folding was successful.
14
//    This is the 'bool' return value used by most of the code in this file. A
15
//    'false' return value indicates that constant folding has failed, and any
16
//    appropriate diagnostic has already been produced.
17
//
18
//  * An evaluated result, valid only if constant folding has not failed.
19
//
20
//  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21
//    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22
//    where it is possible to determine the evaluated result regardless.
23
//
24
//  * A set of notes indicating why the evaluation was not a constant expression
25
//    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26
//    too, why the expression could not be folded.
27
//
28
// If we are checking for a potential constant expression, failure to constant
29
// fold a potential constant sub-expression will be indicated by a 'false'
30
// return value (the expression could not be folded) and no diagnostic (the
31
// expression is not necessarily non-constant).
32
//
33
//===----------------------------------------------------------------------===//
34
35
#include "Interp/Context.h"
36
#include "Interp/Frame.h"
37
#include "Interp/State.h"
38
#include "clang/AST/APValue.h"
39
#include "clang/AST/ASTContext.h"
40
#include "clang/AST/ASTDiagnostic.h"
41
#include "clang/AST/ASTLambda.h"
42
#include "clang/AST/Attr.h"
43
#include "clang/AST/CXXInheritance.h"
44
#include "clang/AST/CharUnits.h"
45
#include "clang/AST/CurrentSourceLocExprScope.h"
46
#include "clang/AST/Expr.h"
47
#include "clang/AST/OSLog.h"
48
#include "clang/AST/OptionalDiagnostic.h"
49
#include "clang/AST/RecordLayout.h"
50
#include "clang/AST/StmtVisitor.h"
51
#include "clang/AST/TypeLoc.h"
52
#include "clang/Basic/Builtins.h"
53
#include "clang/Basic/DiagnosticSema.h"
54
#include "clang/Basic/TargetInfo.h"
55
#include "llvm/ADT/APFixedPoint.h"
56
#include "llvm/ADT/SmallBitVector.h"
57
#include "llvm/ADT/StringExtras.h"
58
#include "llvm/Support/Debug.h"
59
#include "llvm/Support/SaveAndRestore.h"
60
#include "llvm/Support/TimeProfiler.h"
61
#include "llvm/Support/raw_ostream.h"
62
#include <cstring>
63
#include <functional>
64
#include <optional>
65
66
#define DEBUG_TYPE "exprconstant"
67
68
using namespace clang;
69
using llvm::APFixedPoint;
70
using llvm::APInt;
71
using llvm::APSInt;
72
using llvm::APFloat;
73
using llvm::FixedPointSemantics;
74
75
namespace {
76
  struct LValue;
77
  class CallStackFrame;
78
  class EvalInfo;
79
80
  using SourceLocExprScopeGuard =
81
      CurrentSourceLocExprScope::SourceLocExprScopeGuard;
82
83
26.8M
  static QualType getType(APValue::LValueBase B) {
84
26.8M
    return B.getType();
85
26.8M
  }
86
87
  /// Get an LValue path entry, which is known to not be an array index, as a
88
  /// field declaration.
89
74.3k
  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
90
74.3k
    return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
91
74.3k
  }
92
  /// Get an LValue path entry, which is known to not be an array index, as a
93
  /// base class declaration.
94
3.97k
  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
95
3.97k
    return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
96
3.97k
  }
97
  /// Determine whether this LValue path entry for a base class names a virtual
98
  /// base class.
99
844
  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
100
844
    return E.getAsBaseOrMember().getInt();
101
844
  }
102
103
  /// Given an expression, determine the type used to store the result of
104
  /// evaluating that expression.
105
1.78M
  static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
106
1.78M
    if (E->isPRValue())
107
1.74M
      return E->getType();
108
40.3k
    return Ctx.getLValueReferenceType(E->getType());
109
1.78M
  }
110
111
  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
112
5.97k
  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
113
5.97k
    if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
114
4.39k
      return DirectCallee->getAttr<AllocSizeAttr>();
115
1.58k
    if (const Decl *IndirectCallee = CE->getCalleeDecl())
116
1.58k
      return IndirectCallee->getAttr<AllocSizeAttr>();
117
0
    return nullptr;
118
1.58k
  }
119
120
  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
121
  /// This will look through a single cast.
122
  ///
123
  /// Returns null if we couldn't unwrap a function with alloc_size.
124
5.27k
  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
125
5.27k
    if (!E->getType()->isPointerType())
126
0
      return nullptr;
127
128
5.27k
    E = E->IgnoreParens();
129
    // If we're doing a variable assignment from e.g. malloc(N), there will
130
    // probably be a cast of some kind. In exotic cases, we might also see a
131
    // top-level ExprWithCleanups. Ignore them either way.
132
5.27k
    if (const auto *FE = dyn_cast<FullExpr>(E))
133
15
      E = FE->getSubExpr()->IgnoreParens();
134
135
5.27k
    if (const auto *Cast = dyn_cast<CastExpr>(E))
136
1.79k
      E = Cast->getSubExpr()->IgnoreParens();
137
138
5.27k
    if (const auto *CE = dyn_cast<CallExpr>(E))
139
4.79k
      return getAllocSizeAttr(CE) ? 
CE4.35k
:
nullptr439
;
140
476
    return nullptr;
141
5.27k
  }
142
143
  /// Determines whether or not the given Base contains a call to a function
144
  /// with the alloc_size attribute.
145
1.11M
  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146
1.11M
    const auto *E = Base.dyn_cast<const Expr *>();
147
1.11M
    return E && 
E->getType()->isPointerType()124k
&&
tryUnwrapAllocSizeCall(E)2.73k
;
148
1.11M
  }
149
150
  /// Determines whether the given kind of constant expression is only ever
151
  /// used for name mangling. If so, it's permitted to reference things that we
152
  /// can't generate code for (in particular, dllimported functions).
153
42.1k
  static bool isForManglingOnly(ConstantExprKind Kind) {
154
42.1k
    switch (Kind) {
155
40.2k
    case ConstantExprKind::Normal:
156
40.2k
    case ConstantExprKind::ClassTemplateArgument:
157
40.3k
    case ConstantExprKind::ImmediateInvocation:
158
      // Note that non-type template arguments of class type are emitted as
159
      // template parameter objects.
160
40.3k
      return false;
161
162
1.87k
    case ConstantExprKind::NonClassTemplateArgument:
163
1.87k
      return true;
164
42.1k
    }
165
0
    llvm_unreachable("unknown ConstantExprKind");
166
0
  }
167
168
139k
  static bool isTemplateArgument(ConstantExprKind Kind) {
169
139k
    switch (Kind) {
170
137k
    case ConstantExprKind::Normal:
171
137k
    case ConstantExprKind::ImmediateInvocation:
172
137k
      return false;
173
174
55
    case ConstantExprKind::ClassTemplateArgument:
175
2.18k
    case ConstantExprKind::NonClassTemplateArgument:
176
2.18k
      return true;
177
139k
    }
178
0
    llvm_unreachable("unknown ConstantExprKind");
179
0
  }
180
181
  /// The bound to claim that an array of unknown bound has.
182
  /// The value in MostDerivedArraySize is undefined in this case. So, set it
183
  /// to an arbitrary value that's likely to loudly break things if it's used.
184
  static const uint64_t AssumedSizeForUnsizedArray =
185
      std::numeric_limits<uint64_t>::max() / 2;
186
187
  /// Determines if an LValue with the given LValueBase will have an unsized
188
  /// array in its designator.
189
  /// Find the path length and type of the most-derived subobject in the given
190
  /// path, and find the size of the containing array, if any.
191
  static unsigned
192
  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
193
                           ArrayRef<APValue::LValuePathEntry> Path,
194
                           uint64_t &ArraySize, QualType &Type, bool &IsArray,
195
1.10M
                           bool &FirstEntryIsUnsizedArray) {
196
    // This only accepts LValueBases from APValues, and APValues don't support
197
    // arrays that lack size info.
198
1.10M
    assert(!isBaseAnAllocSizeCall(Base) &&
199
1.10M
           "Unsized arrays shouldn't appear here");
200
1.10M
    unsigned MostDerivedLength = 0;
201
1.10M
    Type = getType(Base);
202
203
1.26M
    for (unsigned I = 0, N = Path.size(); I != N; 
++I161k
) {
204
161k
      if (Type->isArrayType()) {
205
122k
        const ArrayType *AT = Ctx.getAsArrayType(Type);
206
122k
        Type = AT->getElementType();
207
122k
        MostDerivedLength = I + 1;
208
122k
        IsArray = true;
209
210
122k
        if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211
122k
          ArraySize = CAT->getSize().getZExtValue();
212
122k
        } else {
213
160
          assert(I == 0 && "unexpected unsized array designator");
214
160
          FirstEntryIsUnsizedArray = true;
215
160
          ArraySize = AssumedSizeForUnsizedArray;
216
160
        }
217
122k
      } else 
if (38.4k
Type->isAnyComplexType()38.4k
) {
218
133
        const ComplexType *CT = Type->castAs<ComplexType>();
219
133
        Type = CT->getElementType();
220
133
        ArraySize = 2;
221
133
        MostDerivedLength = I + 1;
222
133
        IsArray = true;
223
38.3k
      } else if (const FieldDecl *FD = getAsField(Path[I])) {
224
30.2k
        Type = FD->getType();
225
30.2k
        ArraySize = 0;
226
30.2k
        MostDerivedLength = I + 1;
227
30.2k
        IsArray = false;
228
30.2k
      } else {
229
        // Path[I] describes a base class.
230
8.05k
        ArraySize = 0;
231
8.05k
        IsArray = false;
232
8.05k
      }
233
161k
    }
234
1.10M
    return MostDerivedLength;
235
1.10M
  }
236
237
  /// A path from a glvalue to a subobject of that glvalue.
238
  struct SubobjectDesignator {
239
    /// True if the subobject was named in a manner not supported by C++11. Such
240
    /// lvalues can still be folded, but they are not core constant expressions
241
    /// and we cannot perform lvalue-to-rvalue conversions on them.
242
    unsigned Invalid : 1;
243
244
    /// Is this a pointer one past the end of an object?
245
    unsigned IsOnePastTheEnd : 1;
246
247
    /// Indicator of whether the first entry is an unsized array.
248
    unsigned FirstEntryIsAnUnsizedArray : 1;
249
250
    /// Indicator of whether the most-derived object is an array element.
251
    unsigned MostDerivedIsArrayElement : 1;
252
253
    /// The length of the path to the most-derived object of which this is a
254
    /// subobject.
255
    unsigned MostDerivedPathLength : 28;
256
257
    /// The size of the array of which the most-derived object is an element.
258
    /// This will always be 0 if the most-derived object is not an array
259
    /// element. 0 is not an indicator of whether or not the most-derived object
260
    /// is an array, however, because 0-length arrays are allowed.
261
    ///
262
    /// If the current array is an unsized array, the value of this is
263
    /// undefined.
264
    uint64_t MostDerivedArraySize;
265
266
    /// The type of the most derived object referred to by this address.
267
    QualType MostDerivedType;
268
269
    typedef APValue::LValuePathEntry PathEntry;
270
271
    /// The entries on the path from the glvalue to the designated subobject.
272
    SmallVector<PathEntry, 8> Entries;
273
274
19.9M
    SubobjectDesignator() : Invalid(true) {}
275
276
    explicit SubobjectDesignator(QualType T)
277
15.8M
        : Invalid(false), IsOnePastTheEnd(false),
278
15.8M
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279
15.8M
          MostDerivedPathLength(0), MostDerivedArraySize(0),
280
15.8M
          MostDerivedType(T) {}
281
282
    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
283
1.12M
        : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
284
1.12M
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
285
1.12M
          MostDerivedPathLength(0), MostDerivedArraySize(0) {
286
1.12M
      assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
287
1.12M
      if (!Invalid) {
288
1.11M
        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
289
1.11M
        ArrayRef<PathEntry> VEntries = V.getLValuePath();
290
1.11M
        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
291
1.11M
        if (V.getLValueBase()) {
292
1.10M
          bool IsArray = false;
293
1.10M
          bool FirstIsUnsizedArray = false;
294
1.10M
          MostDerivedPathLength = findMostDerivedSubobject(
295
1.10M
              Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
296
1.10M
              MostDerivedType, IsArray, FirstIsUnsizedArray);
297
1.10M
          MostDerivedIsArrayElement = IsArray;
298
1.10M
          FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
299
1.10M
        }
300
1.11M
      }
301
1.12M
    }
302
303
    void truncate(ASTContext &Ctx, APValue::LValueBase Base,
304
215
                  unsigned NewLength) {
305
215
      if (Invalid)
306
0
        return;
307
308
215
      assert(Base && "cannot truncate path for null pointer");
309
215
      assert(NewLength <= Entries.size() && "not a truncation");
310
311
215
      if (NewLength == Entries.size())
312
0
        return;
313
215
      Entries.resize(NewLength);
314
315
215
      bool IsArray = false;
316
215
      bool FirstIsUnsizedArray = false;
317
215
      MostDerivedPathLength = findMostDerivedSubobject(
318
215
          Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
319
215
          FirstIsUnsizedArray);
320
215
      MostDerivedIsArrayElement = IsArray;
321
215
      FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
322
215
    }
323
324
12.3k
    void setInvalid() {
325
12.3k
      Invalid = true;
326
12.3k
      Entries.clear();
327
12.3k
    }
328
329
    /// Determine whether the most derived subobject is an array without a
330
    /// known bound.
331
6.29M
    bool isMostDerivedAnUnsizedArray() const {
332
6.29M
      assert(!Invalid && "Calling this makes no sense on invalid designators");
333
6.29M
      return Entries.size() == 1 && 
FirstEntryIsAnUnsizedArray724k
;
334
6.29M
    }
335
336
    /// Determine what the most derived array's size is. Results in an assertion
337
    /// failure if the most derived array lacks a size.
338
228k
    uint64_t getMostDerivedArraySize() const {
339
228k
      assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
340
228k
      return MostDerivedArraySize;
341
228k
    }
342
343
    /// Determine whether this is a one-past-the-end pointer.
344
3.13M
    bool isOnePastTheEnd() const {
345
3.13M
      assert(!Invalid);
346
3.13M
      if (IsOnePastTheEnd)
347
154
        return true;
348
3.13M
      if (!isMostDerivedAnUnsizedArray() && 
MostDerivedIsArrayElement3.13M
&&
349
3.13M
          Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
350
147k
              MostDerivedArraySize)
351
932
        return true;
352
3.13M
      return false;
353
3.13M
    }
354
355
    /// Get the range of valid index adjustments in the form
356
    ///   {maximum value that can be subtracted from this pointer,
357
    ///    maximum value that can be added to this pointer}
358
2.49k
    std::pair<uint64_t, uint64_t> validIndexAdjustments() {
359
2.49k
      if (Invalid || isMostDerivedAnUnsizedArray())
360
64
        return {0, 0};
361
362
      // [expr.add]p4: For the purposes of these operators, a pointer to a
363
      // nonarray object behaves the same as a pointer to the first element of
364
      // an array of length one with the type of the object as its element type.
365
2.42k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
366
2.42k
                     
MostDerivedIsArrayElement2.34k
;
367
2.42k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()2.15k
368
2.42k
                                    : 
(uint64_t)IsOnePastTheEnd270
;
369
2.42k
      uint64_t ArraySize =
370
2.42k
          IsArray ? 
getMostDerivedArraySize()2.15k
:
(uint64_t)1270
;
371
2.42k
      return {ArrayIndex, ArraySize - ArrayIndex};
372
2.49k
    }
373
374
    /// Check that this refers to a valid subobject.
375
0
    bool isValidSubobject() const {
376
0
      if (Invalid)
377
0
        return false;
378
0
      return !isOnePastTheEnd();
379
0
    }
380
    /// Check that this refers to a valid subobject, and if not, produce a
381
    /// relevant diagnostic and set the designator as invalid.
382
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
383
384
    /// Get the type of the designated object.
385
14.5k
    QualType getType(ASTContext &Ctx) const {
386
14.5k
      assert(!Invalid && "invalid designator has no subobject type");
387
14.5k
      return MostDerivedPathLength == Entries.size()
388
14.5k
                 ? 
MostDerivedType14.4k
389
14.5k
                 : 
Ctx.getRecordType(getAsBaseClass(Entries.back()))116
;
390
14.5k
    }
391
392
    /// Update this designator to refer to the first element within this array.
393
112k
    void addArrayUnchecked(const ConstantArrayType *CAT) {
394
112k
      Entries.push_back(PathEntry::ArrayIndex(0));
395
396
      // This is a most-derived object.
397
112k
      MostDerivedType = CAT->getElementType();
398
112k
      MostDerivedIsArrayElement = true;
399
112k
      MostDerivedArraySize = CAT->getSize().getZExtValue();
400
112k
      MostDerivedPathLength = Entries.size();
401
112k
    }
402
    /// Update this designator to refer to the first element within the array of
403
    /// elements of type T. This is an array of unknown size.
404
5.19k
    void addUnsizedArrayUnchecked(QualType ElemTy) {
405
5.19k
      Entries.push_back(PathEntry::ArrayIndex(0));
406
407
5.19k
      MostDerivedType = ElemTy;
408
5.19k
      MostDerivedIsArrayElement = true;
409
      // The value in MostDerivedArraySize is undefined in this case. So, set it
410
      // to an arbitrary value that's likely to loudly break things if it's
411
      // used.
412
5.19k
      MostDerivedArraySize = AssumedSizeForUnsizedArray;
413
5.19k
      MostDerivedPathLength = Entries.size();
414
5.19k
    }
415
    /// Update this designator to refer to the given base or member of this
416
    /// object.
417
223k
    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
418
223k
      Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
419
420
      // If this isn't a base class, it's a new most-derived object.
421
223k
      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
422
208k
        MostDerivedType = FD->getType();
423
208k
        MostDerivedIsArrayElement = false;
424
208k
        MostDerivedArraySize = 0;
425
208k
        MostDerivedPathLength = Entries.size();
426
208k
      }
427
223k
    }
428
    /// Update this designator to refer to the given complex component.
429
371
    void addComplexUnchecked(QualType EltTy, bool Imag) {
430
371
      Entries.push_back(PathEntry::ArrayIndex(Imag));
431
432
      // This is technically a most-derived object, though in practice this
433
      // is unlikely to matter.
434
371
      MostDerivedType = EltTy;
435
371
      MostDerivedIsArrayElement = true;
436
371
      MostDerivedArraySize = 2;
437
371
      MostDerivedPathLength = Entries.size();
438
371
    }
439
    void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
440
    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
441
                                   const APSInt &N);
442
    /// Add N to the address of this subobject.
443
226k
    void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
444
226k
      if (Invalid || !N) 
return0
;
445
226k
      uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
446
226k
      if (isMostDerivedAnUnsizedArray()) {
447
742
        diagnoseUnsizedArrayPointerArithmetic(Info, E);
448
        // Can't verify -- trust that the user is doing the right thing (or if
449
        // not, trust that the caller will catch the bad behavior).
450
        // FIXME: Should we reject if this overflows, at least?
451
742
        Entries.back() = PathEntry::ArrayIndex(
452
742
            Entries.back().getAsArrayIndex() + TruncatedN);
453
742
        return;
454
742
      }
455
456
      // [expr.add]p4: For the purposes of these operators, a pointer to a
457
      // nonarray object behaves the same as a pointer to the first element of
458
      // an array of length one with the type of the object as its element type.
459
225k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
460
225k
                     
MostDerivedIsArrayElement225k
;
461
225k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()225k
462
225k
                                    : 
(uint64_t)IsOnePastTheEnd385
;
463
225k
      uint64_t ArraySize =
464
225k
          IsArray ? 
getMostDerivedArraySize()225k
:
(uint64_t)1385
;
465
466
225k
      if (N < -(int64_t)ArrayIndex || 
N > ArraySize - ArrayIndex225k
) {
467
        // Calculate the actual index in a wide enough type, so we can include
468
        // it in the note.
469
532
        N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
470
532
        (llvm::APInt&)N += ArrayIndex;
471
532
        assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
472
532
        diagnosePointerArithmetic(Info, E, N);
473
532
        setInvalid();
474
532
        return;
475
532
      }
476
477
225k
      ArrayIndex += TruncatedN;
478
225k
      assert(ArrayIndex <= ArraySize &&
479
225k
             "bounds check succeeded for out-of-bounds index");
480
481
225k
      if (IsArray)
482
224k
        Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
483
225
      else
484
225
        IsOnePastTheEnd = (ArrayIndex != 0);
485
225k
    }
486
  };
487
488
  /// A scope at the end of which an object can need to be destroyed.
489
  enum class ScopeKind {
490
    Block,
491
    FullExpression,
492
    Call
493
  };
494
495
  /// A reference to a particular call and its arguments.
496
  struct CallRef {
497
26.3M
    CallRef() : OrigCallee(), CallIndex(0), Version() {}
498
    CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
499
800k
        : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
500
501
1.09M
    explicit operator bool() const { return OrigCallee; }
502
503
    /// Get the parameter that the caller initialized, corresponding to the
504
    /// given parameter in the callee.
505
272k
    const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
506
272k
      return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
507
272k
                        : 
PVD0
;
508
272k
    }
509
510
    /// The callee at the point where the arguments were evaluated. This might
511
    /// be different from the actual callee (a different redeclaration, or a
512
    /// virtual override), but this function's parameters are the ones that
513
    /// appear in the parameter map.
514
    const FunctionDecl *OrigCallee;
515
    /// The call index of the frame that holds the argument values.
516
    unsigned CallIndex;
517
    /// The version of the parameters corresponding to this call.
518
    unsigned Version;
519
  };
520
521
  /// A stack frame in the constexpr call stack.
522
  class CallStackFrame : public interp::Frame {
523
  public:
524
    EvalInfo &Info;
525
526
    /// Parent - The caller of this stack frame.
527
    CallStackFrame *Caller;
528
529
    /// Callee - The function which was called.
530
    const FunctionDecl *Callee;
531
532
    /// This - The binding for the this pointer in this call, if any.
533
    const LValue *This;
534
535
    /// CallExpr - The syntactical structure of member function calls
536
    const Expr *CallExpr;
537
538
    /// Information on how to find the arguments to this call. Our arguments
539
    /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
540
    /// key and this value as the version.
541
    CallRef Arguments;
542
543
    /// Source location information about the default argument or default
544
    /// initializer expression we're evaluating, if any.
545
    CurrentSourceLocExprScope CurSourceLocExprScope;
546
547
    // Note that we intentionally use std::map here so that references to
548
    // values are stable.
549
    typedef std::pair<const void *, unsigned> MapKeyTy;
550
    typedef std::map<MapKeyTy, APValue> MapTy;
551
    /// Temporaries - Temporary lvalues materialized within this stack frame.
552
    MapTy Temporaries;
553
554
    /// CallRange - The source range of the call expression for this call.
555
    SourceRange CallRange;
556
557
    /// Index - The call index of this call.
558
    unsigned Index;
559
560
    /// The stack of integers for tracking version numbers for temporaries.
561
    SmallVector<unsigned, 2> TempVersionStack = {1};
562
    unsigned CurTempVersion = TempVersionStack.back();
563
564
84.1k
    unsigned getTempVersion() const { return TempVersionStack.back(); }
565
566
38.9M
    void pushTempVersion() {
567
38.9M
      TempVersionStack.push_back(++CurTempVersion);
568
38.9M
    }
569
570
38.9M
    void popTempVersion() {
571
38.9M
      TempVersionStack.pop_back();
572
38.9M
    }
573
574
800k
    CallRef createCall(const FunctionDecl *Callee) {
575
800k
      return {Callee, Index, ++CurTempVersion};
576
800k
    }
577
578
    // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
579
    // on the overall stack usage of deeply-recursing constexpr evaluations.
580
    // (We should cache this map rather than recomputing it repeatedly.)
581
    // But let's try this and see how it goes; we can look into caching the map
582
    // as a later change.
583
584
    /// LambdaCaptureFields - Mapping from captured variables/this to
585
    /// corresponding data members in the closure class.
586
    llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
587
    FieldDecl *LambdaThisCaptureField = nullptr;
588
589
    CallStackFrame(EvalInfo &Info, SourceRange CallRange,
590
                   const FunctionDecl *Callee, const LValue *This,
591
                   const Expr *CallExpr, CallRef Arguments);
592
    ~CallStackFrame();
593
594
    // Return the temporary for Key whose version number is Version.
595
449k
    APValue *getTemporary(const void *Key, unsigned Version) {
596
449k
      MapKeyTy KV(Key, Version);
597
449k
      auto LB = Temporaries.lower_bound(KV);
598
449k
      if (LB != Temporaries.end() && 
LB->first == KV447k
)
599
447k
        return &LB->second;
600
1.91k
      return nullptr;
601
449k
    }
602
603
    // Return the current temporary for Key in the map.
604
4.04k
    APValue *getCurrentTemporary(const void *Key) {
605
4.04k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606
4.04k
      if (UB != Temporaries.begin() && 
std::prev(UB)->first.first == Key2.85k
)
607
2.80k
        return &std::prev(UB)->second;
608
1.23k
      return nullptr;
609
4.04k
    }
610
611
    // Return the version number of the current temporary for Key.
612
124k
    unsigned getCurrentTemporaryVersion(const void *Key) const {
613
124k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614
124k
      if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615
124k
        return std::prev(UB)->first.second;
616
0
      return 0;
617
124k
    }
618
619
    /// Allocate storage for an object of type T in this stack frame.
620
    /// Populates LV with a handle to the created object. Key identifies
621
    /// the temporary within the stack frame, and must not be reused without
622
    /// bumping the temporary version number.
623
    template<typename KeyT>
624
    APValue &createTemporary(const KeyT *Key, QualType T,
625
                             ScopeKind Scope, LValue &LV);
626
627
    /// Allocate storage for a parameter of a function call made in this frame.
628
    APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629
630
    void describe(llvm::raw_ostream &OS) const override;
631
632
4.32k
    Frame *getCaller() const override { return Caller; }
633
4.34k
    SourceRange getCallRange() const override { return CallRange; }
634
10.8k
    const FunctionDecl *getCallee() const override { return Callee; }
635
636
1.05k
    bool isStdFunction() const {
637
1.90k
      for (const DeclContext *DC = Callee; DC; 
DC = DC->getParent()845
)
638
1.68k
        if (DC->isStdNamespace())
639
839
          return true;
640
218
      return false;
641
1.05k
    }
642
643
  private:
644
    APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645
                         ScopeKind Scope);
646
  };
647
648
  /// Temporarily override 'this'.
649
  class ThisOverrideRAII {
650
  public:
651
    ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652
47.2k
        : Frame(Frame), OldThis(Frame.This) {
653
47.2k
      if (Enable)
654
4.25k
        Frame.This = NewThis;
655
47.2k
    }
656
47.2k
    ~ThisOverrideRAII() {
657
47.2k
      Frame.This = OldThis;
658
47.2k
    }
659
  private:
660
    CallStackFrame &Frame;
661
    const LValue *OldThis;
662
  };
663
664
  // A shorthand time trace scope struct, prints source range, for example
665
  // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
666
  class ExprTimeTraceScope {
667
  public:
668
    ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
669
26.2M
        : TimeScope(Name, [E, &Ctx] {
670
19
            return E->getSourceRange().printToString(Ctx.getSourceManager());
671
26.2M
          }) {}
672
673
  private:
674
    llvm::TimeTraceScope TimeScope;
675
  };
676
}
677
678
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
679
                              const LValue &This, QualType ThisType);
680
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
681
                              APValue::LValueBase LVBase, APValue &Value,
682
                              QualType T);
683
684
namespace {
685
  /// A cleanup, and a flag indicating whether it is lifetime-extended.
686
  class Cleanup {
687
    llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
688
    APValue::LValueBase Base;
689
    QualType T;
690
691
  public:
692
    Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
693
            ScopeKind Scope)
694
661k
        : Value(Val, Scope), Base(Base), T(T) {}
695
696
    /// Determine whether this cleanup should be performed at the end of the
697
    /// given kind of scope.
698
1.36M
    bool isDestroyedAtEndOf(ScopeKind K) const {
699
1.36M
      return (int)Value.getInt() >= (int)K;
700
1.36M
    }
701
626k
    bool endLifetime(EvalInfo &Info, bool RunDestructors) {
702
626k
      if (RunDestructors) {
703
101k
        SourceLocation Loc;
704
101k
        if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
705
92.6k
          Loc = VD->getLocation();
706
9.30k
        else if (const Expr *E = Base.dyn_cast<const Expr*>())
707
9.30k
          Loc = E->getExprLoc();
708
101k
        return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
709
101k
      }
710
524k
      *Value.getPointer() = APValue();
711
524k
      return true;
712
626k
    }
713
714
34.4k
    bool hasSideEffect() {
715
34.4k
      return T.isDestructedType();
716
34.4k
    }
717
  };
718
719
  /// A reference to an object whose construction we are currently evaluating.
720
  struct ObjectUnderConstruction {
721
    APValue::LValueBase Base;
722
    ArrayRef<APValue::LValuePathEntry> Path;
723
    friend bool operator==(const ObjectUnderConstruction &LHS,
724
2.55M
                           const ObjectUnderConstruction &RHS) {
725
2.55M
      return LHS.Base == RHS.Base && 
LHS.Path == RHS.Path1.99M
;
726
2.55M
    }
727
149k
    friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
728
149k
      return llvm::hash_combine(Obj.Base, Obj.Path);
729
149k
    }
730
  };
731
  enum class ConstructionPhase {
732
    None,
733
    Bases,
734
    AfterBases,
735
    AfterFields,
736
    Destroying,
737
    DestroyingBases
738
  };
739
}
740
741
namespace llvm {
742
template<> struct DenseMapInfo<ObjectUnderConstruction> {
743
  using Base = DenseMapInfo<APValue::LValueBase>;
744
244k
  static ObjectUnderConstruction getEmptyKey() {
745
244k
    return {Base::getEmptyKey(), {}}; }
746
217k
  static ObjectUnderConstruction getTombstoneKey() {
747
217k
    return {Base::getTombstoneKey(), {}};
748
217k
  }
749
149k
  static unsigned getHashValue(const ObjectUnderConstruction &Object) {
750
149k
    return hash_value(Object);
751
149k
  }
752
  static bool isEqual(const ObjectUnderConstruction &LHS,
753
2.55M
                      const ObjectUnderConstruction &RHS) {
754
2.55M
    return LHS == RHS;
755
2.55M
  }
756
};
757
}
758
759
namespace {
760
  /// A dynamically-allocated heap object.
761
  struct DynAlloc {
762
    /// The value of this heap-allocated object.
763
    APValue Value;
764
    /// The allocating expression; used for diagnostics. Either a CXXNewExpr
765
    /// or a CallExpr (the latter is for direct calls to operator new inside
766
    /// std::allocator<T>::allocate).
767
    const Expr *AllocExpr = nullptr;
768
769
    enum Kind {
770
      New,
771
      ArrayNew,
772
      StdAllocator
773
    };
774
775
    /// Get the kind of the allocation. This must match between allocation
776
    /// and deallocation.
777
509
    Kind getKind() const {
778
509
      if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
779
484
        return NE->isArray() ? 
ArrayNew357
:
New127
;
780
25
      assert(isa<CallExpr>(AllocExpr));
781
25
      return StdAllocator;
782
25
    }
783
  };
784
785
  struct DynAllocOrder {
786
200k
    bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
787
200k
      return L.getIndex() < R.getIndex();
788
200k
    }
789
  };
790
791
  /// EvalInfo - This is a private struct used by the evaluator to capture
792
  /// information about a subexpression as it is folded.  It retains information
793
  /// about the AST context, but also maintains information about the folded
794
  /// expression.
795
  ///
796
  /// If an expression could be evaluated, it is still possible it is not a C
797
  /// "integer constant expression" or constant expression.  If not, this struct
798
  /// captures information about how and why not.
799
  ///
800
  /// One bit of information passed *into* the request for constant folding
801
  /// indicates whether the subexpression is "evaluated" or not according to C
802
  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
803
  /// evaluate the expression regardless of what the RHS is, but C only allows
804
  /// certain things in certain situations.
805
  class EvalInfo : public interp::State {
806
  public:
807
    ASTContext &Ctx;
808
809
    /// EvalStatus - Contains information about the evaluation.
810
    Expr::EvalStatus &EvalStatus;
811
812
    /// CurrentCall - The top of the constexpr call stack.
813
    CallStackFrame *CurrentCall;
814
815
    /// CallStackDepth - The number of calls in the call stack right now.
816
    unsigned CallStackDepth;
817
818
    /// NextCallIndex - The next call index to assign.
819
    unsigned NextCallIndex;
820
821
    /// StepsLeft - The remaining number of evaluation steps we're permitted
822
    /// to perform. This is essentially a limit for the number of statements
823
    /// we will evaluate.
824
    unsigned StepsLeft;
825
826
    /// Enable the experimental new constant interpreter. If an expression is
827
    /// not supported by the interpreter, an error is triggered.
828
    bool EnableNewConstInterp;
829
830
    /// BottomFrame - The frame in which evaluation started. This must be
831
    /// initialized after CurrentCall and CallStackDepth.
832
    CallStackFrame BottomFrame;
833
834
    /// A stack of values whose lifetimes end at the end of some surrounding
835
    /// evaluation frame.
836
    llvm::SmallVector<Cleanup, 16> CleanupStack;
837
838
    /// EvaluatingDecl - This is the declaration whose initializer is being
839
    /// evaluated, if any.
840
    APValue::LValueBase EvaluatingDecl;
841
842
    enum class EvaluatingDeclKind {
843
      None,
844
      /// We're evaluating the construction of EvaluatingDecl.
845
      Ctor,
846
      /// We're evaluating the destruction of EvaluatingDecl.
847
      Dtor,
848
    };
849
    EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
850
851
    /// EvaluatingDeclValue - This is the value being constructed for the
852
    /// declaration whose initializer is being evaluated, if any.
853
    APValue *EvaluatingDeclValue;
854
855
    /// Set of objects that are currently being constructed.
856
    llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
857
        ObjectsUnderConstruction;
858
859
    /// Current heap allocations, along with the location where each was
860
    /// allocated. We use std::map here because we need stable addresses
861
    /// for the stored APValues.
862
    std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
863
864
    /// The number of heap allocations performed so far in this evaluation.
865
    unsigned NumHeapAllocs = 0;
866
867
    struct EvaluatingConstructorRAII {
868
      EvalInfo &EI;
869
      ObjectUnderConstruction Object;
870
      bool DidInsert;
871
      EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
872
                                bool HasBases)
873
40.5k
          : EI(EI), Object(Object) {
874
40.5k
        DidInsert =
875
40.5k
            EI.ObjectsUnderConstruction
876
40.5k
                .insert({Object, HasBases ? 
ConstructionPhase::Bases2.20k
877
40.5k
                                          : 
ConstructionPhase::AfterBases38.3k
})
878
40.5k
                .second;
879
40.5k
      }
880
2.04k
      void finishedConstructingBases() {
881
2.04k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
882
2.04k
      }
883
36.0k
      void finishedConstructingFields() {
884
36.0k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
885
36.0k
      }
886
40.5k
      ~EvaluatingConstructorRAII() {
887
40.5k
        if (DidInsert) 
EI.ObjectsUnderConstruction.erase(Object)40.4k
;
888
40.5k
      }
889
    };
890
891
    struct EvaluatingDestructorRAII {
892
      EvalInfo &EI;
893
      ObjectUnderConstruction Object;
894
      bool DidInsert;
895
      EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
896
1.11k
          : EI(EI), Object(Object) {
897
1.11k
        DidInsert = EI.ObjectsUnderConstruction
898
1.11k
                        .insert({Object, ConstructionPhase::Destroying})
899
1.11k
                        .second;
900
1.11k
      }
901
55
      void startedDestroyingBases() {
902
55
        EI.ObjectsUnderConstruction[Object] =
903
55
            ConstructionPhase::DestroyingBases;
904
55
      }
905
1.11k
      ~EvaluatingDestructorRAII() {
906
1.11k
        if (DidInsert)
907
1.11k
          EI.ObjectsUnderConstruction.erase(Object);
908
1.11k
      }
909
    };
910
911
    ConstructionPhase
912
    isEvaluatingCtorDtor(APValue::LValueBase Base,
913
33.9k
                         ArrayRef<APValue::LValuePathEntry> Path) {
914
33.9k
      return ObjectsUnderConstruction.lookup({Base, Path});
915
33.9k
    }
916
917
    /// If we're currently speculatively evaluating, the outermost call stack
918
    /// depth at which we can mutate state, otherwise 0.
919
    unsigned SpeculativeEvaluationDepth = 0;
920
921
    /// The current array initialization index, if we're performing array
922
    /// initialization.
923
    uint64_t ArrayInitIndex = -1;
924
925
    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
926
    /// notes attached to it will also be stored, otherwise they will not be.
927
    bool HasActiveDiagnostic;
928
929
    /// Have we emitted a diagnostic explaining why we couldn't constant
930
    /// fold (not just why it's not strictly a constant expression)?
931
    bool HasFoldFailureDiagnostic;
932
933
    /// Whether we're checking that an expression is a potential constant
934
    /// expression. If so, do not fail on constructs that could become constant
935
    /// later on (such as a use of an undefined global).
936
    bool CheckingPotentialConstantExpression = false;
937
938
    /// Whether we're checking for an expression that has undefined behavior.
939
    /// If so, we will produce warnings if we encounter an operation that is
940
    /// always undefined.
941
    ///
942
    /// Note that we still need to evaluate the expression normally when this
943
    /// is set; this is used when evaluating ICEs in C.
944
    bool CheckingForUndefinedBehavior = false;
945
946
    enum EvaluationMode {
947
      /// Evaluate as a constant expression. Stop if we find that the expression
948
      /// is not a constant expression.
949
      EM_ConstantExpression,
950
951
      /// Evaluate as a constant expression. Stop if we find that the expression
952
      /// is not a constant expression. Some expressions can be retried in the
953
      /// optimizer if we don't constant fold them here, but in an unevaluated
954
      /// context we try to fold them immediately since the optimizer never
955
      /// gets a chance to look at it.
956
      EM_ConstantExpressionUnevaluated,
957
958
      /// Fold the expression to a constant. Stop if we hit a side-effect that
959
      /// we can't model.
960
      EM_ConstantFold,
961
962
      /// Evaluate in any way we know how. Don't worry about side-effects that
963
      /// can't be modeled.
964
      EM_IgnoreSideEffects,
965
    } EvalMode;
966
967
    /// Are we checking whether the expression is a potential constant
968
    /// expression?
969
14.3M
    bool checkingPotentialConstantExpression() const override  {
970
14.3M
      return CheckingPotentialConstantExpression;
971
14.3M
    }
972
973
    /// Are we checking an expression for overflow?
974
    // FIXME: We should check for any kind of undefined or suspicious behavior
975
    // in such constructs, not just overflow.
976
6.40M
    bool checkingForUndefinedBehavior() const override {
977
6.40M
      return CheckingForUndefinedBehavior;
978
6.40M
    }
979
980
    EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
981
25.1M
        : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
982
25.1M
          CallStackDepth(0), NextCallIndex(1),
983
25.1M
          StepsLeft(C.getLangOpts().ConstexprStepLimit),
984
25.1M
          EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
985
25.1M
          BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
986
25.1M
                      /*This=*/nullptr,
987
25.1M
                      /*CallExpr=*/nullptr, CallRef()),
988
25.1M
          EvaluatingDecl((const ValueDecl *)nullptr),
989
25.1M
          EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
990
25.1M
          HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
991
992
25.1M
    ~EvalInfo() {
993
25.1M
      discardCleanups();
994
25.1M
    }
995
996
38.8M
    ASTContext &getCtx() const override { return Ctx; }
997
998
    void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
999
2.37M
                           EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1000
2.37M
      EvaluatingDecl = Base;
1001
2.37M
      IsEvaluatingDecl = EDK;
1002
2.37M
      EvaluatingDeclValue = &Value;
1003
2.37M
    }
1004
1005
472k
    bool CheckCallLimit(SourceLocation Loc) {
1006
      // Don't perform any constexpr calls (other than the call we're checking)
1007
      // when checking a potential constant expression.
1008
472k
      if (checkingPotentialConstantExpression() && 
CallStackDepth > 170.0k
)
1009
4.69k
        return false;
1010
467k
      if (NextCallIndex == 0) {
1011
        // NextCallIndex has wrapped around.
1012
0
        FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1013
0
        return false;
1014
0
      }
1015
467k
      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1016
467k
        return true;
1017
19
      FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1018
19
        << getLangOpts().ConstexprCallDepth;
1019
19
      return false;
1020
467k
    }
1021
1022
    bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1023
2.77k
                        uint64_t ElemCount, bool Diag) {
1024
      // FIXME: GH63562
1025
      // APValue stores array extents as unsigned,
1026
      // so anything that is greater that unsigned would overflow when
1027
      // constructing the array, we catch this here.
1028
2.77k
      if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1029
2.77k
          
ElemCount > uint64_t(std::numeric_limits<unsigned>::max())2.76k
) {
1030
6
        if (Diag)
1031
5
          FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1032
6
        return false;
1033
6
      }
1034
1035
      // FIXME: GH63562
1036
      // Arrays allocate an APValue per element.
1037
      // We use the number of constexpr steps as a proxy for the maximum size
1038
      // of arrays to avoid exhausting the system resources, as initialization
1039
      // of each element is likely to take some number of steps anyway.
1040
2.76k
      uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1041
2.76k
      if (ElemCount > Limit) {
1042
8
        if (Diag)
1043
8
          FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1044
8
              << ElemCount << Limit;
1045
8
        return false;
1046
8
      }
1047
2.76k
      return true;
1048
2.76k
    }
1049
1050
    std::pair<CallStackFrame *, unsigned>
1051
675k
    getCallFrameAndDepth(unsigned CallIndex) {
1052
675k
      assert(CallIndex && "no call index in getCallFrameAndDepth");
1053
      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1054
      // be null in this loop.
1055
675k
      unsigned Depth = CallStackDepth;
1056
675k
      CallStackFrame *Frame = CurrentCall;
1057
1.38M
      while (Frame->Index > CallIndex) {
1058
705k
        Frame = Frame->Caller;
1059
705k
        --Depth;
1060
705k
      }
1061
675k
      if (Frame->Index == CallIndex)
1062
675k
        return {Frame, Depth};
1063
23
      return {nullptr, 0};
1064
675k
    }
1065
1066
13.6M
    bool nextStep(const Stmt *S) {
1067
13.6M
      if (!StepsLeft) {
1068
17
        FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1069
17
        return false;
1070
17
      }
1071
13.6M
      --StepsLeft;
1072
13.6M
      return true;
1073
13.6M
    }
1074
1075
    APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1076
1077
46.4k
    std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1078
46.4k
      std::optional<DynAlloc *> Result;
1079
46.4k
      auto It = HeapAllocs.find(DA);
1080
46.4k
      if (It != HeapAllocs.end())
1081
46.4k
        Result = &It->second;
1082
46.4k
      return Result;
1083
46.4k
    }
1084
1085
    /// Get the allocated storage for the given parameter of the given call.
1086
5.07k
    APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1087
5.07k
      CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1088
5.07k
      return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1089
5.07k
                   : 
nullptr0
;
1090
5.07k
    }
1091
1092
    /// Information about a stack frame for std::allocator<T>::[de]allocate.
1093
    struct StdAllocatorCaller {
1094
      unsigned FrameIndex;
1095
      QualType ElemType;
1096
958
      explicit operator bool() const { return FrameIndex != 0; };
1097
    };
1098
1099
958
    StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1100
1.02k
      for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1101
958
           
Call = Call->Caller70
) {
1102
213
        const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1103
213
        if (!MD)
1104
25
          continue;
1105
188
        const IdentifierInfo *FnII = MD->getIdentifier();
1106
188
        if (!FnII || 
!FnII->isStr(FnName)173
)
1107
45
          continue;
1108
1109
143
        const auto *CTSD =
1110
143
            dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1111
143
        if (!CTSD)
1112
0
          continue;
1113
1114
143
        const IdentifierInfo *ClassII = CTSD->getIdentifier();
1115
143
        const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1116
143
        if (CTSD->isInStdNamespace() && ClassII &&
1117
143
            ClassII->isStr("allocator") && TAL.size() >= 1 &&
1118
143
            TAL[0].getKind() == TemplateArgument::Type)
1119
143
          return {Call->Index, TAL[0].getAsType()};
1120
143
      }
1121
1122
815
      return {};
1123
958
    }
1124
1125
437k
    void performLifetimeExtension() {
1126
      // Disable the cleanups for lifetime-extended temporaries.
1127
437k
      llvm::erase_if(CleanupStack, [](Cleanup &C) {
1128
425
        return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1129
425
      });
1130
437k
    }
1131
1132
    /// Throw away any remaining cleanups at the end of evaluation. If any
1133
    /// cleanups would have had a side-effect, note that as an unmodeled
1134
    /// side-effect and return false. Otherwise, return true.
1135
29.9M
    bool discardCleanups() {
1136
29.9M
      for (Cleanup &C : CleanupStack) {
1137
34.4k
        if (C.hasSideEffect() && 
!noteSideEffect()1.70k
) {
1138
463
          CleanupStack.clear();
1139
463
          return false;
1140
463
        }
1141
34.4k
      }
1142
29.9M
      CleanupStack.clear();
1143
29.9M
      return true;
1144
29.9M
    }
1145
1146
  private:
1147
1.04M
    interp::Frame *getCurrentFrame() override { return CurrentCall; }
1148
1.04M
    const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1149
1150
6.14M
    bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1151
8.74M
    void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1152
1153
1.04M
    void setFoldFailureDiagnostic(bool Flag) override {
1154
1.04M
      HasFoldFailureDiagnostic = Flag;
1155
1.04M
    }
1156
1157
13.7M
    Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1158
1159
    // If we have a prior diagnostic, it will be noting that the expression
1160
    // isn't a constant expression. This diagnostic is more important,
1161
    // unless we require this evaluation to produce a constant expression.
1162
    //
1163
    // FIXME: We might want to show both diagnostics to the user in
1164
    // EM_ConstantFold mode.
1165
1.04M
    bool hasPriorDiagnostic() override {
1166
1.04M
      if (!EvalStatus.Diag->empty()) {
1167
3.88k
        switch (EvalMode) {
1168
662
        case EM_ConstantFold:
1169
735
        case EM_IgnoreSideEffects:
1170
735
          if (!HasFoldFailureDiagnostic)
1171
669
            break;
1172
          // We've already failed to fold something. Keep that diagnostic.
1173
735
          
[[fallthrough]];66
1174
3.21k
        case EM_ConstantExpression:
1175
3.21k
        case EM_ConstantExpressionUnevaluated:
1176
3.21k
          setActiveDiagnostic(false);
1177
3.21k
          return true;
1178
3.88k
        }
1179
3.88k
      }
1180
1.04M
      return false;
1181
1.04M
    }
1182
1183
2.08M
    unsigned getCallStackDepth() override { return CallStackDepth; }
1184
1185
  public:
1186
    /// Should we continue evaluation after encountering a side-effect that we
1187
    /// couldn't model?
1188
1.50M
    bool keepEvaluatingAfterSideEffect() {
1189
1.50M
      switch (EvalMode) {
1190
88.3k
      case EM_IgnoreSideEffects:
1191
88.3k
        return true;
1192
1193
1.40M
      case EM_ConstantExpression:
1194
1.41M
      case EM_ConstantExpressionUnevaluated:
1195
1.41M
      case EM_ConstantFold:
1196
        // By default, assume any side effect might be valid in some other
1197
        // evaluation of this expression from a different context.
1198
1.41M
        return checkingPotentialConstantExpression() ||
1199
1.41M
               
checkingForUndefinedBehavior()3.08k
;
1200
1.50M
      }
1201
0
      llvm_unreachable("Missed EvalMode case");
1202
0
    }
1203
1204
    /// Note that we have had a side-effect, and determine whether we should
1205
    /// keep evaluating.
1206
1.50M
    bool noteSideEffect() {
1207
1.50M
      EvalStatus.HasSideEffects = true;
1208
1.50M
      return keepEvaluatingAfterSideEffect();
1209
1.50M
    }
1210
1211
    /// Should we continue evaluation after encountering undefined behavior?
1212
703
    bool keepEvaluatingAfterUndefinedBehavior() {
1213
703
      switch (EvalMode) {
1214
562
      case EM_IgnoreSideEffects:
1215
577
      case EM_ConstantFold:
1216
577
        return true;
1217
1218
126
      case EM_ConstantExpression:
1219
126
      case EM_ConstantExpressionUnevaluated:
1220
126
        return checkingForUndefinedBehavior();
1221
703
      }
1222
0
      llvm_unreachable("Missed EvalMode case");
1223
0
    }
1224
1225
    /// Note that we hit something that was technically undefined behavior, but
1226
    /// that we can evaluate past it (such as signed overflow or floating-point
1227
    /// division by zero.)
1228
703
    bool noteUndefinedBehavior() override {
1229
703
      EvalStatus.HasUndefinedBehavior = true;
1230
703
      return keepEvaluatingAfterUndefinedBehavior();
1231
703
    }
1232
1233
    /// Should we continue evaluation as much as possible after encountering a
1234
    /// construct which can't be reduced to a value?
1235
6.45M
    bool keepEvaluatingAfterFailure() const override {
1236
6.45M
      if (!StepsLeft)
1237
0
        return false;
1238
1239
6.45M
      switch (EvalMode) {
1240
221k
      case EM_ConstantExpression:
1241
240k
      case EM_ConstantExpressionUnevaluated:
1242
273k
      case EM_ConstantFold:
1243
6.45M
      case EM_IgnoreSideEffects:
1244
6.45M
        return checkingPotentialConstantExpression() ||
1245
6.45M
               
checkingForUndefinedBehavior()6.40M
;
1246
6.45M
      }
1247
0
      llvm_unreachable("Missed EvalMode case");
1248
0
    }
1249
1250
    /// Notes that we failed to evaluate an expression that other expressions
1251
    /// directly depend on, and determine if we should keep evaluating. This
1252
    /// should only be called if we actually intend to keep evaluating.
1253
    ///
1254
    /// Call noteSideEffect() instead if we may be able to ignore the value that
1255
    /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1256
    ///
1257
    /// (Foo(), 1)      // use noteSideEffect
1258
    /// (Foo() || true) // use noteSideEffect
1259
    /// Foo() + 1       // use noteFailure
1260
5.52M
    [[nodiscard]] bool noteFailure() {
1261
      // Failure when evaluating some expression often means there is some
1262
      // subexpression whose evaluation was skipped. Therefore, (because we
1263
      // don't track whether we skipped an expression when unwinding after an
1264
      // evaluation failure) every evaluation failure that bubbles up from a
1265
      // subexpression implies that a side-effect has potentially happened. We
1266
      // skip setting the HasSideEffects flag to true until we decide to
1267
      // continue evaluating after that point, which happens here.
1268
5.52M
      bool KeepGoing = keepEvaluatingAfterFailure();
1269
5.52M
      EvalStatus.HasSideEffects |= KeepGoing;
1270
5.52M
      return KeepGoing;
1271
5.52M
    }
1272
1273
    class ArrayInitLoopIndex {
1274
      EvalInfo &Info;
1275
      uint64_t OuterIndex;
1276
1277
    public:
1278
      ArrayInitLoopIndex(EvalInfo &Info)
1279
41
          : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1280
41
        Info.ArrayInitIndex = 0;
1281
41
      }
1282
41
      ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1283
1284
417
      operator uint64_t&() { return Info.ArrayInitIndex; }
1285
    };
1286
  };
1287
1288
  /// Object used to treat all foldable expressions as constant expressions.
1289
  struct FoldConstant {
1290
    EvalInfo &Info;
1291
    bool Enabled;
1292
    bool HadNoPriorDiags;
1293
    EvalInfo::EvaluationMode OldMode;
1294
1295
    explicit FoldConstant(EvalInfo &Info, bool Enabled)
1296
329k
      : Info(Info),
1297
329k
        Enabled(Enabled),
1298
329k
        HadNoPriorDiags(Info.EvalStatus.Diag &&
1299
329k
                        
Info.EvalStatus.Diag->empty()88.7k
&&
1300
329k
                        
!Info.EvalStatus.HasSideEffects88.7k
),
1301
329k
        OldMode(Info.EvalMode) {
1302
329k
      if (Enabled)
1303
6.18k
        Info.EvalMode = EvalInfo::EM_ConstantFold;
1304
329k
    }
1305
241k
    void keepDiagnostics() { Enabled = false; }
1306
329k
    ~FoldConstant() {
1307
329k
      if (Enabled && 
HadNoPriorDiags1.55k
&&
!Info.EvalStatus.Diag->empty()71
&&
1308
329k
          
!Info.EvalStatus.HasSideEffects71
)
1309
71
        Info.EvalStatus.Diag->clear();
1310
329k
      Info.EvalMode = OldMode;
1311
329k
    }
1312
  };
1313
1314
  /// RAII object used to set the current evaluation mode to ignore
1315
  /// side-effects.
1316
  struct IgnoreSideEffectsRAII {
1317
    EvalInfo &Info;
1318
    EvalInfo::EvaluationMode OldMode;
1319
    explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1320
12.4k
        : Info(Info), OldMode(Info.EvalMode) {
1321
12.4k
      Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1322
12.4k
    }
1323
1324
12.4k
    ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1325
  };
1326
1327
  /// RAII object used to optionally suppress diagnostics and side-effects from
1328
  /// a speculative evaluation.
1329
  class SpeculativeEvaluationRAII {
1330
    EvalInfo *Info = nullptr;
1331
    Expr::EvalStatus OldStatus;
1332
    unsigned OldSpeculativeEvaluationDepth = 0;
1333
1334
160k
    void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1335
160k
      Info = Other.Info;
1336
160k
      OldStatus = Other.OldStatus;
1337
160k
      OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1338
160k
      Other.Info = nullptr;
1339
160k
    }
1340
1341
23.2M
    void maybeRestoreState() {
1342
23.2M
      if (!Info)
1343
23.1M
        return;
1344
1345
113k
      Info->EvalStatus = OldStatus;
1346
113k
      Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1347
113k
    }
1348
1349
  public:
1350
22.9M
    SpeculativeEvaluationRAII() = default;
1351
1352
    SpeculativeEvaluationRAII(
1353
        EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1354
113k
        : Info(&Info), OldStatus(Info.EvalStatus),
1355
113k
          OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1356
113k
      Info.EvalStatus.Diag = NewDiag;
1357
113k
      Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1358
113k
    }
1359
1360
    SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1361
69.1k
    SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1362
69.1k
      moveFromAndCancel(std::move(Other));
1363
69.1k
    }
1364
1365
91.1k
    SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1366
91.1k
      maybeRestoreState();
1367
91.1k
      moveFromAndCancel(std::move(Other));
1368
91.1k
      return *this;
1369
91.1k
    }
1370
1371
23.1M
    ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1372
  };
1373
1374
  /// RAII object wrapping a full-expression or block scope, and handling
1375
  /// the ending of the lifetime of temporaries created within it.
1376
  template<ScopeKind Kind>
1377
  class ScopeRAII {
1378
    EvalInfo &Info;
1379
    unsigned OldStackSize;
1380
  public:
1381
    ScopeRAII(EvalInfo &Info)
1382
38.9M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1383
      // Push a new temporary version. This is needed to distinguish between
1384
      // temporaries created in different iterations of a loop.
1385
38.9M
      Info.CurrentCall->pushTempVersion();
1386
38.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1382
1.17M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1383
      // Push a new temporary version. This is needed to distinguish between
1384
      // temporaries created in different iterations of a loop.
1385
1.17M
      Info.CurrentCall->pushTempVersion();
1386
1.17M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1382
34.2M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1383
      // Push a new temporary version. This is needed to distinguish between
1384
      // temporaries created in different iterations of a loop.
1385
34.2M
      Info.CurrentCall->pushTempVersion();
1386
34.2M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1382
3.52M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1383
      // Push a new temporary version. This is needed to distinguish between
1384
      // temporaries created in different iterations of a loop.
1385
3.52M
      Info.CurrentCall->pushTempVersion();
1386
3.52M
    }
1387
38.9M
    bool destroy(bool RunDestructors = true) {
1388
38.9M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1389
38.9M
      OldStackSize = -1U;
1390
38.9M
      return OK;
1391
38.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::destroy(bool)
Line
Count
Source
1387
34.2M
    bool destroy(bool RunDestructors = true) {
1388
34.2M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1389
34.2M
      OldStackSize = -1U;
1390
34.2M
      return OK;
1391
34.2M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::destroy(bool)
Line
Count
Source
1387
1.17M
    bool destroy(bool RunDestructors = true) {
1388
1.17M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1389
1.17M
      OldStackSize = -1U;
1390
1.17M
      return OK;
1391
1.17M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::destroy(bool)
Line
Count
Source
1387
3.52M
    bool destroy(bool RunDestructors = true) {
1388
3.52M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1389
3.52M
      OldStackSize = -1U;
1390
3.52M
      return OK;
1391
3.52M
    }
1392
38.9M
    ~ScopeRAII() {
1393
38.9M
      if (OldStackSize != -1U)
1394
1.01M
        destroy(false);
1395
      // Body moved to a static method to encourage the compiler to inline away
1396
      // instances of this class.
1397
38.9M
      Info.CurrentCall->popTempVersion();
1398
38.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::~ScopeRAII()
Line
Count
Source
1392
34.2M
    ~ScopeRAII() {
1393
34.2M
      if (OldStackSize != -1U)
1394
70.8k
        destroy(false);
1395
      // Body moved to a static method to encourage the compiler to inline away
1396
      // instances of this class.
1397
34.2M
      Info.CurrentCall->popTempVersion();
1398
34.2M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::~ScopeRAII()
Line
Count
Source
1392
1.17M
    ~ScopeRAII() {
1393
1.17M
      if (OldStackSize != -1U)
1394
793k
        destroy(false);
1395
      // Body moved to a static method to encourage the compiler to inline away
1396
      // instances of this class.
1397
1.17M
      Info.CurrentCall->popTempVersion();
1398
1.17M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::~ScopeRAII()
Line
Count
Source
1392
3.52M
    ~ScopeRAII() {
1393
3.52M
      if (OldStackSize != -1U)
1394
152k
        destroy(false);
1395
      // Body moved to a static method to encourage the compiler to inline away
1396
      // instances of this class.
1397
3.52M
      Info.CurrentCall->popTempVersion();
1398
3.52M
    }
1399
  private:
1400
    static bool cleanup(EvalInfo &Info, bool RunDestructors,
1401
38.9M
                        unsigned OldStackSize) {
1402
38.9M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1403
38.9M
             "running cleanups out of order?");
1404
1405
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1406
      // for a full-expression scope.
1407
38.9M
      bool Success = true;
1408
39.6M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I694k
) {
1409
694k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1410
626k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1411
494
            Success = false;
1412
494
            break;
1413
494
          }
1414
626k
        }
1415
694k
      }
1416
1417
      // Compact any retained cleanups.
1418
38.9M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1419
38.9M
      if (Kind != ScopeKind::Block)
1420
4.70M
        NewEnd =
1421
4.70M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
674k
              return C.isDestroyedAtEndOf(Kind);
1423
674k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1421
630k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
630k
              return C.isDestroyedAtEndOf(Kind);
1423
630k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1421
43.6k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
43.6k
              return C.isDestroyedAtEndOf(Kind);
1423
43.6k
            });
1424
38.9M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1425
38.9M
      return Success;
1426
38.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1401
34.2M
                        unsigned OldStackSize) {
1402
34.2M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1403
34.2M
             "running cleanups out of order?");
1404
1405
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1406
      // for a full-expression scope.
1407
34.2M
      bool Success = true;
1408
34.2M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I20.5k
) {
1409
20.8k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1410
20.8k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1411
241
            Success = false;
1412
241
            break;
1413
241
          }
1414
20.8k
        }
1415
20.8k
      }
1416
1417
      // Compact any retained cleanups.
1418
34.2M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1419
34.2M
      if (Kind != ScopeKind::Block)
1420
0
        NewEnd =
1421
0
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
0
              return C.isDestroyedAtEndOf(Kind);
1423
0
            });
1424
34.2M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1425
34.2M
      return Success;
1426
34.2M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1401
1.17M
                        unsigned OldStackSize) {
1402
1.17M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1403
1.17M
             "running cleanups out of order?");
1404
1405
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1406
      // for a full-expression scope.
1407
1.17M
      bool Success = true;
1408
1.80M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I630k
) {
1409
630k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1410
584k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1411
202
            Success = false;
1412
202
            break;
1413
202
          }
1414
584k
        }
1415
630k
      }
1416
1417
      // Compact any retained cleanups.
1418
1.17M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1419
1.17M
      if (Kind != ScopeKind::Block)
1420
1.17M
        NewEnd =
1421
1.17M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
1.17M
              return C.isDestroyedAtEndOf(Kind);
1423
1.17M
            });
1424
1.17M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1425
1.17M
      return Success;
1426
1.17M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1401
3.52M
                        unsigned OldStackSize) {
1402
3.52M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1403
3.52M
             "running cleanups out of order?");
1404
1405
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1406
      // for a full-expression scope.
1407
3.52M
      bool Success = true;
1408
3.57M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I43.5k
) {
1409
43.6k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1410
20.9k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1411
51
            Success = false;
1412
51
            break;
1413
51
          }
1414
20.9k
        }
1415
43.6k
      }
1416
1417
      // Compact any retained cleanups.
1418
3.52M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1419
3.52M
      if (Kind != ScopeKind::Block)
1420
3.52M
        NewEnd =
1421
3.52M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1422
3.52M
              return C.isDestroyedAtEndOf(Kind);
1423
3.52M
            });
1424
3.52M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1425
3.52M
      return Success;
1426
3.52M
    }
1427
  };
1428
  typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1429
  typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1430
  typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1431
}
1432
1433
bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1434
341k
                                         CheckSubobjectKind CSK) {
1435
341k
  if (Invalid)
1436
35
    return false;
1437
341k
  if (isOnePastTheEnd()) {
1438
47
    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1439
47
      << CSK;
1440
47
    setInvalid();
1441
47
    return false;
1442
47
  }
1443
  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1444
  // must actually be at least one array element; even a VLA cannot have a
1445
  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1446
341k
  return true;
1447
341k
}
1448
1449
void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1450
742
                                                                const Expr *E) {
1451
742
  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1452
  // Do not set the designator as invalid: we can represent this situation,
1453
  // and correct handling of __builtin_object_size requires us to do so.
1454
742
}
1455
1456
void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1457
                                                    const Expr *E,
1458
532
                                                    const APSInt &N) {
1459
  // If we're complaining, we must be able to statically determine the size of
1460
  // the most derived array.
1461
532
  if (MostDerivedPathLength == Entries.size() && 
MostDerivedIsArrayElement520
)
1462
372
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1463
372
      << N << /*array*/ 0
1464
372
      << static_cast<unsigned>(getMostDerivedArraySize());
1465
160
  else
1466
160
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1467
160
      << N << /*non-array*/ 1;
1468
532
  setInvalid();
1469
532
}
1470
1471
CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1472
                               const FunctionDecl *Callee, const LValue *This,
1473
                               const Expr *CallExpr, CallRef Call)
1474
25.6M
    : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1475
25.6M
      CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1476
25.6M
      Index(Info.NextCallIndex++) {
1477
25.6M
  Info.CurrentCall = this;
1478
25.6M
  ++Info.CallStackDepth;
1479
25.6M
}
1480
1481
25.6M
CallStackFrame::~CallStackFrame() {
1482
25.6M
  assert(Info.CurrentCall == this && "calls retired out of order");
1483
25.6M
  --Info.CallStackDepth;
1484
25.6M
  Info.CurrentCall = Caller;
1485
25.6M
}
1486
1487
19.7M
static bool isRead(AccessKinds AK) {
1488
19.7M
  return AK == AK_Read || 
AK == AK_ReadObjectRepresentation768k
;
1489
19.7M
}
1490
1491
13.3M
static bool isModification(AccessKinds AK) {
1492
13.3M
  switch (AK) {
1493
12.1M
  case AK_Read:
1494
12.1M
  case AK_ReadObjectRepresentation:
1495
12.4M
  case AK_MemberCall:
1496
12.4M
  case AK_DynamicCast:
1497
12.4M
  case AK_TypeId:
1498
12.4M
    return false;
1499
241k
  case AK_Assign:
1500
950k
  case AK_Increment:
1501
955k
  case AK_Decrement:
1502
958k
  case AK_Construct:
1503
958k
  case AK_Destroy:
1504
958k
    return true;
1505
13.3M
  }
1506
0
  llvm_unreachable("unknown access kind");
1507
0
}
1508
1509
19.7M
static bool isAnyAccess(AccessKinds AK) {
1510
19.7M
  return isRead(AK) || 
isModification(AK)766k
;
1511
19.7M
}
1512
1513
/// Is this an access per the C++ definition?
1514
9.84M
static bool isFormalAccess(AccessKinds AK) {
1515
9.84M
  return isAnyAccess(AK) && 
AK != AK_Construct9.77M
&&
AK != AK_Destroy9.77M
;
1516
9.84M
}
1517
1518
/// Is this kind of axcess valid on an indeterminate object value?
1519
15.7k
static bool isValidIndeterminateAccess(AccessKinds AK) {
1520
15.7k
  switch (AK) {
1521
101
  case AK_Read:
1522
106
  case AK_Increment:
1523
111
  case AK_Decrement:
1524
    // These need the object's value.
1525
111
    return false;
1526
1527
0
  case AK_ReadObjectRepresentation:
1528
15.6k
  case AK_Assign:
1529
15.6k
  case AK_Construct:
1530
15.6k
  case AK_Destroy:
1531
    // Construction and destruction don't need the value.
1532
15.6k
    return true;
1533
1534
0
  case AK_MemberCall:
1535
0
  case AK_DynamicCast:
1536
0
  case AK_TypeId:
1537
    // These aren't really meaningful on scalars.
1538
0
    return true;
1539
15.7k
  }
1540
0
  llvm_unreachable("unknown access kind");
1541
0
}
1542
1543
namespace {
1544
  struct ComplexValue {
1545
  private:
1546
    bool IsInt;
1547
1548
  public:
1549
    APSInt IntReal, IntImag;
1550
    APFloat FloatReal, FloatImag;
1551
1552
4.72k
    ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1553
1554
1.03k
    void makeComplexFloat() { IsInt = false; }
1555
1.11k
    bool isComplexFloat() const { return !IsInt; }
1556
1.30k
    APFloat &getComplexFloatReal() { return FloatReal; }
1557
1.32k
    APFloat &getComplexFloatImag() { return FloatImag; }
1558
1559
293
    void makeComplexInt() { IsInt = true; }
1560
4
    bool isComplexInt() const { return IsInt; }
1561
327
    APSInt &getComplexIntReal() { return IntReal; }
1562
318
    APSInt &getComplexIntImag() { return IntImag; }
1563
1564
403
    void moveInto(APValue &v) const {
1565
403
      if (isComplexFloat())
1566
286
        v = APValue(FloatReal, FloatImag);
1567
117
      else
1568
117
        v = APValue(IntReal, IntImag);
1569
403
    }
1570
39
    void setFrom(const APValue &v) {
1571
39
      assert(v.isComplexFloat() || v.isComplexInt());
1572
39
      if (v.isComplexFloat()) {
1573
19
        makeComplexFloat();
1574
19
        FloatReal = v.getComplexFloatReal();
1575
19
        FloatImag = v.getComplexFloatImag();
1576
20
      } else {
1577
20
        makeComplexInt();
1578
20
        IntReal = v.getComplexIntReal();
1579
20
        IntImag = v.getComplexIntImag();
1580
20
      }
1581
39
    }
1582
  };
1583
1584
  struct LValue {
1585
    APValue::LValueBase Base;
1586
    CharUnits Offset;
1587
    SubobjectDesignator Designator;
1588
    bool IsNullPtr : 1;
1589
    bool InvalidBase : 1;
1590
1591
3.63M
    const APValue::LValueBase getLValueBase() const { return Base; }
1592
769k
    CharUnits &getLValueOffset() { return Offset; }
1593
449
    const CharUnits &getLValueOffset() const { return Offset; }
1594
15.6k
    SubobjectDesignator &getLValueDesignator() { return Designator; }
1595
140k
    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1596
719k
    bool isNullPointer() const { return IsNullPtr;}
1597
1598
10.4M
    unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1599
4.83M
    unsigned getLValueVersion() const { return Base.getVersion(); }
1600
1601
1.74M
    void moveInto(APValue &V) const {
1602
1.74M
      if (Designator.Invalid)
1603
8.35k
        V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1604
1.73M
      else {
1605
1.73M
        assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1606
1.73M
        V = APValue(Base, Offset, Designator.Entries,
1607
1.73M
                    Designator.IsOnePastTheEnd, IsNullPtr);
1608
1.73M
      }
1609
1.74M
    }
1610
1.12M
    void setFrom(ASTContext &Ctx, const APValue &V) {
1611
1.12M
      assert(V.isLValue() && "Setting LValue from a non-LValue?");
1612
1.12M
      Base = V.getLValueBase();
1613
1.12M
      Offset = V.getLValueOffset();
1614
1.12M
      InvalidBase = false;
1615
1.12M
      Designator = SubobjectDesignator(Ctx, V);
1616
1.12M
      IsNullPtr = V.isNullPointer();
1617
1.12M
    }
1618
1619
15.8M
    void set(APValue::LValueBase B, bool BInvalid = false) {
1620
15.8M
#ifndef NDEBUG
1621
      // We only allow a few types of invalid bases. Enforce that here.
1622
15.8M
      if (BInvalid) {
1623
1.81k
        const auto *E = B.get<const Expr *>();
1624
1.81k
        assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1625
1.81k
               "Unexpected type of invalid base");
1626
1.81k
      }
1627
15.8M
#endif
1628
1629
15.8M
      Base = B;
1630
15.8M
      Offset = CharUnits::fromQuantity(0);
1631
15.8M
      InvalidBase = BInvalid;
1632
15.8M
      Designator = SubobjectDesignator(getType(B));
1633
15.8M
      IsNullPtr = false;
1634
15.8M
    }
1635
1636
42.2k
    void setNull(ASTContext &Ctx, QualType PointerTy) {
1637
42.2k
      Base = (const ValueDecl *)nullptr;
1638
42.2k
      Offset =
1639
42.2k
          CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1640
42.2k
      InvalidBase = false;
1641
42.2k
      Designator = SubobjectDesignator(PointerTy->getPointeeType());
1642
42.2k
      IsNullPtr = true;
1643
42.2k
    }
1644
1645
1.81k
    void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1646
1.81k
      set(B, true);
1647
1.81k
    }
1648
1649
888
    std::string toString(ASTContext &Ctx, QualType T) const {
1650
888
      APValue Printable;
1651
888
      moveInto(Printable);
1652
888
      return Printable.getAsString(Ctx, T);
1653
888
    }
1654
1655
  private:
1656
    // Check that this LValue is not based on a null pointer. If it is, produce
1657
    // a diagnostic and mark the designator as invalid.
1658
    template <typename GenDiagType>
1659
458k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1660
458k
      if (Designator.Invalid)
1661
326
        return false;
1662
458k
      if (IsNullPtr) {
1663
1.03k
        GenDiag();
1664
1.03k
        Designator.setInvalid();
1665
1.03k
        return false;
1666
1.03k
      }
1667
456k
      return true;
1668
458k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'()>((anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'() const&)
Line
Count
Source
1659
451k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1660
451k
      if (Designator.Invalid)
1661
326
        return false;
1662
451k
      if (IsNullPtr) {
1663
871
        GenDiag();
1664
871
        Designator.setInvalid();
1665
871
        return false;
1666
871
      }
1667
450k
      return true;
1668
451k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'()>((anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'() const&)
Line
Count
Source
1659
6.96k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1660
6.96k
      if (Designator.Invalid)
1661
0
        return false;
1662
6.96k
      if (IsNullPtr) {
1663
162
        GenDiag();
1664
162
        Designator.setInvalid();
1665
162
        return false;
1666
162
      }
1667
6.80k
      return true;
1668
6.96k
    }
1669
1670
  public:
1671
    bool checkNullPointer(EvalInfo &Info, const Expr *E,
1672
451k
                          CheckSubobjectKind CSK) {
1673
451k
      return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1674
871
        Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1675
871
      });
1676
451k
    }
1677
1678
    bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1679
6.96k
                                       AccessKinds AK) {
1680
6.96k
      return checkNullPointerDiagnosingWith([&Info, E, AK] {
1681
162
        Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1682
162
      });
1683
6.96k
    }
1684
1685
    // Check this LValue refers to an object. If not, set the designator to be
1686
    // invalid and emit a diagnostic.
1687
342k
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1688
342k
      return (CSK == CSK_ArrayToPointer || 
checkNullPointer(Info, E, CSK)224k
) &&
1689
342k
             
Designator.checkSubobject(Info, E, CSK)341k
;
1690
342k
    }
1691
1692
    void addDecl(EvalInfo &Info, const Expr *E,
1693
223k
                 const Decl *D, bool Virtual = false) {
1694
223k
      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? 
CSK_Field208k
:
CSK_Base14.9k
))
1695
222k
        Designator.addDeclUnchecked(D, Virtual);
1696
223k
    }
1697
5.26k
    void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1698
5.26k
      if (!Designator.Entries.empty()) {
1699
70
        Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1700
70
        Designator.setInvalid();
1701
70
        return;
1702
70
      }
1703
5.19k
      if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1704
5.19k
        assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1705
5.19k
        Designator.FirstEntryIsAnUnsizedArray = true;
1706
5.19k
        Designator.addUnsizedArrayUnchecked(ElemTy);
1707
5.19k
      }
1708
5.19k
    }
1709
112k
    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1710
112k
      if (checkSubobject(Info, E, CSK_ArrayToPointer))
1711
112k
        Designator.addArrayUnchecked(CAT);
1712
112k
    }
1713
383
    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1714
383
      if (checkSubobject(Info, E, Imag ? 
CSK_Imag181
:
CSK_Real202
))
1715
371
        Designator.addComplexUnchecked(EltTy, Imag);
1716
383
    }
1717
294k
    void clearIsNullPointer() {
1718
294k
      IsNullPtr = false;
1719
294k
    }
1720
    void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1721
238k
                              const APSInt &Index, CharUnits ElementSize) {
1722
      // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1723
      // but we're not required to diagnose it and it's valid in C++.)
1724
238k
      if (!Index)
1725
11.4k
        return;
1726
1727
      // Compute the new offset in the appropriate width, wrapping at 64 bits.
1728
      // FIXME: When compiling for a 32-bit target, we should use 32-bit
1729
      // offsets.
1730
226k
      uint64_t Offset64 = Offset.getQuantity();
1731
226k
      uint64_t ElemSize64 = ElementSize.getQuantity();
1732
226k
      uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1733
226k
      Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1734
1735
226k
      if (checkNullPointer(Info, E, CSK_ArrayIndex))
1736
226k
        Designator.adjustIndex(Info, E, Index);
1737
226k
      clearIsNullPointer();
1738
226k
    }
1739
208k
    void adjustOffset(CharUnits N) {
1740
208k
      Offset += N;
1741
208k
      if (N.getQuantity())
1742
67.8k
        clearIsNullPointer();
1743
208k
    }
1744
  };
1745
1746
  struct MemberPtr {
1747
5.10k
    MemberPtr() {}
1748
    explicit MemberPtr(const ValueDecl *Decl)
1749
3.98k
        : DeclAndIsDerivedMember(Decl, false) {}
1750
1751
    /// The member or (direct or indirect) field referred to by this member
1752
    /// pointer, or 0 if this is a null member pointer.
1753
6.22k
    const ValueDecl *getDecl() const {
1754
6.22k
      return DeclAndIsDerivedMember.getPointer();
1755
6.22k
    }
1756
    /// Is this actually a member of some type derived from the relevant class?
1757
4.90k
    bool isDerivedMember() const {
1758
4.90k
      return DeclAndIsDerivedMember.getInt();
1759
4.90k
    }
1760
    /// Get the class which the declaration actually lives in.
1761
116
    const CXXRecordDecl *getContainingRecord() const {
1762
116
      return cast<CXXRecordDecl>(
1763
116
          DeclAndIsDerivedMember.getPointer()->getDeclContext());
1764
116
    }
1765
1766
3.69k
    void moveInto(APValue &V) const {
1767
3.69k
      V = APValue(getDecl(), isDerivedMember(), Path);
1768
3.69k
    }
1769
268
    void setFrom(const APValue &V) {
1770
268
      assert(V.isMemberPointer());
1771
268
      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1772
268
      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1773
268
      Path.clear();
1774
268
      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1775
268
      Path.insert(Path.end(), P.begin(), P.end());
1776
268
    }
1777
1778
    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1779
    /// whether the member is a member of some class derived from the class type
1780
    /// of the member pointer.
1781
    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1782
    /// Path - The path of base/derived classes from the member declaration's
1783
    /// class (exclusive) to the class type of the member pointer (inclusive).
1784
    SmallVector<const CXXRecordDecl*, 4> Path;
1785
1786
    /// Perform a cast towards the class of the Decl (either up or down the
1787
    /// hierarchy).
1788
144
    bool castBack(const CXXRecordDecl *Class) {
1789
144
      assert(!Path.empty());
1790
144
      const CXXRecordDecl *Expected;
1791
144
      if (Path.size() >= 2)
1792
141
        Expected = Path[Path.size() - 2];
1793
3
      else
1794
3
        Expected = getContainingRecord();
1795
144
      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1796
        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1797
        // if B does not contain the original member and is not a base or
1798
        // derived class of the class containing the original member, the result
1799
        // of the cast is undefined.
1800
        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1801
        // (D::*). We consider that to be a language defect.
1802
0
        return false;
1803
0
      }
1804
144
      Path.pop_back();
1805
144
      return true;
1806
144
    }
1807
    /// Perform a base-to-derived member pointer cast.
1808
541
    bool castToDerived(const CXXRecordDecl *Derived) {
1809
541
      if (!getDecl())
1810
0
        return true;
1811
541
      if (!isDerivedMember()) {
1812
481
        Path.push_back(Derived);
1813
481
        return true;
1814
481
      }
1815
60
      if (!castBack(Derived))
1816
0
        return false;
1817
60
      if (Path.empty())
1818
3
        DeclAndIsDerivedMember.setInt(false);
1819
60
      return true;
1820
60
    }
1821
    /// Perform a derived-to-base member pointer cast.
1822
361
    bool castToBase(const CXXRecordDecl *Base) {
1823
361
      if (!getDecl())
1824
0
        return true;
1825
361
      if (Path.empty())
1826
97
        DeclAndIsDerivedMember.setInt(true);
1827
361
      if (isDerivedMember()) {
1828
277
        Path.push_back(Base);
1829
277
        return true;
1830
277
      }
1831
84
      return castBack(Base);
1832
361
    }
1833
  };
1834
1835
  /// Compare two member pointers, which are assumed to be of the same type.
1836
57
  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1837
57
    if (!LHS.getDecl() || !RHS.getDecl())
1838
0
      return !LHS.getDecl() && !RHS.getDecl();
1839
57
    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1840
12
      return false;
1841
45
    return LHS.Path == RHS.Path;
1842
57
  }
1843
}
1844
1845
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1846
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1847
                            const LValue &This, const Expr *E,
1848
                            bool AllowNonLiteralTypes = false);
1849
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1850
                           bool InvalidBaseOK = false);
1851
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1852
                            bool InvalidBaseOK = false);
1853
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1854
                                  EvalInfo &Info);
1855
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1856
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1857
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1858
                                    EvalInfo &Info);
1859
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1860
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1861
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1862
                           EvalInfo &Info);
1863
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1864
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1865
                                  EvalInfo &Info);
1866
1867
/// Evaluate an integer or fixed point expression into an APResult.
1868
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1869
                                        EvalInfo &Info);
1870
1871
/// Evaluate only a fixed point expression into an APResult.
1872
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1873
                               EvalInfo &Info);
1874
1875
//===----------------------------------------------------------------------===//
1876
// Misc utilities
1877
//===----------------------------------------------------------------------===//
1878
1879
/// Negate an APSInt in place, converting it to a signed form if necessary, and
1880
/// preserving its value (by extending by up to one bit as needed).
1881
349
static void negateAsSigned(APSInt &Int) {
1882
349
  if (Int.isUnsigned() || 
Int.isMinSignedValue()339
) {
1883
10
    Int = Int.extend(Int.getBitWidth() + 1);
1884
10
    Int.setIsSigned(true);
1885
10
  }
1886
349
  Int = -Int;
1887
349
}
1888
1889
template<typename KeyT>
1890
APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1891
84.1k
                                         ScopeKind Scope, LValue &LV) {
1892
84.1k
  unsigned Version = getTempVersion();
1893
84.1k
  APValue::LValueBase Base(Key, Index, Version);
1894
84.1k
  LV.set(Base);
1895
84.1k
  return createLocal(Base, Key, T, Scope);
1896
84.1k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::OpaqueValueExpr>(clang::OpaqueValueExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1891
1.51k
                                         ScopeKind Scope, LValue &LV) {
1892
1.51k
  unsigned Version = getTempVersion();
1893
1.51k
  APValue::LValueBase Base(Key, Index, Version);
1894
1.51k
  LV.set(Base);
1895
1.51k
  return createLocal(Base, Key, T, Scope);
1896
1.51k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::VarDecl>(clang::VarDecl const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1891
20.7k
                                         ScopeKind Scope, LValue &LV) {
1892
20.7k
  unsigned Version = getTempVersion();
1893
20.7k
  APValue::LValueBase Base(Key, Index, Version);
1894
20.7k
  LV.set(Base);
1895
20.7k
  return createLocal(Base, Key, T, Scope);
1896
20.7k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::MaterializeTemporaryExpr>(clang::MaterializeTemporaryExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1891
44.3k
                                         ScopeKind Scope, LValue &LV) {
1892
44.3k
  unsigned Version = getTempVersion();
1893
44.3k
  APValue::LValueBase Base(Key, Index, Version);
1894
44.3k
  LV.set(Base);
1895
44.3k
  return createLocal(Base, Key, T, Scope);
1896
44.3k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::Expr>(clang::Expr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1891
17.4k
                                         ScopeKind Scope, LValue &LV) {
1892
17.4k
  unsigned Version = getTempVersion();
1893
17.4k
  APValue::LValueBase Base(Key, Index, Version);
1894
17.4k
  LV.set(Base);
1895
17.4k
  return createLocal(Base, Key, T, Scope);
1896
17.4k
}
1897
1898
/// Allocate storage for a parameter of a function call made in this frame.
1899
APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1900
591k
                                     LValue &LV) {
1901
591k
  assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1902
591k
  APValue::LValueBase Base(PVD, Index, Args.Version);
1903
591k
  LV.set(Base);
1904
  // We always destroy parameters at the end of the call, even if we'd allow
1905
  // them to live to the end of the full-expression at runtime, in order to
1906
  // give portable results and match other compilers.
1907
591k
  return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1908
591k
}
1909
1910
APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1911
675k
                                     QualType T, ScopeKind Scope) {
1912
675k
  assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1913
675k
  unsigned Version = Base.getVersion();
1914
675k
  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1915
675k
  assert(Result.isAbsent() && "local created multiple times");
1916
1917
  // If we're creating a local immediately in the operand of a speculative
1918
  // evaluation, don't register a cleanup to be run outside the speculative
1919
  // evaluation context, since we won't actually be able to initialize this
1920
  // object.
1921
675k
  if (Index <= Info.SpeculativeEvaluationDepth) {
1922
14.3k
    if (T.isDestructedType())
1923
562
      Info.noteSideEffect();
1924
661k
  } else {
1925
661k
    Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1926
661k
  }
1927
675k
  return Result;
1928
675k
}
1929
1930
1.22k
APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1931
1.22k
  if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1932
0
    FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1933
0
    return nullptr;
1934
0
  }
1935
1936
1.22k
  DynamicAllocLValue DA(NumHeapAllocs++);
1937
1.22k
  LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1938
1.22k
  auto Result = HeapAllocs.emplace(std::piecewise_construct,
1939
1.22k
                                   std::forward_as_tuple(DA), std::tuple<>());
1940
1.22k
  assert(Result.second && "reused a heap alloc index?");
1941
1.22k
  Result.first->second.AllocExpr = E;
1942
1.22k
  return &Result.first->second.Value;
1943
1.22k
}
1944
1945
/// Produce a string describing the given constexpr call.
1946
3.43k
void CallStackFrame::describe(raw_ostream &Out) const {
1947
3.43k
  unsigned ArgIndex = 0;
1948
3.43k
  bool IsMemberCall =
1949
3.43k
      isa<CXXMethodDecl>(Callee) && 
!isa<CXXConstructorDecl>(Callee)2.35k
&&
1950
3.43k
      
cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction()1.77k
;
1951
1952
3.43k
  if (!IsMemberCall)
1953
1.66k
    Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1954
1.66k
                                 /*Qualified=*/false);
1955
1956
3.43k
  if (This && 
IsMemberCall2.35k
) {
1957
1.77k
    if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1958
1.13k
      const Expr *Object = MCE->getImplicitObjectArgument();
1959
1.13k
      Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1960
1.13k
                          /*Indentation=*/0);
1961
1.13k
      if (Object->getType()->isPointerType())
1962
374
          Out << "->";
1963
761
      else
1964
761
          Out << ".";
1965
1.13k
    } else 
if (const auto *636
OCE636
=
1966
636
                   dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1967
337
      OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1968
337
                                  Info.Ctx.getPrintingPolicy(),
1969
337
                                  /*Indentation=*/0);
1970
337
      Out << ".";
1971
337
    } else {
1972
299
      APValue Val;
1973
299
      This->moveInto(Val);
1974
299
      Val.printPretty(
1975
299
          Out, Info.Ctx,
1976
299
          Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1977
299
      Out << ".";
1978
299
    }
1979
1.77k
    Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1980
1.77k
                                 /*Qualified=*/false);
1981
1.77k
    IsMemberCall = false;
1982
1.77k
  }
1983
1984
3.43k
  Out << '(';
1985
1986
3.43k
  for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1987
5.63k
       E = Callee->param_end(); I != E; 
++I, ++ArgIndex2.20k
) {
1988
2.20k
    if (ArgIndex > (unsigned)IsMemberCall)
1989
695
      Out << ", ";
1990
1991
2.20k
    const ParmVarDecl *Param = *I;
1992
2.20k
    APValue *V = Info.getParamSlot(Arguments, Param);
1993
2.20k
    if (V)
1994
2.20k
      V->printPretty(Out, Info.Ctx, Param->getType());
1995
0
    else
1996
0
      Out << "<...>";
1997
1998
2.20k
    if (ArgIndex == 0 && 
IsMemberCall1.51k
)
1999
0
      Out << "->" << *Callee << '(';
2000
2.20k
  }
2001
2002
3.43k
  Out << ')';
2003
3.43k
}
2004
2005
/// Evaluate an expression to see if it had side-effects, and discard its
2006
/// result.
2007
/// \return \c true if the caller should keep evaluating.
2008
114k
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2009
114k
  assert(!E->isValueDependent());
2010
114k
  APValue Scratch;
2011
114k
  if (!Evaluate(Scratch, Info, E))
2012
    // We don't need the value, but we might have skipped a side effect here.
2013
8.41k
    return Info.noteSideEffect();
2014
106k
  return true;
2015
114k
}
2016
2017
/// Should this call expression be treated as a no-op?
2018
10.9k
static bool IsNoOpCall(const CallExpr *E) {
2019
10.9k
  unsigned Builtin = E->getBuiltinCallee();
2020
10.9k
  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2021
10.9k
          
Builtin == Builtin::BI__builtin___NSStringMakeConstantString9.88k
||
2022
10.9k
          
Builtin == Builtin::BI__builtin_function_start9.88k
);
2023
10.9k
}
2024
2025
139k
static bool IsGlobalLValue(APValue::LValueBase B) {
2026
  // C++11 [expr.const]p3 An address constant expression is a prvalue core
2027
  // constant expression of pointer type that evaluates to...
2028
2029
  // ... a null pointer value, or a prvalue core constant expression of type
2030
  // std::nullptr_t.
2031
139k
  if (!B)
2032
11.7k
    return true;
2033
2034
127k
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2035
    // ... the address of an object with static storage duration,
2036
115k
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2037
99.6k
      return VD->hasGlobalStorage();
2038
16.2k
    if (isa<TemplateParamObjectDecl>(D))
2039
99
      return true;
2040
    // ... the address of a function,
2041
    // ... the address of a GUID [MS extension],
2042
    // ... the address of an unnamed global constant
2043
16.1k
    return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2044
16.2k
  }
2045
2046
11.8k
  if (B.is<TypeInfoLValue>() || 
B.is<DynamicAllocLValue>()10.7k
)
2047
1.34k
    return true;
2048
2049
10.5k
  const Expr *E = B.get<const Expr*>();
2050
10.5k
  switch (E->getStmtClass()) {
2051
2
  default:
2052
2
    return false;
2053
134
  case Expr::CompoundLiteralExprClass: {
2054
134
    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2055
134
    return CLE->isFileScope() && 
CLE->isLValue()110
;
2056
0
  }
2057
1.28k
  case Expr::MaterializeTemporaryExprClass:
2058
    // A materialized temporary might have been lifetime-extended to static
2059
    // storage duration.
2060
1.28k
    return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2061
  // A string literal has static storage duration.
2062
5.42k
  case Expr::StringLiteralClass:
2063
5.46k
  case Expr::PredefinedExprClass:
2064
7.97k
  case Expr::ObjCStringLiteralClass:
2065
8.05k
  case Expr::ObjCEncodeExprClass:
2066
8.05k
    return true;
2067
9
  case Expr::ObjCBoxedExprClass:
2068
9
    return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2069
534
  case Expr::CallExprClass:
2070
534
    return IsNoOpCall(cast<CallExpr>(E));
2071
  // For GCC compatibility, &&label has static storage duration.
2072
115
  case Expr::AddrLabelExprClass:
2073
115
    return true;
2074
  // A Block literal expression may be used as the initialization value for
2075
  // Block variables at global or local static scope.
2076
380
  case Expr::BlockExprClass:
2077
380
    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2078
  // The APValue generated from a __builtin_source_location will be emitted as a
2079
  // literal.
2080
0
  case Expr::SourceLocExprClass:
2081
0
    return true;
2082
0
  case Expr::ImplicitValueInitExprClass:
2083
    // FIXME:
2084
    // We can never form an lvalue with an implicit value initialization as its
2085
    // base through expression evaluation, so these only appear in one case: the
2086
    // implicit variable declaration we invent when checking whether a constexpr
2087
    // constructor can produce a constant expression. We must assume that such
2088
    // an expression might be a global lvalue.
2089
0
    return true;
2090
10.5k
  }
2091
10.5k
}
2092
2093
2.10k
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2094
2.10k
  return LVal.Base.dyn_cast<const ValueDecl*>();
2095
2.10k
}
2096
2097
1.34k
static bool IsLiteralLValue(const LValue &Value) {
2098
1.34k
  if (Value.getLValueCallIndex())
2099
23
    return false;
2100
1.32k
  const Expr *E = Value.Base.dyn_cast<const Expr*>();
2101
1.32k
  return E && 
!isa<MaterializeTemporaryExpr>(E)129
;
2102
1.34k
}
2103
2104
1.39k
static bool IsWeakLValue(const LValue &Value) {
2105
1.39k
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2106
1.39k
  return Decl && 
Decl->isWeak()922
;
2107
1.39k
}
2108
2109
712
static bool isZeroSized(const LValue &Value) {
2110
712
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2111
712
  if (Decl && 
isa<VarDecl>(Decl)324
) {
2112
252
    QualType Ty = Decl->getType();
2113
252
    if (Ty->isArrayType())
2114
88
      return Ty->isIncompleteType() ||
2115
88
             
Decl->getASTContext().getTypeSize(Ty) == 068
;
2116
252
  }
2117
624
  return false;
2118
712
}
2119
2120
9.80k
static bool HasSameBase(const LValue &A, const LValue &B) {
2121
9.80k
  if (!A.getLValueBase())
2122
899
    return !B.getLValueBase();
2123
8.90k
  if (!B.getLValueBase())
2124
439
    return false;
2125
2126
8.47k
  if (A.getLValueBase().getOpaqueValue() !=
2127
8.47k
      B.getLValueBase().getOpaqueValue())
2128
968
    return false;
2129
2130
7.50k
  return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2131
7.50k
         A.getLValueVersion() == B.getLValueVersion();
2132
8.47k
}
2133
2134
1.63M
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2135
1.63M
  assert(Base && "no location for a null lvalue");
2136
1.63M
  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2137
2138
  // For a parameter, find the corresponding call stack frame (if it still
2139
  // exists), and point at the parameter of the function definition we actually
2140
  // invoked.
2141
1.63M
  if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2142
1.33M
    unsigned Idx = PVD->getFunctionScopeIndex();
2143
2.69M
    for (CallStackFrame *F = Info.CurrentCall; F; 
F = F->Caller1.35M
) {
2144
1.35M
      if (F->Arguments.CallIndex == Base.getCallIndex() &&
2145
1.35M
          
F->Arguments.Version == Base.getVersion()1.33M
&&
F->Callee1.33M
&&
2146
1.35M
          
Idx < F->Callee->getNumParams()15
) {
2147
12
        VD = F->Callee->getParamDecl(Idx);
2148
12
        break;
2149
12
      }
2150
1.35M
    }
2151
1.33M
  }
2152
2153
1.63M
  if (VD)
2154
1.63M
    Info.Note(VD->getLocation(), diag::note_declared_at);
2155
789
  else if (const Expr *E = Base.dyn_cast<const Expr*>())
2156
509
    Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2157
280
  else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2158
    // FIXME: Produce a note for dangling pointers too.
2159
251
    if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2160
251
      Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2161
251
                diag::note_constexpr_dynamic_alloc_here);
2162
251
  }
2163
2164
  // We have no information to show for a typeid(T) object.
2165
1.63M
}
2166
2167
enum class CheckEvaluationResultKind {
2168
  ConstantExpression,
2169
  FullyInitialized,
2170
};
2171
2172
/// Materialized temporaries that we've already checked to determine if they're
2173
/// initializsed by a constant expression.
2174
using CheckedTemporaries =
2175
    llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2176
2177
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2178
                                  EvalInfo &Info, SourceLocation DiagLoc,
2179
                                  QualType Type, const APValue &Value,
2180
                                  ConstantExprKind Kind,
2181
                                  const FieldDecl *SubobjectDecl,
2182
                                  CheckedTemporaries &CheckedTemps);
2183
2184
/// Check that this reference or pointer core constant expression is a valid
2185
/// value for an address or reference constant expression. Return true if we
2186
/// can fold this expression, whether or not it's a constant expression.
2187
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2188
                                          QualType Type, const LValue &LVal,
2189
                                          ConstantExprKind Kind,
2190
139k
                                          CheckedTemporaries &CheckedTemps) {
2191
139k
  bool IsReferenceType = Type->isReferenceType();
2192
2193
139k
  APValue::LValueBase Base = LVal.getLValueBase();
2194
139k
  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2195
2196
139k
  const Expr *BaseE = Base.dyn_cast<const Expr *>();
2197
139k
  const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2198
2199
  // Additional restrictions apply in a template argument. We only enforce the
2200
  // C++20 restrictions here; additional syntactic and semantic restrictions
2201
  // are applied elsewhere.
2202
139k
  if (isTemplateArgument(Kind)) {
2203
2.18k
    int InvalidBaseKind = -1;
2204
2.18k
    StringRef Ident;
2205
2.18k
    if (Base.is<TypeInfoLValue>())
2206
6
      InvalidBaseKind = 0;
2207
2.17k
    else if (isa_and_nonnull<StringLiteral>(BaseE))
2208
20
      InvalidBaseKind = 1;
2209
2.15k
    else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2210
2.15k
             
isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)2.14k
)
2211
15
      InvalidBaseKind = 2;
2212
2.14k
    else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2213
8
      InvalidBaseKind = 3;
2214
8
      Ident = PE->getIdentKindName();
2215
8
    }
2216
2217
2.18k
    if (InvalidBaseKind != -1) {
2218
49
      Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2219
49
          << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2220
49
          << Ident;
2221
49
      return false;
2222
49
    }
2223
2.18k
  }
2224
2225
139k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2226
139k
      FD && 
FD->isImmediateFunction()15.5k
) {
2227
156
    Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2228
156
        << !Type->isAnyPointerType();
2229
156
    Info.Note(FD->getLocation(), diag::note_declared_at);
2230
156
    return false;
2231
156
  }
2232
2233
  // Check that the object is a global. Note that the fake 'this' object we
2234
  // manufacture when checking potential constant expressions is conservatively
2235
  // assumed to be global here.
2236
139k
  if (!IsGlobalLValue(Base)) {
2237
72.7k
    if (Info.getLangOpts().CPlusPlus11) {
2238
56.0k
      Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2239
56.0k
          << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2240
56.0k
          << BaseVD;
2241
56.0k
      auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2242
56.0k
      if (VarD && 
VarD->isConstexpr()55.6k
) {
2243
        // Non-static local constexpr variables have unintuitive semantics:
2244
        //   constexpr int a = 1;
2245
        //   constexpr const int *p = &a;
2246
        // ... is invalid because the address of 'a' is not constant. Suggest
2247
        // adding a 'static' in this case.
2248
36
        Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2249
36
            << VarD
2250
36
            << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2251
56.0k
      } else {
2252
56.0k
        NoteLValueLocation(Info, Base);
2253
56.0k
      }
2254
56.0k
    } else {
2255
16.6k
      Info.FFDiag(Loc);
2256
16.6k
    }
2257
    // Don't allow references to temporaries to escape.
2258
72.7k
    return false;
2259
72.7k
  }
2260
66.7k
  assert((Info.checkingPotentialConstantExpression() ||
2261
66.7k
          LVal.getLValueCallIndex() == 0) &&
2262
66.7k
         "have call index for global lvalue");
2263
2264
66.7k
  if (Base.is<DynamicAllocLValue>()) {
2265
232
    Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2266
232
        << IsReferenceType << !Designator.Entries.empty();
2267
232
    NoteLValueLocation(Info, Base);
2268
232
    return false;
2269
232
  }
2270
2271
66.5k
  if (BaseVD) {
2272
43.6k
    if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2273
      // Check if this is a thread-local variable.
2274
27.3k
      if (Var->getTLSKind())
2275
        // FIXME: Diagnostic!
2276
173
        return false;
2277
2278
      // A dllimport variable never acts like a constant, unless we're
2279
      // evaluating a value for use only in name mangling.
2280
27.1k
      if (!isForManglingOnly(Kind) && 
Var->hasAttr<DLLImportAttr>()26.6k
)
2281
        // FIXME: Diagnostic!
2282
113
        return false;
2283
2284
      // In CUDA/HIP device compilation, only device side variables have
2285
      // constant addresses.
2286
27.0k
      if (Info.getCtx().getLangOpts().CUDA &&
2287
27.0k
          
Info.getCtx().getLangOpts().CUDAIsDevice934
&&
2288
27.0k
          
Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars485
) {
2289
62
        if ((!Var->hasAttr<CUDADeviceAttr>() &&
2290
62
             
!Var->hasAttr<CUDAConstantAttr>()54
&&
2291
62
             
!Var->getType()->isCUDADeviceBuiltinSurfaceType()20
&&
2292
62
             
!Var->getType()->isCUDADeviceBuiltinTextureType()16
) ||
2293
62
            
Var->hasAttr<HIPManagedAttr>()50
)
2294
16
          return false;
2295
62
      }
2296
27.0k
    }
2297
43.3k
    if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2298
      // __declspec(dllimport) must be handled very carefully:
2299
      // We must never initialize an expression with the thunk in C++.
2300
      // Doing otherwise would allow the same id-expression to yield
2301
      // different addresses for the same function in different translation
2302
      // units.  However, this means that we must dynamically initialize the
2303
      // expression with the contents of the import address table at runtime.
2304
      //
2305
      // The C language has no notion of ODR; furthermore, it has no notion of
2306
      // dynamic initialization.  This means that we are permitted to
2307
      // perform initialization with the address of the thunk.
2308
15.4k
      if (Info.getLangOpts().CPlusPlus && 
!isForManglingOnly(Kind)12.6k
&&
2309
15.4k
          
FD->hasAttr<DLLImportAttr>()11.3k
)
2310
        // FIXME: Diagnostic!
2311
269
        return false;
2312
15.4k
    }
2313
43.3k
  } else 
if (const auto *22.9k
MTE22.9k
=
2314
22.9k
                 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2315
810
    if (CheckedTemps.insert(MTE).second) {
2316
796
      QualType TempType = getType(Base);
2317
796
      if (TempType.isDestructedType()) {
2318
3
        Info.FFDiag(MTE->getExprLoc(),
2319
3
                    diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2320
3
            << TempType;
2321
3
        return false;
2322
3
      }
2323
2324
793
      APValue *V = MTE->getOrCreateValue(false);
2325
793
      assert(V && "evasluation result refers to uninitialised temporary");
2326
793
      if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2327
793
                                 Info, MTE->getExprLoc(), TempType, *V, Kind,
2328
793
                                 /*SubobjectDecl=*/nullptr, CheckedTemps))
2329
7
        return false;
2330
793
    }
2331
810
  }
2332
2333
  // Allow address constant expressions to be past-the-end pointers. This is
2334
  // an extension: the standard requires them to point to an object.
2335
65.9k
  if (!IsReferenceType)
2336
45.3k
    return true;
2337
2338
  // A reference constant expression must refer to an object.
2339
20.5k
  if (!Base) {
2340
    // FIXME: diagnostic
2341
279
    Info.CCEDiag(Loc);
2342
279
    return true;
2343
279
  }
2344
2345
  // Does this refer one past the end of some object?
2346
20.2k
  if (!Designator.Invalid && 
Designator.isOnePastTheEnd()20.2k
) {
2347
71
    Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2348
71
      << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2349
71
    NoteLValueLocation(Info, Base);
2350
71
  }
2351
2352
20.2k
  return true;
2353
20.5k
}
2354
2355
/// Member pointers are constant expressions unless they point to a
2356
/// non-virtual dllimport member function.
2357
static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2358
                                                 SourceLocation Loc,
2359
                                                 QualType Type,
2360
                                                 const APValue &Value,
2361
3.11k
                                                 ConstantExprKind Kind) {
2362
3.11k
  const ValueDecl *Member = Value.getMemberPointerDecl();
2363
3.11k
  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2364
3.11k
  if (!FD)
2365
760
    return true;
2366
2.35k
  if (FD->isImmediateFunction()) {
2367
7
    Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2368
7
    Info.Note(FD->getLocation(), diag::note_declared_at);
2369
7
    return false;
2370
7
  }
2371
2.35k
  return isForManglingOnly(Kind) || 
FD->isVirtual()2.27k
||
2372
2.35k
         
!FD->hasAttr<DLLImportAttr>()1.93k
;
2373
2.35k
}
2374
2375
/// Check that this core constant expression is of literal type, and if not,
2376
/// produce an appropriate diagnostic.
2377
static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2378
17.2M
                             const LValue *This = nullptr) {
2379
17.2M
  if (!E->isPRValue() || 
E->getType()->isLiteralType(Info.Ctx)14.3M
)
2380
17.1M
    return true;
2381
2382
  // C++1y: A constant initializer for an object o [...] may also invoke
2383
  // constexpr constructors for o and its subobjects even if those objects
2384
  // are of non-literal class types.
2385
  //
2386
  // C++11 missed this detail for aggregates, so classes like this:
2387
  //   struct foo_t { union { int i; volatile int j; } u; };
2388
  // are not (obviously) initializable like so:
2389
  //   __attribute__((__require_constant_initialization__))
2390
  //   static const foo_t x = {{0}};
2391
  // because "i" is a subobject with non-literal initialization (due to the
2392
  // volatile member of the union). See:
2393
  //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2394
  // Therefore, we use the C++1y behavior.
2395
120k
  if (This && 
Info.EvaluatingDecl == This->getLValueBase()24.3k
)
2396
3.02k
    return true;
2397
2398
  // Prvalue constant expressions must be of literal types.
2399
116k
  if (Info.getLangOpts().CPlusPlus11)
2400
70.7k
    Info.FFDiag(E, diag::note_constexpr_nonliteral)
2401
70.7k
      << E->getType();
2402
46.2k
  else
2403
46.2k
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2404
116k
  return false;
2405
120k
}
2406
2407
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2408
                                  EvalInfo &Info, SourceLocation DiagLoc,
2409
                                  QualType Type, const APValue &Value,
2410
                                  ConstantExprKind Kind,
2411
                                  const FieldDecl *SubobjectDecl,
2412
12.9M
                                  CheckedTemporaries &CheckedTemps) {
2413
12.9M
  if (!Value.hasValue()) {
2414
1.48k
    if (SubobjectDecl) {
2415
1.48k
      Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2416
1.48k
          << /*(name)*/ 1 << SubobjectDecl;
2417
1.48k
      Info.Note(SubobjectDecl->getLocation(),
2418
1.48k
                diag::note_constexpr_subobject_declared_here);
2419
1.48k
    } else {
2420
3
      Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2421
3
          << /*of type*/ 0 << Type;
2422
3
    }
2423
1.48k
    return false;
2424
1.48k
  }
2425
2426
  // We allow _Atomic(T) to be initialized from anything that T can be
2427
  // initialized from.
2428
12.9M
  if (const AtomicType *AT = Type->getAs<AtomicType>())
2429
119
    Type = AT->getValueType();
2430
2431
  // Core issue 1454: For a literal constant expression of array or class type,
2432
  // each subobject of its value shall have been initialized by a constant
2433
  // expression.
2434
12.9M
  if (Value.isArray()) {
2435
5.48k
    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2436
92.6k
    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; 
++I87.1k
) {
2437
87.2k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2438
87.2k
                                 Value.getArrayInitializedElt(I), Kind,
2439
87.2k
                                 SubobjectDecl, CheckedTemps))
2440
54
        return false;
2441
87.2k
    }
2442
5.42k
    if (!Value.hasArrayFiller())
2443
3.56k
      return true;
2444
1.86k
    return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2445
1.86k
                                 Value.getArrayFiller(), Kind, SubobjectDecl,
2446
1.86k
                                 CheckedTemps);
2447
5.42k
  }
2448
12.9M
  if (Value.isUnion() && 
Value.getUnionField()998
) {
2449
649
    return CheckEvaluationResult(
2450
649
        CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2451
649
        Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2452
649
  }
2453
12.9M
  if (Value.isStruct()) {
2454
39.2k
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2455
39.2k
    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2456
37.8k
      unsigned BaseIndex = 0;
2457
37.8k
      for (const CXXBaseSpecifier &BS : CD->bases()) {
2458
3.62k
        const APValue &BaseValue = Value.getStructBase(BaseIndex);
2459
3.62k
        if (!BaseValue.hasValue()) {
2460
10
          SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2461
10
          Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2462
10
              << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2463
10
          return false;
2464
10
        }
2465
3.61k
        if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2466
3.61k
                                   Kind, /*SubobjectDecl=*/nullptr,
2467
3.61k
                                   CheckedTemps))
2468
609
          return false;
2469
3.01k
        ++BaseIndex;
2470
3.01k
      }
2471
37.8k
    }
2472
38.6k
    for (const auto *I : RD->fields()) {
2473
36.8k
      if (I->isUnnamedBitfield())
2474
271
        continue;
2475
2476
36.5k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2477
36.5k
                                 Value.getStructField(I->getFieldIndex()), Kind,
2478
36.5k
                                 I, CheckedTemps))
2479
1.83k
        return false;
2480
36.5k
    }
2481
38.6k
  }
2482
2483
12.9M
  if (Value.isLValue() &&
2484
12.9M
      
CERK == CheckEvaluationResultKind::ConstantExpression226k
) {
2485
139k
    LValue LVal;
2486
139k
    LVal.setFrom(Info.Ctx, Value);
2487
139k
    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2488
139k
                                         CheckedTemps);
2489
139k
  }
2490
2491
12.7M
  if (Value.isMemberPointer() &&
2492
12.7M
      
CERK == CheckEvaluationResultKind::ConstantExpression3.38k
)
2493
3.11k
    return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2494
2495
  // Everything else is fine.
2496
12.7M
  return true;
2497
12.7M
}
2498
2499
/// Check that this core constant expression value is a valid value for a
2500
/// constant expression. If not, report an appropriate diagnostic. Does not
2501
/// check that the expression is of literal type.
2502
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2503
                                    QualType Type, const APValue &Value,
2504
10.2M
                                    ConstantExprKind Kind) {
2505
  // Nothing to check for a constant expression of type 'cv void'.
2506
10.2M
  if (Type->isVoidType())
2507
237
    return true;
2508
2509
10.2M
  CheckedTemporaries CheckedTemps;
2510
10.2M
  return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2511
10.2M
                               Info, DiagLoc, Type, Value, Kind,
2512
10.2M
                               /*SubobjectDecl=*/nullptr, CheckedTemps);
2513
10.2M
}
2514
2515
/// Check that this evaluated value is fully-initialized and can be loaded by
2516
/// an lvalue-to-rvalue conversion.
2517
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2518
2.54M
                                  QualType Type, const APValue &Value) {
2519
2.54M
  CheckedTemporaries CheckedTemps;
2520
2.54M
  return CheckEvaluationResult(
2521
2.54M
      CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2522
2.54M
      ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2523
2.54M
}
2524
2525
/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2526
/// "the allocated storage is deallocated within the evaluation".
2527
10.1M
static bool CheckMemoryLeaks(EvalInfo &Info) {
2528
10.1M
  if (!Info.HeapAllocs.empty()) {
2529
    // We can still fold to a constant despite a compile-time memory leak,
2530
    // so long as the heap allocation isn't referenced in the result (we check
2531
    // that in CheckConstantExpression).
2532
25
    Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2533
25
                 diag::note_constexpr_memory_leak)
2534
25
        << unsigned(Info.HeapAllocs.size() - 1);
2535
25
  }
2536
10.1M
  return true;
2537
10.1M
}
2538
2539
6.02k
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2540
  // A null base expression indicates a null pointer.  These are always
2541
  // evaluatable, and they are false unless the offset is zero.
2542
6.02k
  if (!Value.getLValueBase()) {
2543
    // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2544
1.06k
    Result = !Value.getLValueOffset().isZero();
2545
1.06k
    return true;
2546
1.06k
  }
2547
2548
  // We have a non-null base.  These are generally known to be true, but if it's
2549
  // a weak declaration it can be null at runtime.
2550
4.96k
  Result = true;
2551
4.96k
  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2552
4.96k
  return !Decl || 
!Decl->isWeak()1.49k
;
2553
6.02k
}
2554
2555
4.06M
static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2556
  // TODO: This function should produce notes if it fails.
2557
4.06M
  switch (Val.getKind()) {
2558
182k
  case APValue::None:
2559
182k
  case APValue::Indeterminate:
2560
182k
    return false;
2561
3.88M
  case APValue::Int:
2562
3.88M
    Result = Val.getInt().getBoolValue();
2563
3.88M
    return true;
2564
0
  case APValue::FixedPoint:
2565
0
    Result = Val.getFixedPoint().getBoolValue();
2566
0
    return true;
2567
139
  case APValue::Float:
2568
139
    Result = !Val.getFloat().isZero();
2569
139
    return true;
2570
4
  case APValue::ComplexInt:
2571
4
    Result = Val.getComplexIntReal().getBoolValue() ||
2572
4
             
Val.getComplexIntImag().getBoolValue()2
;
2573
4
    return true;
2574
14
  case APValue::ComplexFloat:
2575
14
    Result = !Val.getComplexFloatReal().isZero() ||
2576
14
             
!Val.getComplexFloatImag().isZero()7
;
2577
14
    return true;
2578
6.02k
  case APValue::LValue:
2579
6.02k
    return EvalPointerValueAsBool(Val, Result);
2580
78
  case APValue::MemberPointer:
2581
78
    if (Val.getMemberPointerDecl() && 
Val.getMemberPointerDecl()->isWeak()56
) {
2582
2
      return false;
2583
2
    }
2584
76
    Result = Val.getMemberPointerDecl();
2585
76
    return true;
2586
36
  case APValue::Vector:
2587
36
  case APValue::Array:
2588
36
  case APValue::Struct:
2589
36
  case APValue::Union:
2590
36
  case APValue::AddrLabelDiff:
2591
36
    return false;
2592
4.06M
  }
2593
2594
0
  llvm_unreachable("unknown APValue kind");
2595
0
}
2596
2597
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2598
2.00M
                                       EvalInfo &Info) {
2599
2.00M
  assert(!E->isValueDependent());
2600
2.00M
  assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2601
2.00M
  APValue Val;
2602
2.00M
  if (!Evaluate(Val, Info, E))
2603
500k
    return false;
2604
1.50M
  return HandleConversionToBool(Val, Result);
2605
2.00M
}
2606
2607
template<typename T>
2608
static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2609
659
                           const T &SrcValue, QualType DestType) {
2610
659
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2611
659
    << SrcValue << DestType;
2612
659
  return Info.noteUndefinedBehavior();
2613
659
}
ExprConstant.cpp:bool HandleOverflow<llvm::APSInt>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, clang::QualType)
Line
Count
Source
2609
570
                           const T &SrcValue, QualType DestType) {
2610
570
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2611
570
    << SrcValue << DestType;
2612
570
  return Info.noteUndefinedBehavior();
2613
570
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFloat>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFloat const&, clang::QualType)
Line
Count
Source
2609
31
                           const T &SrcValue, QualType DestType) {
2610
31
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2611
31
    << SrcValue << DestType;
2612
31
  return Info.noteUndefinedBehavior();
2613
31
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFixedPoint>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFixedPoint const&, clang::QualType)
Line
Count
Source
2609
58
                           const T &SrcValue, QualType DestType) {
2610
58
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2611
58
    << SrcValue << DestType;
2612
58
  return Info.noteUndefinedBehavior();
2613
58
}
2614
2615
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2616
                                 QualType SrcType, const APFloat &Value,
2617
5.49k
                                 QualType DestType, APSInt &Result) {
2618
5.49k
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2619
  // Determine whether we are converting to unsigned or signed.
2620
5.49k
  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2621
2622
5.49k
  Result = APSInt(DestWidth, !DestSigned);
2623
5.49k
  bool ignored;
2624
5.49k
  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2625
5.49k
      & APFloat::opInvalidOp)
2626
31
    return HandleOverflow(Info, E, Value, DestType);
2627
5.46k
  return true;
2628
5.49k
}
2629
2630
/// Get rounding mode to use in evaluation of the specified expression.
2631
///
2632
/// If rounding mode is unknown at compile time, still try to evaluate the
2633
/// expression. If the result is exact, it does not depend on rounding mode.
2634
/// So return "tonearest" mode instead of "dynamic".
2635
56.2k
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2636
56.2k
  llvm::RoundingMode RM =
2637
56.2k
      E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2638
56.2k
  if (RM == llvm::RoundingMode::Dynamic)
2639
244
    RM = llvm::RoundingMode::NearestTiesToEven;
2640
56.2k
  return RM;
2641
56.2k
}
2642
2643
/// Check if the given evaluation result is allowed for constant evaluation.
2644
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2645
56.2k
                                     APFloat::opStatus St) {
2646
  // In a constant context, assume that any dynamic rounding mode or FP
2647
  // exception state matches the default floating-point environment.
2648
56.2k
  if (Info.InConstantContext)
2649
31.1k
    return true;
2650
2651
25.0k
  FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2652
25.0k
  if ((St & APFloat::opInexact) &&
2653
25.0k
      
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic405
) {
2654
    // Inexact result means that it depends on rounding mode. If the requested
2655
    // mode is dynamic, the evaluation cannot be made in compile time.
2656
28
    Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2657
28
    return false;
2658
28
  }
2659
2660
25.0k
  if ((St != APFloat::opOK) &&
2661
25.0k
      
(391
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic391
||
2662
391
       FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2663
391
       
FPO.getAllowFEnvAccess()389
)) {
2664
2
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2665
2
    return false;
2666
2
  }
2667
2668
25.0k
  if ((St & APFloat::opStatus::opInvalidOp) &&
2669
25.0k
      
FPO.getExceptionMode() != LangOptions::FPE_Ignore0
) {
2670
    // There is no usefully definable result.
2671
0
    Info.FFDiag(E);
2672
0
    return false;
2673
0
  }
2674
2675
  // FIXME: if:
2676
  // - evaluation triggered other FP exception, and
2677
  // - exception mode is not "ignore", and
2678
  // - the expression being evaluated is not a part of global variable
2679
  //   initializer,
2680
  // the evaluation probably need to be rejected.
2681
25.0k
  return true;
2682
25.0k
}
2683
2684
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2685
                                   QualType SrcType, QualType DestType,
2686
11.9k
                                   APFloat &Result) {
2687
11.9k
  assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2688
11.9k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2689
11.9k
  APFloat::opStatus St;
2690
11.9k
  APFloat Value = Result;
2691
11.9k
  bool ignored;
2692
11.9k
  St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2693
11.9k
  return checkFloatingPointResult(Info, E, St);
2694
11.9k
}
2695
2696
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2697
                                 QualType DestType, QualType SrcType,
2698
1.60M
                                 const APSInt &Value) {
2699
1.60M
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2700
  // Figure out if this is a truncate, extend or noop cast.
2701
  // If the input is signed, do a sign extend, noop, or truncate.
2702
1.60M
  APSInt Result = Value.extOrTrunc(DestWidth);
2703
1.60M
  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2704
1.60M
  if (DestType->isBooleanType())
2705
80
    Result = Value.getBoolValue();
2706
1.60M
  return Result;
2707
1.60M
}
2708
2709
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2710
                                 const FPOptions FPO,
2711
                                 QualType SrcType, const APSInt &Value,
2712
25.5k
                                 QualType DestType, APFloat &Result) {
2713
25.5k
  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2714
25.5k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2715
25.5k
  APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2716
25.5k
  return checkFloatingPointResult(Info, E, St);
2717
25.5k
}
2718
2719
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2720
997
                                  APValue &Value, const FieldDecl *FD) {
2721
997
  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2722
2723
997
  if (!Value.isInt()) {
2724
    // Trying to store a pointer-cast-to-integer into a bitfield.
2725
    // FIXME: In this case, we should provide the diagnostic for casting
2726
    // a pointer to an integer.
2727
5
    assert(Value.isLValue() && "integral value neither int nor lvalue?");
2728
5
    Info.FFDiag(E);
2729
5
    return false;
2730
5
  }
2731
2732
992
  APSInt &Int = Value.getInt();
2733
992
  unsigned OldBitWidth = Int.getBitWidth();
2734
992
  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2735
992
  if (NewBitWidth < OldBitWidth)
2736
955
    Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2737
992
  return true;
2738
997
}
2739
2740
/// Perform the given integer operation, which is known to need at most BitWidth
2741
/// bits, and check for overflow in the original type (if that type was not an
2742
/// unsigned type).
2743
template<typename Operation>
2744
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2745
                                 const APSInt &LHS, const APSInt &RHS,
2746
                                 unsigned BitWidth, Operation Op,
2747
4.30M
                                 APSInt &Result) {
2748
4.30M
  if (LHS.isUnsigned()) {
2749
174k
    Result = Op(LHS, RHS);
2750
174k
    return true;
2751
174k
  }
2752
2753
4.13M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2754
4.13M
  Result = Value.trunc(LHS.getBitWidth());
2755
4.13M
  if (Result.extend(BitWidth) != Value) {
2756
516
    if (Info.checkingForUndefinedBehavior())
2757
231
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2758
231
                                       diag::warn_integer_constant_overflow)
2759
231
          << toString(Result, 10) << E->getType() << E->getSourceRange();
2760
516
    return HandleOverflow(Info, E, Value, E->getType());
2761
516
  }
2762
4.13M
  return true;
2763
4.13M
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::multiplies<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::multiplies<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2747
274k
                                 APSInt &Result) {
2748
274k
  if (LHS.isUnsigned()) {
2749
74.4k
    Result = Op(LHS, RHS);
2750
74.4k
    return true;
2751
74.4k
  }
2752
2753
200k
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2754
200k
  Result = Value.trunc(LHS.getBitWidth());
2755
200k
  if (Result.extend(BitWidth) != Value) {
2756
460
    if (Info.checkingForUndefinedBehavior())
2757
216
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2758
216
                                       diag::warn_integer_constant_overflow)
2759
216
          << toString(Result, 10) << E->getType() << E->getSourceRange();
2760
460
    return HandleOverflow(Info, E, Value, E->getType());
2761
460
  }
2762
199k
  return true;
2763
200k
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::plus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::plus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2747
1.38M
                                 APSInt &Result) {
2748
1.38M
  if (LHS.isUnsigned()) {
2749
21.0k
    Result = Op(LHS, RHS);
2750
21.0k
    return true;
2751
21.0k
  }
2752
2753
1.36M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2754
1.36M
  Result = Value.trunc(LHS.getBitWidth());
2755
1.36M
  if (Result.extend(BitWidth) != Value) {
2756
45
    if (Info.checkingForUndefinedBehavior())
2757
15
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2758
15
                                       diag::warn_integer_constant_overflow)
2759
15
          << toString(Result, 10) << E->getType() << E->getSourceRange();
2760
45
    return HandleOverflow(Info, E, Value, E->getType());
2761
45
  }
2762
1.36M
  return true;
2763
1.36M
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::minus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::minus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2747
2.65M
                                 APSInt &Result) {
2748
2.65M
  if (LHS.isUnsigned()) {
2749
78.5k
    Result = Op(LHS, RHS);
2750
78.5k
    return true;
2751
78.5k
  }
2752
2753
2.57M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2754
2.57M
  Result = Value.trunc(LHS.getBitWidth());
2755
2.57M
  if (Result.extend(BitWidth) != Value) {
2756
11
    if (Info.checkingForUndefinedBehavior())
2757
0
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2758
0
                                       diag::warn_integer_constant_overflow)
2759
0
          << toString(Result, 10) << E->getType() << E->getSourceRange();
2760
11
    return HandleOverflow(Info, E, Value, E->getType());
2761
11
  }
2762
2.57M
  return true;
2763
2.57M
}
2764
2765
/// Perform the given binary integer operation.
2766
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2767
                              const APSInt &LHS, BinaryOperatorKind Opcode,
2768
6.10M
                              APSInt RHS, APSInt &Result) {
2769
6.10M
  bool HandleOverflowResult = true;
2770
6.10M
  switch (Opcode) {
2771
0
  default:
2772
0
    Info.FFDiag(E);
2773
0
    return false;
2774
274k
  case BO_Mul:
2775
274k
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2776
274k
                                std::multiplies<APSInt>(), Result);
2777
1.38M
  case BO_Add:
2778
1.38M
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2779
1.38M
                                std::plus<APSInt>(), Result);
2780
2.65M
  case BO_Sub:
2781
2.65M
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2782
2.65M
                                std::minus<APSInt>(), Result);
2783
19.0k
  case BO_And: Result = LHS & RHS; return true;
2784
2.06k
  case BO_Xor: Result = LHS ^ RHS; return true;
2785
93.1k
  case BO_Or:  Result = LHS | RHS; return true;
2786
1.04M
  case BO_Div:
2787
1.04M
  case BO_Rem:
2788
1.04M
    if (RHS == 0) {
2789
298
      Info.FFDiag(E, diag::note_expr_divide_by_zero)
2790
298
          << E->getRHS()->getSourceRange();
2791
298
      return false;
2792
298
    }
2793
    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2794
    // this operation and gives the two's complement result.
2795
1.04M
    if (RHS.isNegative() && 
RHS.isAllOnes()38
&&
LHS.isSigned()18
&&
2796
1.04M
        
LHS.isMinSignedValue()18
)
2797
17
      HandleOverflowResult = HandleOverflow(
2798
17
          Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2799
1.04M
    Result = (Opcode == BO_Rem ? 
LHS % RHS6.86k
:
LHS / RHS1.04M
);
2800
1.04M
    return HandleOverflowResult;
2801
266k
  case BO_Shl: {
2802
266k
    if (Info.getLangOpts().OpenCL)
2803
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2804
18
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2805
18
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2806
18
                    RHS.isUnsigned());
2807
266k
    else if (RHS.isSigned() && 
RHS.isNegative()232k
) {
2808
      // During constant-folding, a negative shift is an opposite shift. Such
2809
      // a shift is not a constant expression.
2810
24
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2811
24
      RHS = -RHS;
2812
24
      goto shift_right;
2813
24
    }
2814
266k
  shift_left:
2815
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2816
    // the shifted type.
2817
266k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2818
266k
    if (SA != RHS) {
2819
46
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2820
46
        << RHS << E->getType() << LHS.getBitWidth();
2821
266k
    } else if (LHS.isSigned() && 
!Info.getLangOpts().CPlusPlus20181k
) {
2822
      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2823
      // operand, and must not overflow the corresponding unsigned type.
2824
      // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2825
      // E1 x 2^E2 module 2^N.
2826
180k
      if (LHS.isNegative())
2827
44
        Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2828
179k
      else if (LHS.countl_zero() < SA)
2829
18
        Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2830
180k
    }
2831
266k
    Result = LHS << SA;
2832
266k
    return true;
2833
266k
  }
2834
11.0k
  case BO_Shr: {
2835
11.0k
    if (Info.getLangOpts().OpenCL)
2836
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2837
2
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2838
2
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2839
2
                    RHS.isUnsigned());
2840
11.0k
    else if (RHS.isSigned() && 
RHS.isNegative()11.0k
) {
2841
      // During constant-folding, a negative shift is an opposite shift. Such a
2842
      // shift is not a constant expression.
2843
21
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2844
21
      RHS = -RHS;
2845
21
      goto shift_left;
2846
21
    }
2847
11.0k
  shift_right:
2848
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2849
    // shifted type.
2850
11.0k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2851
11.0k
    if (SA != RHS)
2852
17
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2853
17
        << RHS << E->getType() << LHS.getBitWidth();
2854
11.0k
    Result = LHS >> SA;
2855
11.0k
    return true;
2856
11.0k
  }
2857
2858
65.9k
  case BO_LT: Result = LHS < RHS; return true;
2859
12.7k
  case BO_GT: Result = LHS > RHS; return true;
2860
23.4k
  case BO_LE: Result = LHS <= RHS; return true;
2861
6.79k
  case BO_GE: Result = LHS >= RHS; return true;
2862
165k
  case BO_EQ: Result = LHS == RHS; return true;
2863
80.8k
  case BO_NE: Result = LHS != RHS; return true;
2864
0
  case BO_Cmp:
2865
0
    llvm_unreachable("BO_Cmp should be handled elsewhere");
2866
6.10M
  }
2867
6.10M
}
2868
2869
/// Perform the given binary floating-point operation, in-place, on LHS.
2870
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2871
                                  APFloat &LHS, BinaryOperatorKind Opcode,
2872
18.7k
                                  const APFloat &RHS) {
2873
18.7k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2874
18.7k
  APFloat::opStatus St;
2875
18.7k
  switch (Opcode) {
2876
0
  default:
2877
0
    Info.FFDiag(E);
2878
0
    return false;
2879
4.21k
  case BO_Mul:
2880
4.21k
    St = LHS.multiply(RHS, RM);
2881
4.21k
    break;
2882
3.28k
  case BO_Add:
2883
3.28k
    St = LHS.add(RHS, RM);
2884
3.28k
    break;
2885
4.70k
  case BO_Sub:
2886
4.70k
    St = LHS.subtract(RHS, RM);
2887
4.70k
    break;
2888
6.57k
  case BO_Div:
2889
    // [expr.mul]p4:
2890
    //   If the second operand of / or % is zero the behavior is undefined.
2891
6.57k
    if (RHS.isZero())
2892
29
      Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2893
6.57k
    St = LHS.divide(RHS, RM);
2894
6.57k
    break;
2895
18.7k
  }
2896
2897
  // [expr.pre]p4:
2898
  //   If during the evaluation of an expression, the result is not
2899
  //   mathematically defined [...], the behavior is undefined.
2900
  // FIXME: C++ rules require us to not conform to IEEE 754 here.
2901
18.7k
  if (LHS.isNaN()) {
2902
16
    Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2903
16
    return Info.noteUndefinedBehavior();
2904
16
  }
2905
2906
18.7k
  return checkFloatingPointResult(Info, E, St);
2907
18.7k
}
2908
2909
static bool handleLogicalOpForVector(const APInt &LHSValue,
2910
                                     BinaryOperatorKind Opcode,
2911
32
                                     const APInt &RHSValue, APInt &Result) {
2912
32
  bool LHS = (LHSValue != 0);
2913
32
  bool RHS = (RHSValue != 0);
2914
2915
32
  if (Opcode == BO_LAnd)
2916
16
    Result = LHS && 
RHS8
;
2917
16
  else
2918
16
    Result = LHS || 
RHS8
;
2919
32
  return true;
2920
32
}
2921
static bool handleLogicalOpForVector(const APFloat &LHSValue,
2922
                                     BinaryOperatorKind Opcode,
2923
96
                                     const APFloat &RHSValue, APInt &Result) {
2924
96
  bool LHS = !LHSValue.isZero();
2925
96
  bool RHS = !RHSValue.isZero();
2926
2927
96
  if (Opcode == BO_LAnd)
2928
48
    Result = LHS && 
RHS24
;
2929
48
  else
2930
48
    Result = LHS || 
RHS40
;
2931
96
  return true;
2932
96
}
2933
2934
static bool handleLogicalOpForVector(const APValue &LHSValue,
2935
                                     BinaryOperatorKind Opcode,
2936
128
                                     const APValue &RHSValue, APInt &Result) {
2937
  // The result is always an int type, however operands match the first.
2938
128
  if (LHSValue.getKind() == APValue::Int)
2939
32
    return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2940
32
                                    RHSValue.getInt(), Result);
2941
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2942
96
  return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2943
96
                                  RHSValue.getFloat(), Result);
2944
96
}
2945
2946
template <typename APTy>
2947
static bool
2948
handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2949
224
                               const APTy &RHSValue, APInt &Result) {
2950
224
  switch (Opcode) {
2951
0
  default:
2952
0
    llvm_unreachable("unsupported binary operator");
2953
36
  case BO_EQ:
2954
36
    Result = (LHSValue == RHSValue);
2955
36
    break;
2956
36
  case BO_NE:
2957
36
    Result = (LHSValue != RHSValue);
2958
36
    break;
2959
44
  case BO_LT:
2960
44
    Result = (LHSValue < RHSValue);
2961
44
    break;
2962
36
  case BO_GT:
2963
36
    Result = (LHSValue > RHSValue);
2964
36
    break;
2965
36
  case BO_LE:
2966
36
    Result = (LHSValue <= RHSValue);
2967
36
    break;
2968
36
  case BO_GE:
2969
36
    Result = (LHSValue >= RHSValue);
2970
36
    break;
2971
224
  }
2972
2973
  // The boolean operations on these vector types use an instruction that
2974
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2975
  // to -1 to make sure that we produce the correct value.
2976
224
  Result.negate();
2977
2978
224
  return true;
2979
224
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APSInt>(llvm::APSInt const&, clang::BinaryOperatorKind, llvm::APSInt const&, llvm::APInt&)
Line
Count
Source
2949
128
                               const APTy &RHSValue, APInt &Result) {
2950
128
  switch (Opcode) {
2951
0
  default:
2952
0
    llvm_unreachable("unsupported binary operator");
2953
20
  case BO_EQ:
2954
20
    Result = (LHSValue == RHSValue);
2955
20
    break;
2956
20
  case BO_NE:
2957
20
    Result = (LHSValue != RHSValue);
2958
20
    break;
2959
28
  case BO_LT:
2960
28
    Result = (LHSValue < RHSValue);
2961
28
    break;
2962
20
  case BO_GT:
2963
20
    Result = (LHSValue > RHSValue);
2964
20
    break;
2965
20
  case BO_LE:
2966
20
    Result = (LHSValue <= RHSValue);
2967
20
    break;
2968
20
  case BO_GE:
2969
20
    Result = (LHSValue >= RHSValue);
2970
20
    break;
2971
128
  }
2972
2973
  // The boolean operations on these vector types use an instruction that
2974
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2975
  // to -1 to make sure that we produce the correct value.
2976
128
  Result.negate();
2977
2978
128
  return true;
2979
128
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APFloat>(llvm::APFloat const&, clang::BinaryOperatorKind, llvm::APFloat const&, llvm::APInt&)
Line
Count
Source
2949
96
                               const APTy &RHSValue, APInt &Result) {
2950
96
  switch (Opcode) {
2951
0
  default:
2952
0
    llvm_unreachable("unsupported binary operator");
2953
16
  case BO_EQ:
2954
16
    Result = (LHSValue == RHSValue);
2955
16
    break;
2956
16
  case BO_NE:
2957
16
    Result = (LHSValue != RHSValue);
2958
16
    break;
2959
16
  case BO_LT:
2960
16
    Result = (LHSValue < RHSValue);
2961
16
    break;
2962
16
  case BO_GT:
2963
16
    Result = (LHSValue > RHSValue);
2964
16
    break;
2965
16
  case BO_LE:
2966
16
    Result = (LHSValue <= RHSValue);
2967
16
    break;
2968
16
  case BO_GE:
2969
16
    Result = (LHSValue >= RHSValue);
2970
16
    break;
2971
96
  }
2972
2973
  // The boolean operations on these vector types use an instruction that
2974
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2975
  // to -1 to make sure that we produce the correct value.
2976
96
  Result.negate();
2977
2978
96
  return true;
2979
96
}
2980
2981
static bool handleCompareOpForVector(const APValue &LHSValue,
2982
                                     BinaryOperatorKind Opcode,
2983
224
                                     const APValue &RHSValue, APInt &Result) {
2984
  // The result is always an int type, however operands match the first.
2985
224
  if (LHSValue.getKind() == APValue::Int)
2986
128
    return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2987
128
                                          RHSValue.getInt(), Result);
2988
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2989
96
  return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2990
96
                                        RHSValue.getFloat(), Result);
2991
96
}
2992
2993
// Perform binary operations for vector types, in place on the LHS.
2994
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2995
                                    BinaryOperatorKind Opcode,
2996
                                    APValue &LHSValue,
2997
559
                                    const APValue &RHSValue) {
2998
559
  assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2999
559
         "Operation not supported on vector types");
3000
3001
559
  const auto *VT = E->getType()->castAs<VectorType>();
3002
559
  unsigned NumElements = VT->getNumElements();
3003
559
  QualType EltTy = VT->getElementType();
3004
3005
  // In the cases (typically C as I've observed) where we aren't evaluating
3006
  // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3007
  // just give up.
3008
559
  if (!LHSValue.isVector()) {
3009
362
    assert(LHSValue.isLValue() &&
3010
362
           "A vector result that isn't a vector OR uncalculated LValue");
3011
362
    Info.FFDiag(E);
3012
362
    return false;
3013
362
  }
3014
3015
197
  assert(LHSValue.getVectorLength() == NumElements &&
3016
197
         RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3017
3018
197
  SmallVector<APValue, 4> ResultElements;
3019
3020
985
  for (unsigned EltNum = 0; EltNum < NumElements; 
++EltNum788
) {
3021
788
    APValue LHSElt = LHSValue.getVectorElt(EltNum);
3022
788
    APValue RHSElt = RHSValue.getVectorElt(EltNum);
3023
3024
788
    if (EltTy->isIntegerType()) {
3025
660
      APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3026
660
                       EltTy->isUnsignedIntegerType()};
3027
660
      bool Success = true;
3028
3029
660
      if (BinaryOperator::isLogicalOp(Opcode))
3030
128
        Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3031
532
      else if (BinaryOperator::isComparisonOp(Opcode))
3032
224
        Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3033
308
      else
3034
308
        Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3035
308
                                    RHSElt.getInt(), EltResult);
3036
3037
660
      if (!Success) {
3038
0
        Info.FFDiag(E);
3039
0
        return false;
3040
0
      }
3041
660
      ResultElements.emplace_back(EltResult);
3042
3043
660
    } else 
if (128
EltTy->isFloatingType()128
) {
3044
128
      assert(LHSElt.getKind() == APValue::Float &&
3045
128
             RHSElt.getKind() == APValue::Float &&
3046
128
             "Mismatched LHS/RHS/Result Type");
3047
128
      APFloat LHSFloat = LHSElt.getFloat();
3048
3049
128
      if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3050
128
                                 RHSElt.getFloat())) {
3051
0
        Info.FFDiag(E);
3052
0
        return false;
3053
0
      }
3054
3055
128
      ResultElements.emplace_back(LHSFloat);
3056
128
    }
3057
788
  }
3058
3059
197
  LHSValue = APValue(ResultElements.data(), ResultElements.size());
3060
197
  return true;
3061
197
}
3062
3063
/// Cast an lvalue referring to a base subobject to a derived class, by
3064
/// truncating the lvalue's path to the given length.
3065
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3066
                               const RecordDecl *TruncatedType,
3067
494
                               unsigned TruncatedElements) {
3068
494
  SubobjectDesignator &D = Result.Designator;
3069
3070
  // Check we actually point to a derived class object.
3071
494
  if (TruncatedElements == D.Entries.size())
3072
207
    return true;
3073
287
  assert(TruncatedElements >= D.MostDerivedPathLength &&
3074
287
         "not casting to a derived class");
3075
287
  if (!Result.checkSubobject(Info, E, CSK_Derived))
3076
6
    return false;
3077
3078
  // Truncate the path to the subobject, and remove any derived-to-base offsets.
3079
281
  const RecordDecl *RD = TruncatedType;
3080
1.12k
  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; 
++I844
) {
3081
844
    if (RD->isInvalidDecl()) 
return false0
;
3082
844
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3083
844
    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3084
844
    if (isVirtualBaseClass(D.Entries[I]))
3085
3
      Result.Offset -= Layout.getVBaseClassOffset(Base);
3086
841
    else
3087
841
      Result.Offset -= Layout.getBaseClassOffset(Base);
3088
844
    RD = Base;
3089
844
  }
3090
281
  D.Entries.resize(TruncatedElements);
3091
281
  return true;
3092
281
}
3093
3094
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3095
                                   const CXXRecordDecl *Derived,
3096
                                   const CXXRecordDecl *Base,
3097
14.8k
                                   const ASTRecordLayout *RL = nullptr) {
3098
14.8k
  if (!RL) {
3099
10.9k
    if (Derived->isInvalidDecl()) 
return false0
;
3100
10.9k
    RL = &Info.Ctx.getASTRecordLayout(Derived);
3101
10.9k
  }
3102
3103
14.8k
  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3104
14.8k
  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3105
14.8k
  return true;
3106
14.8k
}
3107
3108
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3109
                             const CXXRecordDecl *DerivedDecl,
3110
10.7k
                             const CXXBaseSpecifier *Base) {
3111
10.7k
  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3112
3113
10.7k
  if (!Base->isVirtual())
3114
10.6k
    return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3115
3116
131
  SubobjectDesignator &D = Obj.Designator;
3117
131
  if (D.Invalid)
3118
0
    return false;
3119
3120
  // Extract most-derived object and corresponding type.
3121
131
  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3122
131
  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3123
0
    return false;
3124
3125
  // Find the virtual base class.
3126
131
  if (DerivedDecl->isInvalidDecl()) 
return false0
;
3127
131
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3128
131
  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3129
131
  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3130
131
  return true;
3131
131
}
3132
3133
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3134
6.25k
                                 QualType Type, LValue &Result) {
3135
6.25k
  for (CastExpr::path_const_iterator PathI = E->path_begin(),
3136
6.25k
                                     PathE = E->path_end();
3137
16.5k
       PathI != PathE; 
++PathI10.2k
) {
3138
10.2k
    if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3139
10.2k
                          *PathI))
3140
0
      return false;
3141
10.2k
    Type = (*PathI)->getType();
3142
10.2k
  }
3143
6.25k
  return true;
3144
6.25k
}
3145
3146
/// Cast an lvalue referring to a derived class to a known base subobject.
3147
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3148
                            const CXXRecordDecl *DerivedRD,
3149
42
                            const CXXRecordDecl *BaseRD) {
3150
42
  CXXBasePaths Paths(/*FindAmbiguities=*/false,
3151
42
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
3152
42
  if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3153
0
    llvm_unreachable("Class must be derived from the passed in base class!");
3154
3155
42
  for (CXXBasePathElement &Elem : Paths.front())
3156
63
    if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3157
0
      return false;
3158
42
  return true;
3159
42
}
3160
3161
/// Update LVal to refer to the given field, which must be a member of the type
3162
/// currently described by LVal.
3163
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3164
                               const FieldDecl *FD,
3165
208k
                               const ASTRecordLayout *RL = nullptr) {
3166
208k
  if (!RL) {
3167
160k
    if (FD->getParent()->isInvalidDecl()) 
return false4
;
3168
160k
    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3169
160k
  }
3170
3171
208k
  unsigned I = FD->getFieldIndex();
3172
208k
  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3173
208k
  LVal.addDecl(Info, E, FD);
3174
208k
  return true;
3175
208k
}
3176
3177
/// Update LVal to refer to the given indirect field.
3178
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3179
                                       LValue &LVal,
3180
0
                                       const IndirectFieldDecl *IFD) {
3181
0
  for (const auto *C : IFD->chain())
3182
0
    if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3183
0
      return false;
3184
0
  return true;
3185
0
}
3186
3187
/// Get the size of the given type in char units.
3188
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3189
420k
                         QualType Type, CharUnits &Size) {
3190
  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3191
  // extension.
3192
420k
  if (Type->isVoidType() || 
Type->isFunctionType()420k
) {
3193
131
    Size = CharUnits::One();
3194
131
    return true;
3195
131
  }
3196
3197
420k
  if (Type->isDependentType()) {
3198
0
    Info.FFDiag(Loc);
3199
0
    return false;
3200
0
  }
3201
3202
420k
  if (!Type->isConstantSizeType()) {
3203
    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3204
    // FIXME: Better diagnostic.
3205
2.35k
    Info.FFDiag(Loc);
3206
2.35k
    return false;
3207
2.35k
  }
3208
3209
417k
  Size = Info.Ctx.getTypeSizeInChars(Type);
3210
417k
  return true;
3211
420k
}
3212
3213
/// Update a pointer value to model pointer arithmetic.
3214
/// \param Info - Information about the ongoing evaluation.
3215
/// \param E - The expression being evaluated, for diagnostic purposes.
3216
/// \param LVal - The pointer value to be updated.
3217
/// \param EltTy - The pointee type represented by LVal.
3218
/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3219
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3220
                                        LValue &LVal, QualType EltTy,
3221
240k
                                        APSInt Adjustment) {
3222
240k
  CharUnits SizeOfPointee;
3223
240k
  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3224
2.14k
    return false;
3225
3226
238k
  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3227
238k
  return true;
3228
240k
}
3229
3230
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3231
                                        LValue &LVal, QualType EltTy,
3232
195k
                                        int64_t Adjustment) {
3233
195k
  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3234
195k
                                     APSInt::get(Adjustment));
3235
195k
}
3236
3237
/// Update an lvalue to refer to a component of a complex number.
3238
/// \param Info - Information about the ongoing evaluation.
3239
/// \param LVal - The lvalue to be updated.
3240
/// \param EltTy - The complex number's component type.
3241
/// \param Imag - False for the real component, true for the imaginary.
3242
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3243
                                       LValue &LVal, QualType EltTy,
3244
383
                                       bool Imag) {
3245
383
  if (Imag) {
3246
181
    CharUnits SizeOfComponent;
3247
181
    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3248
0
      return false;
3249
181
    LVal.Offset += SizeOfComponent;
3250
181
  }
3251
383
  LVal.addComplex(Info, E, EltTy, Imag);
3252
383
  return true;
3253
383
}
3254
3255
/// Try to evaluate the initializer for a variable declaration.
3256
///
3257
/// \param Info   Information about the ongoing evaluation.
3258
/// \param E      An expression to be used when printing diagnostics.
3259
/// \param VD     The variable whose initializer should be obtained.
3260
/// \param Version The version of the variable within the frame.
3261
/// \param Frame  The frame in which the variable was created. Must be null
3262
///               if this variable is not local to the evaluation.
3263
/// \param Result Filled in with a pointer to the value of the variable.
3264
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3265
                                const VarDecl *VD, CallStackFrame *Frame,
3266
5.09M
                                unsigned Version, APValue *&Result) {
3267
5.09M
  APValue::LValueBase Base(VD, Frame ? 
Frame->Index394k
:
04.70M
, Version);
3268
3269
  // If this is a local variable, dig out its value.
3270
5.09M
  if (Frame) {
3271
394k
    Result = Frame->getTemporary(VD, Version);
3272
394k
    if (Result)
3273
392k
      return true;
3274
3275
1.89k
    if (!isa<ParmVarDecl>(VD)) {
3276
      // Assume variables referenced within a lambda's call operator that were
3277
      // not declared within the call operator are captures and during checking
3278
      // of a potential constant expression, assume they are unknown constant
3279
      // expressions.
3280
0
      assert(isLambdaCallOperator(Frame->Callee) &&
3281
0
             (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3282
0
             "missing value for local variable");
3283
0
      if (Info.checkingPotentialConstantExpression())
3284
0
        return false;
3285
      // FIXME: This diagnostic is bogus; we do support captures. Is this code
3286
      // still reachable at all?
3287
0
      Info.FFDiag(E->getBeginLoc(),
3288
0
                  diag::note_unimplemented_constexpr_lambda_feature_ast)
3289
0
          << "captures not currently allowed";
3290
0
      return false;
3291
0
    }
3292
1.89k
  }
3293
3294
  // If we're currently evaluating the initializer of this declaration, use that
3295
  // in-flight value.
3296
4.70M
  if (Info.EvaluatingDecl == Base) {
3297
71
    Result = Info.EvaluatingDeclValue;
3298
71
    return true;
3299
71
  }
3300
3301
4.70M
  if (isa<ParmVarDecl>(VD)) {
3302
    // Assume parameters of a potential constant expression are usable in
3303
    // constant expressions.
3304
2.24M
    if (!Info.checkingPotentialConstantExpression() ||
3305
2.24M
        
!Info.CurrentCall->Callee67.8k
||
3306
2.24M
        
!Info.CurrentCall->Callee->Equals(VD->getDeclContext())67.8k
) {
3307
2.17M
      if (Info.getLangOpts().CPlusPlus11) {
3308
1.32M
        Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3309
1.32M
            << VD;
3310
1.32M
        NoteLValueLocation(Info, Base);
3311
1.32M
      } else {
3312
846k
        Info.FFDiag(E);
3313
846k
      }
3314
2.17M
    }
3315
2.24M
    return false;
3316
2.24M
  }
3317
3318
2.45M
  if (E->isValueDependent())
3319
2
    return false;
3320
3321
  // Dig out the initializer, and use the declaration which it's attached to.
3322
  // FIXME: We should eventually check whether the variable has a reachable
3323
  // initializing declaration.
3324
2.45M
  const Expr *Init = VD->getAnyInitializer(VD);
3325
2.45M
  if (!Init) {
3326
    // Don't diagnose during potential constant expression checking; an
3327
    // initializer might be added later.
3328
127k
    if (!Info.checkingPotentialConstantExpression()) {
3329
127k
      Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3330
127k
        << VD;
3331
127k
      NoteLValueLocation(Info, Base);
3332
127k
    }
3333
127k
    return false;
3334
127k
  }
3335
3336
2.33M
  if (Init->isValueDependent()) {
3337
    // The DeclRefExpr is not value-dependent, but the variable it refers to
3338
    // has a value-dependent initializer. This should only happen in
3339
    // constant-folding cases, where the variable is not actually of a suitable
3340
    // type for use in a constant expression (otherwise the DeclRefExpr would
3341
    // have been value-dependent too), so diagnose that.
3342
16
    assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3343
16
    if (!Info.checkingPotentialConstantExpression()) {
3344
16
      Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3345
16
                         ? 
diag::note_constexpr_ltor_non_constexpr14
3346
16
                         : 
diag::note_constexpr_ltor_non_integral2
, 1)
3347
16
          << VD << VD->getType();
3348
16
      NoteLValueLocation(Info, Base);
3349
16
    }
3350
16
    return false;
3351
16
  }
3352
3353
  // Check that we can fold the initializer. In C++, we will have already done
3354
  // this in the cases where it matters for conformance.
3355
2.33M
  if (!VD->evaluateValue()) {
3356
122k
    Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3357
122k
    NoteLValueLocation(Info, Base);
3358
122k
    return false;
3359
122k
  }
3360
3361
  // Check that the variable is actually usable in constant expressions. For a
3362
  // const integral variable or a reference, we might have a non-constant
3363
  // initializer that we can nonetheless evaluate the initializer for. Such
3364
  // variables are not usable in constant expressions. In C++98, the
3365
  // initializer also syntactically needs to be an ICE.
3366
  //
3367
  // FIXME: We don't diagnose cases that aren't potentially usable in constant
3368
  // expressions here; doing so would regress diagnostics for things like
3369
  // reading from a volatile constexpr variable.
3370
2.20M
  if ((Info.getLangOpts().CPlusPlus && 
!VD->hasConstantInitialization()2.20M
&&
3371
2.20M
       
VD->mightBeUsableInConstantExpressions(Info.Ctx)948
) ||
3372
2.20M
      
(2.20M
(2.20M
Info.getLangOpts().CPlusPlus2.20M
||
Info.getLangOpts().OpenCL2.44k
) &&
3373
2.20M
       
!Info.getLangOpts().CPlusPlus112.20M
&&
!VD->hasICEInitializer(Info.Ctx)561
)) {
3374
611
    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3375
611
    NoteLValueLocation(Info, Base);
3376
611
  }
3377
3378
  // Never use the initializer of a weak variable, not even for constant
3379
  // folding. We can't be sure that this is the definition that will be used.
3380
2.20M
  if (VD->isWeak()) {
3381
19
    Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3382
19
    NoteLValueLocation(Info, Base);
3383
19
    return false;
3384
19
  }
3385
3386
2.20M
  Result = VD->getEvaluatedValue();
3387
2.20M
  return true;
3388
2.20M
}
3389
3390
/// Get the base index of the given base class within an APValue representing
3391
/// the given derived class.
3392
static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3393
2.36k
                             const CXXRecordDecl *Base) {
3394
2.36k
  Base = Base->getCanonicalDecl();
3395
2.36k
  unsigned Index = 0;
3396
2.36k
  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3397
2.84k
         E = Derived->bases_end(); I != E; 
++I, ++Index488
) {
3398
2.84k
    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3399
2.36k
      return Index;
3400
2.84k
  }
3401
3402
0
  llvm_unreachable("base class missing from derived class's bases list");
3403
0
}
3404
3405
/// Extract the value of a character from a string literal.
3406
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3407
69.0k
                                            uint64_t Index) {
3408
69.0k
  assert(!isa<SourceLocExpr>(Lit) &&
3409
69.0k
         "SourceLocExpr should have already been converted to a StringLiteral");
3410
3411
  // FIXME: Support MakeStringConstant
3412
69.0k
  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3413
0
    std::string Str;
3414
0
    Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3415
0
    assert(Index <= Str.size() && "Index too large");
3416
0
    return APSInt::getUnsigned(Str.c_str()[Index]);
3417
0
  }
3418
3419
69.0k
  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3420
3.37k
    Lit = PE->getFunctionName();
3421
69.0k
  const StringLiteral *S = cast<StringLiteral>(Lit);
3422
69.0k
  const ConstantArrayType *CAT =
3423
69.0k
      Info.Ctx.getAsConstantArrayType(S->getType());
3424
69.0k
  assert(CAT && "string literal isn't an array");
3425
69.0k
  QualType CharType = CAT->getElementType();
3426
69.0k
  assert(CharType->isIntegerType() && "unexpected character type");
3427
69.0k
  APSInt Value(Info.Ctx.getTypeSize(CharType),
3428
69.0k
               CharType->isUnsignedIntegerType());
3429
69.0k
  if (Index < S->getLength())
3430
66.7k
    Value = S->getCodeUnit(Index);
3431
69.0k
  return Value;
3432
69.0k
}
3433
3434
// Expand a string literal into an array of characters.
3435
//
3436
// FIXME: This is inefficient; we should probably introduce something similar
3437
// to the LLVM ConstantDataArray to make this cheaper.
3438
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3439
                                APValue &Result,
3440
1.29k
                                QualType AllocType = QualType()) {
3441
1.29k
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3442
1.29k
      AllocType.isNull() ? 
S->getType()1.27k
:
AllocType19
);
3443
1.29k
  assert(CAT && "string literal isn't an array");
3444
1.29k
  QualType CharType = CAT->getElementType();
3445
1.29k
  assert(CharType->isIntegerType() && "unexpected character type");
3446
3447
1.29k
  unsigned Elts = CAT->getSize().getZExtValue();
3448
1.29k
  Result = APValue(APValue::UninitArray(),
3449
1.29k
                   std::min(S->getLength(), Elts), Elts);
3450
1.29k
  APSInt Value(Info.Ctx.getTypeSize(CharType),
3451
1.29k
               CharType->isUnsignedIntegerType());
3452
1.29k
  if (Result.hasArrayFiller())
3453
1.28k
    Result.getArrayFiller() = APValue(Value);
3454
46.0k
  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; 
++I44.7k
) {
3455
44.7k
    Value = S->getCodeUnit(I);
3456
44.7k
    Result.getArrayInitializedElt(I) = APValue(Value);
3457
44.7k
  }
3458
1.29k
}
3459
3460
// Expand an array so that it has more than Index filled elements.
3461
1.22k
static void expandArray(APValue &Array, unsigned Index) {
3462
1.22k
  unsigned Size = Array.getArraySize();
3463
1.22k
  assert(Index < Size);
3464
3465
  // Always at least double the number of elements for which we store a value.
3466
1.22k
  unsigned OldElts = Array.getArrayInitializedElts();
3467
1.22k
  unsigned NewElts = std::max(Index+1, OldElts * 2);
3468
1.22k
  NewElts = std::min(Size, std::max(NewElts, 8u));
3469
3470
  // Copy the data across.
3471
1.22k
  APValue NewValue(APValue::UninitArray(), NewElts, Size);
3472
21.9k
  for (unsigned I = 0; I != OldElts; 
++I20.7k
)
3473
20.7k
    NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3474
55.1k
  for (unsigned I = OldElts; I != NewElts; 
++I53.9k
)
3475
53.9k
    NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3476
1.22k
  if (NewValue.hasArrayFiller())
3477
586
    NewValue.getArrayFiller() = Array.getArrayFiller();
3478
1.22k
  Array.swap(NewValue);
3479
1.22k
}
3480
3481
/// Determine whether a type would actually be read by an lvalue-to-rvalue
3482
/// conversion. If it's of class type, we may assume that the copy operation
3483
/// is trivial. Note that this is never true for a union type with fields
3484
/// (because the copy always "reads" the active member) and always true for
3485
/// a non-class type.
3486
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3487
2.93k
static bool isReadByLvalueToRvalueConversion(QualType T) {
3488
2.93k
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3489
2.93k
  return !RD || 
isReadByLvalueToRvalueConversion(RD)340
;
3490
2.93k
}
3491
4.66k
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3492
  // FIXME: A trivial copy of a union copies the object representation, even if
3493
  // the union is empty.
3494
4.66k
  if (RD->isUnion())
3495
39
    return !RD->field_empty();
3496
4.62k
  if (RD->isEmpty())
3497
1.81k
    return false;
3498
3499
2.81k
  for (auto *Field : RD->fields())
3500
2.88k
    if (!Field->isUnnamedBitfield() &&
3501
2.88k
        
isReadByLvalueToRvalueConversion(Field->getType())2.88k
)
3502
2.68k
      return true;
3503
3504
130
  for (auto &BaseSpec : RD->bases())
3505
34
    if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3506
28
      return true;
3507
3508
102
  return false;
3509
130
}
3510
3511
/// Diagnose an attempt to read from any unreadable field within the specified
3512
/// type, which might be a class type.
3513
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3514
1.25k
                                  QualType T) {
3515
1.25k
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3516
1.25k
  if (!RD)
3517
519
    return false;
3518
3519
731
  if (!RD->hasMutableFields())
3520
712
    return false;
3521
3522
35
  
for (auto *Field : RD->fields())19
{
3523
    // If we're actually going to read this field in some way, then it can't
3524
    // be mutable. If we're in a union, then assigning to a mutable field
3525
    // (even an empty one) can change the active member, so that's not OK.
3526
    // FIXME: Add core issue number for the union case.
3527
35
    if (Field->isMutable() &&
3528
35
        
(22
RD->isUnion()22
||
isReadByLvalueToRvalueConversion(Field->getType())16
)) {
3529
13
      Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3530
13
      Info.Note(Field->getLocation(), diag::note_declared_at);
3531
13
      return true;
3532
13
    }
3533
3534
22
    if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3535
3
      return true;
3536
22
  }
3537
3538
3
  for (auto &BaseSpec : RD->bases())
3539
0
    if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3540
0
      return true;
3541
3542
  // All mutable fields were empty, and thus not actually read.
3543
3
  return false;
3544
3
}
3545
3546
static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3547
                                        APValue::LValueBase Base,
3548
2.53M
                                        bool MutableSubobject = false) {
3549
  // A temporary or transient heap allocation we created.
3550
2.53M
  if (Base.getCallIndex() || 
Base.is<DynamicAllocLValue>()2.53M
)
3551
1.72k
    return true;
3552
3553
2.53M
  switch (Info.IsEvaluatingDecl) {
3554
2.42M
  case EvalInfo::EvaluatingDeclKind::None:
3555
2.42M
    return false;
3556
3557
106k
  case EvalInfo::EvaluatingDeclKind::Ctor:
3558
    // The variable whose initializer we're evaluating.
3559
106k
    if (Info.EvaluatingDecl == Base)
3560
946
      return true;
3561
3562
    // A temporary lifetime-extended by the variable whose initializer we're
3563
    // evaluating.
3564
105k
    if (auto *BaseE = Base.dyn_cast<const Expr *>())
3565
60
      if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3566
60
        return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3567
105k
    return false;
3568
3569
1.44k
  case EvalInfo::EvaluatingDeclKind::Dtor:
3570
    // C++2a [expr.const]p6:
3571
    //   [during constant destruction] the lifetime of a and its non-mutable
3572
    //   subobjects (but not its mutable subobjects) [are] considered to start
3573
    //   within e.
3574
1.44k
    if (MutableSubobject || 
Base != Info.EvaluatingDecl1.43k
)
3575
8
      return false;
3576
    // FIXME: We can meaningfully extend this to cover non-const objects, but
3577
    // we will need special handling: we should be able to access only
3578
    // subobjects of such objects that are themselves declared const.
3579
1.43k
    QualType T = getType(Base);
3580
1.43k
    return T.isConstQualified() || 
T->isReferenceType()1.35k
;
3581
2.53M
  }
3582
3583
0
  llvm_unreachable("unknown evaluating decl kind");
3584
0
}
3585
3586
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3587
2.21k
                           SourceLocation CallLoc = {}) {
3588
2.21k
  return Info.CheckArraySize(
3589
2.21k
      CAT->getSizeExpr() ? 
CAT->getSizeExpr()->getBeginLoc()0
: CallLoc,
3590
2.21k
      CAT->getNumAddressingBits(Info.Ctx), CAT->getSize().getZExtValue(),
3591
2.21k
      /*Diag=*/true);
3592
2.21k
}
3593
3594
namespace {
3595
/// A handle to a complete object (an object that is not a subobject of
3596
/// another object).
3597
struct CompleteObject {
3598
  /// The identity of the object.
3599
  APValue::LValueBase Base;
3600
  /// The value of the complete object.
3601
  APValue *Value;
3602
  /// The type of the complete object.
3603
  QualType Type;
3604
3605
7.14M
  CompleteObject() : Value(nullptr) {}
3606
  CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3607
2.69M
      : Base(Base), Value(Value), Type(Type) {}
3608
3609
30.1k
  bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3610
    // If this isn't a "real" access (eg, if it's just accessing the type
3611
    // info), allow it. We assume the type doesn't change dynamically for
3612
    // subobjects of constexpr objects (even though we'd hit UB here if it
3613
    // did). FIXME: Is this right?
3614
30.1k
    if (!isAnyAccess(AK))
3615
27.1k
      return true;
3616
3617
    // In C++14 onwards, it is permitted to read a mutable member whose
3618
    // lifetime began within the evaluation.
3619
    // FIXME: Should we also allow this in C++11?
3620
3.00k
    if (!Info.getLangOpts().CPlusPlus14)
3621
591
      return false;
3622
2.40k
    return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3623
3.00k
  }
3624
3625
9.87M
  explicit operator bool() const { return !Type.isNull(); }
3626
};
3627
} // end anonymous namespace
3628
3629
static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3630
35.2k
                                 bool IsMutable = false) {
3631
  // C++ [basic.type.qualifier]p1:
3632
  // - A const object is an object of type const T or a non-mutable subobject
3633
  //   of a const object.
3634
35.2k
  if (ObjType.isConstQualified() && 
!IsMutable18.3k
)
3635
18.3k
    SubobjType.addConst();
3636
  // - A volatile object is an object of type const T or a subobject of a
3637
  //   volatile object.
3638
35.2k
  if (ObjType.isVolatileQualified())
3639
11
    SubobjType.addVolatile();
3640
35.2k
  return SubobjType;
3641
35.2k
}
3642
3643
/// Find the designated sub-object of an rvalue.
3644
template<typename SubobjectHandler>
3645
typename SubobjectHandler::result_type
3646
findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3647
2.65M
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
2.65M
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
2.65M
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()2.65M
) {
3652
391
    if (Info.getLangOpts().CPlusPlus11)
3653
388
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
388
                         ? diag::note_constexpr_access_past_end
3655
388
                         : 
diag::note_constexpr_access_unsized_array0
)
3656
388
          << handler.AccessKind;
3657
3
    else
3658
3
      Info.FFDiag(E);
3659
391
    return handler.failed();
3660
391
  }
3661
3662
2.65M
  APValue *O = Obj.Value;
3663
2.65M
  QualType ObjType = Obj.Type;
3664
2.65M
  const FieldDecl *LastField = nullptr;
3665
2.65M
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
2.75M
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I100k
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
2.75M
    if ((O->isAbsent() && 
!(1.16k
handler.AccessKind == AK_Construct1.16k
&&
I == N816
)) ||
3671
2.75M
        
(2.75M
O->isIndeterminate()2.75M
&&
3672
2.75M
         
!isValidIndeterminateAccess(handler.AccessKind)15.7k
)) {
3673
462
      if (!Info.checkingPotentialConstantExpression())
3674
437
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
437
            << handler.AccessKind << O->isIndeterminate()
3676
437
            << E->getSourceRange();
3677
462
      return handler.failed();
3678
462
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
2.75M
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()481k
) &&
3684
2.75M
        
ObjType->isRecordType()2.27M
&&
3685
2.75M
        Info.isEvaluatingCtorDtor(
3686
33.3k
            Obj.Base,
3687
33.3k
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
33.3k
            ConstructionPhase::None) {
3689
1.75k
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
1.75k
      ObjType.removeLocalConst();
3691
1.75k
      ObjType.removeLocalVolatile();
3692
1.75k
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
2.75M
    if (I == N || 
(101k
I == N - 1101k
&&
ObjType->isAnyComplexType()89.2k
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
2.65M
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)24
) {
3698
24
        if (Info.getLangOpts().CPlusPlus) {
3699
24
          int DiagKind;
3700
24
          SourceLocation Loc;
3701
24
          const NamedDecl *Decl = nullptr;
3702
24
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
24
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
21
            DiagKind = 1;
3708
21
            Loc = VD->getLocation();
3709
21
            Decl = VD;
3710
21
          } else {
3711
3
            DiagKind = 0;
3712
3
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
3
              Loc = E->getExprLoc();
3714
3
          }
3715
24
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
24
              << handler.AccessKind << DiagKind << Decl;
3717
24
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
24
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
24
        return handler.failed();
3722
24
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
2.65M
      if (ObjType->isRecordType() &&
3729
2.65M
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)30.0k
&&
3730
2.65M
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)1.22k
)
3731
13
        return handler.failed();
3732
2.65M
    }
3733
3734
2.75M
    if (I == N) {
3735
2.65M
      if (!handler.found(*O, ObjType))
3736
70
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
2.65M
      if (isModification(handler.AccessKind) &&
3740
2.65M
          
LastField85.4k
&&
LastField->isBitField()2.21k
&&
3741
2.65M
          
!truncateBitfieldValue(Info, E, *O, LastField)118
)
3742
0
        return false;
3743
3744
2.65M
      return true;
3745
2.65M
    }
3746
3747
101k
    LastField = nullptr;
3748
101k
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
65.4k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
65.4k
      assert(CAT && "vla in literal type?");
3752
65.4k
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
65.4k
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
16
        if (Info.getLangOpts().CPlusPlus11)
3757
16
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
16
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
16
        return handler.failed();
3762
16
      }
3763
3764
65.3k
      ObjType = CAT->getElementType();
3765
3766
65.3k
      if (O->getArrayInitializedElts() > Index)
3767
63.3k
        O = &O->getArrayInitializedElt(Index);
3768
2.00k
      else if (!isRead(handler.AccessKind)) {
3769
1.03k
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
1.03k
        expandArray(*O, Index);
3773
1.03k
        O = &O->getArrayInitializedElt(Index);
3774
1.03k
      } else
3775
974
        O = &O->getArrayFiller();
3776
65.3k
    } else 
if (35.6k
ObjType->isAnyComplexType()35.6k
) {
3777
      // Next subobject is a complex number.
3778
24
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
24
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
24
      ObjType = getSubobjectType(
3789
24
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
24
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
24
      if (O->isComplexInt()) {
3793
12
        return handler.found(Index ? 
O->getComplexIntImag()6
3794
12
                                   : 
O->getComplexIntReal()6
, ObjType);
3795
12
      } else {
3796
12
        assert(O->isComplexFloat());
3797
12
        return handler.found(Index ? 
O->getComplexFloatImag()6
3798
12
                                   : 
O->getComplexFloatReal()6
, ObjType);
3799
12
      }
3800
35.5k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
33.2k
      if (Field->isMutable() &&
3802
33.2k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)44
) {
3803
31
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
31
          << handler.AccessKind << Field;
3805
31
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
31
        return handler.failed();
3807
31
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
33.2k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
33.2k
      if (RD->isUnion()) {
3812
1.30k
        const FieldDecl *UnionField = O->getUnionField();
3813
1.30k
        if (!UnionField ||
3814
1.30k
            
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()1.30k
) {
3815
362
          if (I == N - 1 && 
handler.AccessKind == AK_Construct311
) {
3816
            // Placement new onto an inactive union member makes it active.
3817
3
            O->setUnion(Field, APValue());
3818
359
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
359
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
359
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
359
            return handler.failed();
3826
359
          }
3827
362
        }
3828
949
        O = &O->getUnionValue();
3829
949
      } else
3830
31.9k
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
32.8k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
32.8k
      LastField = Field;
3834
32.8k
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
32.8k
    } else {
3837
      // Next subobject is a base class.
3838
2.31k
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
2.31k
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
2.31k
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
2.31k
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
2.31k
    }
3844
101k
  }
3845
2.65M
}
ExprConstant.cpp:(anonymous namespace)::StartLifetimeOfUnionMemberHandler::result_type findSubobject<(anonymous namespace)::StartLifetimeOfUnionMemberHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::StartLifetimeOfUnionMemberHandler&)
Line
Count
Source
3647
215
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
215
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
215
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3652
0
    if (Info.getLangOpts().CPlusPlus11)
3653
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
0
                         ? diag::note_constexpr_access_past_end
3655
0
                         : diag::note_constexpr_access_unsized_array)
3656
0
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
0
    return handler.failed();
3660
0
  }
3661
3662
215
  APValue *O = Obj.Value;
3663
215
  QualType ObjType = Obj.Type;
3664
215
  const FieldDecl *LastField = nullptr;
3665
215
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
559
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I344
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
559
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3671
559
        (O->isIndeterminate() &&
3672
559
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3673
0
      if (!Info.checkingPotentialConstantExpression())
3674
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
0
            << handler.AccessKind << O->isIndeterminate()
3676
0
            << E->getSourceRange();
3677
0
      return handler.failed();
3678
0
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
559
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()431
) &&
3684
559
        
ObjType->isRecordType()128
&&
3685
559
        Info.isEvaluatingCtorDtor(
3686
64
            Obj.Base,
3687
64
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
64
            ConstructionPhase::None) {
3689
64
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
64
      ObjType.removeLocalConst();
3691
64
      ObjType.removeLocalVolatile();
3692
64
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
559
    if (I == N || 
(346
I == N - 1346
&&
ObjType->isAnyComplexType()74
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
213
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
213
      if (ObjType->isRecordType() &&
3729
213
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3730
213
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
213
    }
3733
3734
559
    if (I == N) {
3735
213
      if (!handler.found(*O, ObjType))
3736
3
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
210
      if (isModification(handler.AccessKind) &&
3740
210
          LastField && 
LastField->isBitField()74
&&
3741
210
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3742
0
        return false;
3743
3744
210
      return true;
3745
210
    }
3746
3747
346
    LastField = nullptr;
3748
346
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
64
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
64
      assert(CAT && "vla in literal type?");
3752
64
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
64
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
64
      ObjType = CAT->getElementType();
3765
3766
64
      if (O->getArrayInitializedElts() > Index)
3767
64
        O = &O->getArrayInitializedElt(Index);
3768
0
      else if (!isRead(handler.AccessKind)) {
3769
0
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
0
        expandArray(*O, Index);
3773
0
        O = &O->getArrayInitializedElt(Index);
3774
0
      } else
3775
0
        O = &O->getArrayFiller();
3776
282
    } else if (ObjType->isAnyComplexType()) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
282
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
214
      if (Field->isMutable() &&
3802
214
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
214
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
214
      if (RD->isUnion()) {
3812
6
        const FieldDecl *UnionField = O->getUnionField();
3813
6
        if (!UnionField ||
3814
6
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
2
          if (I == N - 1 && 
handler.AccessKind == AK_Construct0
) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
2
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
2
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
2
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
2
            return handler.failed();
3826
2
          }
3827
2
        }
3828
4
        O = &O->getUnionValue();
3829
4
      } else
3830
208
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
212
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
212
      LastField = Field;
3834
212
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
212
    } else {
3837
      // Next subobject is a base class.
3838
68
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
68
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
68
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
68
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
68
    }
3844
346
  }
3845
215
}
ExprConstant.cpp:(anonymous namespace)::ModifySubobjectHandler::result_type findSubobject<(anonymous namespace)::ModifySubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::ModifySubobjectHandler&)
Line
Count
Source
3647
20.8k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
20.8k
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
20.8k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()20.8k
) {
3652
12
    if (Info.getLangOpts().CPlusPlus11)
3653
12
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
12
                         ? diag::note_constexpr_access_past_end
3655
12
                         : 
diag::note_constexpr_access_unsized_array0
)
3656
12
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
12
    return handler.failed();
3660
12
  }
3661
3662
20.8k
  APValue *O = Obj.Value;
3663
20.8k
  QualType ObjType = Obj.Type;
3664
20.8k
  const FieldDecl *LastField = nullptr;
3665
20.8k
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
42.1k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I21.3k
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
42.1k
    if ((O->isAbsent() && 
!(53
handler.AccessKind == AK_Construct53
&&
I == N0
)) ||
3671
42.1k
        
(42.1k
O->isIndeterminate()42.1k
&&
3672
42.1k
         
!isValidIndeterminateAccess(handler.AccessKind)15.6k
)) {
3673
53
      if (!Info.checkingPotentialConstantExpression())
3674
50
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
50
            << handler.AccessKind << O->isIndeterminate()
3676
50
            << E->getSourceRange();
3677
53
      return handler.failed();
3678
53
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
42.1k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()41.1k
) &&
3684
42.1k
        
ObjType->isRecordType()979
&&
3685
42.1k
        Info.isEvaluatingCtorDtor(
3686
691
            Obj.Base,
3687
691
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
691
            ConstructionPhase::None) {
3689
684
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
684
      ObjType.removeLocalConst();
3691
684
      ObjType.removeLocalVolatile();
3692
684
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
42.1k
    if (I == N || 
(21.3k
I == N - 121.3k
&&
ObjType->isAnyComplexType()18.5k
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
20.8k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
20.8k
      if (ObjType->isRecordType() &&
3729
20.8k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)110
&&
3730
20.8k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
20.8k
    }
3733
3734
42.1k
    if (I == N) {
3735
20.8k
      if (!handler.found(*O, ObjType))
3736
21
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
20.7k
      if (isModification(handler.AccessKind) &&
3740
20.7k
          LastField && 
LastField->isBitField()1.87k
&&
3741
20.7k
          
!truncateBitfieldValue(Info, E, *O, LastField)78
)
3742
0
        return false;
3743
3744
20.7k
      return true;
3745
20.7k
    }
3746
3747
21.3k
    LastField = nullptr;
3748
21.3k
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
16.9k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
16.9k
      assert(CAT && "vla in literal type?");
3752
16.9k
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
16.9k
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
16.9k
      ObjType = CAT->getElementType();
3765
3766
16.9k
      if (O->getArrayInitializedElts() > Index)
3767
15.9k
        O = &O->getArrayInitializedElt(Index);
3768
990
      else if (!isRead(handler.AccessKind)) {
3769
990
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
990
        expandArray(*O, Index);
3773
990
        O = &O->getArrayInitializedElt(Index);
3774
990
      } else
3775
0
        O = &O->getArrayFiller();
3776
16.9k
    } else 
if (4.40k
ObjType->isAnyComplexType()4.40k
) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
4.40k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
4.06k
      if (Field->isMutable() &&
3802
4.06k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)2
) {
3803
1
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
1
          << handler.AccessKind << Field;
3805
1
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
1
        return handler.failed();
3807
1
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
4.06k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
4.06k
      if (RD->isUnion()) {
3812
422
        const FieldDecl *UnionField = O->getUnionField();
3813
422
        if (!UnionField ||
3814
422
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
7
          if (I == N - 1 && 
handler.AccessKind == AK_Construct1
) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
7
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
7
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
7
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
7
            return handler.failed();
3826
7
          }
3827
7
        }
3828
415
        O = &O->getUnionValue();
3829
415
      } else
3830
3.64k
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
4.06k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
4.06k
      LastField = Field;
3834
4.06k
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
4.06k
    } else {
3837
      // Next subobject is a base class.
3838
335
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
335
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
335
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
335
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
335
    }
3844
21.3k
  }
3845
20.8k
}
ExprConstant.cpp:(anonymous namespace)::IncDecSubobjectHandler::result_type findSubobject<(anonymous namespace)::IncDecSubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::IncDecSubobjectHandler&)
Line
Count
Source
3647
57.8k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
57.8k
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
57.8k
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3652
0
    if (Info.getLangOpts().CPlusPlus11)
3653
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
0
                         ? diag::note_constexpr_access_past_end
3655
0
                         : diag::note_constexpr_access_unsized_array)
3656
0
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
0
    return handler.failed();
3660
0
  }
3661
3662
57.8k
  APValue *O = Obj.Value;
3663
57.8k
  QualType ObjType = Obj.Type;
3664
57.8k
  const FieldDecl *LastField = nullptr;
3665
57.8k
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
58.1k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I289
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
58.1k
    if ((O->isAbsent() && 
!(17
handler.AccessKind == AK_Construct17
&&
I == N0
)) ||
3671
58.1k
        
(58.1k
O->isIndeterminate()58.1k
&&
3672
58.1k
         
!isValidIndeterminateAccess(handler.AccessKind)10
)) {
3673
27
      if (!Info.checkingPotentialConstantExpression())
3674
24
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
24
            << handler.AccessKind << O->isIndeterminate()
3676
24
            << E->getSourceRange();
3677
27
      return handler.failed();
3678
27
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
58.1k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()58.1k
) &&
3684
58.1k
        
ObjType->isRecordType()20
&&
3685
58.1k
        Info.isEvaluatingCtorDtor(
3686
20
            Obj.Base,
3687
20
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
20
            ConstructionPhase::None) {
3689
20
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
20
      ObjType.removeLocalConst();
3691
20
      ObjType.removeLocalVolatile();
3692
20
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
58.1k
    if (I == N || 
(295
I == N - 1295
&&
ObjType->isAnyComplexType()232
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
57.8k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
57.8k
      if (ObjType->isRecordType() &&
3729
57.8k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
&&
3730
57.8k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
57.8k
    }
3733
3734
58.1k
    if (I == N) {
3735
57.8k
      if (!handler.found(*O, ObjType))
3736
8
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
57.8k
      if (isModification(handler.AccessKind) &&
3740
57.8k
          LastField && 
LastField->isBitField()196
&&
3741
57.8k
          
!truncateBitfieldValue(Info, E, *O, LastField)18
)
3742
0
        return false;
3743
3744
57.8k
      return true;
3745
57.8k
    }
3746
3747
295
    LastField = nullptr;
3748
295
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
37
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
37
      assert(CAT && "vla in literal type?");
3752
37
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
37
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
37
      ObjType = CAT->getElementType();
3765
3766
37
      if (O->getArrayInitializedElts() > Index)
3767
27
        O = &O->getArrayInitializedElt(Index);
3768
10
      else if (!isRead(handler.AccessKind)) {
3769
10
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
10
        expandArray(*O, Index);
3773
10
        O = &O->getArrayInitializedElt(Index);
3774
10
      } else
3775
0
        O = &O->getArrayFiller();
3776
258
    } else if (ObjType->isAnyComplexType()) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
258
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
228
      if (Field->isMutable() &&
3802
228
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
228
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
228
      if (RD->isUnion()) {
3812
25
        const FieldDecl *UnionField = O->getUnionField();
3813
25
        if (!UnionField ||
3814
25
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
6
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
6
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
6
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
6
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
6
            return handler.failed();
3826
6
          }
3827
6
        }
3828
19
        O = &O->getUnionValue();
3829
19
      } else
3830
203
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
222
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
222
      LastField = Field;
3834
222
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
222
    } else {
3837
      // Next subobject is a base class.
3838
30
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
30
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
30
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
30
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
30
    }
3844
295
  }
3845
57.8k
}
ExprConstant.cpp:(anonymous namespace)::DestroyObjectHandler::result_type findSubobject<(anonymous namespace)::DestroyObjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::DestroyObjectHandler&)
Line
Count
Source
3647
55
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
55
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
55
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3652
0
    if (Info.getLangOpts().CPlusPlus11)
3653
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
0
                         ? diag::note_constexpr_access_past_end
3655
0
                         : diag::note_constexpr_access_unsized_array)
3656
0
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
0
    return handler.failed();
3660
0
  }
3661
3662
55
  APValue *O = Obj.Value;
3663
55
  QualType ObjType = Obj.Type;
3664
55
  const FieldDecl *LastField = nullptr;
3665
55
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
82
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I27
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
82
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3671
82
        (O->isIndeterminate() &&
3672
82
         
!isValidIndeterminateAccess(handler.AccessKind)2
)) {
3673
0
      if (!Info.checkingPotentialConstantExpression())
3674
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
0
            << handler.AccessKind << O->isIndeterminate()
3676
0
            << E->getSourceRange();
3677
0
      return handler.failed();
3678
0
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
82
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3684
82
        
ObjType->isRecordType()0
&&
3685
82
        Info.isEvaluatingCtorDtor(
3686
0
            Obj.Base,
3687
0
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
0
            ConstructionPhase::None) {
3689
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
0
      ObjType.removeLocalConst();
3691
0
      ObjType.removeLocalVolatile();
3692
0
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
82
    if (I == N || 
(27
I == N - 127
&&
ObjType->isAnyComplexType()22
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
55
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
55
      if (ObjType->isRecordType() &&
3729
55
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)37
&&
3730
55
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
55
    }
3733
3734
82
    if (I == N) {
3735
55
      if (!handler.found(*O, ObjType))
3736
0
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
55
      if (isModification(handler.AccessKind) &&
3740
55
          LastField && 
LastField->isBitField()13
&&
3741
55
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3742
0
        return false;
3743
3744
55
      return true;
3745
55
    }
3746
3747
27
    LastField = nullptr;
3748
27
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
6
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
6
      assert(CAT && "vla in literal type?");
3752
6
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
6
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
6
      ObjType = CAT->getElementType();
3765
3766
6
      if (O->getArrayInitializedElts() > Index)
3767
6
        O = &O->getArrayInitializedElt(Index);
3768
0
      else if (!isRead(handler.AccessKind)) {
3769
0
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
0
        expandArray(*O, Index);
3773
0
        O = &O->getArrayInitializedElt(Index);
3774
0
      } else
3775
0
        O = &O->getArrayFiller();
3776
21
    } else if (ObjType->isAnyComplexType()) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
21
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
16
      if (Field->isMutable() &&
3802
16
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
16
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
16
      if (RD->isUnion()) {
3812
16
        const FieldDecl *UnionField = O->getUnionField();
3813
16
        if (!UnionField ||
3814
16
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
0
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
0
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
0
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
0
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
0
            return handler.failed();
3826
0
          }
3827
0
        }
3828
16
        O = &O->getUnionValue();
3829
16
      } else
3830
0
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
16
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
16
      LastField = Field;
3834
16
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
16
    } else {
3837
      // Next subobject is a base class.
3838
5
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
5
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
5
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
5
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
5
    }
3844
27
  }
3845
55
}
ExprConstant.cpp:(anonymous namespace)::CheckDynamicTypeHandler::result_type findSubobject<(anonymous namespace)::CheckDynamicTypeHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::CheckDynamicTypeHandler&)
Line
Count
Source
3647
27.2k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
27.2k
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
27.2k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()27.1k
) {
3652
18
    if (Info.getLangOpts().CPlusPlus11)
3653
18
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
18
                         ? diag::note_constexpr_access_past_end
3655
18
                         : 
diag::note_constexpr_access_unsized_array0
)
3656
18
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
18
    return handler.failed();
3660
18
  }
3661
3662
27.1k
  APValue *O = Obj.Value;
3663
27.1k
  QualType ObjType = Obj.Type;
3664
27.1k
  const FieldDecl *LastField = nullptr;
3665
27.1k
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
29.6k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I2.42k
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
29.6k
    if ((O->isAbsent() && 
!(20
handler.AccessKind == AK_Construct20
&&
I == N0
)) ||
3671
29.6k
        
(29.5k
O->isIndeterminate()29.5k
&&
3672
29.5k
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3673
20
      if (!Info.checkingPotentialConstantExpression())
3674
18
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
18
            << handler.AccessKind << O->isIndeterminate()
3676
18
            << E->getSourceRange();
3677
20
      return handler.failed();
3678
20
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
29.5k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()15.4k
) &&
3684
29.5k
        
ObjType->isRecordType()14.1k
&&
3685
29.5k
        Info.isEvaluatingCtorDtor(
3686
13.5k
            Obj.Base,
3687
13.5k
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
13.5k
            ConstructionPhase::None) {
3689
540
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
540
      ObjType.removeLocalConst();
3691
540
      ObjType.removeLocalVolatile();
3692
540
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
29.5k
    if (I == N || 
(2.43k
I == N - 12.43k
&&
ObjType->isAnyComplexType()1.42k
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
27.1k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
27.1k
      if (ObjType->isRecordType() &&
3729
27.1k
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3730
27.1k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
27.1k
    }
3733
3734
29.5k
    if (I == N) {
3735
27.1k
      if (!handler.found(*O, ObjType))
3736
0
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
27.1k
      if (isModification(handler.AccessKind) &&
3740
27.1k
          
LastField37
&&
LastField->isBitField()6
&&
3741
27.1k
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3742
0
        return false;
3743
3744
27.1k
      return true;
3745
27.1k
    }
3746
3747
2.43k
    LastField = nullptr;
3748
2.43k
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
664
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
664
      assert(CAT && "vla in literal type?");
3752
664
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
664
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
664
      ObjType = CAT->getElementType();
3765
3766
664
      if (O->getArrayInitializedElts() > Index)
3767
664
        O = &O->getArrayInitializedElt(Index);
3768
0
      else if (!isRead(handler.AccessKind)) {
3769
0
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
0
        expandArray(*O, Index);
3773
0
        O = &O->getArrayInitializedElt(Index);
3774
0
      } else
3775
0
        O = &O->getArrayFiller();
3776
1.76k
    } else if (ObjType->isAnyComplexType()) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
1.76k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
985
      if (Field->isMutable() &&
3802
985
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)2
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
985
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
985
      if (RD->isUnion()) {
3812
35
        const FieldDecl *UnionField = O->getUnionField();
3813
35
        if (!UnionField ||
3814
35
            
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()34
) {
3815
11
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
11
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
11
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
11
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
11
            return handler.failed();
3826
11
          }
3827
11
        }
3828
24
        O = &O->getUnionValue();
3829
24
      } else
3830
950
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
974
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
974
      LastField = Field;
3834
974
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
974
    } else {
3837
      // Next subobject is a base class.
3838
783
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
783
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
783
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
783
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
783
    }
3844
2.43k
  }
3845
27.1k
}
ExprConstant.cpp:(anonymous namespace)::ExtractSubobjectHandler::result_type findSubobject<(anonymous namespace)::ExtractSubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::ExtractSubobjectHandler&)
Line
Count
Source
3647
2.54M
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
2.54M
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
2.54M
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()2.54M
) {
3652
361
    if (Info.getLangOpts().CPlusPlus11)
3653
358
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
358
                         ? diag::note_constexpr_access_past_end
3655
358
                         : 
diag::note_constexpr_access_unsized_array0
)
3656
358
          << handler.AccessKind;
3657
3
    else
3658
3
      Info.FFDiag(E);
3659
361
    return handler.failed();
3660
361
  }
3661
3662
2.54M
  APValue *O = Obj.Value;
3663
2.54M
  QualType ObjType = Obj.Type;
3664
2.54M
  const FieldDecl *LastField = nullptr;
3665
2.54M
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
2.61M
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I75.3k
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
2.61M
    if ((O->isAbsent() && 
!(253
handler.AccessKind == AK_Construct253
&&
I == N0
)) ||
3671
2.61M
        
(2.61M
O->isIndeterminate()2.61M
&&
3672
2.61M
         
!isValidIndeterminateAccess(handler.AccessKind)101
)) {
3673
354
      if (!Info.checkingPotentialConstantExpression())
3674
337
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
337
            << handler.AccessKind << O->isIndeterminate()
3676
337
            << E->getSourceRange();
3677
354
      return handler.failed();
3678
354
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
2.61M
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()358k
) &&
3684
2.61M
        
ObjType->isRecordType()2.25M
&&
3685
2.61M
        Info.isEvaluatingCtorDtor(
3686
19.0k
            Obj.Base,
3687
19.0k
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
19.0k
            ConstructionPhase::None) {
3689
439
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
439
      ObjType.removeLocalConst();
3691
439
      ObjType.removeLocalVolatile();
3692
439
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
2.61M
    if (I == N || 
(75.7k
I == N - 175.7k
&&
ObjType->isAnyComplexType()68.1k
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
2.54M
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)24
) {
3698
24
        if (Info.getLangOpts().CPlusPlus) {
3699
24
          int DiagKind;
3700
24
          SourceLocation Loc;
3701
24
          const NamedDecl *Decl = nullptr;
3702
24
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
24
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
21
            DiagKind = 1;
3708
21
            Loc = VD->getLocation();
3709
21
            Decl = VD;
3710
21
          } else {
3711
3
            DiagKind = 0;
3712
3
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
3
              Loc = E->getExprLoc();
3714
3
          }
3715
24
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
24
              << handler.AccessKind << DiagKind << Decl;
3717
24
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
24
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
24
        return handler.failed();
3722
24
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
2.54M
      if (ObjType->isRecordType() &&
3729
2.54M
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)2.54k
&&
3730
2.54M
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)1.22k
)
3731
13
        return handler.failed();
3732
2.54M
    }
3733
3734
2.61M
    if (I == N) {
3735
2.54M
      if (!handler.found(*O, ObjType))
3736
14
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
2.54M
      if (isModification(handler.AccessKind) &&
3740
2.54M
          
LastField0
&&
LastField->isBitField()0
&&
3741
2.54M
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3742
0
        return false;
3743
3744
2.54M
      return true;
3745
2.54M
    }
3746
3747
75.7k
    LastField = nullptr;
3748
75.7k
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
46.8k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
46.8k
      assert(CAT && "vla in literal type?");
3752
46.8k
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
46.8k
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
16
        if (Info.getLangOpts().CPlusPlus11)
3757
16
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
16
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
16
        return handler.failed();
3762
16
      }
3763
3764
46.8k
      ObjType = CAT->getElementType();
3765
3766
46.8k
      if (O->getArrayInitializedElts() > Index)
3767
45.9k
        O = &O->getArrayInitializedElt(Index);
3768
974
      else if (!isRead(handler.AccessKind)) {
3769
0
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
0
        expandArray(*O, Index);
3773
0
        O = &O->getArrayInitializedElt(Index);
3774
0
      } else
3775
974
        O = &O->getArrayFiller();
3776
46.8k
    } else 
if (28.8k
ObjType->isAnyComplexType()28.8k
) {
3777
      // Next subobject is a complex number.
3778
24
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
24
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
24
      ObjType = getSubobjectType(
3789
24
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
24
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
24
      if (O->isComplexInt()) {
3793
12
        return handler.found(Index ? 
O->getComplexIntImag()6
3794
12
                                   : 
O->getComplexIntReal()6
, ObjType);
3795
12
      } else {
3796
12
        assert(O->isComplexFloat());
3797
12
        return handler.found(Index ? 
O->getComplexFloatImag()6
3798
12
                                   : 
O->getComplexFloatReal()6
, ObjType);
3799
12
      }
3800
28.7k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
27.6k
      if (Field->isMutable() &&
3802
27.6k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)40
) {
3803
30
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
30
          << handler.AccessKind << Field;
3805
30
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
30
        return handler.failed();
3807
30
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
27.6k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
27.6k
      if (RD->isUnion()) {
3812
798
        const FieldDecl *UnionField = O->getUnionField();
3813
798
        if (!UnionField ||
3814
798
            
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()792
) {
3815
330
          if (I == N - 1 && 
handler.AccessKind == AK_Construct290
) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
330
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
330
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
330
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
330
            return handler.failed();
3826
330
          }
3827
330
        }
3828
468
        O = &O->getUnionValue();
3829
468
      } else
3830
26.8k
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
27.3k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
27.3k
      LastField = Field;
3834
27.3k
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
27.3k
    } else {
3837
      // Next subobject is a base class.
3838
1.09k
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
1.09k
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
1.09k
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
1.09k
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
1.09k
    }
3844
75.7k
  }
3845
2.54M
}
ExprConstant.cpp:(anonymous namespace)::CompoundAssignSubobjectHandler::result_type findSubobject<(anonymous namespace)::CompoundAssignSubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::CompoundAssignSubobjectHandler&)
Line
Count
Source
3647
5.72k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
5.72k
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
5.72k
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3652
0
    if (Info.getLangOpts().CPlusPlus11)
3653
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
0
                         ? diag::note_constexpr_access_past_end
3655
0
                         : diag::note_constexpr_access_unsized_array)
3656
0
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
0
    return handler.failed();
3660
0
  }
3661
3662
5.72k
  APValue *O = Obj.Value;
3663
5.72k
  QualType ObjType = Obj.Type;
3664
5.72k
  const FieldDecl *LastField = nullptr;
3665
5.72k
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
5.79k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I63
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
5.79k
    if ((O->isAbsent() && 
!(5
handler.AccessKind == AK_Construct5
&&
I == N0
)) ||
3671
5.79k
        
(5.78k
O->isIndeterminate()5.78k
&&
3672
5.78k
         
!isValidIndeterminateAccess(handler.AccessKind)9
)) {
3673
5
      if (!Info.checkingPotentialConstantExpression())
3674
5
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
5
            << handler.AccessKind << O->isIndeterminate()
3676
5
            << E->getSourceRange();
3677
5
      return handler.failed();
3678
5
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
5.78k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()5.77k
) &&
3684
5.78k
        
ObjType->isRecordType()10
&&
3685
5.78k
        Info.isEvaluatingCtorDtor(
3686
10
            Obj.Base,
3687
10
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
10
            ConstructionPhase::None) {
3689
10
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
10
      ObjType.removeLocalConst();
3691
10
      ObjType.removeLocalVolatile();
3692
10
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
5.78k
    if (I == N || 
(63
I == N - 163
&&
ObjType->isAnyComplexType()61
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
5.72k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
5.72k
      if (ObjType->isRecordType() &&
3729
5.72k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
&&
3730
5.72k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
5.72k
    }
3733
3734
5.78k
    if (I == N) {
3735
5.72k
      if (!handler.found(*O, ObjType))
3736
21
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
5.70k
      if (isModification(handler.AccessKind) &&
3740
5.70k
          LastField && 
LastField->isBitField()44
&&
3741
5.70k
          
!truncateBitfieldValue(Info, E, *O, LastField)22
)
3742
0
        return false;
3743
3744
5.70k
      return true;
3745
5.70k
    }
3746
3747
63
    LastField = nullptr;
3748
63
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
15
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
15
      assert(CAT && "vla in literal type?");
3752
15
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
15
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
15
      ObjType = CAT->getElementType();
3765
3766
15
      if (O->getArrayInitializedElts() > Index)
3767
12
        O = &O->getArrayInitializedElt(Index);
3768
3
      else if (!isRead(handler.AccessKind)) {
3769
3
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
3
        expandArray(*O, Index);
3773
3
        O = &O->getArrayInitializedElt(Index);
3774
3
      } else
3775
0
        O = &O->getArrayFiller();
3776
48
    } else if (ObjType->isAnyComplexType()) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
48
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
48
      if (Field->isMutable() &&
3802
48
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
48
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
48
      if (RD->isUnion()) {
3812
0
        const FieldDecl *UnionField = O->getUnionField();
3813
0
        if (!UnionField ||
3814
0
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
0
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3816
            // Placement new onto an inactive union member makes it active.
3817
0
            O->setUnion(Field, APValue());
3818
0
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
0
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
0
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
0
            return handler.failed();
3826
0
          }
3827
0
        }
3828
0
        O = &O->getUnionValue();
3829
0
      } else
3830
48
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
48
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
48
      LastField = Field;
3834
48
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
48
    } else {
3837
      // Next subobject is a base class.
3838
0
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
0
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
0
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
0
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
0
    }
3844
63
  }
3845
5.72k
}
ExprConstant.cpp:(anonymous namespace)::PointerExprEvaluator::VisitCXXNewExpr(clang::CXXNewExpr const*)::FindObjectHandler::result_type findSubobject<(anonymous namespace)::PointerExprEvaluator::VisitCXXNewExpr(clang::CXXNewExpr const*)::FindObjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::PointerExprEvaluator::VisitCXXNewExpr(clang::CXXNewExpr const*)::FindObjectHandler&)
Line
Count
Source
3647
828
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3648
828
  if (Sub.Invalid)
3649
    // A diagnostic will have already been produced.
3650
0
    return handler.failed();
3651
828
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3652
0
    if (Info.getLangOpts().CPlusPlus11)
3653
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3654
0
                         ? diag::note_constexpr_access_past_end
3655
0
                         : diag::note_constexpr_access_unsized_array)
3656
0
          << handler.AccessKind;
3657
0
    else
3658
0
      Info.FFDiag(E);
3659
0
    return handler.failed();
3660
0
  }
3661
3662
828
  APValue *O = Obj.Value;
3663
828
  QualType ObjType = Obj.Type;
3664
828
  const FieldDecl *LastField = nullptr;
3665
828
  const FieldDecl *VolatileField = nullptr;
3666
3667
  // Walk the designator's path to find the subobject.
3668
1.63k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I804
) {
3669
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3670
1.63k
    if ((O->isAbsent() && 
!(816
handler.AccessKind == AK_Construct816
&&
I == N816
)) ||
3671
1.63k
        
(1.62k
O->isIndeterminate()1.62k
&&
3672
1.62k
         
!isValidIndeterminateAccess(handler.AccessKind)9
)) {
3673
3
      if (!Info.checkingPotentialConstantExpression())
3674
3
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3675
3
            << handler.AccessKind << O->isIndeterminate()
3676
3
            << E->getSourceRange();
3677
3
      return handler.failed();
3678
3
    }
3679
3680
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681
    //    const and volatile semantics are not applied on an object under
3682
    //    {con,de}struction.
3683
1.62k
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3684
1.62k
        
ObjType->isRecordType()0
&&
3685
1.62k
        Info.isEvaluatingCtorDtor(
3686
0
            Obj.Base,
3687
0
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3688
0
            ConstructionPhase::None) {
3689
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3690
0
      ObjType.removeLocalConst();
3691
0
      ObjType.removeLocalVolatile();
3692
0
    }
3693
3694
    // If this is our last pass, check that the final object type is OK.
3695
1.62k
    if (I == N || 
(807
I == N - 1807
&&
ObjType->isAnyComplexType()804
)) {
3696
      // Accesses to volatile objects are prohibited.
3697
822
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3698
0
        if (Info.getLangOpts().CPlusPlus) {
3699
0
          int DiagKind;
3700
0
          SourceLocation Loc;
3701
0
          const NamedDecl *Decl = nullptr;
3702
0
          if (VolatileField) {
3703
0
            DiagKind = 2;
3704
0
            Loc = VolatileField->getLocation();
3705
0
            Decl = VolatileField;
3706
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3707
0
            DiagKind = 1;
3708
0
            Loc = VD->getLocation();
3709
0
            Decl = VD;
3710
0
          } else {
3711
0
            DiagKind = 0;
3712
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3713
0
              Loc = E->getExprLoc();
3714
0
          }
3715
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3716
0
              << handler.AccessKind << DiagKind << Decl;
3717
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3718
0
        } else {
3719
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3720
0
        }
3721
0
        return handler.failed();
3722
0
      }
3723
3724
      // If we are reading an object of class type, there may still be more
3725
      // things we need to check: if there are any mutable subobjects, we
3726
      // cannot perform this read. (This only happens when performing a trivial
3727
      // copy or assignment.)
3728
822
      if (ObjType->isRecordType() &&
3729
822
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)20
&&
3730
822
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3731
0
        return handler.failed();
3732
822
    }
3733
3734
1.62k
    if (I == N) {
3735
822
      if (!handler.found(*O, ObjType))
3736
3
        return false;
3737
3738
      // If we modified a bit-field, truncate it to the right width.
3739
819
      if (isModification(handler.AccessKind) &&
3740
819
          LastField && 
LastField->isBitField()3
&&
3741
819
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3742
0
        return false;
3743
3744
819
      return true;
3745
819
    }
3746
3747
807
    LastField = nullptr;
3748
807
    if (ObjType->isArrayType()) {
3749
      // Next subobject is an array element.
3750
801
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3751
801
      assert(CAT && "vla in literal type?");
3752
801
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3753
801
      if (CAT->getSize().ule(Index)) {
3754
        // Note, it should not be possible to form a pointer with a valid
3755
        // designator which points more than one past the end of the array.
3756
0
        if (Info.getLangOpts().CPlusPlus11)
3757
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3758
0
            << handler.AccessKind;
3759
0
        else
3760
0
          Info.FFDiag(E);
3761
0
        return handler.failed();
3762
0
      }
3763
3764
801
      ObjType = CAT->getElementType();
3765
3766
801
      if (O->getArrayInitializedElts() > Index)
3767
774
        O = &O->getArrayInitializedElt(Index);
3768
27
      else if (!isRead(handler.AccessKind)) {
3769
27
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3770
0
          return handler.failed();
3771
3772
27
        expandArray(*O, Index);
3773
27
        O = &O->getArrayInitializedElt(Index);
3774
27
      } else
3775
0
        O = &O->getArrayFiller();
3776
801
    } else 
if (6
ObjType->isAnyComplexType()6
) {
3777
      // Next subobject is a complex number.
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (Index > 1) {
3780
0
        if (Info.getLangOpts().CPlusPlus11)
3781
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782
0
            << handler.AccessKind;
3783
0
        else
3784
0
          Info.FFDiag(E);
3785
0
        return handler.failed();
3786
0
      }
3787
3788
0
      ObjType = getSubobjectType(
3789
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790
3791
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3792
0
      if (O->isComplexInt()) {
3793
0
        return handler.found(Index ? O->getComplexIntImag()
3794
0
                                   : O->getComplexIntReal(), ObjType);
3795
0
      } else {
3796
0
        assert(O->isComplexFloat());
3797
0
        return handler.found(Index ? O->getComplexFloatImag()
3798
0
                                   : O->getComplexFloatReal(), ObjType);
3799
0
      }
3800
6
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801
6
      if (Field->isMutable() &&
3802
6
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3803
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804
0
          << handler.AccessKind << Field;
3805
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3806
0
        return handler.failed();
3807
0
      }
3808
3809
      // Next subobject is a class, struct or union field.
3810
6
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811
6
      if (RD->isUnion()) {
3812
6
        const FieldDecl *UnionField = O->getUnionField();
3813
6
        if (!UnionField ||
3814
6
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815
6
          if (I == N - 1 && 
handler.AccessKind == AK_Construct3
) {
3816
            // Placement new onto an inactive union member makes it active.
3817
3
            O->setUnion(Field, APValue());
3818
3
          } else {
3819
            // FIXME: If O->getUnionValue() is absent, report that there's no
3820
            // active union member rather than reporting the prior active union
3821
            // member. We'll need to fix nullptr_t to not use APValue() as its
3822
            // representation first.
3823
3
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824
3
                << handler.AccessKind << Field << !UnionField << UnionField;
3825
3
            return handler.failed();
3826
3
          }
3827
6
        }
3828
3
        O = &O->getUnionValue();
3829
3
      } else
3830
0
        O = &O->getStructField(Field->getFieldIndex());
3831
3832
3
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833
3
      LastField = Field;
3834
3
      if (Field->getType().isVolatileQualified())
3835
0
        VolatileField = Field;
3836
3
    } else {
3837
      // Next subobject is a base class.
3838
0
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839
0
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840
0
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3841
3842
0
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843
0
    }
3844
807
  }
3845
828
}
3846
3847
namespace {
3848
struct ExtractSubobjectHandler {
3849
  EvalInfo &Info;
3850
  const Expr *E;
3851
  APValue &Result;
3852
  const AccessKinds AccessKind;
3853
3854
  typedef bool result_type;
3855
1.12k
  bool failed() { return false; }
3856
2.54M
  bool found(APValue &Subobj, QualType SubobjType) {
3857
2.54M
    Result = Subobj;
3858
2.54M
    if (AccessKind == AK_ReadObjectRepresentation)
3859
453
      return true;
3860
2.54M
    return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3861
2.54M
  }
3862
12
  bool found(APSInt &Value, QualType SubobjType) {
3863
12
    Result = APValue(Value);
3864
12
    return true;
3865
12
  }
3866
12
  bool found(APFloat &Value, QualType SubobjType) {
3867
12
    Result = APValue(Value);
3868
12
    return true;
3869
12
  }
3870
};
3871
} // end anonymous namespace
3872
3873
/// Extract the designated sub-object of an rvalue.
3874
static bool extractSubobject(EvalInfo &Info, const Expr *E,
3875
                             const CompleteObject &Obj,
3876
                             const SubobjectDesignator &Sub, APValue &Result,
3877
2.54M
                             AccessKinds AK = AK_Read) {
3878
2.54M
  assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3879
2.54M
  ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3880
2.54M
  return findSubobject(Info, E, Obj, Sub, Handler);
3881
2.54M
}
3882
3883
namespace {
3884
struct ModifySubobjectHandler {
3885
  EvalInfo &Info;
3886
  APValue &NewVal;
3887
  const Expr *E;
3888
3889
  typedef bool result_type;
3890
  static const AccessKinds AccessKind = AK_Assign;
3891
3892
20.8k
  bool checkConst(QualType QT) {
3893
    // Assigning to a const object has undefined behavior.
3894
20.8k
    if (QT.isConstQualified()) {
3895
21
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3896
21
      return false;
3897
21
    }
3898
20.7k
    return true;
3899
20.8k
  }
3900
3901
73
  bool failed() { return false; }
3902
20.8k
  bool found(APValue &Subobj, QualType SubobjType) {
3903
20.8k
    if (!checkConst(SubobjType))
3904
21
      return false;
3905
    // We've been given ownership of NewVal, so just swap it in.
3906
20.7k
    Subobj.swap(NewVal);
3907
20.7k
    return true;
3908
20.8k
  }
3909
0
  bool found(APSInt &Value, QualType SubobjType) {
3910
0
    if (!checkConst(SubobjType))
3911
0
      return false;
3912
0
    if (!NewVal.isInt()) {
3913
      // Maybe trying to write a cast pointer value into a complex?
3914
0
      Info.FFDiag(E);
3915
0
      return false;
3916
0
    }
3917
0
    Value = NewVal.getInt();
3918
0
    return true;
3919
0
  }
3920
0
  bool found(APFloat &Value, QualType SubobjType) {
3921
0
    if (!checkConst(SubobjType))
3922
0
      return false;
3923
0
    Value = NewVal.getFloat();
3924
0
    return true;
3925
0
  }
3926
};
3927
} // end anonymous namespace
3928
3929
const AccessKinds ModifySubobjectHandler::AccessKind;
3930
3931
/// Update the designated sub-object of an rvalue to the given value.
3932
static bool modifySubobject(EvalInfo &Info, const Expr *E,
3933
                            const CompleteObject &Obj,
3934
                            const SubobjectDesignator &Sub,
3935
20.8k
                            APValue &NewVal) {
3936
20.8k
  ModifySubobjectHandler Handler = { Info, NewVal, E };
3937
20.8k
  return findSubobject(Info, E, Obj, Sub, Handler);
3938
20.8k
}
3939
3940
/// Find the position where two subobject designators diverge, or equivalently
3941
/// the length of the common initial subsequence.
3942
static unsigned FindDesignatorMismatch(QualType ObjType,
3943
                                       const SubobjectDesignator &A,
3944
                                       const SubobjectDesignator &B,
3945
482
                                       bool &WasArrayIndex) {
3946
482
  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3947
775
  for (/**/; I != N; 
++I293
) {
3948
645
    if (!ObjType.isNull() &&
3949
645
        
(613
ObjType->isArrayType()613
||
ObjType->isAnyComplexType()220
)) {
3950
      // Next subobject is an array element.
3951
393
      if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3952
304
        WasArrayIndex = true;
3953
304
        return I;
3954
304
      }
3955
89
      if (ObjType->isAnyComplexType())
3956
0
        ObjType = ObjType->castAs<ComplexType>()->getElementType();
3957
89
      else
3958
89
        ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3959
252
    } else {
3960
252
      if (A.Entries[I].getAsBaseOrMember() !=
3961
252
          B.Entries[I].getAsBaseOrMember()) {
3962
48
        WasArrayIndex = false;
3963
48
        return I;
3964
48
      }
3965
204
      if (const FieldDecl *FD = getAsField(A.Entries[I]))
3966
        // Next subobject is a field.
3967
172
        ObjType = FD->getType();
3968
32
      else
3969
        // Next subobject is a base class.
3970
32
        ObjType = QualType();
3971
204
    }
3972
645
  }
3973
130
  WasArrayIndex = false;
3974
130
  return I;
3975
482
}
3976
3977
/// Determine whether the given subobject designators refer to elements of the
3978
/// same array object.
3979
static bool AreElementsOfSameArray(QualType ObjType,
3980
                                   const SubobjectDesignator &A,
3981
244
                                   const SubobjectDesignator &B) {
3982
244
  if (A.Entries.size() != B.Entries.size())
3983
0
    return false;
3984
3985
244
  bool IsArray = A.MostDerivedIsArrayElement;
3986
244
  if (IsArray && 
A.MostDerivedPathLength != A.Entries.size()205
)
3987
    // A is a subobject of the array element.
3988
2
    return false;
3989
3990
  // If A (and B) designates an array element, the last entry will be the array
3991
  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3992
  // of length 1' case, and the entire path must match.
3993
242
  bool WasArrayIndex;
3994
242
  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3995
242
  return CommonLength >= A.Entries.size() - IsArray;
3996
244
}
3997
3998
/// Find the complete object to which an LValue refers.
3999
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4000
                                         AccessKinds AK, const LValue &LVal,
4001
9.84M
                                         QualType LValType) {
4002
9.84M
  if (LVal.InvalidBase) {
4003
8
    Info.FFDiag(E);
4004
8
    return CompleteObject();
4005
8
  }
4006
4007
9.84M
  if (!LVal.Base) {
4008
162
    Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4009
162
    return CompleteObject();
4010
162
  }
4011
4012
9.84M
  CallStackFrame *Frame = nullptr;
4013
9.84M
  unsigned Depth = 0;
4014
9.84M
  if (LVal.getLValueCallIndex()) {
4015
402k
    std::tie(Frame, Depth) =
4016
402k
        Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4017
402k
    if (!Frame) {
4018
23
      Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4019
23
        << AK << LVal.Base.is<const ValueDecl*>();
4020
23
      NoteLValueLocation(Info, LVal.Base);
4021
23
      return CompleteObject();
4022
23
    }
4023
402k
  }
4024
4025
9.84M
  bool IsAccess = isAnyAccess(AK);
4026
4027
  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4028
  // is not a constant expression (even if the object is non-volatile). We also
4029
  // apply this rule to C++98, in order to conform to the expected 'volatile'
4030
  // semantics.
4031
9.84M
  if (isFormalAccess(AK) && 
LValType.isVolatileQualified()9.76M
) {
4032
5.69k
    if (Info.getLangOpts().CPlusPlus)
4033
2.77k
      Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4034
2.77k
        << AK << LValType;
4035
2.91k
    else
4036
2.91k
      Info.FFDiag(E);
4037
5.69k
    return CompleteObject();
4038
5.69k
  }
4039
4040
  // Compute value storage location and type of base object.
4041
9.83M
  APValue *BaseVal = nullptr;
4042
9.83M
  QualType BaseType = getType(LVal.Base);
4043
4044
9.83M
  if (Info.getLangOpts().CPlusPlus14 && 
LVal.Base == Info.EvaluatingDecl3.23M
&&
4045
9.83M
      
lifetimeStartedInEvaluation(Info, LVal.Base)1.69k
) {
4046
    // This is the object whose initializer we're evaluating, so its lifetime
4047
    // started in the current evaluation.
4048
1.01k
    BaseVal = Info.EvaluatingDeclValue;
4049
9.83M
  } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4050
    // Allow reading from a GUID declaration.
4051
9.73M
    if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4052
102
      if (isModification(AK)) {
4053
        // All the remaining cases do not permit modification of the object.
4054
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4055
0
        return CompleteObject();
4056
0
      }
4057
102
      APValue &V = GD->getAsAPValue();
4058
102
      if (V.isAbsent()) {
4059
19
        Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4060
19
            << GD->getType();
4061
19
        return CompleteObject();
4062
19
      }
4063
83
      return CompleteObject(LVal.Base, &V, GD->getType());
4064
102
    }
4065
4066
    // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4067
9.73M
    if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4068
529
      if (isModification(AK)) {
4069
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4070
0
        return CompleteObject();
4071
0
      }
4072
529
      return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4073
529
                            GCD->getType());
4074
529
    }
4075
4076
    // Allow reading from template parameter objects.
4077
9.73M
    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4078
248
      if (isModification(AK)) {
4079
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4080
0
        return CompleteObject();
4081
0
      }
4082
248
      return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4083
248
                            TPO->getType());
4084
248
    }
4085
4086
    // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4087
    // In C++11, constexpr, non-volatile variables initialized with constant
4088
    // expressions are constant expressions too. Inside constexpr functions,
4089
    // parameters are constant expressions even if they're non-const.
4090
    // In C++1y, objects local to a constant expression (those with a Frame) are
4091
    // both readable and writable inside constant expressions.
4092
    // In C, such things can also be folded, although they are not ICEs.
4093
9.73M
    const VarDecl *VD = dyn_cast<VarDecl>(D);
4094
9.73M
    if (VD) {
4095
9.73M
      if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4096
9.04M
        VD = VDef;
4097
9.73M
    }
4098
9.73M
    if (!VD || 
VD->isInvalidDecl()9.73M
) {
4099
6
      Info.FFDiag(E);
4100
6
      return CompleteObject();
4101
6
    }
4102
4103
9.73M
    bool IsConstant = BaseType.isConstant(Info.Ctx);
4104
4105
    // Unless we're looking at a local variable or argument in a constexpr call,
4106
    // the variable we're reading must be const.
4107
9.73M
    if (!Frame) {
4108
9.38M
      if (IsAccess && 
isa<ParmVarDecl>(VD)9.34M
) {
4109
        // Access of a parameter that's not associated with a frame isn't going
4110
        // to work out, but we can leave it to evaluateVarDeclInit to provide a
4111
        // suitable diagnostic.
4112
7.33M
      } else if (Info.getLangOpts().CPlusPlus14 &&
4113
7.33M
                 
lifetimeStartedInEvaluation(Info, LVal.Base)2.53M
) {
4114
        // OK, we can read and modify an object if we're in the process of
4115
        // evaluating its initializer, because its lifetime began in this
4116
        // evaluation.
4117
7.33M
      } else if (isModification(AK)) {
4118
        // All the remaining cases do not permit modification of the object.
4119
208k
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4120
208k
        return CompleteObject();
4121
7.13M
      } else if (VD->isConstexpr()) {
4122
        // OK, we can read this variable.
4123
5.50M
      } else if (BaseType->isIntegralOrEnumerationType()) {
4124
4.96M
        if (!IsConstant) {
4125
4.18M
          if (!IsAccess)
4126
0
            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4127
4.18M
          if (Info.getLangOpts().CPlusPlus) {
4128
3.96M
            Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4129
3.96M
            Info.Note(VD->getLocation(), diag::note_declared_at);
4130
3.96M
          } else {
4131
224k
            Info.FFDiag(E);
4132
224k
          }
4133
4.18M
          return CompleteObject();
4134
4.18M
        }
4135
4.96M
      } else 
if (537k
!IsAccess537k
) {
4136
44.1k
        return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4137
493k
      } else if (IsConstant && 
Info.checkingPotentialConstantExpression()8.86k
&&
4138
493k
                 
BaseType->isLiteralType(Info.Ctx)5
&&
!VD->hasDefinition()5
) {
4139
        // This variable might end up being constexpr. Don't diagnose it yet.
4140
493k
      } else if (IsConstant) {
4141
        // Keep evaluating to see what we can do. In particular, we support
4142
        // folding of const floating-point types, in order to make static const
4143
        // data members of such types (supported as an extension) more useful.
4144
8.85k
        if (Info.getLangOpts().CPlusPlus) {
4145
7.09k
          Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4146
7.09k
                              ? 
diag::note_constexpr_ltor_non_constexpr7.03k
4147
7.09k
                              : 
diag::note_constexpr_ltor_non_integral63
, 1)
4148
7.09k
              << VD << BaseType;
4149
7.09k
          Info.Note(VD->getLocation(), diag::note_declared_at);
4150
7.09k
        } else {
4151
1.76k
          Info.CCEDiag(E);
4152
1.76k
        }
4153
484k
      } else {
4154
        // Never allow reading a non-const value.
4155
484k
        if (Info.getLangOpts().CPlusPlus) {
4156
423k
          Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4157
423k
                             ? 
diag::note_constexpr_ltor_non_constexpr411k
4158
423k
                             : 
diag::note_constexpr_ltor_non_integral11.8k
, 1)
4159
423k
              << VD << BaseType;
4160
423k
          Info.Note(VD->getLocation(), diag::note_declared_at);
4161
423k
        } else {
4162
61.4k
          Info.FFDiag(E);
4163
61.4k
        }
4164
484k
        return CompleteObject();
4165
484k
      }
4166
9.38M
    }
4167
4168
4.81M
    if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4169
2.25M
      return CompleteObject();
4170
4.81M
  } else 
if (DynamicAllocLValue 96.1k
DA96.1k
= LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4171
45.7k
    std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4172
45.7k
    if (!Alloc) {
4173
6
      Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4174
6
      return CompleteObject();
4175
6
    }
4176
45.7k
    return CompleteObject(LVal.Base, &(*Alloc)->Value,
4177
45.7k
                          LVal.Base.getDynamicAllocType());
4178
50.3k
  } else {
4179
50.3k
    const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4180
4181
50.3k
    if (!Frame) {
4182
300
      if (const MaterializeTemporaryExpr *MTE =
4183
300
              dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4184
254
        assert(MTE->getStorageDuration() == SD_Static &&
4185
254
               "should have a frame for a non-global materialized temporary");
4186
4187
        // C++20 [expr.const]p4: [DR2126]
4188
        //   An object or reference is usable in constant expressions if it is
4189
        //   - a temporary object of non-volatile const-qualified literal type
4190
        //     whose lifetime is extended to that of a variable that is usable
4191
        //     in constant expressions
4192
        //
4193
        // C++20 [expr.const]p5:
4194
        //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4195
        //   - a non-volatile glvalue that refers to an object that is usable
4196
        //     in constant expressions, or
4197
        //   - a non-volatile glvalue of literal type that refers to a
4198
        //     non-volatile object whose lifetime began within the evaluation
4199
        //     of E;
4200
        //
4201
        // C++11 misses the 'began within the evaluation of e' check and
4202
        // instead allows all temporaries, including things like:
4203
        //   int &&r = 1;
4204
        //   int x = ++r;
4205
        //   constexpr int k = r;
4206
        // Therefore we use the C++14-onwards rules in C++11 too.
4207
        //
4208
        // Note that temporaries whose lifetimes began while evaluating a
4209
        // variable's constructor are not usable while evaluating the
4210
        // corresponding destructor, not even if they're of const-qualified
4211
        // types.
4212
254
        if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4213
254
            
!lifetimeStartedInEvaluation(Info, LVal.Base)156
) {
4214
129
          if (!IsAccess)
4215
0
            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4216
129
          Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4217
129
          Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4218
129
          return CompleteObject();
4219
129
        }
4220
4221
125
        BaseVal = MTE->getOrCreateValue(false);
4222
125
        assert(BaseVal && "got reference to unevaluated temporary");
4223
125
      } else {
4224
46
        if (!IsAccess)
4225
7
          return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4226
39
        APValue Val;
4227
39
        LVal.moveInto(Val);
4228
39
        Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4229
39
            << AK
4230
39
            << Val.getAsString(Info.Ctx,
4231
39
                               Info.Ctx.getLValueReferenceType(LValType));
4232
39
        NoteLValueLocation(Info, LVal.Base);
4233
39
        return CompleteObject();
4234
46
      }
4235
50.0k
    } else {
4236
50.0k
      BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4237
50.0k
      assert(BaseVal && "missing value for temporary");
4238
50.0k
    }
4239
50.3k
  }
4240
4241
  // In C++14, we can't safely access any mutable state when we might be
4242
  // evaluating after an unmodeled side effect. Parameters are modeled as state
4243
  // in the caller, but aren't visible once the call returns, so they can be
4244
  // modified in a speculatively-evaluated call.
4245
  //
4246
  // FIXME: Not all local state is mutable. Allow local constant subobjects
4247
  // to be read here (but take care with 'mutable' fields).
4248
2.60M
  unsigned VisibleDepth = Depth;
4249
2.60M
  if (llvm::isa_and_nonnull<ParmVarDecl>(
4250
2.60M
          LVal.Base.dyn_cast<const ValueDecl *>()))
4251
224k
    ++VisibleDepth;
4252
2.60M
  if ((Frame && 
Info.getLangOpts().CPlusPlus14400k
&&
4253
2.60M
       
Info.EvalStatus.HasSideEffects267k
) ||
4254
2.60M
      
(2.60M
isModification(AK)2.60M
&&
VisibleDepth < Info.SpeculativeEvaluationDepth69.7k
))
4255
1.60k
    return CompleteObject();
4256
4257
2.60M
  return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4258
2.60M
}
4259
4260
/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4261
/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4262
/// glvalue referred to by an entity of reference type.
4263
///
4264
/// \param Info - Information about the ongoing evaluation.
4265
/// \param Conv - The expression for which we are performing the conversion.
4266
///               Used for diagnostics.
4267
/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4268
///               case of a non-class type).
4269
/// \param LVal - The glvalue on which we are attempting to perform this action.
4270
/// \param RVal - The produced value will be placed here.
4271
/// \param WantObjectRepresentation - If true, we're looking for the object
4272
///               representation rather than the value, and in particular,
4273
///               there is no requirement that the result be fully initialized.
4274
static bool
4275
handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4276
                               const LValue &LVal, APValue &RVal,
4277
9.56M
                               bool WantObjectRepresentation = false) {
4278
9.56M
  if (LVal.Designator.Invalid)
4279
1.76k
    return false;
4280
4281
  // Check for special cases where there is no existing APValue to look at.
4282
9.56M
  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4283
4284
9.56M
  AccessKinds AK =
4285
9.56M
      WantObjectRepresentation ? 
AK_ReadObjectRepresentation623
:
AK_Read9.56M
;
4286
4287
9.56M
  if (Base && 
!LVal.getLValueCallIndex()114k
&&
!Type.isVolatileQualified()90.8k
) {
4288
90.8k
    if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4289
      // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4290
      // initializer until now for such expressions. Such an expression can't be
4291
      // an ICE in C, so this only matters for fold.
4292
21.4k
      if (Type.isVolatileQualified()) {
4293
0
        Info.FFDiag(Conv);
4294
0
        return false;
4295
0
      }
4296
4297
21.4k
      APValue Lit;
4298
21.4k
      if (!Evaluate(Lit, Info, CLE->getInitializer()))
4299
20.3k
        return false;
4300
4301
      // According to GCC info page:
4302
      //
4303
      // 6.28 Compound Literals
4304
      //
4305
      // As an optimization, G++ sometimes gives array compound literals longer
4306
      // lifetimes: when the array either appears outside a function or has a
4307
      // const-qualified type. If foo and its initializer had elements of type
4308
      // char *const rather than char *, or if foo were a global variable, the
4309
      // array would have static storage duration. But it is probably safest
4310
      // just to avoid the use of array compound literals in C++ code.
4311
      //
4312
      // Obey that rule by checking constness for converted array types.
4313
4314
1.08k
      QualType CLETy = CLE->getType();
4315
1.08k
      if (CLETy->isArrayType() && 
!Type->isArrayType()36
) {
4316
36
        if (!CLETy.isConstant(Info.Ctx)) {
4317
28
          Info.FFDiag(Conv);
4318
28
          Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4319
28
          return false;
4320
28
        }
4321
36
      }
4322
4323
1.06k
      CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4324
1.06k
      return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4325
69.4k
    } else if (isa<StringLiteral>(Base) || 
isa<PredefinedExpr>(Base)3.66k
) {
4326
      // Special-case character extraction so we don't have to construct an
4327
      // APValue for the whole string.
4328
69.1k
      assert(LVal.Designator.Entries.size() <= 1 &&
4329
69.1k
             "Can only read characters from string literals");
4330
69.1k
      if (LVal.Designator.Entries.empty()) {
4331
        // Fail for now for LValue to RValue conversion of an array.
4332
        // (This shouldn't show up in C/C++, but it could be triggered by a
4333
        // weird EvaluateAsRValue call from a tool.)
4334
30
        Info.FFDiag(Conv);
4335
30
        return false;
4336
30
      }
4337
69.1k
      if (LVal.Designator.isOnePastTheEnd()) {
4338
133
        if (Info.getLangOpts().CPlusPlus11)
4339
133
          Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4340
0
        else
4341
0
          Info.FFDiag(Conv);
4342
133
        return false;
4343
133
      }
4344
69.0k
      uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4345
69.0k
      RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4346
69.0k
      return true;
4347
69.1k
    }
4348
90.8k
  }
4349
4350
9.47M
  CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4351
9.47M
  return Obj && 
extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK)2.54M
;
4352
9.56M
}
4353
4354
/// Perform an assignment of Val to LVal. Takes ownership of Val.
4355
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4356
93.9k
                             QualType LValType, APValue &Val) {
4357
93.9k
  if (LVal.Designator.Invalid)
4358
43
    return false;
4359
4360
93.8k
  if (!Info.getLangOpts().CPlusPlus14) {
4361
37.9k
    Info.FFDiag(E);
4362
37.9k
    return false;
4363
37.9k
  }
4364
4365
55.9k
  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4366
55.9k
  return Obj && 
modifySubobject(Info, E, Obj, LVal.Designator, Val)20.8k
;
4367
93.8k
}
4368
4369
namespace {
4370
struct CompoundAssignSubobjectHandler {
4371
  EvalInfo &Info;
4372
  const CompoundAssignOperator *E;
4373
  QualType PromotedLHSType;
4374
  BinaryOperatorKind Opcode;
4375
  const APValue &RHS;
4376
4377
  static const AccessKinds AccessKind = AK_Assign;
4378
4379
  typedef bool result_type;
4380
4381
5.71k
  bool checkConst(QualType QT) {
4382
    // Assigning to a const object has undefined behavior.
4383
5.71k
    if (QT.isConstQualified()) {
4384
0
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4385
0
      return false;
4386
0
    }
4387
5.71k
    return true;
4388
5.71k
  }
4389
4390
5
  bool failed() { return false; }
4391
5.72k
  bool found(APValue &Subobj, QualType SubobjType) {
4392
5.72k
    switch (Subobj.getKind()) {
4393
1.59k
    case APValue::Int:
4394
1.59k
      return found(Subobj.getInt(), SubobjType);
4395
4.00k
    case APValue::Float:
4396
4.00k
      return found(Subobj.getFloat(), SubobjType);
4397
0
    case APValue::ComplexInt:
4398
0
    case APValue::ComplexFloat:
4399
      // FIXME: Implement complex compound assignment.
4400
0
      Info.FFDiag(E);
4401
0
      return false;
4402
86
    case APValue::LValue:
4403
86
      return foundPointer(Subobj, SubobjType);
4404
28
    case APValue::Vector:
4405
28
      return foundVector(Subobj, SubobjType);
4406
9
    case APValue::Indeterminate:
4407
9
      Info.FFDiag(E, diag::note_constexpr_access_uninit)
4408
9
          << /*read of=*/0 << /*uninitialized object=*/1
4409
9
          << E->getLHS()->getSourceRange();
4410
9
      return false;
4411
0
    default:
4412
      // FIXME: can this happen?
4413
0
      Info.FFDiag(E);
4414
0
      return false;
4415
5.72k
    }
4416
5.72k
  }
4417
4418
28
  bool foundVector(APValue &Value, QualType SubobjType) {
4419
28
    if (!checkConst(SubobjType))
4420
0
      return false;
4421
4422
28
    if (!SubobjType->isVectorType()) {
4423
0
      Info.FFDiag(E);
4424
0
      return false;
4425
0
    }
4426
28
    return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4427
28
  }
4428
4429
1.59k
  bool found(APSInt &Value, QualType SubobjType) {
4430
1.59k
    if (!checkConst(SubobjType))
4431
0
      return false;
4432
4433
1.59k
    if (!SubobjType->isIntegerType()) {
4434
      // We don't support compound assignment on integer-cast-to-pointer
4435
      // values.
4436
0
      Info.FFDiag(E);
4437
0
      return false;
4438
0
    }
4439
4440
1.59k
    if (RHS.isInt()) {
4441
1.56k
      APSInt LHS =
4442
1.56k
          HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4443
1.56k
      if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4444
12
        return false;
4445
1.54k
      Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4446
1.54k
      return true;
4447
1.56k
    } else 
if (29
RHS.isFloat()29
) {
4448
29
      const FPOptions FPO = E->getFPFeaturesInEffect(
4449
29
                                    Info.Ctx.getLangOpts());
4450
29
      APFloat FValue(0.0);
4451
29
      return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4452
29
                                  PromotedLHSType, FValue) &&
4453
29
             handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4454
29
             HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4455
29
                                  Value);
4456
29
    }
4457
4458
0
    Info.FFDiag(E);
4459
0
    return false;
4460
1.59k
  }
4461
4.00k
  bool found(APFloat &Value, QualType SubobjType) {
4462
4.00k
    return checkConst(SubobjType) &&
4463
4.00k
           HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4464
4.00k
                                  Value) &&
4465
4.00k
           handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4466
4.00k
           HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4467
4.00k
  }
4468
86
  bool foundPointer(APValue &Subobj, QualType SubobjType) {
4469
86
    if (!checkConst(SubobjType))
4470
0
      return false;
4471
4472
86
    QualType PointeeType;
4473
86
    if (const PointerType *PT = SubobjType->getAs<PointerType>())
4474
86
      PointeeType = PT->getPointeeType();
4475
4476
86
    if (PointeeType.isNull() || !RHS.isInt() ||
4477
86
        (Opcode != BO_Add && 
Opcode != BO_Sub16
)) {
4478
0
      Info.FFDiag(E);
4479
0
      return false;
4480
0
    }
4481
4482
86
    APSInt Offset = RHS.getInt();
4483
86
    if (Opcode == BO_Sub)
4484
16
      negateAsSigned(Offset);
4485
4486
86
    LValue LVal;
4487
86
    LVal.setFrom(Info.Ctx, Subobj);
4488
86
    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4489
0
      return false;
4490
86
    LVal.moveInto(Subobj);
4491
86
    return true;
4492
86
  }
4493
};
4494
} // end anonymous namespace
4495
4496
const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4497
4498
/// Perform a compound assignment of LVal <op>= RVal.
4499
static bool handleCompoundAssignment(EvalInfo &Info,
4500
                                     const CompoundAssignOperator *E,
4501
                                     const LValue &LVal, QualType LValType,
4502
                                     QualType PromotedLValType,
4503
                                     BinaryOperatorKind Opcode,
4504
52.7k
                                     const APValue &RVal) {
4505
52.7k
  if (LVal.Designator.Invalid)
4506
0
    return false;
4507
4508
52.7k
  if (!Info.getLangOpts().CPlusPlus14) {
4509
32.0k
    Info.FFDiag(E);
4510
32.0k
    return false;
4511
32.0k
  }
4512
4513
20.6k
  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4514
20.6k
  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4515
20.6k
                                             RVal };
4516
20.6k
  return Obj && 
findSubobject(Info, E, Obj, LVal.Designator, Handler)5.72k
;
4517
52.7k
}
4518
4519
namespace {
4520
struct IncDecSubobjectHandler {
4521
  EvalInfo &Info;
4522
  const UnaryOperator *E;
4523
  AccessKinds AccessKind;
4524
  APValue *Old;
4525
4526
  typedef bool result_type;
4527
4528
57.8k
  bool checkConst(QualType QT) {
4529
    // Assigning to a const object has undefined behavior.
4530
57.8k
    if (QT.isConstQualified()) {
4531
0
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4532
0
      return false;
4533
0
    }
4534
57.8k
    return true;
4535
57.8k
  }
4536
4537
33
  bool failed() { return false; }
4538
57.8k
  bool found(APValue &Subobj, QualType SubobjType) {
4539
    // Stash the old value. Also clear Old, so we don't clobber it later
4540
    // if we're post-incrementing a complex.
4541
57.8k
    if (Old) {
4542
3.15k
      *Old = Subobj;
4543
3.15k
      Old = nullptr;
4544
3.15k
    }
4545
4546
57.8k
    switch (Subobj.getKind()) {
4547
32.6k
    case APValue::Int:
4548
32.6k
      return found(Subobj.getInt(), SubobjType);
4549
26
    case APValue::Float:
4550
26
      return found(Subobj.getFloat(), SubobjType);
4551
0
    case APValue::ComplexInt:
4552
0
      return found(Subobj.getComplexIntReal(),
4553
0
                   SubobjType->castAs<ComplexType>()->getElementType()
4554
0
                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4555
0
    case APValue::ComplexFloat:
4556
0
      return found(Subobj.getComplexFloatReal(),
4557
0
                   SubobjType->castAs<ComplexType>()->getElementType()
4558
0
                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4559
25.2k
    case APValue::LValue:
4560
25.2k
      return foundPointer(Subobj, SubobjType);
4561
0
    default:
4562
      // FIXME: can this happen?
4563
0
      Info.FFDiag(E);
4564
0
      return false;
4565
57.8k
    }
4566
57.8k
  }
4567
32.6k
  bool found(APSInt &Value, QualType SubobjType) {
4568
32.6k
    if (!checkConst(SubobjType))
4569
0
      return false;
4570
4571
32.6k
    if (!SubobjType->isIntegerType()) {
4572
      // We don't support increment / decrement on integer-cast-to-pointer
4573
      // values.
4574
0
      Info.FFDiag(E);
4575
0
      return false;
4576
0
    }
4577
4578
32.6k
    if (Old) 
*Old = APValue(Value)0
;
4579
4580
    // bool arithmetic promotes to int, and the conversion back to bool
4581
    // doesn't reduce mod 2^n, so special-case it.
4582
32.6k
    if (SubobjType->isBooleanType()) {
4583
6
      if (AccessKind == AK_Increment)
4584
6
        Value = 1;
4585
0
      else
4586
0
        Value = !Value;
4587
6
      return true;
4588
6
    }
4589
4590
32.5k
    bool WasNegative = Value.isNegative();
4591
32.5k
    if (AccessKind == AK_Increment) {
4592
32.5k
      ++Value;
4593
4594
32.5k
      if (!WasNegative && 
Value.isNegative()32.4k
&&
E->canOverflow()18
) {
4595
12
        APSInt ActualValue(Value, /*IsUnsigned*/true);
4596
12
        return HandleOverflow(Info, E, ActualValue, SubobjType);
4597
12
      }
4598
32.5k
    } else {
4599
90
      --Value;
4600
4601
90
      if (WasNegative && 
!Value.isNegative()12
&&
E->canOverflow()10
) {
4602
4
        unsigned BitWidth = Value.getBitWidth();
4603
4
        APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4604
4
        ActualValue.setBit(BitWidth);
4605
4
        return HandleOverflow(Info, E, ActualValue, SubobjType);
4606
4
      }
4607
90
    }
4608
32.5k
    return true;
4609
32.5k
  }
4610
26
  bool found(APFloat &Value, QualType SubobjType) {
4611
26
    if (!checkConst(SubobjType))
4612
0
      return false;
4613
4614
26
    if (Old) 
*Old = APValue(Value)0
;
4615
4616
26
    APFloat One(Value.getSemantics(), 1);
4617
26
    if (AccessKind == AK_Increment)
4618
15
      Value.add(One, APFloat::rmNearestTiesToEven);
4619
11
    else
4620
11
      Value.subtract(One, APFloat::rmNearestTiesToEven);
4621
26
    return true;
4622
26
  }
4623
25.2k
  bool foundPointer(APValue &Subobj, QualType SubobjType) {
4624
25.2k
    if (!checkConst(SubobjType))
4625
0
      return false;
4626
4627
25.2k
    QualType PointeeType;
4628
25.2k
    if (const PointerType *PT = SubobjType->getAs<PointerType>())
4629
25.2k
      PointeeType = PT->getPointeeType();
4630
0
    else {
4631
0
      Info.FFDiag(E);
4632
0
      return false;
4633
0
    }
4634
4635
25.2k
    LValue LVal;
4636
25.2k
    LVal.setFrom(Info.Ctx, Subobj);
4637
25.2k
    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4638
25.2k
                                     AccessKind == AK_Increment ? 
125.0k
:
-1233
))
4639
0
      return false;
4640
25.2k
    LVal.moveInto(Subobj);
4641
25.2k
    return true;
4642
25.2k
  }
4643
};
4644
} // end anonymous namespace
4645
4646
/// Perform an increment or decrement on LVal.
4647
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4648
396k
                         QualType LValType, bool IsIncrement, APValue *Old) {
4649
396k
  if (LVal.Designator.Invalid)
4650
1
    return false;
4651
4652
396k
  if (!Info.getLangOpts().CPlusPlus14) {
4653
176k
    Info.FFDiag(E);
4654
176k
    return false;
4655
176k
  }
4656
4657
219k
  AccessKinds AK = IsIncrement ? 
AK_Increment217k
:
AK_Decrement2.01k
;
4658
219k
  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4659
219k
  IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4660
219k
  return Obj && 
findSubobject(Info, E, Obj, LVal.Designator, Handler)57.8k
;
4661
396k
}
4662
4663
/// Build an lvalue for the object argument of a member function call.
4664
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4665
172k
                                   LValue &This) {
4666
172k
  if (Object->getType()->isPointerType() && 
Object->isPRValue()33.2k
)
4667
33.2k
    return EvaluatePointer(Object, This, Info);
4668
4669
139k
  if (Object->isGLValue())
4670
139k
    return EvaluateLValue(Object, This, Info);
4671
4672
2
  if (Object->getType()->isLiteralType(Info.Ctx))
4673
0
    return EvaluateTemporary(Object, This, Info);
4674
4675
2
  if (Object->getType()->isRecordType() && Object->isPRValue())
4676
2
    return EvaluateTemporary(Object, This, Info);
4677
4678
0
  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4679
0
  return false;
4680
2
}
4681
4682
/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4683
/// lvalue referring to the result.
4684
///
4685
/// \param Info - Information about the ongoing evaluation.
4686
/// \param LV - An lvalue referring to the base of the member pointer.
4687
/// \param RHS - The member pointer expression.
4688
/// \param IncludeMember - Specifies whether the member itself is included in
4689
///        the resulting LValue subobject designator. This is not possible when
4690
///        creating a bound member function.
4691
/// \return The field or method declaration to which the member pointer refers,
4692
///         or 0 if evaluation fails.
4693
static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4694
                                                  QualType LVType,
4695
                                                  LValue &LV,
4696
                                                  const Expr *RHS,
4697
499
                                                  bool IncludeMember = true) {
4698
499
  MemberPtr MemPtr;
4699
499
  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4700
190
    return nullptr;
4701
4702
  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4703
  // member value, the behavior is undefined.
4704
309
  if (!MemPtr.getDecl()) {
4705
    // FIXME: Specific diagnostic.
4706
0
    Info.FFDiag(RHS);
4707
0
    return nullptr;
4708
0
  }
4709
4710
309
  if (MemPtr.isDerivedMember()) {
4711
    // This is a member of some derived class. Truncate LV appropriately.
4712
    // The end of the derived-to-base path for the base object must match the
4713
    // derived-to-base path for the member pointer.
4714
72
    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4715
72
        LV.Designator.Entries.size()) {
4716
15
      Info.FFDiag(RHS);
4717
15
      return nullptr;
4718
15
    }
4719
57
    unsigned PathLengthToMember =
4720
57
        LV.Designator.Entries.size() - MemPtr.Path.size();
4721
528
    for (unsigned I = 0, N = MemPtr.Path.size(); I != N; 
++I471
) {
4722
471
      const CXXRecordDecl *LVDecl = getAsBaseClass(
4723
471
          LV.Designator.Entries[PathLengthToMember + I]);
4724
471
      const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4725
471
      if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4726
0
        Info.FFDiag(RHS);
4727
0
        return nullptr;
4728
0
      }
4729
471
    }
4730
4731
    // Truncate the lvalue to the appropriate derived class.
4732
57
    if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4733
57
                            PathLengthToMember))
4734
0
      return nullptr;
4735
237
  } else if (!MemPtr.Path.empty()) {
4736
    // Extend the LValue path with the member pointer's path.
4737
56
    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4738
56
                                  MemPtr.Path.size() + IncludeMember);
4739
4740
    // Walk down to the appropriate base class.
4741
56
    if (const PointerType *PT = LVType->getAs<PointerType>())
4742
30
      LVType = PT->getPointeeType();
4743
56
    const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4744
56
    assert(RD && "member pointer access on non-class-type expression");
4745
    // The first class in the path is that of the lvalue.
4746
356
    
for (unsigned I = 1, N = MemPtr.Path.size(); 56
I != N;
++I300
) {
4747
300
      const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4748
300
      if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4749
0
        return nullptr;
4750
300
      RD = Base;
4751
300
    }
4752
    // Finally cast to the class containing the member.
4753
56
    if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4754
56
                                MemPtr.getContainingRecord()))
4755
0
      return nullptr;
4756
56
  }
4757
4758
  // Add the member. Note that we cannot build bound member functions here.
4759
294
  if (IncludeMember) {
4760
217
    if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4761
217
      if (!HandleLValueMember(Info, RHS, LV, FD))
4762
0
        return nullptr;
4763
217
    } else 
if (const IndirectFieldDecl *0
IFD0
=
4764
0
                 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4765
0
      if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4766
0
        return nullptr;
4767
0
    } else {
4768
0
      llvm_unreachable("can't construct reference to bound member function");
4769
0
    }
4770
217
  }
4771
4772
294
  return MemPtr.getDecl();
4773
294
}
4774
4775
static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4776
                                                  const BinaryOperator *BO,
4777
                                                  LValue &LV,
4778
745
                                                  bool IncludeMember = true) {
4779
745
  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4780
4781
745
  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4782
246
    if (Info.noteFailure()) {
4783
145
      MemberPtr MemPtr;
4784
145
      EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4785
145
    }
4786
246
    return nullptr;
4787
246
  }
4788
4789
499
  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4790
499
                                   BO->getRHS(), IncludeMember);
4791
745
}
4792
4793
/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4794
/// the provided lvalue, which currently refers to the base object.
4795
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4796
188
                                    LValue &Result) {
4797
188
  SubobjectDesignator &D = Result.Designator;
4798
188
  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4799
2
    return false;
4800
4801
186
  QualType TargetQT = E->getType();
4802
186
  if (const PointerType *PT = TargetQT->getAs<PointerType>())
4803
138
    TargetQT = PT->getPointeeType();
4804
4805
  // Check this cast lands within the final derived-to-base subobject path.
4806
186
  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4807
94
    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4808
94
      << D.MostDerivedType << TargetQT;
4809
94
    return false;
4810
94
  }
4811
4812
  // Check the type of the final cast. We don't need to check the path,
4813
  // since a cast can only be formed if the path is unique.
4814
92
  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4815
92
  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4816
92
  const CXXRecordDecl *FinalType;
4817
92
  if (NewEntriesSize == D.MostDerivedPathLength)
4818
55
    FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4819
37
  else
4820
37
    FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4821
92
  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4822
12
    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4823
12
      << D.MostDerivedType << TargetQT;
4824
12
    return false;
4825
12
  }
4826
4827
  // Truncate the lvalue to the appropriate derived class.
4828
80
  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4829
92
}
4830
4831
/// Get the value to use for a default-initialized object of type T.
4832
/// Return false if it encounters something invalid.
4833
20.1k
static bool handleDefaultInitValue(QualType T, APValue &Result) {
4834
20.1k
  bool Success = true;
4835
4836
  // If there is already a value present don't overwrite it.
4837
20.1k
  if (!Result.isAbsent())
4838
26
    return true;
4839
4840
20.1k
  if (auto *RD = T->getAsCXXRecordDecl()) {
4841
11.1k
    if (RD->isInvalidDecl()) {
4842
1
      Result = APValue();
4843
1
      return false;
4844
1
    }
4845
11.0k
    if (RD->isUnion()) {
4846
440
      Result = APValue((const FieldDecl *)nullptr);
4847
440
      return true;
4848
440
    }
4849
10.6k
    Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4850
10.6k
                     std::distance(RD->field_begin(), RD->field_end()));
4851
4852
10.6k
    unsigned Index = 0;
4853
10.6k
    for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4854
10.6k
                                                  End = RD->bases_end();
4855
12.9k
         I != End; 
++I, ++Index2.27k
)
4856
2.27k
      Success &=
4857
2.27k
          handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4858
4859
10.6k
    for (const auto *I : RD->fields()) {
4860
4.14k
      if (I->isUnnamedBitfield())
4861
35
        continue;
4862
4.11k
      Success &= handleDefaultInitValue(
4863
4.11k
          I->getType(), Result.getStructField(I->getFieldIndex()));
4864
4.11k
    }
4865
10.6k
    return Success;
4866
11.0k
  }
4867
4868
9.01k
  if (auto *AT =
4869
9.01k
          dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4870
661
    Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4871
661
    if (Result.hasArrayFiller())
4872
628
      Success &=
4873
628
          handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4874
4875
661
    return Success;
4876
661
  }
4877
4878
8.35k
  Result = APValue::IndeterminateValue();
4879
8.35k
  return true;
4880
9.01k
}
4881
4882
namespace {
4883
enum EvalStmtResult {
4884
  /// Evaluation failed.
4885
  ESR_Failed,
4886
  /// Hit a 'return' statement.
4887
  ESR_Returned,
4888
  /// Evaluation succeeded.
4889
  ESR_Succeeded,
4890
  /// Hit a 'continue' statement.
4891
  ESR_Continue,
4892
  /// Hit a 'break' statement.
4893
  ESR_Break,
4894
  /// Still scanning for 'case' or 'default' statement.
4895
  ESR_CaseNotFound
4896
};
4897
}
4898
4899
20.9k
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4900
20.9k
  if (VD->isInvalidDecl())
4901
5
    return false;
4902
  // We don't need to evaluate the initializer for a static local.
4903
20.9k
  if (!VD->hasLocalStorage())
4904
202
    return true;
4905
4906
20.7k
  LValue Result;
4907
20.7k
  APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4908
20.7k
                                                   ScopeKind::Block, Result);
4909
4910
20.7k
  const Expr *InitE = VD->getInit();
4911
20.7k
  if (!InitE) {
4912
4.59k
    if (VD->getType()->isDependentType())
4913
0
      return Info.noteSideEffect();
4914
4.59k
    return handleDefaultInitValue(VD->getType(), Val);
4915
4.59k
  }
4916
16.1k
  if (InitE->isValueDependent())
4917
1
    return false;
4918
4919
16.1k
  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4920
    // Wipe out any partially-computed value, to allow tracking that this
4921
    // evaluation failed.
4922
4.65k
    Val = APValue();
4923
4.65k
    return false;
4924
4.65k
  }
4925
4926
11.5k
  return true;
4927
16.1k
}
4928
4929
22.4k
static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4930
22.4k
  bool OK = true;
4931
4932
22.4k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4933
20.9k
    OK &= EvaluateVarDecl(Info, VD);
4934
4935
22.4k
  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4936
377
    for (auto *BD : DD->bindings())
4937
1.02k
      if (auto *VD = BD->getHoldingVar())
4938
18
        OK &= EvaluateDecl(Info, VD);
4939
4940
22.4k
  return OK;
4941
22.4k
}
4942
4943
1.39M
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4944
1.39M
  assert(E->isValueDependent());
4945
1.39M
  if (Info.noteSideEffect())
4946
1.39M
    return true;
4947
43
  assert(E->containsErrors() && "valid value-dependent expression should never "
4948
43
                                "reach invalid code path.");
4949
43
  return false;
4950
43
}
4951
4952
/// Evaluate a condition (either a variable declaration or an expression).
4953
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4954
1.11M
                         const Expr *Cond, bool &Result) {
4955
1.11M
  if (Cond->isValueDependent())
4956
18
    return false;
4957
1.11M
  FullExpressionRAII Scope(Info);
4958
1.11M
  if (CondDecl && 
!EvaluateDecl(Info, CondDecl)248
)
4959
3
    return false;
4960
1.11M
  if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4961
739
    return false;
4962
1.11M
  return Scope.destroy();
4963
1.11M
}
4964
4965
namespace {
4966
/// A location where the result (returned value) of evaluating a
4967
/// statement should be stored.
4968
struct StmtResult {
4969
  /// The APValue that should be filled in with the returned value.
4970
  APValue &Value;
4971
  /// The location containing the result, if any (used to support RVO).
4972
  const LValue *Slot;
4973
};
4974
4975
struct TempVersionRAII {
4976
  CallStackFrame &Frame;
4977
4978
7.93k
  TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4979
7.93k
    Frame.pushTempVersion();
4980
7.93k
  }
4981
4982
7.93k
  ~TempVersionRAII() {
4983
7.93k
    Frame.popTempVersion();
4984
7.93k
  }
4985
};
4986
4987
}
4988
4989
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4990
                                   const Stmt *S,
4991
                                   const SwitchCase *SC = nullptr);
4992
4993
/// Evaluate the body of a loop, and translate the result as appropriate.
4994
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4995
                                       const Stmt *Body,
4996
11.9M
                                       const SwitchCase *Case = nullptr) {
4997
11.9M
  BlockScopeRAII Scope(Info);
4998
4999
11.9M
  EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5000
11.9M
  if (ESR != ESR_Failed && 
ESR != ESR_CaseNotFound11.9M
&&
!Scope.destroy()11.9M
)
5001
0
    ESR = ESR_Failed;
5002
5003
11.9M
  switch (ESR) {
5004
185
  case ESR_Break:
5005
185
    return ESR_Succeeded;
5006
11.9M
  case ESR_Succeeded:
5007
11.9M
  case ESR_Continue:
5008
11.9M
    return ESR_Continue;
5009
33
  case ESR_Failed:
5010
188
  case ESR_Returned:
5011
278
  case ESR_CaseNotFound:
5012
278
    return ESR;
5013
11.9M
  }
5014
0
  llvm_unreachable("Invalid EvalStmtResult!");
5015
0
}
5016
5017
/// Evaluate a switch statement.
5018
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5019
375
                                     const SwitchStmt *SS) {
5020
375
  BlockScopeRAII Scope(Info);
5021
5022
  // Evaluate the switch condition.
5023
375
  APSInt Value;
5024
375
  {
5025
375
    if (const Stmt *Init = SS->getInit()) {
5026
39
      EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5027
39
      if (ESR != ESR_Succeeded) {
5028
0
        if (ESR != ESR_Failed && !Scope.destroy())
5029
0
          ESR = ESR_Failed;
5030
0
        return ESR;
5031
0
      }
5032
39
    }
5033
5034
375
    FullExpressionRAII CondScope(Info);
5035
375
    if (SS->getConditionVariable() &&
5036
375
        
!EvaluateDecl(Info, SS->getConditionVariable())10
)
5037
1
      return ESR_Failed;
5038
374
    if (SS->getCond()->isValueDependent()) {
5039
      // We don't know what the value is, and which branch should jump to.
5040
9
      EvaluateDependentExpr(SS->getCond(), Info);
5041
9
      return ESR_Failed;
5042
9
    }
5043
365
    if (!EvaluateInteger(SS->getCond(), Value, Info))
5044
72
      return ESR_Failed;
5045
5046
293
    if (!CondScope.destroy())
5047
0
      return ESR_Failed;
5048
293
  }
5049
5050
  // Find the switch case corresponding to the value of the condition.
5051
  // FIXME: Cache this lookup.
5052
293
  const SwitchCase *Found = nullptr;
5053
1.04k
  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5054
1.02k
       
SC = SC->getNextSwitchCase()750
) {
5055
1.02k
    if (isa<DefaultStmt>(SC)) {
5056
99
      Found = SC;
5057
99
      continue;
5058
99
    }
5059
5060
929
    const CaseStmt *CS = cast<CaseStmt>(SC);
5061
929
    APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5062
929
    APSInt RHS = CS->getRHS() ? 
CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)0
5063
929
                              : LHS;
5064
929
    if (LHS <= Value && 
Value <= RHS420
) {
5065
278
      Found = SC;
5066
278
      break;
5067
278
    }
5068
929
  }
5069
5070
293
  if (!Found)
5071
5
    return Scope.destroy() ? ESR_Succeeded : 
ESR_Failed0
;
5072
5073
  // Search the switch body for the switch case and evaluate it from there.
5074
288
  EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5075
288
  if (ESR != ESR_Failed && 
ESR != ESR_CaseNotFound253
&&
!Scope.destroy()244
)
5076
0
    return ESR_Failed;
5077
5078
288
  switch (ESR) {
5079
58
  case ESR_Break:
5080
58
    return ESR_Succeeded;
5081
30
  case ESR_Succeeded:
5082
38
  case ESR_Continue:
5083
73
  case ESR_Failed:
5084
221
  case ESR_Returned:
5085
221
    return ESR;
5086
9
  case ESR_CaseNotFound:
5087
    // This can only happen if the switch case is nested within a statement
5088
    // expression. We have no intention of supporting that.
5089
9
    Info.FFDiag(Found->getBeginLoc(),
5090
9
                diag::note_constexpr_stmt_expr_unsupported);
5091
9
    return ESR_Failed;
5092
288
  }
5093
0
  llvm_unreachable("Invalid EvalStmtResult!");
5094
0
}
5095
5096
20.7k
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5097
  // An expression E is a core constant expression unless the evaluation of E
5098
  // would evaluate one of the following: [C++23] - a control flow that passes
5099
  // through a declaration of a variable with static or thread storage duration
5100
  // unless that variable is usable in constant expressions.
5101
20.7k
  if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5102
20.7k
      
!VD->isUsableInConstantExpressions(Info.Ctx)120
) {
5103
32
    Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5104
32
        << (VD->getTSCSpec() == TSCS_unspecified ? 
015
:
117
) << VD;
5105
32
    return false;
5106
32
  }
5107
20.7k
  return true;
5108
20.7k
}
5109
5110
// Evaluate a statement.
5111
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5112
13.6M
                                   const Stmt *S, const SwitchCase *Case) {
5113
13.6M
  if (!Info.nextStep(S))
5114
17
    return ESR_Failed;
5115
5116
  // If we're hunting down a 'case' or 'default' label, recurse through
5117
  // substatements until we hit the label.
5118
13.6M
  if (Case) {
5119
2.87k
    switch (S->getStmtClass()) {
5120
559
    case Stmt::CompoundStmtClass:
5121
      // FIXME: Precompute which substatement of a compound statement we
5122
      // would jump to, and go straight there rather than performing a
5123
      // linear scan each time.
5124
559
    case Stmt::LabelStmtClass:
5125
559
    case Stmt::AttributedStmtClass:
5126
603
    case Stmt::DoStmtClass:
5127
603
      break;
5128
5129
1.00k
    case Stmt::CaseStmtClass:
5130
1.01k
    case Stmt::DefaultStmtClass:
5131
1.01k
      if (Case == S)
5132
279
        Case = nullptr;
5133
1.01k
      break;
5134
5135
116
    case Stmt::IfStmtClass: {
5136
      // FIXME: Precompute which side of an 'if' we would jump to, and go
5137
      // straight there rather than scanning both sides.
5138
116
      const IfStmt *IS = cast<IfStmt>(S);
5139
5140
      // Wrap the evaluation in a block scope, in case it's a DeclStmt
5141
      // preceded by our switch label.
5142
116
      BlockScopeRAII Scope(Info);
5143
5144
      // Step into the init statement in case it brings an (uninitialized)
5145
      // variable into scope.
5146
116
      if (const Stmt *Init = IS->getInit()) {
5147
2
        EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5148
2
        if (ESR != ESR_CaseNotFound) {
5149
0
          assert(ESR != ESR_Succeeded);
5150
0
          return ESR;
5151
0
        }
5152
2
      }
5153
5154
      // Condition variable must be initialized if it exists.
5155
      // FIXME: We can skip evaluating the body if there's a condition
5156
      // variable, as there can't be any case labels within it.
5157
      // (The same is true for 'for' statements.)
5158
5159
116
      EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5160
116
      if (ESR == ESR_Failed)
5161
0
        return ESR;
5162
116
      if (ESR != ESR_CaseNotFound)
5163
68
        return Scope.destroy() ? ESR : 
ESR_Failed0
;
5164
48
      if (!IS->getElse())
5165
30
        return ESR_CaseNotFound;
5166
5167
18
      ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5168
18
      if (ESR == ESR_Failed)
5169
0
        return ESR;
5170
18
      if (ESR != ESR_CaseNotFound)
5171
18
        return Scope.destroy() ? ESR : 
ESR_Failed0
;
5172
0
      return ESR_CaseNotFound;
5173
18
    }
5174
5175
54
    case Stmt::WhileStmtClass: {
5176
54
      EvalStmtResult ESR =
5177
54
          EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5178
54
      if (ESR != ESR_Continue)
5179
54
        return ESR;
5180
0
      break;
5181
54
    }
5182
5183
90
    case Stmt::ForStmtClass: {
5184
90
      const ForStmt *FS = cast<ForStmt>(S);
5185
90
      BlockScopeRAII Scope(Info);
5186
5187
      // Step into the init statement in case it brings an (uninitialized)
5188
      // variable into scope.
5189
90
      if (const Stmt *Init = FS->getInit()) {
5190
2
        EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5191
2
        if (ESR != ESR_CaseNotFound) {
5192
0
          assert(ESR != ESR_Succeeded);
5193
0
          return ESR;
5194
0
        }
5195
2
      }
5196
5197
90
      EvalStmtResult ESR =
5198
90
          EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5199
90
      if (ESR != ESR_Continue)
5200
50
        return ESR;
5201
40
      if (const auto *Inc = FS->getInc()) {
5202
28
        if (Inc->isValueDependent()) {
5203
1
          if (!EvaluateDependentExpr(Inc, Info))
5204
0
            return ESR_Failed;
5205
27
        } else {
5206
27
          FullExpressionRAII IncScope(Info);
5207
27
          if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5208
0
            return ESR_Failed;
5209
27
        }
5210
28
      }
5211
40
      break;
5212
40
    }
5213
5214
80
    case Stmt::DeclStmtClass: {
5215
      // Start the lifetime of any uninitialized variables we encounter. They
5216
      // might be used by the selected branch of the switch.
5217
80
      const DeclStmt *DS = cast<DeclStmt>(S);
5218
80
      for (const auto *D : DS->decls()) {
5219
80
        if (const auto *VD = dyn_cast<VarDecl>(D)) {
5220
80
          if (!CheckLocalVariableDeclaration(Info, VD))
5221
0
            return ESR_Failed;
5222
80
          if (VD->hasLocalStorage() && !VD->getInit())
5223
5
            if (!EvaluateVarDecl(Info, VD))
5224
0
              return ESR_Failed;
5225
          // FIXME: If the variable has initialization that can't be jumped
5226
          // over, bail out of any immediately-surrounding compound-statement
5227
          // too. There can't be any case labels here.
5228
80
        }
5229
80
      }
5230
80
      return ESR_CaseNotFound;
5231
80
    }
5232
5233
921
    default:
5234
921
      return ESR_CaseNotFound;
5235
2.87k
    }
5236
2.87k
  }
5237
5238
13.6M
  switch (S->getStmtClass()) {
5239
39.9k
  default:
5240
39.9k
    if (const Expr *E = dyn_cast<Expr>(S)) {
5241
39.9k
      if (E->isValueDependent()) {
5242
7
        if (!EvaluateDependentExpr(E, Info))
5243
2
          return ESR_Failed;
5244
39.9k
      } else {
5245
        // Don't bother evaluating beyond an expression-statement which couldn't
5246
        // be evaluated.
5247
        // FIXME: Do we need the FullExpressionRAII object here?
5248
        // VisitExprWithCleanups should create one when necessary.
5249
39.9k
        FullExpressionRAII Scope(Info);
5250
39.9k
        if (!EvaluateIgnoredValue(Info, E) || 
!Scope.destroy()39.5k
)
5251
426
          return ESR_Failed;
5252
39.9k
      }
5253
39.4k
      return ESR_Succeeded;
5254
39.9k
    }
5255
5256
33
    Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5257
33
    return ESR_Failed;
5258
5259
2.44M
  case Stmt::NullStmtClass:
5260
2.44M
    return ESR_Succeeded;
5261
5262
22.1k
  case Stmt::DeclStmtClass: {
5263
22.1k
    const DeclStmt *DS = cast<DeclStmt>(S);
5264
22.2k
    for (const auto *D : DS->decls()) {
5265
22.2k
      const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5266
22.2k
      if (VD && 
!CheckLocalVariableDeclaration(Info, VD)20.7k
)
5267
32
        return ESR_Failed;
5268
      // Each declaration initialization is its own full-expression.
5269
22.2k
      FullExpressionRAII Scope(Info);
5270
22.2k
      if (!EvaluateDecl(Info, D) && 
!Info.noteFailure()4.65k
)
5271
4.11k
        return ESR_Failed;
5272
18.0k
      if (!Scope.destroy())
5273
0
        return ESR_Failed;
5274
18.0k
    }
5275
18.0k
    return ESR_Succeeded;
5276
22.1k
  }
5277
5278
432k
  case Stmt::ReturnStmtClass: {
5279
432k
    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5280
432k
    FullExpressionRAII Scope(Info);
5281
432k
    if (RetExpr && 
RetExpr->isValueDependent()432k
) {
5282
37
      EvaluateDependentExpr(RetExpr, Info);
5283
      // We know we returned, but we don't know what the value is.
5284
37
      return ESR_Failed;
5285
37
    }
5286
432k
    if (RetExpr &&
5287
432k
        
!(432k
Result.Slot432k
5288
432k
              ? 
EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)6.88k
5289
432k
              : 
Evaluate(Result.Value, Info, RetExpr)425k
))
5290
59.2k
      return ESR_Failed;
5291
373k
    return Scope.destroy() ? 
ESR_Returned373k
:
ESR_Failed5
;
5292
432k
  }
5293
5294
10.2M
  case Stmt::CompoundStmtClass: {
5295
10.2M
    BlockScopeRAII Scope(Info);
5296
5297
10.2M
    const CompoundStmt *CS = cast<CompoundStmt>(S);
5298
10.2M
    for (const auto *BI : CS->body()) {
5299
848k
      EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5300
848k
      if (ESR == ESR_Succeeded)
5301
411k
        Case = nullptr;
5302
436k
      else if (ESR != ESR_CaseNotFound) {
5303
435k
        if (ESR != ESR_Failed && 
!Scope.destroy()374k
)
5304
165
          return ESR_Failed;
5305
435k
        return ESR;
5306
435k
      }
5307
848k
    }
5308
9.85M
    if (Case)
5309
138
      return ESR_CaseNotFound;
5310
9.85M
    return Scope.destroy() ? 
ESR_Succeeded9.85M
:
ESR_Failed74
;
5311
9.85M
  }
5312
5313
21.9k
  case Stmt::IfStmtClass: {
5314
21.9k
    const IfStmt *IS = cast<IfStmt>(S);
5315
5316
    // Evaluate the condition, as either a var decl or as an expression.
5317
21.9k
    BlockScopeRAII Scope(Info);
5318
21.9k
    if (const Stmt *Init = IS->getInit()) {
5319
396
      EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5320
396
      if (ESR != ESR_Succeeded) {
5321
220
        if (ESR != ESR_Failed && 
!Scope.destroy()0
)
5322
0
          return ESR_Failed;
5323
220
        return ESR;
5324
220
      }
5325
396
    }
5326
21.6k
    bool Cond;
5327
21.6k
    if (IS->isConsteval()) {
5328
39
      Cond = IS->isNonNegatedConsteval();
5329
      // If we are not in a constant context, if consteval should not evaluate
5330
      // to true.
5331
39
      if (!Info.InConstantContext)
5332
10
        Cond = !Cond;
5333
21.6k
    } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5334
21.6k
                             Cond))
5335
582
      return ESR_Failed;
5336
5337
21.1k
    if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5338
1.94k
      EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5339
1.94k
      if (ESR != ESR_Succeeded) {
5340
1.40k
        if (ESR != ESR_Failed && 
!Scope.destroy()1.32k
)
5341
0
          return ESR_Failed;
5342
1.40k
        return ESR;
5343
1.40k
      }
5344
1.94k
    }
5345
19.6k
    return Scope.destroy() ? ESR_Succeeded : 
ESR_Failed0
;
5346
21.1k
  }
5347
5348
634
  case Stmt::WhileStmtClass: {
5349
634
    const WhileStmt *WS = cast<WhileStmt>(S);
5350
1.06M
    while (true) {
5351
1.06M
      BlockScopeRAII Scope(Info);
5352
1.06M
      bool Continue;
5353
1.06M
      if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5354
1.06M
                        Continue))
5355
21
        return ESR_Failed;
5356
1.06M
      if (!Continue)
5357
490
        break;
5358
5359
1.06M
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5360
1.06M
      if (ESR != ESR_Continue) {
5361
123
        if (ESR != ESR_Failed && 
!Scope.destroy()116
)
5362
0
          return ESR_Failed;
5363
123
        return ESR;
5364
123
      }
5365
1.06M
      if (!Scope.destroy())
5366
0
        return ESR_Failed;
5367
1.06M
    }
5368
490
    return ESR_Succeeded;
5369
634
  }
5370
5371
118
  case Stmt::DoStmtClass: {
5372
118
    const DoStmt *DS = cast<DoStmt>(S);
5373
118
    bool Continue;
5374
324
    do {
5375
324
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5376
324
      if (ESR != ESR_Continue)
5377
83
        return ESR;
5378
241
      Case = nullptr;
5379
5380
241
      if (DS->getCond()->isValueDependent()) {
5381
7
        EvaluateDependentExpr(DS->getCond(), Info);
5382
        // Bailout as we don't know whether to keep going or terminate the loop.
5383
7
        return ESR_Failed;
5384
7
      }
5385
234
      FullExpressionRAII CondScope(Info);
5386
234
      if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5387
234
          !CondScope.destroy())
5388
0
        return ESR_Failed;
5389
234
    } while (Continue);
5390
28
    return ESR_Succeeded;
5391
118
  }
5392
5393
530
  case Stmt::ForStmtClass: {
5394
530
    const ForStmt *FS = cast<ForStmt>(S);
5395
530
    BlockScopeRAII ForScope(Info);
5396
530
    if (FS->getInit()) {
5397
285
      EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5398
285
      if (ESR != ESR_Succeeded) {
5399
0
        if (ESR != ESR_Failed && !ForScope.destroy())
5400
0
          return ESR_Failed;
5401
0
        return ESR;
5402
0
      }
5403
285
    }
5404
10.8M
    
while (530
true) {
5405
10.8M
      BlockScopeRAII IterScope(Info);
5406
10.8M
      bool Continue = true;
5407
10.8M
      if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5408
31.9k
                                         FS->getCond(), Continue))
5409
157
        return ESR_Failed;
5410
10.8M
      if (!Continue)
5411
232
        break;
5412
5413
10.8M
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5414
10.8M
      if (ESR != ESR_Continue) {
5415
141
        if (ESR != ESR_Failed && 
(117
!IterScope.destroy()117
||
!ForScope.destroy()117
))
5416
0
          return ESR_Failed;
5417
141
        return ESR;
5418
141
      }
5419
5420
10.8M
      if (const auto *Inc = FS->getInc()) {
5421
1.42M
        if (Inc->isValueDependent()) {
5422
1.39M
          if (!EvaluateDependentExpr(Inc, Info))
5423
0
            return ESR_Failed;
5424
1.39M
        } else {
5425
31.3k
          FullExpressionRAII IncScope(Info);
5426
31.3k
          if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5427
0
            return ESR_Failed;
5428
31.3k
        }
5429
1.42M
      }
5430
5431
10.8M
      if (!IterScope.destroy())
5432
0
        return ESR_Failed;
5433
10.8M
    }
5434
232
    return ForScope.destroy() ? ESR_Succeeded : 
ESR_Failed0
;
5435
530
  }
5436
5437
147
  case Stmt::CXXForRangeStmtClass: {
5438
147
    const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5439
147
    BlockScopeRAII Scope(Info);
5440
5441
    // Evaluate the init-statement if present.
5442
147
    if (FS->getInit()) {
5443
2
      EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5444
2
      if (ESR != ESR_Succeeded) {
5445
0
        if (ESR != ESR_Failed && !Scope.destroy())
5446
0
          return ESR_Failed;
5447
0
        return ESR;
5448
0
      }
5449
2
    }
5450
5451
    // Initialize the __range variable.
5452
147
    EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5453
147
    if (ESR != ESR_Succeeded) {
5454
0
      if (ESR != ESR_Failed && !Scope.destroy())
5455
0
        return ESR_Failed;
5456
0
      return ESR;
5457
0
    }
5458
5459
    // In error-recovery cases it's possible to get here even if we failed to
5460
    // synthesize the __begin and __end variables.
5461
147
    if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5462
0
      return ESR_Failed;
5463
5464
    // Create the __begin and __end iterators.
5465
147
    ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5466
147
    if (ESR != ESR_Succeeded) {
5467
0
      if (ESR != ESR_Failed && !Scope.destroy())
5468
0
        return ESR_Failed;
5469
0
      return ESR;
5470
0
    }
5471
147
    ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5472
147
    if (ESR != ESR_Succeeded) {
5473
0
      if (ESR != ESR_Failed && !Scope.destroy())
5474
0
        return ESR_Failed;
5475
0
      return ESR;
5476
0
    }
5477
5478
3.51k
    
while (147
true) {
5479
      // Condition: __begin != __end.
5480
3.51k
      {
5481
3.51k
        if (FS->getCond()->isValueDependent()) {
5482
0
          EvaluateDependentExpr(FS->getCond(), Info);
5483
          // We don't know whether to keep going or terminate the loop.
5484
0
          return ESR_Failed;
5485
0
        }
5486
3.51k
        bool Continue = true;
5487
3.51k
        FullExpressionRAII CondExpr(Info);
5488
3.51k
        if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5489
26
          return ESR_Failed;
5490
3.49k
        if (!Continue)
5491
109
          break;
5492
3.49k
      }
5493
5494
      // User's variable declaration, initialized by *__begin.
5495
3.38k
      BlockScopeRAII InnerScope(Info);
5496
3.38k
      ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5497
3.38k
      if (ESR != ESR_Succeeded) {
5498
0
        if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5499
0
          return ESR_Failed;
5500
0
        return ESR;
5501
0
      }
5502
5503
      // Loop body.
5504
3.38k
      ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5505
3.38k
      if (ESR != ESR_Continue) {
5506
12
        if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5507
0
          return ESR_Failed;
5508
12
        return ESR;
5509
12
      }
5510
3.37k
      if (FS->getInc()->isValueDependent()) {
5511
0
        if (!EvaluateDependentExpr(FS->getInc(), Info))
5512
0
          return ESR_Failed;
5513
3.37k
      } else {
5514
        // Increment: ++__begin
5515
3.37k
        if (!EvaluateIgnoredValue(Info, FS->getInc()))
5516
0
          return ESR_Failed;
5517
3.37k
      }
5518
5519
3.37k
      if (!InnerScope.destroy())
5520
0
        return ESR_Failed;
5521
3.37k
    }
5522
5523
109
    return Scope.destroy() ? ESR_Succeeded : 
ESR_Failed0
;
5524
147
  }
5525
5526
375
  case Stmt::SwitchStmtClass:
5527
375
    return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5528
5529
285
  case Stmt::ContinueStmtClass:
5530
285
    return ESR_Continue;
5531
5532
245
  case Stmt::BreakStmtClass:
5533
245
    return ESR_Break;
5534
5535
9
  case Stmt::LabelStmtClass:
5536
9
    return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5537
5538
6
  case Stmt::AttributedStmtClass:
5539
    // As a general principle, C++11 attributes can be ignored without
5540
    // any semantic impact.
5541
6
    return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5542
6
                        Case);
5543
5544
350k
  case Stmt::CaseStmtClass:
5545
350k
  case Stmt::DefaultStmtClass:
5546
350k
    return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5547
16
  case Stmt::CXXTryStmtClass:
5548
    // Evaluate try blocks by evaluating all sub statements.
5549
16
    return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5550
13.6M
  }
5551
13.6M
}
5552
5553
/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5554
/// default constructor. If so, we'll fold it whether or not it's marked as
5555
/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5556
/// so we need special handling.
5557
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5558
                                           const CXXConstructorDecl *CD,
5559
110k
                                           bool IsValueInitialization) {
5560
110k
  if (!CD->isTrivial() || 
!CD->isDefaultConstructor()46.1k
)
5561
85.8k
    return false;
5562
5563
  // Value-initialization does not call a trivial default constructor, so such a
5564
  // call is a core constant expression whether or not the constructor is
5565
  // constexpr.
5566
24.5k
  if (!CD->isConstexpr() && 
!IsValueInitialization2.55k
) {
5567
2.00k
    if (Info.getLangOpts().CPlusPlus11) {
5568
      // FIXME: If DiagDecl is an implicitly-declared special member function,
5569
      // we should be much more explicit about why it's not constexpr.
5570
1.52k
      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5571
1.52k
        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5572
1.52k
      Info.Note(CD->getLocation(), diag::note_declared_at);
5573
1.52k
    } else {
5574
482
      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5575
482
    }
5576
2.00k
  }
5577
24.5k
  return true;
5578
110k
}
5579
5580
/// CheckConstexprFunction - Check that a function can be called in a constant
5581
/// expression.
5582
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5583
                                   const FunctionDecl *Declaration,
5584
                                   const FunctionDecl *Definition,
5585
560k
                                   const Stmt *Body) {
5586
  // Potential constant expressions can contain calls to declared, but not yet
5587
  // defined, constexpr functions.
5588
560k
  if (Info.checkingPotentialConstantExpression() && 
!Definition8.40k
&&
5589
560k
      
Declaration->isConstexpr()1.84k
)
5590
1.83k
    return false;
5591
5592
  // Bail out if the function declaration itself is invalid.  We will
5593
  // have produced a relevant diagnostic while parsing it, so just
5594
  // note the problematic sub-expression.
5595
558k
  if (Declaration->isInvalidDecl()) {
5596
17
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5597
17
    return false;
5598
17
  }
5599
5600
  // DR1872: An instantiated virtual constexpr function can't be called in a
5601
  // constant expression (prior to C++20). We can still constant-fold such a
5602
  // call.
5603
558k
  if (!Info.Ctx.getLangOpts().CPlusPlus20 && 
isa<CXXMethodDecl>(Declaration)515k
&&
5604
558k
      
cast<CXXMethodDecl>(Declaration)->isVirtual()427k
)
5605
73
    Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5606
5607
558k
  if (Definition && 
Definition->isInvalidDecl()482k
) {
5608
0
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5609
0
    return false;
5610
0
  }
5611
5612
  // Can we evaluate this function call?
5613
558k
  if (Definition && 
Definition->isConstexpr()482k
&&
Body431k
)
5614
431k
    return true;
5615
5616
127k
  if (Info.getLangOpts().CPlusPlus11) {
5617
105k
    const FunctionDecl *DiagDecl = Definition ? 
Definition34.0k
:
Declaration71.1k
;
5618
5619
    // If this function is not constexpr because it is an inherited
5620
    // non-constexpr constructor, diagnose that directly.
5621
105k
    auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5622
105k
    if (CD && 
CD->isInheritingConstructor()26.8k
) {
5623
270
      auto *Inherited = CD->getInheritedConstructor().getConstructor();
5624
270
      if (!Inherited->isConstexpr())
5625
245
        DiagDecl = CD = Inherited;
5626
270
    }
5627
5628
    // FIXME: If DiagDecl is an implicitly-declared special member function
5629
    // or an inheriting constructor, we should be much more explicit about why
5630
    // it's not constexpr.
5631
105k
    if (CD && 
CD->isInheritingConstructor()26.8k
)
5632
25
      Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5633
25
        << CD->getInheritedConstructor().getConstructor()->getParent();
5634
105k
    else
5635
105k
      Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5636
105k
        << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5637
105k
    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5638
105k
  } else {
5639
22.4k
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5640
22.4k
  }
5641
127k
  return false;
5642
558k
}
5643
5644
namespace {
5645
struct CheckDynamicTypeHandler {
5646
  AccessKinds AccessKind;
5647
  typedef bool result_type;
5648
49
  bool failed() { return false; }
5649
27.1k
  bool found(APValue &Subobj, QualType SubobjType) { return true; }
5650
0
  bool found(APSInt &Value, QualType SubobjType) { return true; }
5651
0
  bool found(APFloat &Value, QualType SubobjType) { return true; }
5652
};
5653
} // end anonymous namespace
5654
5655
/// Check that we can access the notional vptr of an object / determine its
5656
/// dynamic type.
5657
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5658
71.9k
                             AccessKinds AK, bool Polymorphic) {
5659
71.9k
  if (This.Designator.Invalid)
5660
7
    return false;
5661
5662
71.9k
  CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5663
5664
71.9k
  if (!Obj)
5665
568
    return false;
5666
5667
71.3k
  if (!Obj.Value) {
5668
    // The object is not usable in constant expressions, so we can't inspect
5669
    // its value to see if it's in-lifetime or what the active union members
5670
    // are. We can still check for a one-past-the-end lvalue.
5671
44.1k
    if (This.Designator.isOnePastTheEnd() ||
5672
44.1k
        
This.Designator.isMostDerivedAnUnsizedArray()44.1k
) {
5673
12
      Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5674
12
                         ? diag::note_constexpr_access_past_end
5675
12
                         : 
diag::note_constexpr_access_unsized_array0
)
5676
12
          << AK;
5677
12
      return false;
5678
44.1k
    } else if (Polymorphic) {
5679
      // Conservatively refuse to perform a polymorphic operation if we would
5680
      // not be able to read a notional 'vptr' value.
5681
234
      APValue Val;
5682
234
      This.moveInto(Val);
5683
234
      QualType StarThisType =
5684
234
          Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5685
234
      Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5686
234
          << AK << Val.getAsString(Info.Ctx, StarThisType);
5687
234
      return false;
5688
234
    }
5689
43.8k
    return true;
5690
44.1k
  }
5691
5692
27.2k
  CheckDynamicTypeHandler Handler{AK};
5693
27.2k
  return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5694
71.3k
}
5695
5696
/// Check that the pointee of the 'this' pointer in a member function call is
5697
/// either within its lifetime or in its period of construction or destruction.
5698
static bool
5699
checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5700
                                     const LValue &This,
5701
71.4k
                                     const CXXMethodDecl *NamedMember) {
5702
71.4k
  return checkDynamicType(
5703
71.4k
      Info, E, This,
5704
71.4k
      isa<CXXDestructorDecl>(NamedMember) ? 
AK_Destroy51
:
AK_MemberCall71.3k
, false);
5705
71.4k
}
5706
5707
struct DynamicType {
5708
  /// The dynamic class type of the object.
5709
  const CXXRecordDecl *Type;
5710
  /// The corresponding path length in the lvalue.
5711
  unsigned PathLength;
5712
};
5713
5714
static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5715
583
                                             unsigned PathLength) {
5716
583
  assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5717
583
      Designator.Entries.size() && "invalid path length");
5718
583
  return (PathLength == Designator.MostDerivedPathLength)
5719
583
             ? 
Designator.MostDerivedType->getAsCXXRecordDecl()404
5720
583
             : 
getAsBaseClass(Designator.Entries[PathLength - 1])179
;
5721
583
}
5722
5723
/// Determine the dynamic type of an object.
5724
static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5725
                                                     const Expr *E,
5726
                                                     LValue &This,
5727
501
                                                     AccessKinds AK) {
5728
  // If we don't have an lvalue denoting an object of class type, there is no
5729
  // meaningful dynamic type. (We consider objects of non-class type to have no
5730
  // dynamic type.)
5731
501
  if (!checkDynamicType(Info, E, This, AK, true))
5732
242
    return std::nullopt;
5733
5734
  // Refuse to compute a dynamic type in the presence of virtual bases. This
5735
  // shouldn't happen other than in constant-folding situations, since literal
5736
  // types can't have virtual bases.
5737
  //
5738
  // Note that consumers of DynamicType assume that the type has no virtual
5739
  // bases, and will need modifications if this restriction is relaxed.
5740
259
  const CXXRecordDecl *Class =
5741
259
      This.Designator.MostDerivedType->getAsCXXRecordDecl();
5742
259
  if (!Class || Class->getNumVBases()) {
5743
0
    Info.FFDiag(E);
5744
0
    return std::nullopt;
5745
0
  }
5746
5747
  // FIXME: For very deep class hierarchies, it might be beneficial to use a
5748
  // binary search here instead. But the overwhelmingly common case is that
5749
  // we're not in the middle of a constructor, so it probably doesn't matter
5750
  // in practice.
5751
259
  ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5752
259
  for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5753
360
       PathLength <= Path.size(); 
++PathLength101
) {
5754
358
    switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5755
358
                                      Path.slice(0, PathLength))) {
5756
65
    case ConstructionPhase::Bases:
5757
101
    case ConstructionPhase::DestroyingBases:
5758
      // We're constructing or destroying a base class. This is not the dynamic
5759
      // type.
5760
101
      break;
5761
5762
192
    case ConstructionPhase::None:
5763
233
    case ConstructionPhase::AfterBases:
5764
237
    case ConstructionPhase::AfterFields:
5765
257
    case ConstructionPhase::Destroying:
5766
      // We've finished constructing the base classes and not yet started
5767
      // destroying them again, so this is the dynamic type.
5768
257
      return DynamicType{getBaseClassType(This.Designator, PathLength),
5769
257
                         PathLength};
5770
358
    }
5771
358
  }
5772
5773
  // CWG issue 1517: we're constructing a base class of the object described by
5774
  // 'This', so that object has not yet begun its period of construction and
5775
  // any polymorphic operation on it results in undefined behavior.
5776
2
  Info.FFDiag(E);
5777
2
  return std::nullopt;
5778
259
}
5779
5780
/// Perform virtual dispatch.
5781
static const CXXMethodDecl *HandleVirtualDispatch(
5782
    EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5783
408
    llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5784
408
  std::optional<DynamicType> DynType = ComputeDynamicType(
5785
408
      Info, E, This,
5786
408
      isa<CXXDestructorDecl>(Found) ? 
AK_Destroy4
:
AK_MemberCall404
);
5787
408
  if (!DynType)
5788
189
    return nullptr;
5789
5790
  // Find the final overrider. It must be declared in one of the classes on the
5791
  // path from the dynamic type to the static type.
5792
  // FIXME: If we ever allow literal types to have virtual base classes, that
5793
  // won't be true.
5794
219
  const CXXMethodDecl *Callee = Found;
5795
219
  unsigned PathLength = DynType->PathLength;
5796
224
  for (/**/; PathLength <= This.Designator.Entries.size(); 
++PathLength5
) {
5797
224
    const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5798
224
    const CXXMethodDecl *Overrider =
5799
224
        Found->getCorrespondingMethodDeclaredInClass(Class, false);
5800
224
    if (Overrider) {
5801
219
      Callee = Overrider;
5802
219
      break;
5803
219
    }
5804
224
  }
5805
5806
  // C++2a [class.abstract]p6:
5807
  //   the effect of making a virtual call to a pure virtual function [...] is
5808
  //   undefined
5809
219
  if (Callee->isPure()) {
5810
2
    Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5811
2
    Info.Note(Callee->getLocation(), diag::note_declared_at);
5812
2
    return nullptr;
5813
2
  }
5814
5815
  // If necessary, walk the rest of the path to determine the sequence of
5816
  // covariant adjustment steps to apply.
5817
217
  if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5818
217
                                       Found->getReturnType())) {
5819
28
    CovariantAdjustmentPath.push_back(Callee->getReturnType());
5820
28
    for (unsigned CovariantPathLength = PathLength + 1;
5821
42
         CovariantPathLength != This.Designator.Entries.size();
5822
28
         
++CovariantPathLength14
) {
5823
14
      const CXXRecordDecl *NextClass =
5824
14
          getBaseClassType(This.Designator, CovariantPathLength);
5825
14
      const CXXMethodDecl *Next =
5826
14
          Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5827
14
      if (Next && !Info.Ctx.hasSameUnqualifiedType(
5828
14
                      Next->getReturnType(), CovariantAdjustmentPath.back()))
5829
14
        CovariantAdjustmentPath.push_back(Next->getReturnType());
5830
14
    }
5831
28
    if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5832
28
                                         CovariantAdjustmentPath.back()))
5833
28
      CovariantAdjustmentPath.push_back(Found->getReturnType());
5834
28
  }
5835
5836
  // Perform 'this' adjustment.
5837
217
  if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5838
0
    return nullptr;
5839
5840
217
  return Callee;
5841
217
}
5842
5843
/// Perform the adjustment from a value returned by a virtual function to
5844
/// a value of the statically expected type, which may be a pointer or
5845
/// reference to a base class of the returned type.
5846
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5847
                                            APValue &Result,
5848
28
                                            ArrayRef<QualType> Path) {
5849
28
  assert(Result.isLValue() &&
5850
28
         "unexpected kind of APValue for covariant return");
5851
28
  if (Result.isNullPointer())
5852
0
    return true;
5853
5854
28
  LValue LVal;
5855
28
  LVal.setFrom(Info.Ctx, Result);
5856
5857
28
  const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5858
70
  for (unsigned I = 1; I != Path.size(); 
++I42
) {
5859
42
    const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5860
42
    assert(OldClass && NewClass && "unexpected kind of covariant return");
5861
42
    if (OldClass != NewClass &&
5862
42
        !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5863
0
      return false;
5864
42
    OldClass = NewClass;
5865
42
  }
5866
5867
28
  LVal.moveInto(Result);
5868
28
  return true;
5869
28
}
5870
5871
/// Determine whether \p Base, which is known to be a direct base class of
5872
/// \p Derived, is a public base class.
5873
static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5874
36
                              const CXXRecordDecl *Base) {
5875
70
  for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5876
70
    auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5877
70
    if (BaseClass && declaresSameEntity(BaseClass, Base))
5878
36
      return BaseSpec.getAccessSpecifier() == AS_public;
5879
70
  }
5880
0
  llvm_unreachable("Base is not a direct base of Derived");
5881
0
}
5882
5883
/// Apply the given dynamic cast operation on the provided lvalue.
5884
///
5885
/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5886
/// to find a suitable target subobject.
5887
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5888
69
                              LValue &Ptr) {
5889
  // We can't do anything with a non-symbolic pointer value.
5890
69
  SubobjectDesignator &D = Ptr.Designator;
5891
69
  if (D.Invalid)
5892
0
    return false;
5893
5894
  // C++ [expr.dynamic.cast]p6:
5895
  //   If v is a null pointer value, the result is a null pointer value.
5896
69
  if (Ptr.isNullPointer() && 
!E->isGLValue()5
)
5897
5
    return true;
5898
5899
  // For all the other cases, we need the pointer to point to an object within
5900
  // its lifetime / period of construction / destruction, and we need to know
5901
  // its dynamic type.
5902
64
  std::optional<DynamicType> DynType =
5903
64
      ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5904
64
  if (!DynType)
5905
42
    return false;
5906
5907
  // C++ [expr.dynamic.cast]p7:
5908
  //   If T is "pointer to cv void", then the result is a pointer to the most
5909
  //   derived object
5910
22
  if (E->getType()->isVoidPointerType())
5911
2
    return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5912
5913
20
  const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5914
20
  assert(C && "dynamic_cast target is not void pointer nor class");
5915
20
  CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5916
5917
20
  auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5918
    // C++ [expr.dynamic.cast]p9:
5919
13
    if (!E->isGLValue()) {
5920
      //   The value of a failed cast to pointer type is the null pointer value
5921
      //   of the required result type.
5922
1
      Ptr.setNull(Info.Ctx, E->getType());
5923
1
      return true;
5924
1
    }
5925
5926
    //   A failed cast to reference type throws [...] std::bad_cast.
5927
12
    unsigned DiagKind;
5928
12
    if (!Paths && 
(4
declaresSameEntity(DynType->Type, C)4
||
5929
4
                   DynType->Type->isDerivedFrom(C)))
5930
2
      DiagKind = 0;
5931
10
    else if (!Paths || 
Paths->begin() == Paths->end()8
)
5932
4
      DiagKind = 1;
5933
6
    else if (Paths->isAmbiguous(CQT))
5934
4
      DiagKind = 2;
5935
2
    else {
5936
2
      assert(Paths->front().Access != AS_public && "why did the cast fail?");
5937
2
      DiagKind = 3;
5938
2
    }
5939
12
    Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5940
12
        << DiagKind << Ptr.Designator.getType(Info.Ctx)
5941
12
        << Info.Ctx.getRecordType(DynType->Type)
5942
12
        << E->getType().getUnqualifiedType();
5943
12
    return false;
5944
12
  };
5945
5946
  // Runtime check, phase 1:
5947
  //   Walk from the base subobject towards the derived object looking for the
5948
  //   target type.
5949
20
  for (int PathLength = Ptr.Designator.Entries.size();
5950
64
       PathLength >= (int)DynType->PathLength; 
--PathLength44
) {
5951
52
    const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5952
52
    if (declaresSameEntity(Class, C))
5953
4
      return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5954
    // We can only walk across public inheritance edges.
5955
48
    if (PathLength > (int)DynType->PathLength &&
5956
48
        !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5957
36
                           Class))
5958
4
      return RuntimeCheckFailed(nullptr);
5959
48
  }
5960
5961
  // Runtime check, phase 2:
5962
  //   Search the dynamic type for an unambiguous public base of type C.
5963
12
  CXXBasePaths Paths(/*FindAmbiguities=*/true,
5964
12
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
5965
12
  if (DynType->Type->isDerivedFrom(C, Paths) && 
!Paths.isAmbiguous(CQT)10
&&
5966
12
      
Paths.front().Access == AS_public5
) {
5967
    // Downcast to the dynamic type...
5968
3
    if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5969
0
      return false;
5970
    // ... then upcast to the chosen base class subobject.
5971
3
    for (CXXBasePathElement &Elem : Paths.front())
5972
5
      if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5973
0
        return false;
5974
3
    return true;
5975
3
  }
5976
5977
  // Otherwise, the runtime check fails.
5978
9
  return RuntimeCheckFailed(&Paths);
5979
12
}
5980
5981
namespace {
5982
struct StartLifetimeOfUnionMemberHandler {
5983
  EvalInfo &Info;
5984
  const Expr *LHSExpr;
5985
  const FieldDecl *Field;
5986
  bool DuringInit;
5987
  bool Failed = false;
5988
  static const AccessKinds AccessKind = AK_Assign;
5989
5990
  typedef bool result_type;
5991
2
  bool failed() { return Failed; }
5992
213
  bool found(APValue &Subobj, QualType SubobjType) {
5993
    // We are supposed to perform no initialization but begin the lifetime of
5994
    // the object. We interpret that as meaning to do what default
5995
    // initialization of the object would do if all constructors involved were
5996
    // trivial:
5997
    //  * All base, non-variant member, and array element subobjects' lifetimes
5998
    //    begin
5999
    //  * No variant members' lifetimes begin
6000
    //  * All scalar subobjects whose lifetimes begin have indeterminate values
6001
213
    assert(SubobjType->isUnionType());
6002
213
    if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6003
      // This union member is already active. If it's also in-lifetime, there's
6004
      // nothing to do.
6005
127
      if (Subobj.getUnionValue().hasValue())
6006
119
        return true;
6007
127
    } else 
if (86
DuringInit86
) {
6008
      // We're currently in the process of initializing a different union
6009
      // member.  If we carried on, that initialization would attempt to
6010
      // store to an inactive union member, resulting in undefined behavior.
6011
3
      Info.FFDiag(LHSExpr,
6012
3
                  diag::note_constexpr_union_member_change_during_init);
6013
3
      return false;
6014
3
    }
6015
91
    APValue Result;
6016
91
    Failed = !handleDefaultInitValue(Field->getType(), Result);
6017
91
    Subobj.setUnion(Field, Result);
6018
91
    return true;
6019
213
  }
6020
0
  bool found(APSInt &Value, QualType SubobjType) {
6021
0
    llvm_unreachable("wrong value kind for union object");
6022
0
  }
6023
0
  bool found(APFloat &Value, QualType SubobjType) {
6024
0
    llvm_unreachable("wrong value kind for union object");
6025
0
  }
6026
};
6027
} // end anonymous namespace
6028
6029
const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6030
6031
/// Handle a builtin simple-assignment or a call to a trivial assignment
6032
/// operator whose left-hand side might involve a union member access. If it
6033
/// does, implicitly start the lifetime of any accessed union elements per
6034
/// C++20 [class.union]5.
6035
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6036
                                               const Expr *LHSExpr,
6037
5.19k
                                               const LValue &LHS) {
6038
5.19k
  if (LHS.InvalidBase || LHS.Designator.Invalid)
6039
28
    return false;
6040
6041
5.17k
  llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6042
  // C++ [class.union]p5:
6043
  //   define the set S(E) of subexpressions of E as follows:
6044
5.17k
  unsigned PathLength = LHS.Designator.Entries.size();
6045
7.95k
  for (const Expr *E = LHSExpr; E != nullptr;) {
6046
    //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6047
7.95k
    if (auto *ME = dyn_cast<MemberExpr>(E)) {
6048
2.36k
      auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6049
      // Note that we can't implicitly start the lifetime of a reference,
6050
      // so we don't need to proceed any further if we reach one.
6051
2.36k
      if (!FD || 
FD->getType()->isReferenceType()2.36k
)
6052
15
        break;
6053
6054
      //    ... and also contains A.B if B names a union member ...
6055
2.34k
      if (FD->getParent()->isUnion()) {
6056
        //    ... of a non-class, non-array type, or of a class type with a
6057
        //    trivial default constructor that is not deleted, or an array of
6058
        //    such types.
6059
310
        auto *RD =
6060
310
            FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6061
310
        if (!RD || 
RD->hasTrivialDefaultConstructor()263
)
6062
276
          UnionPathLengths.push_back({PathLength - 1, FD});
6063
310
      }
6064
6065
2.34k
      E = ME->getBase();
6066
2.34k
      --PathLength;
6067
2.34k
      assert(declaresSameEntity(FD,
6068
2.34k
                                LHS.Designator.Entries[PathLength]
6069
2.34k
                                    .getAsBaseOrMember().getPointer()));
6070
6071
      //   -- If E is of the form A[B] and is interpreted as a built-in array
6072
      //      subscripting operator, S(E) is [S(the array operand, if any)].
6073
5.59k
    } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6074
      // Step over an ArrayToPointerDecay implicit cast.
6075
913
      auto *Base = ASE->getBase()->IgnoreImplicit();
6076
913
      if (!Base->getType()->isArrayType())
6077
536
        break;
6078
6079
377
      E = Base;
6080
377
      --PathLength;
6081
6082
4.68k
    } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6083
      // Step over a derived-to-base conversion.
6084
388
      E = ICE->getSubExpr();
6085
388
      if (ICE->getCastKind() == CK_NoOp)
6086
0
        continue;
6087
388
      if (ICE->getCastKind() != CK_DerivedToBase &&
6088
388
          ICE->getCastKind() != CK_UncheckedDerivedToBase)
6089
325
        break;
6090
      // Walk path backwards as we walk up from the base to the derived class.
6091
74
      
for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path()))63
{
6092
74
        if (Elt->isVirtual()) {
6093
          // A class with virtual base classes never has a trivial default
6094
          // constructor, so S(E) is empty in this case.
6095
1
          E = nullptr;
6096
1
          break;
6097
1
        }
6098
6099
73
        --PathLength;
6100
73
        assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6101
73
                                  LHS.Designator.Entries[PathLength]
6102
73
                                      .getAsBaseOrMember().getPointer()));
6103
73
      }
6104
6105
    //   -- Otherwise, S(E) is empty.
6106
4.29k
    } else {
6107
4.29k
      break;
6108
4.29k
    }
6109
7.95k
  }
6110
6111
  // Common case: no unions' lifetimes are started.
6112
5.17k
  if (UnionPathLengths.empty())
6113
4.89k
    return true;
6114
6115
  //   if modification of X [would access an inactive union member], an object
6116
  //   of the type of X is implicitly created
6117
276
  CompleteObject Obj =
6118
276
      findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6119
276
  if (!Obj)
6120
61
    return false;
6121
215
  for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6122
215
           llvm::reverse(UnionPathLengths)) {
6123
    // Form a designator for the union object.
6124
215
    SubobjectDesignator D = LHS.Designator;
6125
215
    D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6126
6127
215
    bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6128
215
                      ConstructionPhase::AfterBases;
6129
215
    StartLifetimeOfUnionMemberHandler StartLifetime{
6130
215
        Info, LHSExpr, LengthAndField.second, DuringInit};
6131
215
    if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6132
5
      return false;
6133
215
  }
6134
6135
210
  return true;
6136
215
}
6137
6138
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6139
                            CallRef Call, EvalInfo &Info,
6140
597k
                            bool NonNull = false) {
6141
597k
  LValue LV;
6142
  // Create the parameter slot and register its destruction. For a vararg
6143
  // argument, create a temporary.
6144
  // FIXME: For calling conventions that destroy parameters in the callee,
6145
  // should we consider performing destruction when the function returns
6146
  // instead?
6147
597k
  APValue &V = PVD ? 
Info.CurrentCall->createParam(Call, PVD, LV)591k
6148
597k
                   : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6149
5.81k
                                                       ScopeKind::Call, LV);
6150
597k
  if (!EvaluateInPlace(V, Info, LV, Arg))
6151
405k
    return false;
6152
6153
  // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6154
  // undefined behavior, so is non-constant.
6155
192k
  if (NonNull && 
V.isLValue()18
&&
V.isNullPointer()17
) {
6156
8
    Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6157
8
    return false;
6158
8
  }
6159
6160
192k
  return true;
6161
192k
}
6162
6163
/// Evaluate the arguments to a function call.
6164
static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6165
                         EvalInfo &Info, const FunctionDecl *Callee,
6166
799k
                         bool RightToLeft = false) {
6167
799k
  bool Success = true;
6168
799k
  llvm::SmallBitVector ForbiddenNullArgs;
6169
799k
  if (Callee->hasAttr<NonNullAttr>()) {
6170
11
    ForbiddenNullArgs.resize(Args.size());
6171
11
    for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6172
11
      if (!Attr->args_size()) {
6173
8
        ForbiddenNullArgs.set();
6174
8
        break;
6175
8
      } else
6176
3
        for (auto Idx : Attr->args()) {
6177
3
          unsigned ASTIdx = Idx.getASTIndex();
6178
3
          if (ASTIdx >= Args.size())
6179
0
            continue;
6180
3
          ForbiddenNullArgs[ASTIdx] = true;
6181
3
        }
6182
11
    }
6183
11
  }
6184
1.29M
  for (unsigned I = 0; I < Args.size(); 
I++494k
) {
6185
596k
    unsigned Idx = RightToLeft ? 
Args.size() - I - 1830
:
I595k
;
6186
596k
    const ParmVarDecl *PVD =
6187
596k
        Idx < Callee->getNumParams() ? 
Callee->getParamDecl(Idx)590k
:
nullptr5.81k
;
6188
596k
    bool NonNull = !ForbiddenNullArgs.empty() && 
ForbiddenNullArgs[Idx]21
;
6189
596k
    if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6190
      // If we're checking for a potential constant expression, evaluate all
6191
      // initializers even if some of them fail.
6192
405k
      if (!Info.noteFailure())
6193
102k
        return false;
6194
302k
      Success = false;
6195
302k
    }
6196
596k
  }
6197
697k
  return Success;
6198
799k
}
6199
6200
/// Perform a trivial copy from Param, which is the parameter of a copy or move
6201
/// constructor or assignment operator.
6202
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6203
                              const Expr *E, APValue &Result,
6204
2.68k
                              bool CopyObjectRepresentation) {
6205
  // Find the reference argument.
6206
2.68k
  CallStackFrame *Frame = Info.CurrentCall;
6207
2.68k
  APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6208
2.68k
  if (!RefValue) {
6209
0
    Info.FFDiag(E);
6210
0
    return false;
6211
0
  }
6212
6213
  // Copy out the contents of the RHS object.
6214
2.68k
  LValue RefLValue;
6215
2.68k
  RefLValue.setFrom(Info.Ctx, *RefValue);
6216
2.68k
  return handleLValueToRValueConversion(
6217
2.68k
      Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6218
2.68k
      CopyObjectRepresentation);
6219
2.68k
}
6220
6221
/// Evaluate a function call.
6222
static bool HandleFunctionCall(SourceLocation CallLoc,
6223
                               const FunctionDecl *Callee, const LValue *This,
6224
                               const Expr *E, ArrayRef<const Expr *> Args,
6225
                               CallRef Call, const Stmt *Body, EvalInfo &Info,
6226
438k
                               APValue &Result, const LValue *ResultSlot) {
6227
438k
  if (!Info.CheckCallLimit(CallLoc))
6228
2.83k
    return false;
6229
6230
436k
  CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6231
6232
  // For a trivial copy or move assignment, perform an APValue copy. This is
6233
  // essential for unions, where the operations performed by the assignment
6234
  // operator cannot be represented as statements.
6235
  //
6236
  // Skip this for non-union classes with no fields; in that case, the defaulted
6237
  // copy/move does not actually read the object.
6238
436k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6239
436k
  if (MD && 
MD->isDefaulted()369k
&&
6240
436k
      
(339
MD->getParent()->isUnion()339
||
6241
339
       
(326
MD->isTrivial()326
&&
6242
326
        
isReadByLvalueToRvalueConversion(MD->getParent())63
))) {
6243
55
    assert(This &&
6244
55
           (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6245
55
    APValue RHSValue;
6246
55
    if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6247
55
                           MD->getParent()->isUnion()))
6248
15
      return false;
6249
40
    if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6250
40
                          RHSValue))
6251
0
      return false;
6252
40
    This->moveInto(Result);
6253
40
    return true;
6254
436k
  } else if (MD && 
isLambdaCallOperator(MD)368k
) {
6255
    // We're in a lambda; determine the lambda capture field maps unless we're
6256
    // just constexpr checking a lambda's call operator. constexpr checking is
6257
    // done before the captures have been added to the closure object (unless
6258
    // we're inferring constexpr-ness), so we don't have access to them in this
6259
    // case. But since we don't need the captures to constexpr check, we can
6260
    // just ignore them.
6261
1.49k
    if (!Info.checkingPotentialConstantExpression())
6262
1.36k
      MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6263
1.36k
                                        Frame.LambdaThisCaptureField);
6264
1.49k
  }
6265
6266
436k
  StmtResult Ret = {Result, ResultSlot};
6267
436k
  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6268
436k
  if (ESR == ESR_Succeeded) {
6269
2.01k
    if (Callee->getReturnType()->isVoidType())
6270
1.99k
      return true;
6271
15
    Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6272
15
  }
6273
434k
  return ESR == ESR_Returned;
6274
436k
}
6275
6276
/// Evaluate a constructor call.
6277
static bool HandleConstructorCall(const Expr *E, const LValue &This,
6278
                                  CallRef Call,
6279
                                  const CXXConstructorDecl *Definition,
6280
32.6k
                                  EvalInfo &Info, APValue &Result) {
6281
32.6k
  SourceLocation CallLoc = E->getExprLoc();
6282
32.6k
  if (!Info.CheckCallLimit(CallLoc))
6283
1.87k
    return false;
6284
6285
30.7k
  const CXXRecordDecl *RD = Definition->getParent();
6286
30.7k
  if (RD->getNumVBases()) {
6287
8
    Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6288
8
    return false;
6289
8
  }
6290
6291
30.7k
  EvalInfo::EvaluatingConstructorRAII EvalObj(
6292
30.7k
      Info,
6293
30.7k
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6294
30.7k
      RD->getNumBases());
6295
30.7k
  CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6296
6297
  // FIXME: Creating an APValue just to hold a nonexistent return value is
6298
  // wasteful.
6299
30.7k
  APValue RetVal;
6300
30.7k
  StmtResult Ret = {RetVal, nullptr};
6301
6302
  // If it's a delegating constructor, delegate.
6303
30.7k
  if (Definition->isDelegatingConstructor()) {
6304
189
    CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6305
189
    if ((*I)->getInit()->isValueDependent()) {
6306
0
      if (!EvaluateDependentExpr((*I)->getInit(), Info))
6307
0
        return false;
6308
189
    } else {
6309
189
      FullExpressionRAII InitScope(Info);
6310
189
      if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6311
189
          
!InitScope.destroy()165
)
6312
24
        return false;
6313
189
    }
6314
165
    return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6315
189
  }
6316
6317
  // For a trivial copy or move constructor, perform an APValue copy. This is
6318
  // essential for unions (or classes with anonymous union members), where the
6319
  // operations performed by the constructor cannot be represented by
6320
  // ctor-initializers.
6321
  //
6322
  // Skip this for empty non-union classes; we should not perform an
6323
  // lvalue-to-rvalue conversion on them because their copy constructor does not
6324
  // actually read them.
6325
30.5k
  if (Definition->isDefaulted() && 
Definition->isCopyOrMoveConstructor()7.55k
&&
6326
30.5k
      
(4.33k
Definition->getParent()->isUnion()4.33k
||
6327
4.33k
       
(4.27k
Definition->isTrivial()4.27k
&&
6328
4.27k
        
isReadByLvalueToRvalueConversion(Definition->getParent())4.26k
))) {
6329
2.62k
    return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6330
2.62k
                             Definition->getParent()->isUnion());
6331
2.62k
  }
6332
6333
  // Reserve space for the struct members.
6334
27.9k
  if (!Result.hasValue()) {
6335
27.3k
    if (!RD->isUnion())
6336
27.0k
      Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6337
27.0k
                       std::distance(RD->field_begin(), RD->field_end()));
6338
282
    else
6339
      // A union starts with no active member.
6340
282
      Result = APValue((const FieldDecl*)nullptr);
6341
27.3k
  }
6342
6343
27.9k
  if (RD->isInvalidDecl()) 
return false4
;
6344
27.8k
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6345
6346
  // A scope for temporaries lifetime-extended by reference members.
6347
27.8k
  BlockScopeRAII LifetimeExtendedScope(Info);
6348
6349
27.8k
  bool Success = true;
6350
27.8k
  unsigned BasesSeen = 0;
6351
27.8k
#ifndef NDEBUG
6352
27.8k
  CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6353
27.8k
#endif
6354
27.8k
  CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6355
27.9k
  auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6356
    // We might be initializing the same field again if this is an indirect
6357
    // field initialization.
6358
27.9k
    if (FieldIt == RD->field_end() ||
6359
27.9k
        
FieldIt->getFieldIndex() > FD->getFieldIndex()27.8k
) {
6360
75
      assert(Indirect && "fields out of order?");
6361
75
      return;
6362
75
    }
6363
6364
    // Default-initialize any fields with no explicit initializer.
6365
27.8k
    
for (; 27.8k
!declaresSameEntity(*FieldIt, FD);
++FieldIt50
) {
6366
50
      assert(FieldIt != RD->field_end() && "missing field?");
6367
50
      if (!FieldIt->isUnnamedBitfield())
6368
23
        Success &= handleDefaultInitValue(
6369
23
            FieldIt->getType(),
6370
23
            Result.getStructField(FieldIt->getFieldIndex()));
6371
50
    }
6372
27.8k
    ++FieldIt;
6373
27.8k
  };
6374
30.2k
  for (const auto *I : Definition->inits()) {
6375
30.2k
    LValue Subobject = This;
6376
30.2k
    LValue SubobjectParent = This;
6377
30.2k
    APValue *Value = &Result;
6378
6379
    // Determine the subobject to initialize.
6380
30.2k
    FieldDecl *FD = nullptr;
6381
30.2k
    if (I->isBaseInitializer()) {
6382
2.05k
      QualType BaseType(I->getBaseClass(), 0);
6383
2.05k
#ifndef NDEBUG
6384
      // Non-virtual base classes are initialized in the order in the class
6385
      // definition. We have already checked for virtual base classes.
6386
2.05k
      assert(!BaseIt->isVirtual() && "virtual base for literal type");
6387
2.05k
      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6388
2.05k
             "base class initializers not in expected order");
6389
2.05k
      ++BaseIt;
6390
2.05k
#endif
6391
2.05k
      if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6392
2.05k
                                  BaseType->getAsCXXRecordDecl(), &Layout))
6393
0
        return false;
6394
2.05k
      Value = &Result.getStructBase(BasesSeen++);
6395
28.2k
    } else if ((FD = I->getMember())) {
6396
27.4k
      if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6397
0
        return false;
6398
27.4k
      if (RD->isUnion()) {
6399
309
        Result = APValue(FD);
6400
309
        Value = &Result.getUnionValue();
6401
27.1k
      } else {
6402
27.1k
        SkipToField(FD, false);
6403
27.1k
        Value = &Result.getStructField(FD->getFieldIndex());
6404
27.1k
      }
6405
27.4k
    } else 
if (IndirectFieldDecl *723
IFD723
= I->getIndirectMember()) {
6406
      // Walk the indirect field decl's chain to find the object to initialize,
6407
      // and make sure we've initialized every step along it.
6408
723
      auto IndirectFieldChain = IFD->chain();
6409
1.55k
      for (auto *C : IndirectFieldChain) {
6410
1.55k
        FD = cast<FieldDecl>(C);
6411
1.55k
        CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6412
        // Switch the union field if it differs. This happens if we had
6413
        // preceding zero-initialization, and we're now initializing a union
6414
        // subobject other than the first.
6415
        // FIXME: In this case, the values of the other subobjects are
6416
        // specified, since zero-initialization sets all padding bits to zero.
6417
1.55k
        if (!Value->hasValue() ||
6418
1.55k
            
(908
Value->isUnion()908
&&
Value->getUnionField() != FD71
)) {
6419
693
          if (CD->isUnion())
6420
623
            *Value = APValue(FD);
6421
70
          else
6422
            // FIXME: This immediately starts the lifetime of all members of
6423
            // an anonymous struct. It would be preferable to strictly start
6424
            // member lifetime in initialization order.
6425
70
            Success &=
6426
70
                handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6427
693
        }
6428
        // Store Subobject as its parent before updating it for the last element
6429
        // in the chain.
6430
1.55k
        if (C == IndirectFieldChain.back())
6431
723
          SubobjectParent = Subobject;
6432
1.55k
        if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6433
0
          return false;
6434
1.55k
        if (CD->isUnion())
6435
648
          Value = &Value->getUnionValue();
6436
907
        else {
6437
907
          if (C == IndirectFieldChain.front() && 
!RD->isUnion()723
)
6438
723
            SkipToField(FD, true);
6439
907
          Value = &Value->getStructField(FD->getFieldIndex());
6440
907
        }
6441
1.55k
      }
6442
723
    } else {
6443
0
      llvm_unreachable("unknown base initializer kind");
6444
0
    }
6445
6446
    // Need to override This for implicit field initializers as in this case
6447
    // This refers to innermost anonymous struct/union containing initializer,
6448
    // not to currently constructed class.
6449
30.2k
    const Expr *Init = I->getInit();
6450
30.2k
    if (Init->isValueDependent()) {
6451
10
      if (!EvaluateDependentExpr(Init, Info))
6452
7
        return false;
6453
30.2k
    } else {
6454
30.2k
      ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6455
30.2k
                                    isa<CXXDefaultInitExpr>(Init));
6456
30.2k
      FullExpressionRAII InitScope(Info);
6457
30.2k
      if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6458
30.2k
          
(27.1k
FD27.1k
&&
FD->isBitField()25.2k
&&
6459
27.1k
           
!truncateBitfieldValue(Info, Init, *Value, FD)95
)) {
6460
        // If we're checking for a potential constant expression, evaluate all
6461
        // initializers even if some of them fail.
6462
3.10k
        if (!Info.noteFailure())
6463
536
          return false;
6464
2.56k
        Success = false;
6465
2.56k
      }
6466
30.2k
    }
6467
6468
    // This is the point at which the dynamic type of the object becomes this
6469
    // class type.
6470
29.7k
    if (I->isBaseInitializer() && 
BasesSeen == RD->getNumBases()2.04k
)
6471
1.72k
      EvalObj.finishedConstructingBases();
6472
29.7k
  }
6473
6474
  // Default-initialize any remaining fields.
6475
27.3k
  if (!RD->isUnion()) {
6476
27.2k
    for (; FieldIt != RD->field_end(); 
++FieldIt224
) {
6477
224
      if (!FieldIt->isUnnamedBitfield())
6478
221
        Success &= handleDefaultInitValue(
6479
221
            FieldIt->getType(),
6480
221
            Result.getStructField(FieldIt->getFieldIndex()));
6481
224
    }
6482
27.0k
  }
6483
6484
27.3k
  EvalObj.finishedConstructingFields();
6485
6486
27.3k
  return Success &&
6487
27.3k
         
EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed25.3k
&&
6488
27.3k
         
LifetimeExtendedScope.destroy()25.3k
;
6489
27.8k
}
6490
6491
static bool HandleConstructorCall(const Expr *E, const LValue &This,
6492
                                  ArrayRef<const Expr*> Args,
6493
                                  const CXXConstructorDecl *Definition,
6494
39.7k
                                  EvalInfo &Info, APValue &Result) {
6495
39.7k
  CallScopeRAII CallScope(Info);
6496
39.7k
  CallRef Call = Info.CurrentCall->createCall(Definition);
6497
39.7k
  if (!EvaluateArgs(Args, Call, Info, Definition))
6498
7.19k
    return false;
6499
6500
32.5k
  return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6501
32.5k
         
CallScope.destroy()26.9k
;
6502
39.7k
}
6503
6504
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6505
                                  const LValue &This, APValue &Value,
6506
161k
                                  QualType T) {
6507
  // Objects can only be destroyed while they're within their lifetimes.
6508
  // FIXME: We have no representation for whether an object of type nullptr_t
6509
  // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6510
  // as indeterminate instead?
6511
161k
  if (Value.isAbsent() && 
!T->isNullPtrType()11
) {
6512
11
    APValue Printable;
6513
11
    This.moveInto(Printable);
6514
11
    Info.FFDiag(CallRange.getBegin(),
6515
11
                diag::note_constexpr_destroy_out_of_lifetime)
6516
11
        << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6517
11
    return false;
6518
11
  }
6519
6520
  // Invent an expression for location purposes.
6521
  // FIXME: We shouldn't need to do this.
6522
161k
  OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6523
6524
  // For arrays, destroy elements right-to-left.
6525
161k
  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6526
1.18k
    uint64_t Size = CAT->getSize().getZExtValue();
6527
1.18k
    QualType ElemT = CAT->getElementType();
6528
6529
1.18k
    if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6530
6
      return false;
6531
6532
1.18k
    LValue ElemLV = This;
6533
1.18k
    ElemLV.addArray(Info, &LocE, CAT);
6534
1.18k
    if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6535
0
      return false;
6536
6537
    // Ensure that we have actual array elements available to destroy; the
6538
    // destructors might mutate the value, so we can't run them on the array
6539
    // filler.
6540
1.18k
    if (Size && 
Size > Value.getArrayInitializedElts()1.17k
)
6541
193
      expandArray(Value, Value.getArraySize() - 1);
6542
6543
58.7k
    for (; Size != 0; 
--Size57.6k
) {
6544
57.6k
      APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6545
57.6k
      if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6546
57.6k
          !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6547
22
        return false;
6548
57.6k
    }
6549
6550
    // End the lifetime of this array now.
6551
1.15k
    Value = APValue();
6552
1.15k
    return true;
6553
1.18k
  }
6554
6555
160k
  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6556
160k
  if (!RD) {
6557
151k
    if (T.isDestructedType()) {
6558
0
      Info.FFDiag(CallRange.getBegin(),
6559
0
                  diag::note_constexpr_unsupported_destruction)
6560
0
          << T;
6561
0
      return false;
6562
0
    }
6563
6564
151k
    Value = APValue();
6565
151k
    return true;
6566
151k
  }
6567
6568
8.36k
  if (RD->getNumVBases()) {
6569
0
    Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6570
0
    return false;
6571
0
  }
6572
6573
8.36k
  const CXXDestructorDecl *DD = RD->getDestructor();
6574
8.36k
  if (!DD && 
!RD->hasTrivialDestructor()278
) {
6575
0
    Info.FFDiag(CallRange.getBegin());
6576
0
    return false;
6577
0
  }
6578
6579
8.36k
  if (!DD || 
DD->isTrivial()8.08k
||
6580
8.36k
      
(1.12k
RD->isAnonymousStructOrUnion()1.12k
&&
RD->isUnion()1
)) {
6581
    // A trivial destructor just ends the lifetime of the object. Check for
6582
    // this case before checking for a body, because we might not bother
6583
    // building a body for a trivial destructor. Note that it doesn't matter
6584
    // whether the destructor is constexpr in this case; all trivial
6585
    // destructors are constexpr.
6586
    //
6587
    // If an anonymous union would be destroyed, some enclosing destructor must
6588
    // have been explicitly defined, and the anonymous union destruction should
6589
    // have no effect.
6590
7.23k
    Value = APValue();
6591
7.23k
    return true;
6592
7.23k
  }
6593
6594
1.12k
  if (!Info.CheckCallLimit(CallRange.getBegin()))
6595
5
    return false;
6596
6597
1.12k
  const FunctionDecl *Definition = nullptr;
6598
1.12k
  const Stmt *Body = DD->getBody(Definition);
6599
6600
1.12k
  if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6601
5
    return false;
6602
6603
1.11k
  CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6604
1.11k
                       CallRef());
6605
6606
  // We're now in the period of destruction of this object.
6607
1.11k
  unsigned BasesLeft = RD->getNumBases();
6608
1.11k
  EvalInfo::EvaluatingDestructorRAII EvalObj(
6609
1.11k
      Info,
6610
1.11k
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6611
1.11k
  if (!EvalObj.DidInsert) {
6612
    // C++2a [class.dtor]p19:
6613
    //   the behavior is undefined if the destructor is invoked for an object
6614
    //   whose lifetime has ended
6615
    // (Note that formally the lifetime ends when the period of destruction
6616
    // begins, even though certain uses of the object remain valid until the
6617
    // period of destruction ends.)
6618
1
    Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6619
1
    return false;
6620
1
  }
6621
6622
  // FIXME: Creating an APValue just to hold a nonexistent return value is
6623
  // wasteful.
6624
1.11k
  APValue RetVal;
6625
1.11k
  StmtResult Ret = {RetVal, nullptr};
6626
1.11k
  if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6627
275
    return false;
6628
6629
  // A union destructor does not implicitly destroy its members.
6630
842
  if (RD->isUnion())
6631
8
    return true;
6632
6633
834
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6634
6635
  // We don't have a good way to iterate fields in reverse, so collect all the
6636
  // fields first and then walk them backwards.
6637
834
  SmallVector<FieldDecl*, 16> Fields(RD->fields());
6638
950
  for (const FieldDecl *FD : llvm::reverse(Fields)) {
6639
950
    if (FD->isUnnamedBitfield())
6640
1
      continue;
6641
6642
949
    LValue Subobject = This;
6643
949
    if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6644
0
      return false;
6645
6646
949
    APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6647
949
    if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6648
949
                               FD->getType()))
6649
18
      return false;
6650
949
  }
6651
6652
816
  if (BasesLeft != 0)
6653
55
    EvalObj.startedDestroyingBases();
6654
6655
  // Destroy base classes in reverse order.
6656
816
  for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6657
71
    --BasesLeft;
6658
6659
71
    QualType BaseType = Base.getType();
6660
71
    LValue Subobject = This;
6661
71
    if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6662
71
                                BaseType->getAsCXXRecordDecl(), &Layout))
6663
0
      return false;
6664
6665
71
    APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6666
71
    if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6667
71
                               BaseType))
6668
0
      return false;
6669
71
  }
6670
816
  assert(BasesLeft == 0 && "NumBases was wrong?");
6671
6672
  // The period of destruction ends now. The object is gone.
6673
816
  Value = APValue();
6674
816
  return true;
6675
816
}
6676
6677
namespace {
6678
struct DestroyObjectHandler {
6679
  EvalInfo &Info;
6680
  const Expr *E;
6681
  const LValue &This;
6682
  const AccessKinds AccessKind;
6683
6684
  typedef bool result_type;
6685
0
  bool failed() { return false; }
6686
55
  bool found(APValue &Subobj, QualType SubobjType) {
6687
55
    return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6688
55
                                 SubobjType);
6689
55
  }
6690
0
  bool found(APSInt &Value, QualType SubobjType) {
6691
0
    Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6692
0
    return false;
6693
0
  }
6694
0
  bool found(APFloat &Value, QualType SubobjType) {
6695
0
    Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6696
0
    return false;
6697
0
  }
6698
};
6699
}
6700
6701
/// Perform a destructor or pseudo-destructor call on the given object, which
6702
/// might in general not be a complete object.
6703
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6704
67
                              const LValue &This, QualType ThisType) {
6705
67
  CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6706
67
  DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6707
67
  return Obj && 
findSubobject(Info, E, Obj, This.Designator, Handler)55
;
6708
67
}
6709
6710
/// Destroy and end the lifetime of the given complete object.
6711
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6712
                              APValue::LValueBase LVBase, APValue &Value,
6713
103k
                              QualType T) {
6714
  // If we've had an unmodeled side-effect, we can't rely on mutable state
6715
  // (such as the object we're about to destroy) being correct.
6716
103k
  if (Info.EvalStatus.HasSideEffects)
6717
464
    return false;
6718
6719
102k
  LValue LV;
6720
102k
  LV.set({LVBase});
6721
102k
  return HandleDestructionImpl(Info, Loc, LV, Value, T);
6722
103k
}
6723
6724
/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6725
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6726
686
                                  LValue &Result) {
6727
686
  if (Info.checkingPotentialConstantExpression() ||
6728
686
      
Info.SpeculativeEvaluationDepth674
)
6729
12
    return false;
6730
6731
  // This is permitted only within a call to std::allocator<T>::allocate.
6732
674
  auto Caller = Info.getStdAllocatorCaller("allocate");
6733
674
  if (!Caller) {
6734
606
    Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6735
606
                                     ? 
diag::note_constexpr_new_untyped31
6736
606
                                     : 
diag::note_constexpr_new575
);
6737
606
    return false;
6738
606
  }
6739
6740
68
  QualType ElemType = Caller.ElemType;
6741
68
  if (ElemType->isIncompleteType() || 
ElemType->isFunctionType()62
) {
6742
12
    Info.FFDiag(E->getExprLoc(),
6743
12
                diag::note_constexpr_new_not_complete_object_type)
6744
12
        << (ElemType->isIncompleteType() ? 
06
:
16
) << ElemType;
6745
12
    return false;
6746
12
  }
6747
6748
56
  APSInt ByteSize;
6749
56
  if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6750
0
    return false;
6751
56
  bool IsNothrow = false;
6752
56
  for (unsigned I = 1, N = E->getNumArgs(); I != N; 
++I0
) {
6753
0
    EvaluateIgnoredValue(Info, E->getArg(I));
6754
0
    IsNothrow |= E->getType()->isNothrowT();
6755
0
  }
6756
6757
56
  CharUnits ElemSize;
6758
56
  if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6759
0
    return false;
6760
56
  APInt Size, Remainder;
6761
56
  APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6762
56
  APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6763
56
  if (Remainder != 0) {
6764
    // This likely indicates a bug in the implementation of 'std::allocator'.
6765
6
    Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6766
6
        << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6767
6
    return false;
6768
6
  }
6769
6770
50
  if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6771
50
                           Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6772
6
    if (IsNothrow) {
6773
0
      Result.setNull(Info.Ctx, E->getType());
6774
0
      return true;
6775
0
    }
6776
6
    return false;
6777
6
  }
6778
6779
44
  QualType AllocType = Info.Ctx.getConstantArrayType(
6780
44
      ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6781
44
  APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6782
44
  *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6783
44
  Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6784
44
  return true;
6785
50
}
6786
6787
7
static bool hasVirtualDestructor(QualType T) {
6788
7
  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6789
7
    if (CXXDestructorDecl *DD = RD->getDestructor())
6790
7
      return DD->isVirtual();
6791
0
  return false;
6792
7
}
6793
6794
111
static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6795
111
  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6796
55
    if (CXXDestructorDecl *DD = RD->getDestructor())
6797
55
      return DD->isVirtual() ? 
DD->getOperatorDelete()5
:
nullptr50
;
6798
56
  return nullptr;
6799
111
}
6800
6801
/// Check that the given object is a suitable pointer to a heap allocation that
6802
/// still exists and is of the right kind for the purpose of a deletion.
6803
///
6804
/// On success, returns the heap allocation to deallocate. On failure, produces
6805
/// a diagnostic and returns std::nullopt.
6806
static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6807
                                                 const LValue &Pointer,
6808
499
                                                 DynAlloc::Kind DeallocKind) {
6809
499
  auto PointerAsString = [&] {
6810
14
    return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6811
14
  };
6812
6813
499
  DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6814
499
  if (!DA) {
6815
8
    Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6816
8
        << PointerAsString();
6817
8
    if (Pointer.Base)
6818
8
      NoteLValueLocation(Info, Pointer.Base);
6819
8
    return std::nullopt;
6820
8
  }
6821
6822
491
  std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6823
491
  if (!Alloc) {
6824
1
    Info.FFDiag(E, diag::note_constexpr_double_delete);
6825
1
    return std::nullopt;
6826
1
  }
6827
6828
490
  if (DeallocKind != (*Alloc)->getKind()) {
6829
19
    QualType AllocType = Pointer.Base.getDynamicAllocType();
6830
19
    Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6831
19
        << DeallocKind << (*Alloc)->getKind() << AllocType;
6832
19
    NoteLValueLocation(Info, Pointer.Base);
6833
19
    return std::nullopt;
6834
19
  }
6835
6836
471
  bool Subobject = false;
6837
471
  if (DeallocKind == DynAlloc::New) {
6838
119
    Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6839
119
                
Pointer.Designator.isOnePastTheEnd()118
;
6840
352
  } else {
6841
352
    Subobject = Pointer.Designator.Entries.size() != 1 ||
6842
352
                
Pointer.Designator.Entries[0].getAsArrayIndex() != 0349
;
6843
352
  }
6844
471
  if (Subobject) {
6845
6
    Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6846
6
        << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6847
6
    return std::nullopt;
6848
6
  }
6849
6850
465
  return Alloc;
6851
471
}
6852
6853
// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6854
60
bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6855
60
  if (Info.checkingPotentialConstantExpression() ||
6856
60
      
Info.SpeculativeEvaluationDepth57
)
6857
3
    return false;
6858
6859
  // This is permitted only within a call to std::allocator<T>::deallocate.
6860
57
  if (!Info.getStdAllocatorCaller("deallocate")) {
6861
26
    Info.FFDiag(E->getExprLoc());
6862
26
    return true;
6863
26
  }
6864
6865
31
  LValue Pointer;
6866
31
  if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6867
0
    return false;
6868
31
  for (unsigned I = 1, N = E->getNumArgs(); I != N; 
++I0
)
6869
0
    EvaluateIgnoredValue(Info, E->getArg(I));
6870
6871
31
  if (Pointer.Designator.Invalid)
6872
0
    return false;
6873
6874
  // Deleting a null pointer would have no effect, but it's not permitted by
6875
  // std::allocator<T>::deallocate's contract.
6876
31
  if (Pointer.isNullPointer()) {
6877
6
    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6878
6
    return true;
6879
6
  }
6880
6881
25
  if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6882
12
    return false;
6883
6884
13
  Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6885
13
  return true;
6886
25
}
6887
6888
//===----------------------------------------------------------------------===//
6889
// Generic Evaluation
6890
//===----------------------------------------------------------------------===//
6891
namespace {
6892
6893
class BitCastBuffer {
6894
  // FIXME: We're going to need bit-level granularity when we support
6895
  // bit-fields.
6896
  // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6897
  // we don't support a host or target where that is the case. Still, we should
6898
  // use a more generic type in case we ever do.
6899
  SmallVector<std::optional<unsigned char>, 32> Bytes;
6900
6901
  static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6902
                "Need at least 8 bit unsigned char");
6903
6904
  bool TargetIsLittleEndian;
6905
6906
public:
6907
  BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6908
690
      : Bytes(Width.getQuantity()),
6909
690
        TargetIsLittleEndian(TargetIsLittleEndian) {}
6910
6911
  [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6912
3.43k
                                SmallVectorImpl<unsigned char> &Output) const {
6913
10.5k
    for (CharUnits I = Offset, E = Offset + Width; I != E; 
++I7.15k
) {
6914
      // If a byte of an integer is uninitialized, then the whole integer is
6915
      // uninitialized.
6916
7.41k
      if (!Bytes[I.getQuantity()])
6917
251
        return false;
6918
7.15k
      Output.push_back(*Bytes[I.getQuantity()]);
6919
7.15k
    }
6920
3.17k
    if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6921
1.69k
      std::reverse(Output.begin(), Output.end());
6922
3.17k
    return true;
6923
3.43k
  }
6924
6925
2.02k
  void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6926
2.02k
    if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6927
881
      std::reverse(Input.begin(), Input.end());
6928
6929
2.02k
    size_t Index = 0;
6930
7.39k
    for (unsigned char Byte : Input) {
6931
7.39k
      assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6932
7.39k
      Bytes[Offset.getQuantity() + Index] = Byte;
6933
7.39k
      ++Index;
6934
7.39k
    }
6935
2.02k
  }
6936
6937
2.60k
  size_t size() { return Bytes.size(); }
6938
};
6939
6940
/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6941
/// target would represent the value at runtime.
6942
class APValueToBufferConverter {
6943
  EvalInfo &Info;
6944
  BitCastBuffer Buffer;
6945
  const CastExpr *BCE;
6946
6947
  APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6948
                           const CastExpr *BCE)
6949
690
      : Info(Info),
6950
690
        Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6951
690
        BCE(BCE) {}
6952
6953
690
  bool visit(const APValue &Val, QualType Ty) {
6954
690
    return visit(Val, Ty, CharUnits::fromQuantity(0));
6955
690
  }
6956
6957
  // Write out Val with type Ty into Buffer starting at Offset.
6958
2.60k
  bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6959
2.60k
    assert((size_t)Offset.getQuantity() <= Buffer.size());
6960
6961
    // As a special case, nullptr_t has an indeterminate value.
6962
2.60k
    if (Ty->isNullPtrType())
6963
12
      return true;
6964
6965
    // Dig through Src to find the byte at SrcOffset.
6966
2.58k
    switch (Val.getKind()) {
6967
98
    case APValue::Indeterminate:
6968
98
    case APValue::None:
6969
98
      return true;
6970
6971
1.82k
    case APValue::Int:
6972
1.82k
      return visitInt(Val.getInt(), Ty, Offset);
6973
155
    case APValue::Float:
6974
155
      return visitFloat(Val.getFloat(), Ty, Offset);
6975
58
    case APValue::Array:
6976
58
      return visitArray(Val, Ty, Offset);
6977
168
    case APValue::Struct:
6978
168
      return visitRecord(Val, Ty, Offset);
6979
281
    case APValue::Vector:
6980
281
      return visitVector(Val, Ty, Offset);
6981
6982
0
    case APValue::ComplexInt:
6983
0
    case APValue::ComplexFloat:
6984
0
    case APValue::FixedPoint:
6985
      // FIXME: We should support these.
6986
6987
0
    case APValue::Union:
6988
0
    case APValue::MemberPointer:
6989
0
    case APValue::AddrLabelDiff: {
6990
0
      Info.FFDiag(BCE->getBeginLoc(),
6991
0
                  diag::note_constexpr_bit_cast_unsupported_type)
6992
0
          << Ty;
6993
0
      return false;
6994
0
    }
6995
6996
0
    case APValue::LValue:
6997
0
      llvm_unreachable("LValue subobject in bit_cast?");
6998
2.58k
    }
6999
0
    llvm_unreachable("Unhandled APValue::ValueKind");
7000
0
  }
7001
7002
186
  bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7003
186
    const RecordDecl *RD = Ty->getAsRecordDecl();
7004
186
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7005
7006
    // Visit the base classes.
7007
186
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7008
204
      for (size_t I = 0, E = CXXRD->getNumBases(); I != E; 
++I18
) {
7009
18
        const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7010
18
        CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7011
7012
18
        if (!visitRecord(Val.getStructBase(I), BS.getType(),
7013
18
                         Layout.getBaseClassOffset(BaseDecl) + Offset))
7014
0
          return false;
7015
18
      }
7016
186
    }
7017
7018
    // Visit the fields.
7019
186
    unsigned FieldIdx = 0;
7020
323
    for (FieldDecl *FD : RD->fields()) {
7021
323
      if (FD->isBitField()) {
7022
3
        Info.FFDiag(BCE->getBeginLoc(),
7023
3
                    diag::note_constexpr_bit_cast_unsupported_bitfield);
7024
3
        return false;
7025
3
      }
7026
7027
320
      uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7028
7029
320
      assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7030
320
             "only bit-fields can have sub-char alignment");
7031
320
      CharUnits FieldOffset =
7032
320
          Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7033
320
      QualType FieldTy = FD->getType();
7034
320
      if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7035
0
        return false;
7036
320
      ++FieldIdx;
7037
320
    }
7038
7039
183
    return true;
7040
186
  }
7041
7042
58
  bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7043
58
    const auto *CAT =
7044
58
        dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7045
58
    if (!CAT)
7046
0
      return false;
7047
7048
58
    CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7049
58
    unsigned NumInitializedElts = Val.getArrayInitializedElts();
7050
58
    unsigned ArraySize = Val.getArraySize();
7051
    // First, initialize the initialized elements.
7052
387
    for (unsigned I = 0; I != NumInitializedElts; 
++I329
) {
7053
329
      const APValue &SubObj = Val.getArrayInitializedElt(I);
7054
329
      if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7055
0
        return false;
7056
329
    }
7057
7058
    // Next, initialize the rest of the array using the filler.
7059
58
    if (Val.hasArrayFiller()) {
7060
7
      const APValue &Filler = Val.getArrayFiller();
7061
39
      for (unsigned I = NumInitializedElts; I != ArraySize; 
++I32
) {
7062
32
        if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7063
0
          return false;
7064
32
      }
7065
7
    }
7066
7067
58
    return true;
7068
58
  }
7069
7070
281
  bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7071
281
    const VectorType *VTy = Ty->castAs<VectorType>();
7072
281
    QualType EltTy = VTy->getElementType();
7073
281
    unsigned NElts = VTy->getNumElements();
7074
281
    unsigned EltSize =
7075
281
        VTy->isExtVectorBoolType() ? 
139
:
Info.Ctx.getTypeSize(EltTy)242
;
7076
7077
281
    if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7078
      // The vector's size in bits is not a multiple of the target's byte size,
7079
      // so its layout is unspecified. For now, we'll simply treat these cases
7080
      // as unsupported (this should only be possible with OpenCL bool vectors
7081
      // whose element count isn't a multiple of the byte size).
7082
3
      Info.FFDiag(BCE->getBeginLoc(),
7083
3
                  diag::note_constexpr_bit_cast_invalid_vector)
7084
3
          << Ty.getCanonicalType() << EltSize << NElts
7085
3
          << Info.Ctx.getCharWidth();
7086
3
      return false;
7087
3
    }
7088
7089
278
    if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7090
42
                                           &APFloat::x87DoubleExtended()) {
7091
      // The layout for x86_fp80 vectors seems to be handled very inconsistently
7092
      // by both clang and LLVM, so for now we won't allow bit_casts involving
7093
      // it in a constexpr context.
7094
8
      Info.FFDiag(BCE->getBeginLoc(),
7095
8
                  diag::note_constexpr_bit_cast_unsupported_type)
7096
8
          << EltTy;
7097
8
      return false;
7098
8
    }
7099
7100
270
    if (VTy->isExtVectorBoolType()) {
7101
      // Special handling for OpenCL bool vectors:
7102
      // Since these vectors are stored as packed bits, but we can't write
7103
      // individual bits to the BitCastBuffer, we'll buffer all of the elements
7104
      // together into an appropriately sized APInt and write them all out at
7105
      // once. Because we don't accept vectors where NElts * EltSize isn't a
7106
      // multiple of the char size, there will be no padding space, so we don't
7107
      // have to worry about writing data which should have been left
7108
      // uninitialized.
7109
36
      bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7110
7111
36
      llvm::APInt Res = llvm::APInt::getZero(NElts);
7112
852
      for (unsigned I = 0; I < NElts; 
++I816
) {
7113
816
        const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7114
816
        assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7115
816
               "bool vector element must be 1-bit unsigned integer!");
7116
7117
816
        Res.insertBits(EltAsInt, BigEndian ? 
(NElts - I - 1)272
:
I544
);
7118
816
      }
7119
7120
36
      SmallVector<uint8_t, 8> Bytes(NElts / 8);
7121
36
      llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7122
36
      Buffer.writeObject(Offset, Bytes);
7123
234
    } else {
7124
      // Iterate over each of the elements and write them out to the buffer at
7125
      // the appropriate offset.
7126
234
      CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7127
1.46k
      for (unsigned I = 0; I < NElts; 
++I1.23k
) {
7128
1.23k
        if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7129
0
          return false;
7130
1.23k
      }
7131
234
    }
7132
7133
270
    return true;
7134
270
  }
7135
7136
1.98k
  bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7137
1.98k
    APSInt AdjustedVal = Val;
7138
1.98k
    unsigned Width = AdjustedVal.getBitWidth();
7139
1.98k
    if (Ty->isBooleanType()) {
7140
18
      Width = Info.Ctx.getTypeSize(Ty);
7141
18
      AdjustedVal = AdjustedVal.extend(Width);
7142
18
    }
7143
7144
1.98k
    SmallVector<uint8_t, 8> Bytes(Width / 8);
7145
1.98k
    llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7146
1.98k
    Buffer.writeObject(Offset, Bytes);
7147
1.98k
    return true;
7148
1.98k
  }
7149
7150
155
  bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7151
155
    APSInt AsInt(Val.bitcastToAPInt());
7152
155
    return visitInt(AsInt, Ty, Offset);
7153
155
  }
7154
7155
public:
7156
  static std::optional<BitCastBuffer>
7157
690
  convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7158
690
    CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7159
690
    APValueToBufferConverter Converter(Info, DstSize, BCE);
7160
690
    if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7161
14
      return std::nullopt;
7162
676
    return Converter.Buffer;
7163
690
  }
7164
};
7165
7166
/// Write an BitCastBuffer into an APValue.
7167
class BufferToAPValueConverter {
7168
  EvalInfo &Info;
7169
  const BitCastBuffer &Buffer;
7170
  const CastExpr *BCE;
7171
7172
  BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7173
                           const CastExpr *BCE)
7174
676
      : Info(Info), Buffer(Buffer), BCE(BCE) {}
7175
7176
  // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7177
  // with an invalid type, so anything left is a deficiency on our part (FIXME).
7178
  // Ideally this will be unreachable.
7179
0
  std::nullopt_t unsupportedType(QualType Ty) {
7180
0
    Info.FFDiag(BCE->getBeginLoc(),
7181
0
                diag::note_constexpr_bit_cast_unsupported_type)
7182
0
        << Ty;
7183
0
    return std::nullopt;
7184
0
  }
7185
7186
6
  std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7187
6
    Info.FFDiag(BCE->getBeginLoc(),
7188
6
                diag::note_constexpr_bit_cast_unrepresentable_value)
7189
6
        << Ty << toString(Val, /*Radix=*/10);
7190
6
    return std::nullopt;
7191
6
  }
7192
7193
  std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7194
3.42k
                               const EnumType *EnumSugar = nullptr) {
7195
3.42k
    if (T->isNullPtrType()) {
7196
12
      uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7197
12
      return APValue((Expr *)nullptr,
7198
12
                     /*Offset=*/CharUnits::fromQuantity(NullValue),
7199
12
                     APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7200
12
    }
7201
7202
3.41k
    CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7203
7204
    // Work around floating point types that contain unused padding bytes. This
7205
    // is really just `long double` on x86, which is the only fundamental type
7206
    // with padding bytes.
7207
3.41k
    if (T->isRealFloatingType()) {
7208
255
      const llvm::fltSemantics &Semantics =
7209
255
          Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7210
255
      unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7211
255
      assert(NumBits % 8 == 0);
7212
255
      CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7213
255
      if (NumBytes != SizeOf)
7214
8
        SizeOf = NumBytes;
7215
255
    }
7216
7217
3.41k
    SmallVector<uint8_t, 8> Bytes;
7218
3.41k
    if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7219
      // If this is std::byte or unsigned char, then its okay to store an
7220
      // indeterminate value.
7221
251
      bool IsStdByte = EnumSugar && 
EnumSugar->isStdByteType()12
;
7222
251
      bool IsUChar =
7223
251
          !EnumSugar && 
(239
T->isSpecificBuiltinType(BuiltinType::UChar)239
||
7224
239
                         
T->isSpecificBuiltinType(BuiltinType::Char_U)21
);
7225
251
      if (!IsStdByte && 
!IsUChar242
) {
7226
21
        QualType DisplayType(EnumSugar ? 
(const Type *)EnumSugar3
:
T18
, 0);
7227
21
        Info.FFDiag(BCE->getExprLoc(),
7228
21
                    diag::note_constexpr_bit_cast_indet_dest)
7229
21
            << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7230
21
        return std::nullopt;
7231
21
      }
7232
7233
230
      return APValue::IndeterminateValue();
7234
251
    }
7235
7236
3.16k
    APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7237
3.16k
    llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7238
7239
3.16k
    if (T->isIntegralOrEnumerationType()) {
7240
2.90k
      Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7241
7242
2.90k
      unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7243
2.90k
      if (IntWidth != Val.getBitWidth()) {
7244
24
        APSInt Truncated = Val.trunc(IntWidth);
7245
24
        if (Truncated.extend(Val.getBitWidth()) != Val)
7246
6
          return unrepresentableValue(QualType(T, 0), Val);
7247
18
        Val = Truncated;
7248
18
      }
7249
7250
2.90k
      return APValue(Val);
7251
2.90k
    }
7252
7253
255
    if (T->isRealFloatingType()) {
7254
255
      const llvm::fltSemantics &Semantics =
7255
255
          Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7256
255
      return APValue(APFloat(Semantics, Val));
7257
255
    }
7258
7259
0
    return unsupportedType(QualType(T, 0));
7260
255
  }
7261
7262
163
  std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7263
163
    const RecordDecl *RD = RTy->getAsRecordDecl();
7264
163
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7265
7266
163
    unsigned NumBases = 0;
7267
163
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7268
163
      NumBases = CXXRD->getNumBases();
7269
7270
163
    APValue ResultVal(APValue::UninitStruct(), NumBases,
7271
163
                      std::distance(RD->field_begin(), RD->field_end()));
7272
7273
    // Visit the base classes.
7274
163
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7275
172
      for (size_t I = 0, E = CXXRD->getNumBases(); I != E; 
++I9
) {
7276
9
        const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7277
9
        CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7278
9
        if (BaseDecl->isEmpty() ||
7279
9
            
Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()6
)
7280
3
          continue;
7281
7282
6
        std::optional<APValue> SubObj = visitType(
7283
6
            BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7284
6
        if (!SubObj)
7285
0
          return std::nullopt;
7286
6
        ResultVal.getStructBase(I) = *SubObj;
7287
6
      }
7288
163
    }
7289
7290
    // Visit the fields.
7291
163
    unsigned FieldIdx = 0;
7292
287
    for (FieldDecl *FD : RD->fields()) {
7293
      // FIXME: We don't currently support bit-fields. A lot of the logic for
7294
      // this is in CodeGen, so we need to factor it around.
7295
287
      if (FD->isBitField()) {
7296
1
        Info.FFDiag(BCE->getBeginLoc(),
7297
1
                    diag::note_constexpr_bit_cast_unsupported_bitfield);
7298
1
        return std::nullopt;
7299
1
      }
7300
7301
286
      uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7302
286
      assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7303
7304
286
      CharUnits FieldOffset =
7305
286
          CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7306
286
          Offset;
7307
286
      QualType FieldTy = FD->getType();
7308
286
      std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7309
286
      if (!SubObj)
7310
9
        return std::nullopt;
7311
277
      ResultVal.getStructField(FieldIdx) = *SubObj;
7312
277
      ++FieldIdx;
7313
277
    }
7314
7315
153
    return ResultVal;
7316
163
  }
7317
7318
30
  std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7319
30
    QualType RepresentationType = Ty->getDecl()->getIntegerType();
7320
30
    assert(!RepresentationType.isNull() &&
7321
30
           "enum forward decl should be caught by Sema");
7322
30
    const auto *AsBuiltin =
7323
30
        RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7324
    // Recurse into the underlying type. Treat std::byte transparently as
7325
    // unsigned char.
7326
30
    return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7327
30
  }
7328
7329
93
  std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7330
93
    size_t Size = Ty->getSize().getLimitedValue();
7331
93
    CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7332
7333
93
    APValue ArrayValue(APValue::UninitArray(), Size, Size);
7334
604
    for (size_t I = 0; I != Size; 
++I511
) {
7335
516
      std::optional<APValue> ElementValue =
7336
516
          visitType(Ty->getElementType(), Offset + I * ElementWidth);
7337
516
      if (!ElementValue)
7338
5
        return std::nullopt;
7339
511
      ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7340
511
    }
7341
7342
88
    return ArrayValue;
7343
93
  }
7344
7345
327
  std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7346
327
    QualType EltTy = VTy->getElementType();
7347
327
    unsigned NElts = VTy->getNumElements();
7348
327
    unsigned EltSize =
7349
327
        VTy->isExtVectorBoolType() ? 
124
:
Info.Ctx.getTypeSize(EltTy)303
;
7350
7351
327
    if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7352
      // The vector's size in bits is not a multiple of the target's byte size,
7353
      // so its layout is unspecified. For now, we'll simply treat these cases
7354
      // as unsupported (this should only be possible with OpenCL bool vectors
7355
      // whose element count isn't a multiple of the byte size).
7356
6
      Info.FFDiag(BCE->getBeginLoc(),
7357
6
                  diag::note_constexpr_bit_cast_invalid_vector)
7358
6
          << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7359
6
      return std::nullopt;
7360
6
    }
7361
7362
321
    if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7363
65
                                           &APFloat::x87DoubleExtended()) {
7364
      // The layout for x86_fp80 vectors seems to be handled very inconsistently
7365
      // by both clang and LLVM, so for now we won't allow bit_casts involving
7366
      // it in a constexpr context.
7367
3
      Info.FFDiag(BCE->getBeginLoc(),
7368
3
                  diag::note_constexpr_bit_cast_unsupported_type)
7369
3
          << EltTy;
7370
3
      return std::nullopt;
7371
3
    }
7372
7373
318
    SmallVector<APValue, 4> Elts;
7374
318
    Elts.reserve(NElts);
7375
318
    if (VTy->isExtVectorBoolType()) {
7376
      // Special handling for OpenCL bool vectors:
7377
      // Since these vectors are stored as packed bits, but we can't read
7378
      // individual bits from the BitCastBuffer, we'll buffer all of the
7379
      // elements together into an appropriately sized APInt and write them all
7380
      // out at once. Because we don't accept vectors where NElts * EltSize
7381
      // isn't a multiple of the char size, there will be no padding space, so
7382
      // we don't have to worry about reading any padding data which didn't
7383
      // actually need to be accessed.
7384
18
      bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7385
7386
18
      SmallVector<uint8_t, 8> Bytes;
7387
18
      Bytes.reserve(NElts / 8);
7388
18
      if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7389
0
        return std::nullopt;
7390
7391
18
      APSInt SValInt(NElts, true);
7392
18
      llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7393
7394
618
      for (unsigned I = 0; I < NElts; 
++I600
) {
7395
600
        llvm::APInt Elt =
7396
600
            SValInt.extractBits(1, (BigEndian ? 
NElts - I - 1200
:
I400
) * EltSize);
7397
600
        Elts.emplace_back(
7398
600
            APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7399
600
      }
7400
300
    } else {
7401
      // Iterate over each of the elements and read them from the buffer at
7402
      // the appropriate offset.
7403
300
      CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7404
2.82k
      for (unsigned I = 0; I < NElts; 
++I2.52k
) {
7405
2.52k
        std::optional<APValue> EltValue =
7406
2.52k
            visitType(EltTy, Offset + I * EltSizeChars);
7407
2.52k
        if (!EltValue)
7408
0
          return std::nullopt;
7409
2.52k
        Elts.push_back(std::move(*EltValue));
7410
2.52k
      }
7411
300
    }
7412
7413
318
    return APValue(Elts.data(), Elts.size());
7414
318
  }
7415
7416
0
  std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7417
0
    return unsupportedType(QualType(Ty, 0));
7418
0
  }
7419
7420
4.00k
  std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7421
4.00k
    QualType Can = Ty.getCanonicalType();
7422
7423
4.00k
    switch (Can->getTypeClass()) {
7424
0
#define TYPE(Class, Base)                                                      \
7425
4.00k
  case Type::Class:                                                            \
7426
4.00k
    return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7427
0
#define ABSTRACT_TYPE(Class, Base)
7428
0
#define NON_CANONICAL_TYPE(Class, Base)                                        \
7429
0
  case Type::Class:                                                            \
7430
0
    llvm_unreachable("non-canonical type should be impossible!");
7431
0
#define DEPENDENT_TYPE(Class, Base)                                            \
7432
0
  case Type::Class:                                                            \
7433
93
    llvm_unreachable(                                                          \
7434
0
        "dependent types aren't supported in the constant evaluator!");
7435
0
#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7436
0
  case Type::Class:                                                            \
7437
0
    llvm_unreachable("either dependent or not canonical!");
7438
4.00k
#include 
"clang/AST/TypeNodes.inc"0
7439
4.00k
    }
7440
0
    llvm_unreachable("Unhandled Type::TypeClass");
7441
0
  }
7442
7443
public:
7444
  // Pull out a full value of type DstType.
7445
  static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7446
676
                                        const CastExpr *BCE) {
7447
676
    BufferToAPValueConverter Converter(Info, Buffer, BCE);
7448
676
    return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7449
676
  }
7450
};
7451
7452
static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7453
                                                 QualType Ty, EvalInfo *Info,
7454
                                                 const ASTContext &Ctx,
7455
2.31k
                                                 bool CheckingDest) {
7456
2.31k
  Ty = Ty.getCanonicalType();
7457
7458
2.31k
  auto diag = [&](int Reason) {
7459
30
    if (Info)
7460
30
      Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7461
30
          << CheckingDest << (Reason == 4) << Reason;
7462
30
    return false;
7463
30
  };
7464
2.31k
  auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7465
24
    if (Info)
7466
24
      Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7467
24
          << NoteTy << Construct << Ty;
7468
24
    return false;
7469
24
  };
7470
7471
2.31k
  if (Ty->isUnionType())
7472
9
    return diag(0);
7473
2.30k
  if (Ty->isPointerType())
7474
9
    return diag(1);
7475
2.29k
  if (Ty->isMemberPointerType())
7476
9
    return diag(2);
7477
2.28k
  if (Ty.isVolatileQualified())
7478
0
    return diag(3);
7479
7480
2.28k
  if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7481
395
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7482
395
      for (CXXBaseSpecifier &BS : CXXRD->bases())
7483
30
        if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7484
30
                                                  CheckingDest))
7485
3
          return note(1, BS.getType(), BS.getBeginLoc());
7486
395
    }
7487
684
    
for (FieldDecl *FD : Record->fields())392
{
7488
684
      if (FD->getType()->isReferenceType())
7489
3
        return diag(4);
7490
681
      if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7491
681
                                                CheckingDest))
7492
21
        return note(0, FD->getType(), FD->getBeginLoc());
7493
681
    }
7494
392
  }
7495
7496
2.26k
  if (Ty->isArrayType() &&
7497
2.26k
      !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7498
171
                                            Info, Ctx, CheckingDest))
7499
3
    return false;
7500
7501
2.25k
  return true;
7502
2.26k
}
7503
7504
static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7505
                                             const ASTContext &Ctx,
7506
720
                                             const CastExpr *BCE) {
7507
720
  bool DestOK = checkBitCastConstexprEligibilityType(
7508
720
      BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7509
720
  bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7510
714
                                BCE->getBeginLoc(),
7511
714
                                BCE->getSubExpr()->getType(), Info, Ctx, false);
7512
720
  return SourceOK;
7513
720
}
7514
7515
static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7516
                                        const APValue &SourceRValue,
7517
720
                                        const CastExpr *BCE) {
7518
720
  assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7519
720
         "no host or target supports non 8-bit chars");
7520
7521
720
  if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7522
30
    return false;
7523
7524
  // Read out SourceValue into a char buffer.
7525
690
  std::optional<BitCastBuffer> Buffer =
7526
690
      APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7527
690
  if (!Buffer)
7528
14
    return false;
7529
7530
  // Write out the buffer into a new APValue.
7531
676
  std::optional<APValue> MaybeDestValue =
7532
676
      BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7533
676
  if (!MaybeDestValue)
7534
37
    return false;
7535
7536
639
  DestValue = std::move(*MaybeDestValue);
7537
639
  return true;
7538
676
}
7539
7540
static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7541
                                        APValue &SourceValue,
7542
551
                                        const CastExpr *BCE) {
7543
551
  assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7544
551
         "no host or target supports non 8-bit chars");
7545
551
  assert(SourceValue.isLValue() &&
7546
551
         "LValueToRValueBitcast requires an lvalue operand!");
7547
7548
551
  LValue SourceLValue;
7549
551
  APValue SourceRValue;
7550
551
  SourceLValue.setFrom(Info.Ctx, SourceValue);
7551
551
  if (!handleLValueToRValueConversion(
7552
551
          Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7553
551
          SourceRValue, /*WantObjectRepresentation=*/true))
7554
127
    return false;
7555
7556
424
  return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7557
551
}
7558
7559
template <class Derived>
7560
class ExprEvaluatorBase
7561
  : public ConstStmtVisitor<Derived, bool> {
7562
private:
7563
2.85M
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::getDerived()
Line
Count
Source
7563
3.73k
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::getDerived()
Line
Count
Source
7563
300
  Derived &getDerived() { return static_cast<Derived&>(*this); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::getDerived()
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::getDerived()
Line
Count
Source
7563
381
  Derived &getDerived() { return static_cast<Derived&>(*this); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::getDerived()
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::getDerived()
Line
Count
Source
7563
10.4k
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::getDerived()
Line
Count
Source
7563
52
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::getDerived()
Line
Count
Source
7563
1.30k
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::getDerived()
Line
Count
Source
7563
29
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::getDerived()
Line
Count
Source
7563
745
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::getDerived()
Line
Count
Source
7563
2.81M
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::getDerived()
Line
Count
Source
7563
1.68k
  Derived &getDerived() { return static_cast<Derived&>(*this); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::getDerived()
Line
Count
Source
7563
15.3k
  Derived &getDerived() { return static_cast<Derived&>(*this); }
7564
2.83M
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
2.83M
    return getDerived().Success(V, E);
7566
2.83M
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
3.73k
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
3.73k
    return getDerived().Success(V, E);
7566
3.73k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
268
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
268
    return getDerived().Success(V, E);
7566
268
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
10
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
10
    return getDerived().Success(V, E);
7566
10
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
10.1k
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
10.1k
    return getDerived().Success(V, E);
7566
10.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
39
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
39
    return getDerived().Success(V, E);
7566
39
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
819
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
819
    return getDerived().Success(V, E);
7566
819
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
21
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
21
    return getDerived().Success(V, E);
7566
21
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
735
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
735
    return getDerived().Success(V, E);
7566
735
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
2.81M
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
2.81M
    return getDerived().Success(V, E);
7566
2.81M
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
1.59k
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
1.59k
    return getDerived().Success(V, E);
7566
1.59k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Line
Count
Source
7564
3.74k
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7565
3.74k
    return getDerived().Success(V, E);
7566
3.74k
  }
7567
20.2k
  bool DerivedZeroInitialization(const Expr *E) {
7568
20.2k
    return getDerived().ZeroInitialization(E);
7569
20.2k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
32
  bool DerivedZeroInitialization(const Expr *E) {
7568
32
    return getDerived().ZeroInitialization(E);
7569
32
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
245
  bool DerivedZeroInitialization(const Expr *E) {
7568
245
    return getDerived().ZeroInitialization(E);
7569
245
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
13
  bool DerivedZeroInitialization(const Expr *E) {
7568
13
    return getDerived().ZeroInitialization(E);
7569
13
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
488
  bool DerivedZeroInitialization(const Expr *E) {
7568
488
    return getDerived().ZeroInitialization(E);
7569
488
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
371
  bool DerivedZeroInitialization(const Expr *E) {
7568
371
    return getDerived().ZeroInitialization(E);
7569
371
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
8
  bool DerivedZeroInitialization(const Expr *E) {
7568
8
    return getDerived().ZeroInitialization(E);
7569
8
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
10
  bool DerivedZeroInitialization(const Expr *E) {
7568
10
    return getDerived().ZeroInitialization(E);
7569
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
7.31k
  bool DerivedZeroInitialization(const Expr *E) {
7568
7.31k
    return getDerived().ZeroInitialization(E);
7569
7.31k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
90
  bool DerivedZeroInitialization(const Expr *E) {
7568
90
    return getDerived().ZeroInitialization(E);
7569
90
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Line
Count
Source
7567
11.6k
  bool DerivedZeroInitialization(const Expr *E) {
7568
11.6k
    return getDerived().ZeroInitialization(E);
7569
11.6k
  }
7570
7571
  // Check whether a conditional operator with a non-constant condition is a
7572
  // potential constant expression. If neither arm is a potential constant
7573
  // expression, then the conditional operator is not either.
7574
  template<typename ConditionalOperator>
7575
3.68k
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
3.68k
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
3.68k
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
3.68k
    {
7581
3.68k
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
3.68k
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
3.68k
      if (Diag.empty())
7584
3.67k
        return;
7585
3.68k
    }
7586
7587
13
    {
7588
13
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
13
      Diag.clear();
7590
13
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
13
      if (Diag.empty())
7592
10
        return;
7593
13
    }
7594
7595
3
    Error(E, diag::note_constexpr_conditional_never_const);
7596
3
  }
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7575
346
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
346
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
346
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
346
    {
7581
346
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
346
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
346
      if (Diag.empty())
7584
346
        return;
7585
346
    }
7586
7587
0
    {
7588
0
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
0
      Diag.clear();
7590
0
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
0
      if (Diag.empty())
7592
0
        return;
7593
0
    }
7594
7595
0
    Error(E, diag::note_constexpr_conditional_never_const);
7596
0
  }
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Line
Count
Source
7575
1
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
1
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
1
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
1
    {
7581
1
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
1
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
1
      if (Diag.empty())
7584
1
        return;
7585
1
    }
7586
7587
0
    {
7588
0
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
0
      Diag.clear();
7590
0
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
0
      if (Diag.empty())
7592
0
        return;
7593
0
    }
7594
7595
0
    Error(E, diag::note_constexpr_conditional_never_const);
7596
0
  }
ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7575
17
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
17
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
17
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
17
    {
7581
17
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
17
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
17
      if (Diag.empty())
7584
14
        return;
7585
17
    }
7586
7587
3
    {
7588
3
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
3
      Diag.clear();
7590
3
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
3
      if (Diag.empty())
7592
3
        return;
7593
3
    }
7594
7595
0
    Error(E, diag::note_constexpr_conditional_never_const);
7596
0
  }
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7575
3.29k
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
3.29k
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
3.29k
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
3.29k
    {
7581
3.29k
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
3.29k
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
3.29k
      if (Diag.empty())
7584
3.28k
        return;
7585
3.29k
    }
7586
7587
9
    {
7588
9
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
9
      Diag.clear();
7590
9
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
9
      if (Diag.empty())
7592
6
        return;
7593
9
    }
7594
7595
3
    Error(E, diag::note_constexpr_conditional_never_const);
7596
3
  }
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7575
28
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7576
28
    assert(Info.checkingPotentialConstantExpression());
7577
7578
    // Speculatively evaluate both arms.
7579
28
    SmallVector<PartialDiagnosticAt, 8> Diag;
7580
28
    {
7581
28
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7582
28
      StmtVisitorTy::Visit(E->getFalseExpr());
7583
28
      if (Diag.empty())
7584
27
        return;
7585
28
    }
7586
7587
1
    {
7588
1
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7589
1
      Diag.clear();
7590
1
      StmtVisitorTy::Visit(E->getTrueExpr());
7591
1
      if (Diag.empty())
7592
1
        return;
7593
1
    }
7594
7595
0
    Error(E, diag::note_constexpr_conditional_never_const);
7596
0
  }
7597
7598
7599
  template<typename ConditionalOperator>
7600
325k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
325k
    bool BoolResult;
7602
325k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
236k
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()3.68k
) {
7604
3.68k
        CheckPotentialConstantConditional(E);
7605
3.68k
        return false;
7606
3.68k
      }
7607
232k
      if (Info.noteFailure()) {
7608
229k
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
229k
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
229k
      }
7611
232k
      return false;
7612
236k
    }
7613
7614
88.4k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()29.5k
:
E->getFalseExpr()58.9k
;
7615
88.4k
    return StmtVisitorTy::Visit(EvalExpr);
7616
325k
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Line
Count
Source
7600
28
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
28
    bool BoolResult;
7602
28
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
26
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
26
      if (Info.noteFailure()) {
7608
12
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
12
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
12
      }
7611
26
      return false;
7612
26
    }
7613
7614
2
    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : 
E->getFalseExpr()0
;
7615
2
    return StmtVisitorTy::Visit(EvalExpr);
7616
28
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
13.9k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
13.9k
    bool BoolResult;
7602
13.9k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
6.17k
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()346
) {
7604
346
        CheckPotentialConstantConditional(E);
7605
346
        return false;
7606
346
      }
7607
5.82k
      if (Info.noteFailure()) {
7608
4.97k
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
4.97k
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
4.97k
      }
7611
5.82k
      return false;
7612
6.17k
    }
7613
7614
7.80k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()261
:
E->getFalseExpr()7.54k
;
7615
7.80k
    return StmtVisitorTy::Visit(EvalExpr);
7616
13.9k
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
15
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
15
    bool BoolResult;
7602
15
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
15
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
15
      if (Info.noteFailure()) {
7608
15
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
15
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
15
      }
7611
15
      return false;
7612
15
    }
7613
7614
0
    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7615
0
    return StmtVisitorTy::Visit(EvalExpr);
7616
15
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
98
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
98
    bool BoolResult;
7602
98
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
83
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
83
      if (Info.noteFailure()) {
7608
67
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
67
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
67
      }
7611
83
      return false;
7612
83
    }
7613
7614
15
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()14
:
E->getFalseExpr()1
;
7615
15
    return StmtVisitorTy::Visit(EvalExpr);
7616
98
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
26
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
26
    bool BoolResult;
7602
26
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
22
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
22
      if (Info.noteFailure()) {
7608
11
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
11
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
11
      }
7611
22
      return false;
7612
22
    }
7613
7614
4
    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : 
E->getFalseExpr()0
;
7615
4
    return StmtVisitorTy::Visit(EvalExpr);
7616
26
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Line
Count
Source
7600
3
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
3
    bool BoolResult;
7602
3
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
1
      if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7604
1
        CheckPotentialConstantConditional(E);
7605
1
        return false;
7606
1
      }
7607
0
      if (Info.noteFailure()) {
7608
0
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
0
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
0
      }
7611
0
      return false;
7612
1
    }
7613
7614
2
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()0
: E->getFalseExpr();
7615
2
    return StmtVisitorTy::Visit(EvalExpr);
7616
3
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
2.19k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
2.19k
    bool BoolResult;
7602
2.19k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
82
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()17
) {
7604
17
        CheckPotentialConstantConditional(E);
7605
17
        return false;
7606
17
      }
7607
65
      if (Info.noteFailure()) {
7608
20
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
20
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
20
      }
7611
65
      return false;
7612
82
    }
7613
7614
2.11k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()338
:
E->getFalseExpr()1.77k
;
7615
2.11k
    return StmtVisitorTy::Visit(EvalExpr);
7616
2.19k
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
8
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
8
    bool BoolResult;
7602
8
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
6
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
6
      if (Info.noteFailure()) {
7608
6
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
6
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
6
      }
7611
6
      return false;
7612
6
    }
7613
7614
2
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()1
:
E->getFalseExpr()1
;
7615
2
    return StmtVisitorTy::Visit(EvalExpr);
7616
8
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Line
Count
Source
7600
1.35k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
1.35k
    bool BoolResult;
7602
1.35k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
0
      if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
0
      if (Info.noteFailure()) {
7608
0
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
0
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
0
      }
7611
0
      return false;
7612
0
    }
7613
7614
1.35k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()1.17k
:
E->getFalseExpr()180
;
7615
1.35k
    return StmtVisitorTy::Visit(EvalExpr);
7616
1.35k
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
305k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
305k
    bool BoolResult;
7602
305k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
229k
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()3.29k
) {
7604
3.29k
        CheckPotentialConstantConditional(E);
7605
3.29k
        return false;
7606
3.29k
      }
7607
226k
      if (Info.noteFailure()) {
7608
224k
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
224k
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
224k
      }
7611
226k
      return false;
7612
229k
    }
7613
7614
75.6k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()26.8k
:
E->getFalseExpr()48.7k
;
7615
75.6k
    return StmtVisitorTy::Visit(EvalExpr);
7616
305k
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
67
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
67
    bool BoolResult;
7602
67
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
8
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()0
) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
8
      if (Info.noteFailure()) {
7608
8
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
8
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
8
      }
7611
8
      return false;
7612
8
    }
7613
7614
59
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()50
:
E->getFalseExpr()9
;
7615
59
    return StmtVisitorTy::Visit(EvalExpr);
7616
67
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Line
Count
Source
7600
11
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
11
    bool BoolResult;
7602
11
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
0
      if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7604
0
        CheckPotentialConstantConditional(E);
7605
0
        return false;
7606
0
      }
7607
0
      if (Info.noteFailure()) {
7608
0
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
0
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
0
      }
7611
0
      return false;
7612
0
    }
7613
7614
11
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()4
:
E->getFalseExpr()7
;
7615
11
    return StmtVisitorTy::Visit(EvalExpr);
7616
11
  }
ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Line
Count
Source
7600
2.19k
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7601
2.19k
    bool BoolResult;
7602
2.19k
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7603
709
      if (Info.checkingPotentialConstantExpression() && 
Info.noteFailure()28
) {
7604
28
        CheckPotentialConstantConditional(E);
7605
28
        return false;
7606
28
      }
7607
681
      if (Info.noteFailure()) {
7608
247
        StmtVisitorTy::Visit(E->getTrueExpr());
7609
247
        StmtVisitorTy::Visit(E->getFalseExpr());
7610
247
      }
7611
681
      return false;
7612
709
    }
7613
7614
1.48k
    Expr *EvalExpr = BoolResult ? 
E->getTrueExpr()839
:
E->getFalseExpr()648
;
7615
1.48k
    return StmtVisitorTy::Visit(EvalExpr);
7616
2.19k
  }
7617
7618
protected:
7619
  EvalInfo &Info;
7620
  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7621
  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7622
7623
19.1k
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7624
19.1k
    return Info.CCEDiag(E, D);
7625
19.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Line
Count
Source
7623
10
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7624
10
    return Info.CCEDiag(E, D);
7625
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Line
Count
Source
7623
288
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7624
288
    return Info.CCEDiag(E, D);
7625
288
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Line
Count
Source
7623
8.14k
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7624
8.14k
    return Info.CCEDiag(E, D);
7625
8.14k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Line
Count
Source
7623
10.7k
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7624
10.7k
    return Info.CCEDiag(E, D);
7625
10.7k
  }
7626
7627
0
  bool ZeroInitialization(const Expr *E) { return Error(E); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::ZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::ZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::ZeroInitialization(clang::Expr const*)
7628
7629
862k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
862k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
862k
    return BuiltinOp != 0 &&
7632
862k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)173k
;
7633
862k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
59.1k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
59.1k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
59.1k
    return BuiltinOp != 0 &&
7632
59.1k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)5.53k
;
7633
59.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
48.5k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
48.5k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
48.5k
    return BuiltinOp != 0 &&
7632
48.5k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)39.3k
;
7633
48.5k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
322
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
322
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
322
    return BuiltinOp != 0 &&
7632
322
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)287
;
7633
322
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
696k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
696k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
696k
    return BuiltinOp != 0 &&
7632
696k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)111k
;
7633
696k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
6.78k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
6.78k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
6.78k
    return BuiltinOp != 0 &&
7632
6.78k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)4.06k
;
7633
6.78k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Line
Count
Source
7629
50.9k
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7630
50.9k
    unsigned BuiltinOp = E->getBuiltinCallee();
7631
50.9k
    return BuiltinOp != 0 &&
7632
50.9k
           
Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp)12.9k
;
7633
50.9k
  }
7634
7635
public:
7636
50.3M
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
14.1M
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
5.04k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
5
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
13.6k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
120k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
3.72k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
386k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
4.28k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
474
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
2.32M
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
30.5M
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
10.3k
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7636
2.81M
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7637
7638
4.60M
  EvalInfo &getEvalInfo() { return Info; }
7639
7640
  /// Report an evaluation error. This should only be called when an error is
7641
  /// first discovered. When propagating an error, just return false.
7642
627k
  bool Error(const Expr *E, diag::kind D) {
7643
627k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
627k
    return false;
7645
627k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
20.9k
  bool Error(const Expr *E, diag::kind D) {
7643
20.9k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
20.9k
    return false;
7645
20.9k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
53
  bool Error(const Expr *E, diag::kind D) {
7643
53
    Info.FFDiag(E, D) << E->getSourceRange();
7644
53
    return false;
7645
53
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Error(clang::Expr const*, unsigned int)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
48
  bool Error(const Expr *E, diag::kind D) {
7643
48
    Info.FFDiag(E, D) << E->getSourceRange();
7644
48
    return false;
7645
48
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
548
  bool Error(const Expr *E, diag::kind D) {
7643
548
    Info.FFDiag(E, D) << E->getSourceRange();
7644
548
    return false;
7645
548
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
34.1k
  bool Error(const Expr *E, diag::kind D) {
7643
34.1k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
34.1k
    return false;
7645
34.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
329
  bool Error(const Expr *E, diag::kind D) {
7643
329
    Info.FFDiag(E, D) << E->getSourceRange();
7644
329
    return false;
7645
329
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
2.11k
  bool Error(const Expr *E, diag::kind D) {
7643
2.11k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
2.11k
    return false;
7645
2.11k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
4
  bool Error(const Expr *E, diag::kind D) {
7643
4
    Info.FFDiag(E, D) << E->getSourceRange();
7644
4
    return false;
7645
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
115k
  bool Error(const Expr *E, diag::kind D) {
7643
115k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
115k
    return false;
7645
115k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
167k
  bool Error(const Expr *E, diag::kind D) {
7643
167k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
167k
    return false;
7645
167k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
126
  bool Error(const Expr *E, diag::kind D) {
7643
126
    Info.FFDiag(E, D) << E->getSourceRange();
7644
126
    return false;
7645
126
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7642
286k
  bool Error(const Expr *E, diag::kind D) {
7643
286k
    Info.FFDiag(E, D) << E->getSourceRange();
7644
286k
    return false;
7645
286k
  }
7646
627k
  bool Error(const Expr *E) {
7647
627k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
627k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
20.9k
  bool Error(const Expr *E) {
7647
20.9k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
20.9k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
53
  bool Error(const Expr *E) {
7647
53
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
53
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Error(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
48
  bool Error(const Expr *E) {
7647
48
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
48
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
548
  bool Error(const Expr *E) {
7647
548
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
548
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
34.1k
  bool Error(const Expr *E) {
7647
34.1k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
34.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
329
  bool Error(const Expr *E) {
7647
329
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
329
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
2.11k
  bool Error(const Expr *E) {
7647
2.11k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
2.11k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
4
  bool Error(const Expr *E) {
7647
4
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
115k
  bool Error(const Expr *E) {
7647
115k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
115k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
167k
  bool Error(const Expr *E) {
7647
167k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
167k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
126
  bool Error(const Expr *E) {
7647
126
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
126
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7646
286k
  bool Error(const Expr *E) {
7647
286k
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7648
286k
  }
7649
7650
0
  bool VisitStmt(const Stmt *) {
7651
0
    llvm_unreachable("Expression evaluator should not be called on stmts");
7652
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitStmt(clang::Stmt const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitStmt(clang::Stmt const*)
7653
124k
  bool VisitExpr(const Expr *E) {
7654
124k
    return Error(E);
7655
124k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
3.51k
  bool VisitExpr(const Expr *E) {
7654
3.51k
    return Error(E);
7655
3.51k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExpr(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
44
  bool VisitExpr(const Expr *E) {
7654
44
    return Error(E);
7655
44
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitExpr(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
129
  bool VisitExpr(const Expr *E) {
7654
129
    return Error(E);
7655
129
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
27
  bool VisitExpr(const Expr *E) {
7654
27
    return Error(E);
7655
27
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
492
  bool VisitExpr(const Expr *E) {
7654
492
    return Error(E);
7655
492
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitExpr(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
114k
  bool VisitExpr(const Expr *E) {
7654
114k
    return Error(E);
7655
114k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
3.74k
  bool VisitExpr(const Expr *E) {
7654
3.74k
    return Error(E);
7655
3.74k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
123
  bool VisitExpr(const Expr *E) {
7654
123
    return Error(E);
7655
123
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitExpr(clang::Expr const*)
Line
Count
Source
7653
1.44k
  bool VisitExpr(const Expr *E) {
7654
1.44k
    return Error(E);
7655
1.44k
  }
7656
7657
1
  bool VisitPredefinedExpr(const PredefinedExpr *E) {
7658
1
    return StmtVisitorTy::Visit(E->getFunctionName());
7659
1
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Line
Count
Source
7657
1
  bool VisitPredefinedExpr(const PredefinedExpr *E) {
7658
1
    return StmtVisitorTy::Visit(E->getFunctionName());
7659
1
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
7660
44.6k
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
44.6k
    if (E->hasAPValueResult())
7662
42.0k
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
2.55k
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
44.6k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
4
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
4
    if (E->hasAPValueResult())
7662
2
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
2
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
35
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
35
    if (E->hasAPValueResult())
7662
13
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
22
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
35
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
365
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
365
    if (E->hasAPValueResult())
7662
2
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
363
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
365
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
6
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
6
    if (E->hasAPValueResult())
7662
0
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
6
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
6
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
620
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
620
    if (E->hasAPValueResult())
7662
180
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
440
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
620
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
5
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
5
    if (E->hasAPValueResult())
7662
0
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
5
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
5
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
15
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
15
    if (E->hasAPValueResult())
7662
1
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
14
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
15
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
43.4k
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
43.4k
    if (E->hasAPValueResult())
7662
41.8k
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
1.63k
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
43.4k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
10
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
10
    if (E->hasAPValueResult())
7662
0
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
10
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Line
Count
Source
7660
78
  bool VisitConstantExpr(const ConstantExpr *E) {
7661
78
    if (E->hasAPValueResult())
7662
17
      return DerivedSuccess(E->getAPValueResult(), E);
7663
7664
61
    return StmtVisitorTy::Visit(E->getSubExpr());
7665
78
  }
7666
7667
  bool VisitParenExpr(const ParenExpr *E)
7668
608k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
35
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
121k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
116
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
7.05k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
432
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
262
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
10
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
32.1k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
407k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
724
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Line
Count
Source
7668
38.9k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
7669
  bool VisitUnaryExtension(const UnaryOperator *E)
7670
5.02k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
281
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
372
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
48
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
507
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
3.48k
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
291
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Line
Count
Source
7670
32
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
7671
  bool VisitUnaryPlus(const UnaryOperator *E)
7672
739
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Line
Count
Source
7672
44
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Line
Count
Source
7672
17
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Line
Count
Source
7672
375
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Line
Count
Source
7672
228
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Line
Count
Source
7672
75
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
7673
  bool VisitChooseExpr(const ChooseExpr *E)
7674
6
    { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Line
Count
Source
7674
3
    { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Line
Count
Source
7674
3
    { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
7675
  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7676
241
    { return StmtVisitorTy::Visit(E->getResultExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Line
Count
Source
7676
1
    { return StmtVisitorTy::Visit(E->getResultExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Line
Count
Source
7676
240
    { return StmtVisitorTy::Visit(E->getResultExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
7677
  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7678
1.13M
    { return StmtVisitorTy::Visit(E->getReplacement()); }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Line
Count
Source
7678
87
    { return StmtVisitorTy::Visit(E->getReplacement()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Line
Count
Source
7678
208
    { return StmtVisitorTy::Visit(E->getReplacement()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Line
Count
Source
7678
1.12M
    { return StmtVisitorTy::Visit(E->getReplacement()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Line
Count
Source
7678
1.20k
    { return StmtVisitorTy::Visit(E->getReplacement()); }
7679
3.67k
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
3.67k
    TempVersionRAII RAII(*Info.CurrentCall);
7681
3.67k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
3.67k
    return StmtVisitorTy::Visit(E->getExpr());
7683
3.67k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Line
Count
Source
7679
70
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
70
    TempVersionRAII RAII(*Info.CurrentCall);
7681
70
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
70
    return StmtVisitorTy::Visit(E->getExpr());
7683
70
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Line
Count
Source
7679
243
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
243
    TempVersionRAII RAII(*Info.CurrentCall);
7681
243
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
243
    return StmtVisitorTy::Visit(E->getExpr());
7683
243
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Line
Count
Source
7679
188
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
188
    TempVersionRAII RAII(*Info.CurrentCall);
7681
188
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
188
    return StmtVisitorTy::Visit(E->getExpr());
7683
188
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Line
Count
Source
7679
2.13k
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
2.13k
    TempVersionRAII RAII(*Info.CurrentCall);
7681
2.13k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
2.13k
    return StmtVisitorTy::Visit(E->getExpr());
7683
2.13k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Line
Count
Source
7679
1.04k
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7680
1.04k
    TempVersionRAII RAII(*Info.CurrentCall);
7681
1.04k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7682
1.04k
    return StmtVisitorTy::Visit(E->getExpr());
7683
1.04k
  }
7684
4.25k
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
4.25k
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
4.25k
    if (!E->getExpr())
7688
0
      return Error(E);
7689
4.25k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
4.25k
    return StmtVisitorTy::Visit(E->getExpr());
7691
4.25k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
71
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
71
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
71
    if (!E->getExpr())
7688
0
      return Error(E);
7689
71
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
71
    return StmtVisitorTy::Visit(E->getExpr());
7691
71
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
101
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
101
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
101
    if (!E->getExpr())
7688
0
      return Error(E);
7689
101
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
101
    return StmtVisitorTy::Visit(E->getExpr());
7691
101
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
459
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
459
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
459
    if (!E->getExpr())
7688
0
      return Error(E);
7689
459
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
459
    return StmtVisitorTy::Visit(E->getExpr());
7691
459
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
80
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
80
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
80
    if (!E->getExpr())
7688
0
      return Error(E);
7689
80
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
80
    return StmtVisitorTy::Visit(E->getExpr());
7691
80
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
2.39k
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
2.39k
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
2.39k
    if (!E->getExpr())
7688
0
      return Error(E);
7689
2.39k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
2.39k
    return StmtVisitorTy::Visit(E->getExpr());
7691
2.39k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Line
Count
Source
7684
1.15k
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7685
1.15k
    TempVersionRAII RAII(*Info.CurrentCall);
7686
    // The initializer may not have been parsed yet, or might be erroneous.
7687
1.15k
    if (!E->getExpr())
7688
0
      return Error(E);
7689
1.15k
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7690
1.15k
    return StmtVisitorTy::Visit(E->getExpr());
7691
1.15k
  }
7692
7693
28.7k
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
28.7k
    FullExpressionRAII Scope(Info);
7695
28.7k
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()12.5k
;
7696
28.7k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
3
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
3
    FullExpressionRAII Scope(Info);
7695
3
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()0
;
7696
3
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
3.38k
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
3.38k
    FullExpressionRAII Scope(Info);
7695
3.38k
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()1.22k
;
7696
3.38k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
20
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
20
    FullExpressionRAII Scope(Info);
7695
20
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()8
;
7696
20
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
14.2k
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
14.2k
    FullExpressionRAII Scope(Info);
7695
14.2k
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()8.93k
;
7696
14.2k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
459
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
459
    FullExpressionRAII Scope(Info);
7695
459
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()22
;
7696
459
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
16
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
16
    FullExpressionRAII Scope(Info);
7695
16
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()6
;
7696
16
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
10
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
10
    FullExpressionRAII Scope(Info);
7695
10
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()0
;
7696
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
10.1k
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
10.1k
    FullExpressionRAII Scope(Info);
7695
10.1k
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()2.20k
;
7696
10.1k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
126
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
126
    FullExpressionRAII Scope(Info);
7695
126
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()85
;
7696
126
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Line
Count
Source
7693
291
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7694
291
    FullExpressionRAII Scope(Info);
7695
291
    return StmtVisitorTy::Visit(E->getSubExpr()) && 
Scope.destroy()73
;
7696
291
  }
7697
7698
  // Temporaries are registered when created, so we don't care about
7699
  // CXXBindTemporaryExpr.
7700
963
  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7701
963
    return StmtVisitorTy::Visit(E->getSubExpr());
7702
963
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Line
Count
Source
7700
2
  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7701
2
    return StmtVisitorTy::Visit(E->getSubExpr());
7702
2
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Line
Count
Source
7700
9
  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7701
9
    return StmtVisitorTy::Visit(E->getSubExpr());
7702
9
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Line
Count
Source
7700
952
  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7701
952
    return StmtVisitorTy::Visit(E->getSubExpr());
7702
952
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
7703
7704
1.06k
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7705
1.06k
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7706
1.06k
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7707
1.06k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Line
Count
Source
7704
10
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7705
10
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7706
10
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7707
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Line
Count
Source
7704
86
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7705
86
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7706
86
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7707
86
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Line
Count
Source
7704
505
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7705
505
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7706
505
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7707
505
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Line
Count
Source
7704
465
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7705
465
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7706
465
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7707
465
  }
7708
231
  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7709
231
    if (!Info.Ctx.getLangOpts().CPlusPlus20)
7710
183
      CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7711
231
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7712
231
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Line
Count
Source
7708
83
  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7709
83
    if (!Info.Ctx.getLangOpts().CPlusPlus20)
7710
61
      CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7711
83
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7712
83
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Line
Count
Source
7708
148
  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7709
148
    if (!Info.Ctx.getLangOpts().CPlusPlus20)
7710
122
      CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7711
148
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7712
148
  }
7713
576
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
576
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
576
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
82
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
82
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
82
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
1
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
1
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
183
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
183
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
183
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
15
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
15
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
15
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
32
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
32
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
32
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
245
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
245
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
245
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Line
Count
Source
7713
18
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7714
18
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7715
18
  }
7716
7717
49.2k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
49.2k
    switch (E->getOpcode()) {
7719
43.5k
    default:
7720
43.5k
      return Error(E);
7721
7722
5.78k
    case BO_Comma:
7723
5.78k
      VisitIgnoredValue(E->getLHS());
7724
5.78k
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
2
    case BO_PtrMemD:
7727
2
    case BO_PtrMemI: {
7728
2
      LValue Obj;
7729
2
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
2
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
49.2k
    }
7737
49.2k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
5.28k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
5.28k
    switch (E->getOpcode()) {
7719
0
    default:
7720
0
      return Error(E);
7721
7722
5.28k
    case BO_Comma:
7723
5.28k
      VisitIgnoredValue(E->getLHS());
7724
5.28k
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
5.28k
    }
7737
5.28k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
551
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
551
    switch (E->getOpcode()) {
7719
548
    default:
7720
548
      return Error(E);
7721
7722
3
    case BO_Comma:
7723
3
      VisitIgnoredValue(E->getLHS());
7724
3
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
551
    }
7737
551
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
33.8k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
33.8k
    switch (E->getOpcode()) {
7719
33.8k
    default:
7720
33.8k
      return Error(E);
7721
7722
11
    case BO_Comma:
7723
11
      VisitIgnoredValue(E->getLHS());
7724
11
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
33.8k
    }
7737
33.8k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
306
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
306
    switch (E->getOpcode()) {
7719
302
    default:
7720
302
      return Error(E);
7721
7722
4
    case BO_Comma:
7723
4
      VisitIgnoredValue(E->getLHS());
7724
4
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
306
    }
7737
306
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
1.67k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
1.67k
    switch (E->getOpcode()) {
7719
1.61k
    default:
7720
1.61k
      return Error(E);
7721
7722
60
    case BO_Comma:
7723
60
      VisitIgnoredValue(E->getLHS());
7724
60
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
1.67k
    }
7737
1.67k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
1
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
1
    switch (E->getOpcode()) {
7719
0
    default:
7720
0
      return Error(E);
7721
7722
1
    case BO_Comma:
7723
1
      VisitIgnoredValue(E->getLHS());
7724
1
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
1
    }
7737
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
2.17k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
2.17k
    switch (E->getOpcode()) {
7719
2.17k
    default:
7720
2.17k
      return Error(E);
7721
7722
0
    case BO_Comma:
7723
0
      VisitIgnoredValue(E->getLHS());
7724
0
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
2
    case BO_PtrMemD:
7727
2
    case BO_PtrMemI: {
7728
2
      LValue Obj;
7729
2
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
2
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
2.17k
    }
7737
2.17k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
175
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
175
    switch (E->getOpcode()) {
7719
0
    default:
7720
0
      return Error(E);
7721
7722
175
    case BO_Comma:
7723
175
      VisitIgnoredValue(E->getLHS());
7724
175
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
175
    }
7737
175
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
7717
5.27k
  bool VisitBinaryOperator(const BinaryOperator *E) {
7718
5.27k
    switch (E->getOpcode()) {
7719
5.03k
    default:
7720
5.03k
      return Error(E);
7721
7722
246
    case BO_Comma:
7723
246
      VisitIgnoredValue(E->getLHS());
7724
246
      return StmtVisitorTy::Visit(E->getRHS());
7725
7726
0
    case BO_PtrMemD:
7727
0
    case BO_PtrMemI: {
7728
0
      LValue Obj;
7729
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7730
0
        return false;
7731
0
      APValue Result;
7732
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7733
0
        return false;
7734
0
      return DerivedSuccess(Result, E);
7735
0
    }
7736
5.27k
    }
7737
5.27k
  }
7738
7739
254
  bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7740
254
    return StmtVisitorTy::Visit(E->getSemanticForm());
7741
254
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Line
Count
Source
7739
9
  bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7740
9
    return StmtVisitorTy::Visit(E->getSemanticForm());
7741
9
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Line
Count
Source
7739
245
  bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7740
245
    return StmtVisitorTy::Visit(E->getSemanticForm());
7741
245
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
7742
7743
1.42k
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
1.42k
    LValue CommonLV;
7747
1.42k
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
1.42k
                      E->getOpaqueValue(),
7749
1.42k
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
1.42k
                      ScopeKind::FullExpression, CommonLV),
7751
1.42k
                  Info, E->getCommon()))
7752
31
      return false;
7753
7754
1.39k
    return HandleConditionalOperator(E);
7755
1.42k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
31
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
31
    LValue CommonLV;
7747
31
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
31
                      E->getOpaqueValue(),
7749
31
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
31
                      ScopeKind::FullExpression, CommonLV),
7751
31
                  Info, E->getCommon()))
7752
3
      return false;
7753
7754
28
    return HandleConditionalOperator(E);
7755
31
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
1
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
1
    LValue CommonLV;
7747
1
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
1
                      E->getOpaqueValue(),
7749
1
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
1
                      ScopeKind::FullExpression, CommonLV),
7751
1
                  Info, E->getCommon()))
7752
1
      return false;
7753
7754
0
    return HandleConditionalOperator(E);
7755
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
2
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
2
    LValue CommonLV;
7747
2
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
2
                      E->getOpaqueValue(),
7749
2
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
2
                      ScopeKind::FullExpression, CommonLV),
7751
2
                  Info, E->getCommon()))
7752
2
      return false;
7753
7754
0
    return HandleConditionalOperator(E);
7755
2
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
3
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
3
    LValue CommonLV;
7747
3
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
3
                      E->getOpaqueValue(),
7749
3
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
3
                      ScopeKind::FullExpression, CommonLV),
7751
3
                  Info, E->getCommon()))
7752
0
      return false;
7753
7754
3
    return HandleConditionalOperator(E);
7755
3
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
1.36k
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
1.36k
    LValue CommonLV;
7747
1.36k
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
1.36k
                      E->getOpaqueValue(),
7749
1.36k
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
1.36k
                      ScopeKind::FullExpression, CommonLV),
7751
1.36k
                  Info, E->getCommon()))
7752
13
      return false;
7753
7754
1.35k
    return HandleConditionalOperator(E);
7755
1.36k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Line
Count
Source
7743
23
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7744
    // Evaluate and cache the common expression. We treat it as a temporary,
7745
    // even though it's not quite the same thing.
7746
23
    LValue CommonLV;
7747
23
    if (!Evaluate(Info.CurrentCall->createTemporary(
7748
23
                      E->getOpaqueValue(),
7749
23
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7750
23
                      ScopeKind::FullExpression, CommonLV),
7751
23
                  Info, E->getCommon()))
7752
12
      return false;
7753
7754
11
    return HandleConditionalOperator(E);
7755
23
  }
7756
7757
323k
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
323k
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
323k
    if (const CallExpr *CallCE =
7764
323k
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
5.71k
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
177
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
323k
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall3.70k
)
7773
7
      return false;
7774
7775
323k
    FoldConstant Fold(Info, IsBcpCall);
7776
323k
    if (!HandleConditionalOperator(E)) {
7777
237k
      Fold.keepDiagnostics();
7778
237k
      return false;
7779
237k
    }
7780
7781
86.5k
    return true;
7782
323k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
13.9k
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
13.9k
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
13.9k
    if (const CallExpr *CallCE =
7764
13.9k
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
562
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
1
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
13.9k
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall346
)
7773
0
      return false;
7774
7775
13.9k
    FoldConstant Fold(Info, IsBcpCall);
7776
13.9k
    if (!HandleConditionalOperator(E)) {
7777
6.19k
      Fold.keepDiagnostics();
7778
6.19k
      return false;
7779
6.19k
    }
7780
7781
7.78k
    return true;
7782
13.9k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
15
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
15
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
15
    if (const CallExpr *CallCE =
7764
15
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
0
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
15
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall0
)
7773
0
      return false;
7774
7775
15
    FoldConstant Fold(Info, IsBcpCall);
7776
15
    if (!HandleConditionalOperator(E)) {
7777
15
      Fold.keepDiagnostics();
7778
15
      return false;
7779
15
    }
7780
7781
0
    return true;
7782
15
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
98
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
98
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
98
    if (const CallExpr *CallCE =
7764
98
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
28
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
98
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall0
)
7773
0
      return false;
7774
7775
98
    FoldConstant Fold(Info, IsBcpCall);
7776
98
    if (!HandleConditionalOperator(E)) {
7777
83
      Fold.keepDiagnostics();
7778
83
      return false;
7779
83
    }
7780
7781
15
    return true;
7782
98
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
26
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
26
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
26
    if (const CallExpr *CallCE =
7764
26
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
0
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
26
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall0
)
7773
0
      return false;
7774
7775
26
    FoldConstant Fold(Info, IsBcpCall);
7776
26
    if (!HandleConditionalOperator(E)) {
7777
22
      Fold.keepDiagnostics();
7778
22
      return false;
7779
22
    }
7780
7781
4
    return true;
7782
26
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
2.19k
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
2.19k
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
2.19k
    if (const CallExpr *CallCE =
7764
2.19k
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
882
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
2.19k
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall17
)
7773
0
      return false;
7774
7775
2.19k
    FoldConstant Fold(Info, IsBcpCall);
7776
2.19k
    if (!HandleConditionalOperator(E)) {
7777
88
      Fold.keepDiagnostics();
7778
88
      return false;
7779
88
    }
7780
7781
2.10k
    return true;
7782
2.19k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
8
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
8
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
8
    if (const CallExpr *CallCE =
7764
8
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
0
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
8
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall0
)
7773
0
      return false;
7774
7775
8
    FoldConstant Fold(Info, IsBcpCall);
7776
8
    if (!HandleConditionalOperator(E)) {
7777
7
      Fold.keepDiagnostics();
7778
7
      return false;
7779
7
    }
7780
7781
1
    return true;
7782
8
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
305k
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
305k
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
305k
    if (const CallExpr *CallCE =
7764
305k
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
3.85k
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
138
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
305k
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall3.31k
)
7773
5
      return false;
7774
7775
305k
    FoldConstant Fold(Info, IsBcpCall);
7776
305k
    if (!HandleConditionalOperator(E)) {
7777
229k
      Fold.keepDiagnostics();
7778
229k
      return false;
7779
229k
    }
7780
7781
75.1k
    return true;
7782
305k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
67
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
67
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
67
    if (const CallExpr *CallCE =
7764
67
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
8
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
0
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
67
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall0
)
7773
0
      return false;
7774
7775
67
    FoldConstant Fold(Info, IsBcpCall);
7776
67
    if (!HandleConditionalOperator(E)) {
7777
17
      Fold.keepDiagnostics();
7778
17
      return false;
7779
17
    }
7780
7781
50
    return true;
7782
67
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Line
Count
Source
7757
2.19k
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7758
2.19k
    bool IsBcpCall = false;
7759
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7760
    // the result is a constant expression if it can be folded without
7761
    // side-effects. This is an important GNU extension. See GCC PR38377
7762
    // for discussion.
7763
2.19k
    if (const CallExpr *CallCE =
7764
2.19k
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7765
387
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7766
38
        IsBcpCall = true;
7767
7768
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769
    // constant expression; we can't check whether it's potentially foldable.
7770
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771
    // it would return 'false' in this mode.
7772
2.19k
    if (Info.checkingPotentialConstantExpression() && 
IsBcpCall30
)
7773
2
      return false;
7774
7775
2.19k
    FoldConstant Fold(Info, IsBcpCall);
7776
2.19k
    if (!HandleConditionalOperator(E)) {
7777
720
      Fold.keepDiagnostics();
7778
720
      return false;
7779
720
    }
7780
7781
1.47k
    return true;
7782
2.19k
  }
7783
7784
4.04k
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
4.04k
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
4.04k
        Value && 
!Value->isAbsent()2.80k
)
7787
2.80k
      return DerivedSuccess(*Value, E);
7788
7789
1.23k
    const Expr *Source = E->getSourceExpr();
7790
1.23k
    if (!Source)
7791
497
      return Error(E);
7792
742
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
742
    return StmtVisitorTy::Visit(Source);
7797
742
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
556
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
556
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
556
        Value && 
!Value->isAbsent()248
)
7787
248
      return DerivedSuccess(*Value, E);
7788
7789
308
    const Expr *Source = E->getSourceExpr();
7790
308
    if (!Source)
7791
0
      return Error(E);
7792
308
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
308
    return StmtVisitorTy::Visit(Source);
7797
308
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
1
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
1
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
1
        Value && 
!Value->isAbsent()0
)
7787
0
      return DerivedSuccess(*Value, E);
7788
7789
1
    const Expr *Source = E->getSourceExpr();
7790
1
    if (!Source)
7791
0
      return Error(E);
7792
1
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
1
    return StmtVisitorTy::Visit(Source);
7797
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
4
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
4
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
4
        Value && 
!Value->isAbsent()0
)
7787
0
      return DerivedSuccess(*Value, E);
7788
7789
4
    const Expr *Source = E->getSourceExpr();
7790
4
    if (!Source)
7791
0
      return Error(E);
7792
4
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
4
    return StmtVisitorTy::Visit(Source);
7797
4
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
4
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
4
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
4
        Value && 
!Value->isAbsent()0
)
7787
0
      return DerivedSuccess(*Value, E);
7788
7789
4
    const Expr *Source = E->getSourceExpr();
7790
4
    if (!Source)
7791
0
      return Error(E);
7792
4
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
4
    return StmtVisitorTy::Visit(Source);
7797
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
3.29k
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
3.29k
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
3.29k
        Value && 
!Value->isAbsent()2.52k
)
7787
2.52k
      return DerivedSuccess(*Value, E);
7788
7789
766
    const Expr *Source = E->getSourceExpr();
7790
766
    if (!Source)
7791
497
      return Error(E);
7792
269
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
269
    return StmtVisitorTy::Visit(Source);
7797
269
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Line
Count
Source
7784
183
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7785
183
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7786
183
        Value && 
!Value->isAbsent()27
)
7787
27
      return DerivedSuccess(*Value, E);
7788
7789
156
    const Expr *Source = E->getSourceExpr();
7790
156
    if (!Source)
7791
0
      return Error(E);
7792
156
    if (Source == E) {
7793
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7794
0
      return Error(E);
7795
0
    }
7796
156
    return StmtVisitorTy::Visit(Source);
7797
156
  }
7798
7799
3.09k
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
4.32k
    for (const Expr *SemE : E->semantics()) {
7801
4.32k
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
1.24k
        if (SemE == E->getResultExpr())
7806
22
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
1.22k
        if (OVE->isUnique())
7811
1.17k
          continue;
7812
7813
50
        LValue LV;
7814
50
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
50
                          OVE, getStorageType(Info.Ctx, OVE),
7816
50
                          ScopeKind::FullExpression, LV),
7817
50
                      Info, OVE->getSourceExpr()))
7818
11
          return false;
7819
3.07k
      } else if (SemE == E->getResultExpr()) {
7820
3.05k
        if (!StmtVisitorTy::Visit(SemE))
7821
3.03k
          return false;
7822
3.05k
      } else {
7823
20
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
20
      }
7826
4.32k
    }
7827
25
    return true;
7828
3.09k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
97
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
207
    for (const Expr *SemE : E->semantics()) {
7801
207
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
113
        if (SemE == E->getResultExpr())
7806
2
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
111
        if (OVE->isUnique())
7811
74
          continue;
7812
7813
37
        LValue LV;
7814
37
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
37
                          OVE, getStorageType(Info.Ctx, OVE),
7816
37
                          ScopeKind::FullExpression, LV),
7817
37
                      Info, OVE->getSourceExpr()))
7818
1
          return false;
7819
94
      } else if (SemE == E->getResultExpr()) {
7820
94
        if (!StmtVisitorTy::Visit(SemE))
7821
76
          return false;
7822
94
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
207
    }
7827
18
    return true;
7828
97
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
613
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
637
    for (const Expr *SemE : E->semantics()) {
7801
637
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
24
        if (SemE == E->getResultExpr())
7806
0
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
24
        if (OVE->isUnique())
7811
24
          continue;
7812
7813
0
        LValue LV;
7814
0
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
0
                          OVE, getStorageType(Info.Ctx, OVE),
7816
0
                          ScopeKind::FullExpression, LV),
7817
0
                      Info, OVE->getSourceExpr()))
7818
0
          return false;
7819
613
      } else if (SemE == E->getResultExpr()) {
7820
613
        if (!StmtVisitorTy::Visit(SemE))
7821
613
          return false;
7822
613
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
637
    }
7827
0
    return true;
7828
613
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
2
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
4
    for (const Expr *SemE : E->semantics()) {
7801
4
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
2
        if (SemE == E->getResultExpr())
7806
0
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
2
        if (OVE->isUnique())
7811
2
          continue;
7812
7813
0
        LValue LV;
7814
0
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
0
                          OVE, getStorageType(Info.Ctx, OVE),
7816
0
                          ScopeKind::FullExpression, LV),
7817
0
                      Info, OVE->getSourceExpr()))
7818
0
          return false;
7819
2
      } else if (SemE == E->getResultExpr()) {
7820
2
        if (!StmtVisitorTy::Visit(SemE))
7821
2
          return false;
7822
2
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
4
    }
7827
0
    return true;
7828
2
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
75
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
151
    for (const Expr *SemE : E->semantics()) {
7801
151
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
77
        if (SemE == E->getResultExpr())
7806
1
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
76
        if (OVE->isUnique())
7811
76
          continue;
7812
7813
0
        LValue LV;
7814
0
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
0
                          OVE, getStorageType(Info.Ctx, OVE),
7816
0
                          ScopeKind::FullExpression, LV),
7817
0
                      Info, OVE->getSourceExpr()))
7818
0
          return false;
7819
74
      } else if (SemE == E->getResultExpr()) {
7820
74
        if (!StmtVisitorTy::Visit(SemE))
7821
74
          return false;
7822
74
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
151
    }
7827
0
    return true;
7828
75
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
2.00k
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
2.63k
    for (const Expr *SemE : E->semantics()) {
7801
2.63k
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
652
        if (SemE == E->getResultExpr())
7806
9
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
643
        if (OVE->isUnique())
7811
633
          continue;
7812
7813
10
        LValue LV;
7814
10
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
10
                          OVE, getStorageType(Info.Ctx, OVE),
7816
10
                          ScopeKind::FullExpression, LV),
7817
10
                      Info, OVE->getSourceExpr()))
7818
10
          return false;
7819
1.98k
      } else if (SemE == E->getResultExpr()) {
7820
1.98k
        if (!StmtVisitorTy::Visit(SemE))
7821
1.98k
          return false;
7822
1.98k
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
2.63k
    }
7827
6
    return true;
7828
2.00k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
1
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
23
    for (const Expr *SemE : E->semantics()) {
7801
23
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
3
        if (SemE == E->getResultExpr())
7806
0
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
3
        if (OVE->isUnique())
7811
0
          continue;
7812
7813
3
        LValue LV;
7814
3
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
3
                          OVE, getStorageType(Info.Ctx, OVE),
7816
3
                          ScopeKind::FullExpression, LV),
7817
3
                      Info, OVE->getSourceExpr()))
7818
0
          return false;
7819
20
      } else if (SemE == E->getResultExpr()) {
7820
0
        if (!StmtVisitorTy::Visit(SemE))
7821
0
          return false;
7822
20
      } else {
7823
20
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
20
      }
7826
23
    }
7827
1
    return true;
7828
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
7799
298
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7800
665
    for (const Expr *SemE : E->semantics()) {
7801
665
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7802
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803
        // result expression: there could be two different LValues that would
7804
        // refer to the same object in that case, and we can't model that.
7805
377
        if (SemE == E->getResultExpr())
7806
10
          return Error(E);
7807
7808
        // Unique OVEs get evaluated if and when we encounter them when
7809
        // emitting the rest of the semantic form, rather than eagerly.
7810
367
        if (OVE->isUnique())
7811
367
          continue;
7812
7813
0
        LValue LV;
7814
0
        if (!Evaluate(Info.CurrentCall->createTemporary(
7815
0
                          OVE, getStorageType(Info.Ctx, OVE),
7816
0
                          ScopeKind::FullExpression, LV),
7817
0
                      Info, OVE->getSourceExpr()))
7818
0
          return false;
7819
288
      } else if (SemE == E->getResultExpr()) {
7820
288
        if (!StmtVisitorTy::Visit(SemE))
7821
288
          return false;
7822
288
      } else {
7823
0
        if (!EvaluateIgnoredValue(Info, SemE))
7824
0
          return false;
7825
0
      }
7826
665
    }
7827
0
    return true;
7828
298
  }
7829
7830
1.11M
  bool VisitCallExpr(const CallExpr *E) {
7831
1.11M
    APValue Result;
7832
1.11M
    if (!handleCallExpr(E, Result, nullptr))
7833
772k
      return false;
7834
343k
    return DerivedSuccess(Result, E);
7835
1.11M
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
54
  bool VisitCallExpr(const CallExpr *E) {
7831
54
    APValue Result;
7832
54
    if (!handleCallExpr(E, Result, nullptr))
7833
51
      return false;
7834
3
    return DerivedSuccess(Result, E);
7835
54
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
53.6k
  bool VisitCallExpr(const CallExpr *E) {
7831
53.6k
    APValue Result;
7832
53.6k
    if (!handleCallExpr(E, Result, nullptr))
7833
50.2k
      return false;
7834
3.44k
    return DerivedSuccess(Result, E);
7835
53.6k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
16.3k
  bool VisitCallExpr(const CallExpr *E) {
7831
16.3k
    APValue Result;
7832
16.3k
    if (!handleCallExpr(E, Result, nullptr))
7833
14.5k
      return false;
7834
1.73k
    return DerivedSuccess(Result, E);
7835
16.3k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
295
  bool VisitCallExpr(const CallExpr *E) {
7831
295
    APValue Result;
7832
295
    if (!handleCallExpr(E, Result, nullptr))
7833
291
      return false;
7834
4
    return DerivedSuccess(Result, E);
7835
295
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
347k
  bool VisitCallExpr(const CallExpr *E) {
7831
347k
    APValue Result;
7832
347k
    if (!handleCallExpr(E, Result, nullptr))
7833
347k
      return false;
7834
59
    return DerivedSuccess(Result, E);
7835
347k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
650k
  bool VisitCallExpr(const CallExpr *E) {
7831
650k
    APValue Result;
7832
650k
    if (!handleCallExpr(E, Result, nullptr))
7833
316k
      return false;
7834
333k
    return DerivedSuccess(Result, E);
7835
650k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
6.72k
  bool VisitCallExpr(const CallExpr *E) {
7831
6.72k
    APValue Result;
7832
6.72k
    if (!handleCallExpr(E, Result, nullptr))
7833
5.13k
      return false;
7834
1.59k
    return DerivedSuccess(Result, E);
7835
6.72k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Line
Count
Source
7830
40.5k
  bool VisitCallExpr(const CallExpr *E) {
7831
40.5k
    APValue Result;
7832
40.5k
    if (!handleCallExpr(E, Result, nullptr))
7833
37.4k
      return false;
7834
3.05k
    return DerivedSuccess(Result, E);
7835
40.5k
  }
7836
7837
  bool handleCallExpr(const CallExpr *E, APValue &Result,
7838
1.13M
                     const LValue *ResultSlot) {
7839
1.13M
    CallScopeRAII CallScope(Info);
7840
7841
1.13M
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
1.13M
    QualType CalleeType = Callee->getType();
7843
7844
1.13M
    const FunctionDecl *FD = nullptr;
7845
1.13M
    LValue *This = nullptr, ThisVal;
7846
1.13M
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
1.13M
    bool HasQualifier = false;
7848
7849
1.13M
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
1.13M
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
133k
      const CXXMethodDecl *Member = nullptr;
7854
133k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
132k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
80.5k
          return false;
7858
52.3k
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
52.3k
        if (!Member)
7860
0
          return Error(Callee);
7861
52.3k
        This = &ThisVal;
7862
52.3k
        HasQualifier = ME->hasQualifier();
7863
52.3k
      } else 
if (const BinaryOperator *241
BE241
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
211
        const ValueDecl *D =
7866
211
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
211
        if (!D)
7868
134
          return false;
7869
77
        Member = dyn_cast<CXXMethodDecl>(D);
7870
77
        if (!Member)
7871
0
          return Error(Callee);
7872
77
        This = &ThisVal;
7873
77
      } else 
if (const auto *30
PDE30
= dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
30
        if (!Info.getLangOpts().CPlusPlus20)
7875
11
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
30
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
30
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
30
      } else
7879
0
        return Error(Callee);
7880
52.3k
      FD = Member;
7881
997k
    } else if (CalleeType->isFunctionPointerType()) {
7882
997k
      LValue CalleeLV;
7883
997k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
278k
        return false;
7885
7886
718k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
718k
      if (CalleeLV.isNullPointer()) {
7889
6
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
6
            << const_cast<Expr *>(Callee);
7891
6
        return false;
7892
6
      }
7893
718k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
718k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
718k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
718k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
718k
        CalleeType->getPointeeType(), FD->getType())) {
7901
77
        return Error(E);
7902
77
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
718k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
718k
      if (OCE && 
OCE->isAssignmentOp()63.7k
) {
7908
701
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
701
        Call = Info.CurrentCall->createCall(FD);
7910
701
        bool HasThis = false;
7911
701
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
568
          HasThis = MD->isImplicitObjectMemberFunction();
7913
701
        if (!EvaluateArgs(HasThis ? 
Args.slice(1)568
:
Args133
, Call, Info, FD,
7914
701
                          /*RightToLeft=*/true))
7915
125
          return false;
7916
701
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
718k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
718k
      if (MD && 
MD->isImplicitObjectMemberFunction()370k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
38.6k
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
38.6k
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
10.8k
          return false;
7930
27.8k
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
27.8k
        if (Info.getLangOpts().CPlusPlus20 && 
OCE2.06k
&&
7936
27.8k
            
OCE->getOperator() == OO_Equal2.06k
&&
MD->isTrivial()198
&&
7937
27.8k
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)54
)
7938
0
          return false;
7939
7940
27.8k
        Args = Args.slice(1);
7941
679k
      } else if (MD && 
MD->isLambdaStaticInvoker()332k
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
43
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
43
        assert(
7948
43
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
43
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
43
        const CXXMethodDecl *LambdaCallOp =
7952
43
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
43
        if (ClosureClass->isGenericLambda()) {
7959
15
          assert(MD->isFunctionTemplateSpecialization() &&
7960
15
                 "A generic lambda's static-invoker function must be a "
7961
15
                 "template specialization");
7962
15
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
15
          FunctionTemplateDecl *CallOpTemplate =
7964
15
              LambdaCallOp->getDescribedFunctionTemplate();
7965
15
          void *InsertPos = nullptr;
7966
15
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
15
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
15
          assert(CorrespondingCallOpSpecialization &&
7969
15
                 "We must always have a function call operator specialization "
7970
15
                 "that corresponds to our static invoker specialization");
7971
15
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
15
        } else
7973
28
          FD = LambdaCallOp;
7974
679k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
191
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
191
            
FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New49
) {
7977
168
          LValue Ptr;
7978
168
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
137
            return false;
7980
31
          Ptr.moveInto(Result);
7981
31
          return CallScope.destroy();
7982
168
        } else {
7983
23
          return HandleOperatorDeleteCall(Info, E) && 
CallScope.destroy()13
;
7984
23
        }
7985
191
      }
7986
718k
    } else
7987
123
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
759k
    if (!Call) {
7991
759k
      Call = Info.CurrentCall->createCall(FD);
7992
759k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
279k
        return false;
7994
759k
    }
7995
7996
480k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
480k
    if (This) {
7998
71.8k
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
71.8k
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier429
) {
8000
        // Perform virtual dispatch, if necessary.
8001
408
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
408
                                   CovariantAdjustmentPath);
8003
408
        if (!FD)
8004
191
          return false;
8005
71.4k
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
71.4k
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
628
          return false;
8011
71.4k
      }
8012
71.8k
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
479k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
37
      assert(This && "no 'this' pointer for destructor call");
8017
37
      return HandleDestruction(Info, E, *This,
8018
37
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
37
             CallScope.destroy();
8020
37
    }
8021
8022
479k
    const FunctionDecl *Definition = nullptr;
8023
479k
    Stmt *Body = FD->getBody(Definition);
8024
8025
479k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
479k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
378k
                            Body, Info, Result, ResultSlot))
8028
129k
      return false;
8029
8030
350k
    if (!CovariantAdjustmentPath.empty() &&
8031
350k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
28
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
350k
    return CallScope.destroy();
8036
350k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
54
                     const LValue *ResultSlot) {
7839
54
    CallScopeRAII CallScope(Info);
7840
7841
54
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
54
    QualType CalleeType = Callee->getType();
7843
7844
54
    const FunctionDecl *FD = nullptr;
7845
54
    LValue *This = nullptr, ThisVal;
7846
54
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
54
    bool HasQualifier = false;
7848
7849
54
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
54
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
30
      const CXXMethodDecl *Member = nullptr;
7854
30
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
30
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
2
          return false;
7858
28
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
28
        if (!Member)
7860
0
          return Error(Callee);
7861
28
        This = &ThisVal;
7862
28
        HasQualifier = ME->hasQualifier();
7863
28
      } else 
if (const BinaryOperator *0
BE0
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
0
        const ValueDecl *D =
7866
0
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
0
        if (!D)
7868
0
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
28
      FD = Member;
7881
28
    } else 
if (24
CalleeType->isFunctionPointerType()24
) {
7882
24
      LValue CalleeLV;
7883
24
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
0
        return false;
7885
7886
24
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
24
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
24
      FD = dyn_cast_or_null<FunctionDecl>(
7894
24
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
24
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
24
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
24
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
24
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
24
      if (OCE && 
OCE->isAssignmentOp()0
) {
7908
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
0
        Call = Info.CurrentCall->createCall(FD);
7910
0
        bool HasThis = false;
7911
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
0
          HasThis = MD->isImplicitObjectMemberFunction();
7913
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7914
0
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
0
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
24
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
24
      if (MD && 
MD->isImplicitObjectMemberFunction()0
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
0
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
0
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
0
          return false;
7930
0
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
0
        if (Info.getLangOpts().CPlusPlus20 && OCE &&
7936
0
            OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7937
0
            !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7938
0
          return false;
7939
7940
0
        Args = Args.slice(1);
7941
24
      } else if (MD && 
MD->isLambdaStaticInvoker()0
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
0
        assert(
7948
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
0
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
0
        const CXXMethodDecl *LambdaCallOp =
7952
0
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
0
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
0
          FD = LambdaCallOp;
7974
24
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
24
    } else
7987
0
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
52
    if (!Call) {
7991
52
      Call = Info.CurrentCall->createCall(FD);
7992
52
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
0
        return false;
7994
52
    }
7995
7996
52
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
52
    if (This) {
7998
28
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
28
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier0
) {
8000
        // Perform virtual dispatch, if necessary.
8001
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
0
                                   CovariantAdjustmentPath);
8003
0
        if (!FD)
8004
0
          return false;
8005
28
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
28
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
0
          return false;
8011
28
      }
8012
28
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
52
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
52
    const FunctionDecl *Definition = nullptr;
8023
52
    Stmt *Body = FD->getBody(Definition);
8024
8025
52
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
52
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
3
                            Body, Info, Result, ResultSlot))
8028
49
      return false;
8029
8030
3
    if (!CovariantAdjustmentPath.empty() &&
8031
3
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
3
    return CallScope.destroy();
8036
3
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
53.6k
                     const LValue *ResultSlot) {
7839
53.6k
    CallScopeRAII CallScope(Info);
7840
7841
53.6k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
53.6k
    QualType CalleeType = Callee->getType();
7843
7844
53.6k
    const FunctionDecl *FD = nullptr;
7845
53.6k
    LValue *This = nullptr, ThisVal;
7846
53.6k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
53.6k
    bool HasQualifier = false;
7848
7849
53.6k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
53.6k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
29.6k
      const CXXMethodDecl *Member = nullptr;
7854
29.6k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
29.6k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
25.9k
          return false;
7858
3.64k
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
3.64k
        if (!Member)
7860
0
          return Error(Callee);
7861
3.64k
        This = &ThisVal;
7862
3.64k
        HasQualifier = ME->hasQualifier();
7863
3.64k
      } else 
if (const BinaryOperator *60
BE60
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
60
        const ValueDecl *D =
7866
60
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
60
        if (!D)
7868
60
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
3.64k
      FD = Member;
7881
24.0k
    } else if (CalleeType->isFunctionPointerType()) {
7882
23.9k
      LValue CalleeLV;
7883
23.9k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
336
        return false;
7885
7886
23.6k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
23.6k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
23.6k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
23.6k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
23.6k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
23.6k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
23.6k
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
23.6k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
23.6k
      if (OCE && 
OCE->isAssignmentOp()16.9k
) {
7908
537
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
537
        Call = Info.CurrentCall->createCall(FD);
7910
537
        bool HasThis = false;
7911
537
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
407
          HasThis = MD->isImplicitObjectMemberFunction();
7913
537
        if (!EvaluateArgs(HasThis ? 
Args.slice(1)407
:
Args130
, Call, Info, FD,
7914
537
                          /*RightToLeft=*/true))
7915
115
          return false;
7916
537
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
23.5k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
23.5k
      if (MD && 
MD->isImplicitObjectMemberFunction()16.8k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
16.5k
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
16.5k
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
3.34k
          return false;
7930
13.2k
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
13.2k
        if (Info.getLangOpts().CPlusPlus20 && 
OCE709
&&
7936
13.2k
            
OCE->getOperator() == OO_Equal709
&&
MD->isTrivial()198
&&
7937
13.2k
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)54
)
7938
0
          return false;
7939
7940
13.2k
        Args = Args.slice(1);
7941
13.2k
      } else 
if (6.97k
MD6.97k
&&
MD->isLambdaStaticInvoker()256
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
0
        assert(
7948
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
0
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
0
        const CXXMethodDecl *LambdaCallOp =
7952
0
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
0
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
0
          FD = LambdaCallOp;
7974
6.97k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
23.5k
    } else
7987
4
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
23.8k
    if (!Call) {
7991
23.4k
      Call = Info.CurrentCall->createCall(FD);
7992
23.4k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
6.80k
        return false;
7994
23.4k
    }
7995
7996
17.0k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
17.0k
    if (This) {
7998
11.4k
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
11.4k
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier0
) {
8000
        // Perform virtual dispatch, if necessary.
8001
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
0
                                   CovariantAdjustmentPath);
8003
0
        if (!FD)
8004
0
          return false;
8005
11.4k
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
11.4k
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
29
          return false;
8011
11.4k
      }
8012
11.4k
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
17.0k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
17.0k
    const FunctionDecl *Definition = nullptr;
8023
17.0k
    Stmt *Body = FD->getBody(Definition);
8024
8025
17.0k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
17.0k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
3.89k
                            Body, Info, Result, ResultSlot))
8028
13.5k
      return false;
8029
8030
3.45k
    if (!CovariantAdjustmentPath.empty() &&
8031
3.45k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
3.45k
    return CallScope.destroy();
8036
3.45k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
16.3k
                     const LValue *ResultSlot) {
7839
16.3k
    CallScopeRAII CallScope(Info);
7840
7841
16.3k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
16.3k
    QualType CalleeType = Callee->getType();
7843
7844
16.3k
    const FunctionDecl *FD = nullptr;
7845
16.3k
    LValue *This = nullptr, ThisVal;
7846
16.3k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
16.3k
    bool HasQualifier = false;
7848
7849
16.3k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
16.3k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
1.16k
      const CXXMethodDecl *Member = nullptr;
7854
1.16k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
1.16k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
896
          return false;
7858
265
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
265
        if (!Member)
7860
0
          return Error(Callee);
7861
265
        This = &ThisVal;
7862
265
        HasQualifier = ME->hasQualifier();
7863
265
      } else 
if (const BinaryOperator *0
BE0
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
0
        const ValueDecl *D =
7866
0
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
0
        if (!D)
7868
0
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
265
      FD = Member;
7881
15.1k
    } else if (CalleeType->isFunctionPointerType()) {
7882
15.1k
      LValue CalleeLV;
7883
15.1k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
5.74k
        return false;
7885
7886
9.41k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
9.41k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
9.41k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
9.41k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
9.41k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
9.41k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
9.41k
        CalleeType->getPointeeType(), FD->getType())) {
7901
7
        return Error(E);
7902
7
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
9.41k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
9.41k
      if (OCE && 
OCE->isAssignmentOp()73
) {
7908
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
0
        Call = Info.CurrentCall->createCall(FD);
7910
0
        bool HasThis = false;
7911
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
0
          HasThis = MD->isImplicitObjectMemberFunction();
7913
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7914
0
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
0
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
9.41k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
9.41k
      if (MD && 
MD->isImplicitObjectMemberFunction()3.22k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
71
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
71
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
18
          return false;
7930
53
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
53
        if (Info.getLangOpts().CPlusPlus20 && 
OCE19
&&
7936
53
            
OCE->getOperator() == OO_Equal19
&&
MD->isTrivial()0
&&
7937
53
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)0
)
7938
0
          return false;
7939
7940
53
        Args = Args.slice(1);
7941
9.34k
      } else if (MD && 
MD->isLambdaStaticInvoker()3.15k
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
3
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
3
        assert(
7948
3
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
3
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
3
        const CXXMethodDecl *LambdaCallOp =
7952
3
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
3
        if (ClosureClass->isGenericLambda()) {
7959
3
          assert(MD->isFunctionTemplateSpecialization() &&
7960
3
                 "A generic lambda's static-invoker function must be a "
7961
3
                 "template specialization");
7962
3
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
3
          FunctionTemplateDecl *CallOpTemplate =
7964
3
              LambdaCallOp->getDescribedFunctionTemplate();
7965
3
          void *InsertPos = nullptr;
7966
3
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
3
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
3
          assert(CorrespondingCallOpSpecialization &&
7969
3
                 "We must always have a function call operator specialization "
7970
3
                 "that corresponds to our static invoker specialization");
7971
3
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
3
        } else
7973
0
          FD = LambdaCallOp;
7974
9.33k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
9.41k
    } else
7987
0
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
9.65k
    if (!Call) {
7991
9.65k
      Call = Info.CurrentCall->createCall(FD);
7992
9.65k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
5.84k
        return false;
7994
9.65k
    }
7995
7996
3.81k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
3.81k
    if (This) {
7998
291
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
291
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier12
) {
8000
        // Perform virtual dispatch, if necessary.
8001
12
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
12
                                   CovariantAdjustmentPath);
8003
12
        if (!FD)
8004
12
          return false;
8005
279
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
279
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
1
          return false;
8011
279
      }
8012
291
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
3.80k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
3.80k
    const FunctionDecl *Definition = nullptr;
8023
3.80k
    Stmt *Body = FD->getBody(Definition);
8024
8025
3.80k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
3.80k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
3.33k
                            Body, Info, Result, ResultSlot))
8028
2.07k
      return false;
8029
8030
1.73k
    if (!CovariantAdjustmentPath.empty() &&
8031
1.73k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
1.73k
    return CallScope.destroy();
8036
1.73k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
295
                     const LValue *ResultSlot) {
7839
295
    CallScopeRAII CallScope(Info);
7840
7841
295
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
295
    QualType CalleeType = Callee->getType();
7843
7844
295
    const FunctionDecl *FD = nullptr;
7845
295
    LValue *This = nullptr, ThisVal;
7846
295
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
295
    bool HasQualifier = false;
7848
7849
295
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
295
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
0
      const CXXMethodDecl *Member = nullptr;
7854
0
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
0
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
0
          return false;
7858
0
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
0
        if (!Member)
7860
0
          return Error(Callee);
7861
0
        This = &ThisVal;
7862
0
        HasQualifier = ME->hasQualifier();
7863
0
      } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
0
        const ValueDecl *D =
7866
0
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
0
        if (!D)
7868
0
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
0
      FD = Member;
7881
295
    } else if (CalleeType->isFunctionPointerType()) {
7882
295
      LValue CalleeLV;
7883
295
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
140
        return false;
7885
7886
155
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
155
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
155
      FD = dyn_cast_or_null<FunctionDecl>(
7894
155
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
155
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
155
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
155
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
155
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
155
      if (OCE && 
OCE->isAssignmentOp()0
) {
7908
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
0
        Call = Info.CurrentCall->createCall(FD);
7910
0
        bool HasThis = false;
7911
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
0
          HasThis = MD->isImplicitObjectMemberFunction();
7913
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7914
0
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
0
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
155
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
155
      if (MD && 
MD->isImplicitObjectMemberFunction()0
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
0
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
0
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
0
          return false;
7930
0
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
0
        if (Info.getLangOpts().CPlusPlus20 && OCE &&
7936
0
            OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7937
0
            !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7938
0
          return false;
7939
7940
0
        Args = Args.slice(1);
7941
155
      } else if (MD && 
MD->isLambdaStaticInvoker()0
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
0
        assert(
7948
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
0
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
0
        const CXXMethodDecl *LambdaCallOp =
7952
0
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
0
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
0
          FD = LambdaCallOp;
7974
155
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
155
    } else
7987
0
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
155
    if (!Call) {
7991
155
      Call = Info.CurrentCall->createCall(FD);
7992
155
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
132
        return false;
7994
155
    }
7995
7996
23
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
23
    if (This) {
7998
0
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
0
      if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8000
        // Perform virtual dispatch, if necessary.
8001
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
0
                                   CovariantAdjustmentPath);
8003
0
        if (!FD)
8004
0
          return false;
8005
0
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
0
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
0
          return false;
8011
0
      }
8012
0
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
23
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
23
    const FunctionDecl *Definition = nullptr;
8023
23
    Stmt *Body = FD->getBody(Definition);
8024
8025
23
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
23
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
4
                            Body, Info, Result, ResultSlot))
8028
19
      return false;
8029
8030
4
    if (!CovariantAdjustmentPath.empty() &&
8031
4
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
4
    return CallScope.destroy();
8036
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
15.0k
                     const LValue *ResultSlot) {
7839
15.0k
    CallScopeRAII CallScope(Info);
7840
7841
15.0k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
15.0k
    QualType CalleeType = Callee->getType();
7843
7844
15.0k
    const FunctionDecl *FD = nullptr;
7845
15.0k
    LValue *This = nullptr, ThisVal;
7846
15.0k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
15.0k
    bool HasQualifier = false;
7848
7849
15.0k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
15.0k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
1.04k
      const CXXMethodDecl *Member = nullptr;
7854
1.04k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
1.04k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
657
          return false;
7858
389
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
389
        if (!Member)
7860
0
          return Error(Callee);
7861
389
        This = &ThisVal;
7862
389
        HasQualifier = ME->hasQualifier();
7863
389
      } else 
if (const BinaryOperator *1
BE1
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
1
        const ValueDecl *D =
7866
1
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
1
        if (!D)
7868
1
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
389
      FD = Member;
7881
13.9k
    } else if (CalleeType->isFunctionPointerType()) {
7882
13.9k
      LValue CalleeLV;
7883
13.9k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
21
        return false;
7885
7886
13.9k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
13.9k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
13.9k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
13.9k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
13.9k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
13.9k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
13.9k
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
13.9k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
13.9k
      if (OCE && 
OCE->isAssignmentOp()3.62k
) {
7908
27
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
27
        Call = Info.CurrentCall->createCall(FD);
7910
27
        bool HasThis = false;
7911
27
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
25
          HasThis = MD->isImplicitObjectMemberFunction();
7913
27
        if (!EvaluateArgs(HasThis ? 
Args.slice(1)25
:
Args2
, Call, Info, FD,
7914
27
                          /*RightToLeft=*/true))
7915
2
          return false;
7916
27
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
13.9k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
13.9k
      if (MD && 
MD->isImplicitObjectMemberFunction()4.89k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
1.15k
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
1.15k
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
230
          return false;
7930
928
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
928
        if (Info.getLangOpts().CPlusPlus20 && 
OCE341
&&
7936
928
            
OCE->getOperator() == OO_Equal341
&&
MD->isTrivial()0
&&
7937
928
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)0
)
7938
0
          return false;
7939
7940
928
        Args = Args.slice(1);
7941
12.8k
      } else if (MD && 
MD->isLambdaStaticInvoker()3.73k
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
4
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
4
        assert(
7948
4
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
4
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
4
        const CXXMethodDecl *LambdaCallOp =
7952
4
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
4
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
4
          FD = LambdaCallOp;
7974
12.8k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
13.9k
    } else
7987
2
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
14.1k
    if (!Call) {
7991
14.0k
      Call = Info.CurrentCall->createCall(FD);
7992
14.0k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
5.55k
        return false;
7994
14.0k
    }
7995
7996
8.56k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
8.56k
    if (This) {
7998
984
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
984
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier0
) {
8000
        // Perform virtual dispatch, if necessary.
8001
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
0
                                   CovariantAdjustmentPath);
8003
0
        if (!FD)
8004
0
          return false;
8005
984
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
984
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
19
          return false;
8011
984
      }
8012
984
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
8.54k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
8.54k
    const FunctionDecl *Definition = nullptr;
8023
8.54k
    Stmt *Body = FD->getBody(Definition);
8024
8025
8.54k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
8.54k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
7.18k
                            Body, Info, Result, ResultSlot))
8028
1.73k
      return false;
8029
8030
6.81k
    if (!CovariantAdjustmentPath.empty() &&
8031
6.81k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
6.81k
    return CallScope.destroy();
8036
6.81k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
347k
                     const LValue *ResultSlot) {
7839
347k
    CallScopeRAII CallScope(Info);
7840
7841
347k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
347k
    QualType CalleeType = Callee->getType();
7843
7844
347k
    const FunctionDecl *FD = nullptr;
7845
347k
    LValue *This = nullptr, ThisVal;
7846
347k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
347k
    bool HasQualifier = false;
7848
7849
347k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
347k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
492
      const CXXMethodDecl *Member = nullptr;
7854
492
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
492
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
0
          return false;
7858
492
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
492
        if (!Member)
7860
0
          return Error(Callee);
7861
492
        This = &ThisVal;
7862
492
        HasQualifier = ME->hasQualifier();
7863
492
      } else 
if (const BinaryOperator *0
BE0
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
0
        const ValueDecl *D =
7866
0
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
0
        if (!D)
7868
0
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
492
      FD = Member;
7881
347k
    } else if (CalleeType->isFunctionPointerType()) {
7882
347k
      LValue CalleeLV;
7883
347k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
212k
        return false;
7885
7886
134k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
134k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
134k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
134k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
134k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
134k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
134k
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
134k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
134k
      if (OCE && 
OCE->isAssignmentOp()0
) {
7908
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
0
        Call = Info.CurrentCall->createCall(FD);
7910
0
        bool HasThis = false;
7911
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
0
          HasThis = MD->isImplicitObjectMemberFunction();
7913
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7914
0
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
0
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
134k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
134k
      if (MD && 
MD->isImplicitObjectMemberFunction()0
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
0
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
0
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
0
          return false;
7930
0
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
0
        if (Info.getLangOpts().CPlusPlus20 && OCE &&
7936
0
            OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7937
0
            !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7938
0
          return false;
7939
7940
0
        Args = Args.slice(1);
7941
134k
      } else if (MD && 
MD->isLambdaStaticInvoker()0
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
0
        assert(
7948
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
0
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
0
        const CXXMethodDecl *LambdaCallOp =
7952
0
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
0
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
0
          FD = LambdaCallOp;
7974
134k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
134k
    } else
7987
0
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
135k
    if (!Call) {
7991
135k
      Call = Info.CurrentCall->createCall(FD);
7992
135k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
118k
        return false;
7994
135k
    }
7995
7996
17.1k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
17.1k
    if (This) {
7998
492
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
492
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier0
) {
8000
        // Perform virtual dispatch, if necessary.
8001
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
0
                                   CovariantAdjustmentPath);
8003
0
        if (!FD)
8004
0
          return false;
8005
492
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
492
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
0
          return false;
8011
492
      }
8012
492
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
17.1k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
17.1k
    const FunctionDecl *Definition = nullptr;
8023
17.1k
    Stmt *Body = FD->getBody(Definition);
8024
8025
17.1k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
17.1k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
61
                            Body, Info, Result, ResultSlot))
8028
17.0k
      return false;
8029
8030
59
    if (!CovariantAdjustmentPath.empty() &&
8031
59
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
59
    return CallScope.destroy();
8036
59
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
650k
                     const LValue *ResultSlot) {
7839
650k
    CallScopeRAII CallScope(Info);
7840
7841
650k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
650k
    QualType CalleeType = Callee->getType();
7843
7844
650k
    const FunctionDecl *FD = nullptr;
7845
650k
    LValue *This = nullptr, ThisVal;
7846
650k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
650k
    bool HasQualifier = false;
7848
7849
650k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
650k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
86.8k
      const CXXMethodDecl *Member = nullptr;
7854
86.8k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
86.6k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
45.0k
          return false;
7858
41.6k
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
41.6k
        if (!Member)
7860
0
          return Error(Callee);
7861
41.6k
        This = &ThisVal;
7862
41.6k
        HasQualifier = ME->hasQualifier();
7863
41.6k
      } else 
if (const BinaryOperator *136
BE136
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
136
        const ValueDecl *D =
7866
136
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
136
        if (!D)
7868
62
          return false;
7869
74
        Member = dyn_cast<CXXMethodDecl>(D);
7870
74
        if (!Member)
7871
0
          return Error(Callee);
7872
74
        This = &ThisVal;
7873
74
      } else 
if (const auto *0
PDE0
= dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
41.7k
      FD = Member;
7881
563k
    } else if (CalleeType->isFunctionPointerType()) {
7882
563k
      LValue CalleeLV;
7883
563k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
54.9k
        return false;
7885
7886
508k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
508k
      if (CalleeLV.isNullPointer()) {
7889
6
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
6
            << const_cast<Expr *>(Callee);
7891
6
        return false;
7892
6
      }
7893
508k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
508k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
508k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
508k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
508k
        CalleeType->getPointeeType(), FD->getType())) {
7901
63
        return Error(E);
7902
63
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
508k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
508k
      if (OCE && 
OCE->isAssignmentOp()42.3k
) {
7908
70
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
70
        Call = Info.CurrentCall->createCall(FD);
7910
70
        bool HasThis = false;
7911
70
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
70
          HasThis = MD->isImplicitObjectMemberFunction();
7913
70
        if (!EvaluateArgs(HasThis ? Args.slice(1) : 
Args0
, Call, Info, FD,
7914
70
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
70
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
508k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
508k
      if (MD && 
MD->isImplicitObjectMemberFunction()340k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
20.1k
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
20.1k
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
6.98k
          return false;
7930
13.1k
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
13.1k
        if (Info.getLangOpts().CPlusPlus20 && 
OCE840
&&
7936
13.1k
            
OCE->getOperator() == OO_Equal840
&&
MD->isTrivial()0
&&
7937
13.1k
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)0
)
7938
0
          return false;
7939
7940
13.1k
        Args = Args.slice(1);
7941
488k
      } else if (MD && 
MD->isLambdaStaticInvoker()320k
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
33
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
33
        assert(
7948
33
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
33
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
33
        const CXXMethodDecl *LambdaCallOp =
7952
33
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
33
        if (ClosureClass->isGenericLambda()) {
7959
9
          assert(MD->isFunctionTemplateSpecialization() &&
7960
9
                 "A generic lambda's static-invoker function must be a "
7961
9
                 "template specialization");
7962
9
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
9
          FunctionTemplateDecl *CallOpTemplate =
7964
9
              LambdaCallOp->getDescribedFunctionTemplate();
7965
9
          void *InsertPos = nullptr;
7966
9
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
9
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
9
          assert(CorrespondingCallOpSpecialization &&
7969
9
                 "We must always have a function call operator specialization "
7970
9
                 "that corresponds to our static invoker specialization");
7971
9
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
9
        } else
7973
24
          FD = LambdaCallOp;
7974
488k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
0
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
0
      }
7986
508k
    } else
7987
89
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
543k
    if (!Call) {
7991
543k
      Call = Info.CurrentCall->createCall(FD);
7992
543k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
129k
        return false;
7994
543k
    }
7995
7996
414k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
414k
    if (This) {
7998
52.2k
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
52.2k
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier356
) {
8000
        // Perform virtual dispatch, if necessary.
8001
336
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
336
                                   CovariantAdjustmentPath);
8003
336
        if (!FD)
8004
156
          return false;
8005
51.9k
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
51.9k
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
552
          return false;
8011
51.9k
      }
8012
52.2k
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
413k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
413k
    const FunctionDecl *Definition = nullptr;
8023
413k
    Stmt *Body = FD->getBody(Definition);
8024
8025
413k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
413k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
358k
                            Body, Info, Result, ResultSlot))
8028
79.9k
      return false;
8029
8030
333k
    if (!CovariantAdjustmentPath.empty() &&
8031
333k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
333k
    return CallScope.destroy();
8036
333k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
6.72k
                     const LValue *ResultSlot) {
7839
6.72k
    CallScopeRAII CallScope(Info);
7840
7841
6.72k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
6.72k
    QualType CalleeType = Callee->getType();
7843
7844
6.72k
    const FunctionDecl *FD = nullptr;
7845
6.72k
    LValue *This = nullptr, ThisVal;
7846
6.72k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
6.72k
    bool HasQualifier = false;
7848
7849
6.72k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
6.72k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
448
      const CXXMethodDecl *Member = nullptr;
7854
448
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
408
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
48
          return false;
7858
360
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
360
        if (!Member)
7860
0
          return Error(Callee);
7861
360
        This = &ThisVal;
7862
360
        HasQualifier = ME->hasQualifier();
7863
360
      } else 
if (const BinaryOperator *40
BE40
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
10
        const ValueDecl *D =
7866
10
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
10
        if (!D)
7868
10
          return false;
7869
0
        Member = dyn_cast<CXXMethodDecl>(D);
7870
0
        if (!Member)
7871
0
          return Error(Callee);
7872
0
        This = &ThisVal;
7873
30
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
30
        if (!Info.getLangOpts().CPlusPlus20)
7875
11
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
30
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
30
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
30
      } else
7879
0
        return Error(Callee);
7880
360
      FD = Member;
7881
6.27k
    } else if (CalleeType->isFunctionPointerType()) {
7882
6.27k
      LValue CalleeLV;
7883
6.27k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
3.99k
        return false;
7885
7886
2.27k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
2.27k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
2.27k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
2.27k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
2.27k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
2.27k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
2.27k
        CalleeType->getPointeeType(), FD->getType())) {
7901
0
        return Error(E);
7902
0
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
2.27k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
2.27k
      if (OCE && 
OCE->isAssignmentOp()141
) {
7908
67
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
67
        Call = Info.CurrentCall->createCall(FD);
7910
67
        bool HasThis = false;
7911
67
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
66
          HasThis = MD->isImplicitObjectMemberFunction();
7913
67
        if (!EvaluateArgs(HasThis ? 
Args.slice(1)66
:
Args1
, Call, Info, FD,
7914
67
                          /*RightToLeft=*/true))
7915
8
          return false;
7916
67
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
2.27k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
2.27k
      if (MD && 
MD->isImplicitObjectMemberFunction()188
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
129
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
129
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
7
          return false;
7930
122
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
122
        if (Info.getLangOpts().CPlusPlus20 && 
OCE98
&&
7936
122
            
OCE->getOperator() == OO_Equal98
&&
MD->isTrivial()0
&&
7937
122
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)0
)
7938
0
          return false;
7939
7940
122
        Args = Args.slice(1);
7941
2.14k
      } else if (MD && 
MD->isLambdaStaticInvoker()59
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
0
        assert(
7948
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
0
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
0
        const CXXMethodDecl *LambdaCallOp =
7952
0
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
0
        if (ClosureClass->isGenericLambda()) {
7959
0
          assert(MD->isFunctionTemplateSpecialization() &&
7960
0
                 "A generic lambda's static-invoker function must be a "
7961
0
                 "template specialization");
7962
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
0
          FunctionTemplateDecl *CallOpTemplate =
7964
0
              LambdaCallOp->getDescribedFunctionTemplate();
7965
0
          void *InsertPos = nullptr;
7966
0
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
0
          assert(CorrespondingCallOpSpecialization &&
7969
0
                 "We must always have a function call operator specialization "
7970
0
                 "that corresponds to our static invoker specialization");
7971
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
0
        } else
7973
0
          FD = LambdaCallOp;
7974
2.14k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
23
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
23
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7977
0
          LValue Ptr;
7978
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
0
            return false;
7980
0
          Ptr.moveInto(Result);
7981
0
          return CallScope.destroy();
7982
23
        } else {
7983
23
          return HandleOperatorDeleteCall(Info, E) && 
CallScope.destroy()13
;
7984
23
        }
7985
23
      }
7986
2.27k
    } else
7987
2
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
2.60k
    if (!Call) {
7991
2.54k
      Call = Info.CurrentCall->createCall(FD);
7992
2.54k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
260
        return false;
7994
2.54k
    }
7995
7996
2.34k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
2.34k
    if (This) {
7998
458
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
458
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier27
) {
8000
        // Perform virtual dispatch, if necessary.
8001
26
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
26
                                   CovariantAdjustmentPath);
8003
26
        if (!FD)
8004
23
          return false;
8005
432
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
432
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
19
          return false;
8011
432
      }
8012
458
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
2.29k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
37
      assert(This && "no 'this' pointer for destructor call");
8017
37
      return HandleDestruction(Info, E, *This,
8018
37
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
37
             CallScope.destroy();
8020
37
    }
8021
8022
2.26k
    const FunctionDecl *Definition = nullptr;
8023
2.26k
    Stmt *Body = FD->getBody(Definition);
8024
8025
2.26k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
2.26k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
1.70k
                            Body, Info, Result, ResultSlot))
8028
681
      return false;
8029
8030
1.58k
    if (!CovariantAdjustmentPath.empty() &&
8031
1.58k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
0
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
1.58k
    return CallScope.destroy();
8036
1.58k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Line
Count
Source
7838
40.5k
                     const LValue *ResultSlot) {
7839
40.5k
    CallScopeRAII CallScope(Info);
7840
7841
40.5k
    const Expr *Callee = E->getCallee()->IgnoreParens();
7842
40.5k
    QualType CalleeType = Callee->getType();
7843
7844
40.5k
    const FunctionDecl *FD = nullptr;
7845
40.5k
    LValue *This = nullptr, ThisVal;
7846
40.5k
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7847
40.5k
    bool HasQualifier = false;
7848
7849
40.5k
    CallRef Call;
7850
7851
    // Extract function decl and 'this' pointer from the callee.
7852
40.5k
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7853
13.3k
      const CXXMethodDecl *Member = nullptr;
7854
13.3k
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7855
        // Explicit bound member calls, such as x.f() or p->g();
7856
13.3k
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7857
7.86k
          return false;
7858
5.50k
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7859
5.50k
        if (!Member)
7860
0
          return Error(Callee);
7861
5.50k
        This = &ThisVal;
7862
5.50k
        HasQualifier = ME->hasQualifier();
7863
5.50k
      } else 
if (const BinaryOperator *4
BE4
= dyn_cast<BinaryOperator>(Callee)) {
7864
        // Indirect bound member calls ('.*' or '->*').
7865
4
        const ValueDecl *D =
7866
4
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7867
4
        if (!D)
7868
1
          return false;
7869
3
        Member = dyn_cast<CXXMethodDecl>(D);
7870
3
        if (!Member)
7871
0
          return Error(Callee);
7872
3
        This = &ThisVal;
7873
3
      } else 
if (const auto *0
PDE0
= dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7874
0
        if (!Info.getLangOpts().CPlusPlus20)
7875
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7876
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7877
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7878
0
      } else
7879
0
        return Error(Callee);
7880
5.50k
      FD = Member;
7881
27.1k
    } else if (CalleeType->isFunctionPointerType()) {
7882
27.1k
      LValue CalleeLV;
7883
27.1k
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7884
1.10k
        return false;
7885
7886
26.0k
      if (!CalleeLV.getLValueOffset().isZero())
7887
0
        return Error(Callee);
7888
26.0k
      if (CalleeLV.isNullPointer()) {
7889
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7890
0
            << const_cast<Expr *>(Callee);
7891
0
        return false;
7892
0
      }
7893
26.0k
      FD = dyn_cast_or_null<FunctionDecl>(
7894
26.0k
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7895
26.0k
      if (!FD)
7896
0
        return Error(Callee);
7897
      // Don't call function pointers which have been cast to some other type.
7898
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7899
26.0k
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7900
26.0k
        CalleeType->getPointeeType(), FD->getType())) {
7901
7
        return Error(E);
7902
7
      }
7903
7904
      // For an (overloaded) assignment expression, evaluate the RHS before the
7905
      // LHS.
7906
26.0k
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7907
26.0k
      if (OCE && 
OCE->isAssignmentOp()665
) {
7908
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7909
0
        Call = Info.CurrentCall->createCall(FD);
7910
0
        bool HasThis = false;
7911
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7912
0
          HasThis = MD->isImplicitObjectMemberFunction();
7913
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7914
0
                          /*RightToLeft=*/true))
7915
0
          return false;
7916
0
      }
7917
7918
      // Overloaded operator calls to member functions are represented as normal
7919
      // calls with '*this' as the first argument.
7920
26.0k
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7921
26.0k
      if (MD && 
MD->isImplicitObjectMemberFunction()4.92k
) {
7922
        // FIXME: When selecting an implicit conversion for an overloaded
7923
        // operator delete, we sometimes try to evaluate calls to conversion
7924
        // operators without a 'this' parameter!
7925
605
        if (Args.empty())
7926
0
          return Error(E);
7927
7928
605
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7929
245
          return false;
7930
360
        This = &ThisVal;
7931
7932
        // If this is syntactically a simple assignment using a trivial
7933
        // assignment operator, start the lifetimes of union members as needed,
7934
        // per C++20 [class.union]5.
7935
360
        if (Info.getLangOpts().CPlusPlus20 && 
OCE54
&&
7936
360
            
OCE->getOperator() == OO_Equal54
&&
MD->isTrivial()0
&&
7937
360
            
!MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)0
)
7938
0
          return false;
7939
7940
360
        Args = Args.slice(1);
7941
25.3k
      } else if (MD && 
MD->isLambdaStaticInvoker()4.31k
) {
7942
        // Map the static invoker for the lambda back to the call operator.
7943
        // Conveniently, we don't have to slice out the 'this' argument (as is
7944
        // being done for the non-static case), since a static member function
7945
        // doesn't have an implicit argument passed in.
7946
3
        const CXXRecordDecl *ClosureClass = MD->getParent();
7947
3
        assert(
7948
3
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7949
3
            "Number of captures must be zero for conversion to function-ptr");
7950
7951
3
        const CXXMethodDecl *LambdaCallOp =
7952
3
            ClosureClass->getLambdaCallOperator();
7953
7954
        // Set 'FD', the function that will be called below, to the call
7955
        // operator.  If the closure object represents a generic lambda, find
7956
        // the corresponding specialization of the call operator.
7957
7958
3
        if (ClosureClass->isGenericLambda()) {
7959
3
          assert(MD->isFunctionTemplateSpecialization() &&
7960
3
                 "A generic lambda's static-invoker function must be a "
7961
3
                 "template specialization");
7962
3
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7963
3
          FunctionTemplateDecl *CallOpTemplate =
7964
3
              LambdaCallOp->getDescribedFunctionTemplate();
7965
3
          void *InsertPos = nullptr;
7966
3
          FunctionDecl *CorrespondingCallOpSpecialization =
7967
3
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7968
3
          assert(CorrespondingCallOpSpecialization &&
7969
3
                 "We must always have a function call operator specialization "
7970
3
                 "that corresponds to our static invoker specialization");
7971
3
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7972
3
        } else
7973
0
          FD = LambdaCallOp;
7974
25.3k
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
7975
168
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7976
168
            
FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New26
) {
7977
168
          LValue Ptr;
7978
168
          if (!HandleOperatorNewCall(Info, E, Ptr))
7979
137
            return false;
7980
31
          Ptr.moveInto(Result);
7981
31
          return CallScope.destroy();
7982
168
        } else {
7983
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7984
0
        }
7985
168
      }
7986
26.0k
    } else
7987
26
      return Error(E);
7988
7989
    // Evaluate the arguments now if we've not already done so.
7990
31.0k
    if (!Call) {
7991
31.0k
      Call = Info.CurrentCall->createCall(FD);
7992
31.0k
      if (!EvaluateArgs(Args, Call, Info, FD))
7993
13.3k
        return false;
7994
31.0k
    }
7995
7996
17.7k
    SmallVector<QualType, 4> CovariantAdjustmentPath;
7997
17.7k
    if (This) {
7998
5.84k
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7999
5.84k
      if (NamedMember && NamedMember->isVirtual() && 
!HasQualifier34
) {
8000
        // Perform virtual dispatch, if necessary.
8001
34
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8002
34
                                   CovariantAdjustmentPath);
8003
34
        if (!FD)
8004
0
          return false;
8005
5.80k
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8006
        // Check that the 'this' pointer points to an object of the right type.
8007
        // FIXME: If this is an assignment operator call, we may need to change
8008
        // the active union member before we check this.
8009
5.80k
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8010
8
          return false;
8011
5.80k
      }
8012
5.84k
    }
8013
8014
    // Destructor calls are different enough that they have their own codepath.
8015
17.7k
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8016
0
      assert(This && "no 'this' pointer for destructor call");
8017
0
      return HandleDestruction(Info, E, *This,
8018
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8019
0
             CallScope.destroy();
8020
0
    }
8021
8022
17.7k
    const FunctionDecl *Definition = nullptr;
8023
17.7k
    Stmt *Body = FD->getBody(Definition);
8024
8025
17.7k
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8026
17.7k
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8027
3.72k
                            Body, Info, Result, ResultSlot))
8028
14.6k
      return false;
8029
8030
3.09k
    if (!CovariantAdjustmentPath.empty() &&
8031
3.09k
        !HandleCovariantReturnAdjustment(Info, E, Result,
8032
28
                                         CovariantAdjustmentPath))
8033
0
      return false;
8034
8035
3.09k
    return CallScope.destroy();
8036
3.09k
  }
8037
8038
3.29k
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
3.29k
    return StmtVisitorTy::Visit(E->getInitializer());
8040
3.29k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Line
Count
Source
8038
34
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
34
    return StmtVisitorTy::Visit(E->getInitializer());
8040
34
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Line
Count
Source
8038
55
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
55
    return StmtVisitorTy::Visit(E->getInitializer());
8040
55
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Line
Count
Source
8038
3.15k
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
3.15k
    return StmtVisitorTy::Visit(E->getInitializer());
8040
3.15k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Line
Count
Source
8038
43
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
43
    return StmtVisitorTy::Visit(E->getInitializer());
8040
43
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Line
Count
Source
8038
7
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8039
7
    return StmtVisitorTy::Visit(E->getInitializer());
8040
7
  }
8041
3.56k
  bool VisitInitListExpr(const InitListExpr *E) {
8042
3.56k
    if (E->getNumInits() == 0)
8043
559
      return DerivedZeroInitialization(E);
8044
3.00k
    if (E->getNumInits() == 1)
8045
3.00k
      return StmtVisitorTy::Visit(E->getInit(0));
8046
1
    return Error(E);
8047
3.00k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
4
  bool VisitInitListExpr(const InitListExpr *E) {
8042
4
    if (E->getNumInits() == 0)
8043
2
      return DerivedZeroInitialization(E);
8044
2
    if (E->getNumInits() == 1)
8045
2
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
2
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
54
  bool VisitInitListExpr(const InitListExpr *E) {
8042
54
    if (E->getNumInits() == 0)
8043
0
      return DerivedZeroInitialization(E);
8044
54
    if (E->getNumInits() == 1)
8045
54
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
54
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
36
  bool VisitInitListExpr(const InitListExpr *E) {
8042
36
    if (E->getNumInits() == 0)
8043
26
      return DerivedZeroInitialization(E);
8044
10
    if (E->getNumInits() == 1)
8045
10
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
10
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
12
  bool VisitInitListExpr(const InitListExpr *E) {
8042
12
    if (E->getNumInits() == 0)
8043
4
      return DerivedZeroInitialization(E);
8044
8
    if (E->getNumInits() == 1)
8045
8
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
8
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
6
  bool VisitInitListExpr(const InitListExpr *E) {
8042
6
    if (E->getNumInits() == 0)
8043
0
      return DerivedZeroInitialization(E);
8044
6
    if (E->getNumInits() == 1)
8045
6
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
6
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
3.31k
  bool VisitInitListExpr(const InitListExpr *E) {
8042
3.31k
    if (E->getNumInits() == 0)
8043
439
      return DerivedZeroInitialization(E);
8044
2.87k
    if (E->getNumInits() == 1)
8045
2.87k
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
2.87k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
7
  bool VisitInitListExpr(const InitListExpr *E) {
8042
7
    if (E->getNumInits() == 0)
8043
0
      return DerivedZeroInitialization(E);
8044
7
    if (E->getNumInits() == 1)
8045
6
      return StmtVisitorTy::Visit(E->getInit(0));
8046
1
    return Error(E);
8047
7
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Line
Count
Source
8041
131
  bool VisitInitListExpr(const InitListExpr *E) {
8042
131
    if (E->getNumInits() == 0)
8043
88
      return DerivedZeroInitialization(E);
8044
43
    if (E->getNumInits() == 1)
8045
43
      return StmtVisitorTy::Visit(E->getInit(0));
8046
0
    return Error(E);
8047
43
  }
8048
5.24k
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
5.24k
    return DerivedZeroInitialization(E);
8050
5.24k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
12
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
12
    return DerivedZeroInitialization(E);
8050
12
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
169
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
169
    return DerivedZeroInitialization(E);
8050
169
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
6
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
6
    return DerivedZeroInitialization(E);
8050
6
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
488
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
488
    return DerivedZeroInitialization(E);
8050
488
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
371
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
371
    return DerivedZeroInitialization(E);
8050
371
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
7
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
7
    return DerivedZeroInitialization(E);
8050
7
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
3
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
3
    return DerivedZeroInitialization(E);
8050
3
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
3.96k
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
3.96k
    return DerivedZeroInitialization(E);
8050
3.96k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Line
Count
Source
8048
219
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8049
219
    return DerivedZeroInitialization(E);
8050
219
  }
8051
4.13k
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
4.13k
    return DerivedZeroInitialization(E);
8053
4.13k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
18
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
18
    return DerivedZeroInitialization(E);
8053
18
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
50
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
50
    return DerivedZeroInitialization(E);
8053
50
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
3
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
3
    return DerivedZeroInitialization(E);
8053
3
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
1
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
1
    return DerivedZeroInitialization(E);
8053
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
7
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
7
    return DerivedZeroInitialization(E);
8053
7
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
2.90k
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
2.90k
    return DerivedZeroInitialization(E);
8053
2.90k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
90
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
90
    return DerivedZeroInitialization(E);
8053
90
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Line
Count
Source
8051
1.06k
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8052
1.06k
    return DerivedZeroInitialization(E);
8053
1.06k
  }
8054
10.2k
  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8055
10.2k
    return DerivedZeroInitialization(E);
8056
10.2k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
Line
Count
Source
8054
10.2k
  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8055
10.2k
    return DerivedZeroInitialization(E);
8056
10.2k
  }
8057
8058
  /// A member expression where the object is a prvalue is itself a prvalue.
8059
180
  bool VisitMemberExpr(const MemberExpr *E) {
8060
180
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
180
           "missing temporary materialization conversion");
8062
180
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
180
    APValue Val;
8065
180
    if (!Evaluate(Val, Info, E->getBase()))
8066
117
      return false;
8067
8068
63
    QualType BaseTy = E->getBase()->getType();
8069
8070
63
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
63
    if (!FD) 
return Error(E)0
;
8072
63
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
63
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
63
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
63
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
63
    SubobjectDesignator Designator(BaseTy);
8081
63
    Designator.addDeclUnchecked(FD);
8082
8083
63
    APValue Result;
8084
63
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
63
           DerivedSuccess(Result, E);
8086
63
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
1
  bool VisitMemberExpr(const MemberExpr *E) {
8060
1
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
1
           "missing temporary materialization conversion");
8062
1
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
1
    APValue Val;
8065
1
    if (!Evaluate(Val, Info, E->getBase()))
8066
0
      return false;
8067
8068
1
    QualType BaseTy = E->getBase()->getType();
8069
8070
1
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
1
    if (!FD) 
return Error(E)0
;
8072
1
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
1
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
1
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
1
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
1
    SubobjectDesignator Designator(BaseTy);
8081
1
    Designator.addDeclUnchecked(FD);
8082
8083
1
    APValue Result;
8084
1
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
1
           DerivedSuccess(Result, E);
8086
1
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
1
  bool VisitMemberExpr(const MemberExpr *E) {
8060
1
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
1
           "missing temporary materialization conversion");
8062
1
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
1
    APValue Val;
8065
1
    if (!Evaluate(Val, Info, E->getBase()))
8066
1
      return false;
8067
8068
0
    QualType BaseTy = E->getBase()->getType();
8069
8070
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
0
    if (!FD) return Error(E);
8072
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
0
    SubobjectDesignator Designator(BaseTy);
8081
0
    Designator.addDeclUnchecked(FD);
8082
8083
0
    APValue Result;
8084
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
0
           DerivedSuccess(Result, E);
8086
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
3
  bool VisitMemberExpr(const MemberExpr *E) {
8060
3
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
3
           "missing temporary materialization conversion");
8062
3
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
3
    APValue Val;
8065
3
    if (!Evaluate(Val, Info, E->getBase()))
8066
3
      return false;
8067
8068
0
    QualType BaseTy = E->getBase()->getType();
8069
8070
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
0
    if (!FD) return Error(E);
8072
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
0
    SubobjectDesignator Designator(BaseTy);
8081
0
    Designator.addDeclUnchecked(FD);
8082
8083
0
    APValue Result;
8084
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
0
           DerivedSuccess(Result, E);
8086
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
7
  bool VisitMemberExpr(const MemberExpr *E) {
8060
7
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
7
           "missing temporary materialization conversion");
8062
7
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
7
    APValue Val;
8065
7
    if (!Evaluate(Val, Info, E->getBase()))
8066
7
      return false;
8067
8068
0
    QualType BaseTy = E->getBase()->getType();
8069
8070
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
0
    if (!FD) return Error(E);
8072
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
0
    SubobjectDesignator Designator(BaseTy);
8081
0
    Designator.addDeclUnchecked(FD);
8082
8083
0
    APValue Result;
8084
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
0
           DerivedSuccess(Result, E);
8086
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
6
  bool VisitMemberExpr(const MemberExpr *E) {
8060
6
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
6
           "missing temporary materialization conversion");
8062
6
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
6
    APValue Val;
8065
6
    if (!Evaluate(Val, Info, E->getBase()))
8066
6
      return false;
8067
8068
0
    QualType BaseTy = E->getBase()->getType();
8069
8070
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
0
    if (!FD) return Error(E);
8072
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
0
    SubobjectDesignator Designator(BaseTy);
8081
0
    Designator.addDeclUnchecked(FD);
8082
8083
0
    APValue Result;
8084
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
0
           DerivedSuccess(Result, E);
8086
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
152
  bool VisitMemberExpr(const MemberExpr *E) {
8060
152
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
152
           "missing temporary materialization conversion");
8062
152
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
152
    APValue Val;
8065
152
    if (!Evaluate(Val, Info, E->getBase()))
8066
90
      return false;
8067
8068
62
    QualType BaseTy = E->getBase()->getType();
8069
8070
62
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
62
    if (!FD) 
return Error(E)0
;
8072
62
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
62
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
62
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
62
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
62
    SubobjectDesignator Designator(BaseTy);
8081
62
    Designator.addDeclUnchecked(FD);
8082
8083
62
    APValue Result;
8084
62
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
62
           DerivedSuccess(Result, E);
8086
62
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8059
10
  bool VisitMemberExpr(const MemberExpr *E) {
8060
10
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8061
10
           "missing temporary materialization conversion");
8062
10
    assert(!E->isArrow() && "missing call to bound member function?");
8063
8064
10
    APValue Val;
8065
10
    if (!Evaluate(Val, Info, E->getBase()))
8066
10
      return false;
8067
8068
0
    QualType BaseTy = E->getBase()->getType();
8069
8070
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8071
0
    if (!FD) return Error(E);
8072
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8073
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8074
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8075
8076
    // Note: there is no lvalue base here. But this case should only ever
8077
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8078
    // constructor, which is the only case the base matters.
8079
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8080
0
    SubobjectDesignator Designator(BaseTy);
8081
0
    Designator.addDeclUnchecked(FD);
8082
8083
0
    APValue Result;
8084
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8085
0
           DerivedSuccess(Result, E);
8086
0
  }
8087
8088
370
  bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8089
370
    APValue Val;
8090
370
    if (!Evaluate(Val, Info, E->getBase()))
8091
93
      return false;
8092
8093
277
    if (Val.isVector()) {
8094
11
      SmallVector<uint32_t, 4> Indices;
8095
11
      E->getEncodedElementAccess(Indices);
8096
11
      if (Indices.size() == 1) {
8097
        // Return scalar.
8098
10
        return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8099
10
      } else {
8100
        // Construct new APValue vector.
8101
1
        SmallVector<APValue, 4> Elts;
8102
3
        for (unsigned I = 0; I < Indices.size(); 
++I2
) {
8103
2
          Elts.push_back(Val.getVectorElt(Indices[I]));
8104
2
        }
8105
1
        APValue VecResult(Elts.data(), Indices.size());
8106
1
        return DerivedSuccess(VecResult, E);
8107
1
      }
8108
11
    }
8109
8110
266
    return false;
8111
277
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Line
Count
Source
8088
342
  bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8089
342
    APValue Val;
8090
342
    if (!Evaluate(Val, Info, E->getBase()))
8091
87
      return false;
8092
8093
255
    if (Val.isVector()) {
8094
0
      SmallVector<uint32_t, 4> Indices;
8095
0
      E->getEncodedElementAccess(Indices);
8096
0
      if (Indices.size() == 1) {
8097
        // Return scalar.
8098
0
        return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8099
0
      } else {
8100
        // Construct new APValue vector.
8101
0
        SmallVector<APValue, 4> Elts;
8102
0
        for (unsigned I = 0; I < Indices.size(); ++I) {
8103
0
          Elts.push_back(Val.getVectorElt(Indices[I]));
8104
0
        }
8105
0
        APValue VecResult(Elts.data(), Indices.size());
8106
0
        return DerivedSuccess(VecResult, E);
8107
0
      }
8108
0
    }
8109
8110
255
    return false;
8111
255
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Line
Count
Source
8088
12
  bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8089
12
    APValue Val;
8090
12
    if (!Evaluate(Val, Info, E->getBase()))
8091
0
      return false;
8092
8093
12
    if (Val.isVector()) {
8094
1
      SmallVector<uint32_t, 4> Indices;
8095
1
      E->getEncodedElementAccess(Indices);
8096
1
      if (Indices.size() == 1) {
8097
        // Return scalar.
8098
0
        return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8099
1
      } else {
8100
        // Construct new APValue vector.
8101
1
        SmallVector<APValue, 4> Elts;
8102
3
        for (unsigned I = 0; I < Indices.size(); 
++I2
) {
8103
2
          Elts.push_back(Val.getVectorElt(Indices[I]));
8104
2
        }
8105
1
        APValue VecResult(Elts.data(), Indices.size());
8106
1
        return DerivedSuccess(VecResult, E);
8107
1
      }
8108
1
    }
8109
8110
11
    return false;
8111
12
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Line
Count
Source
8088
16
  bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8089
16
    APValue Val;
8090
16
    if (!Evaluate(Val, Info, E->getBase()))
8091
6
      return false;
8092
8093
10
    if (Val.isVector()) {
8094
10
      SmallVector<uint32_t, 4> Indices;
8095
10
      E->getEncodedElementAccess(Indices);
8096
10
      if (Indices.size() == 1) {
8097
        // Return scalar.
8098
10
        return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8099
10
      } else {
8100
        // Construct new APValue vector.
8101
0
        SmallVector<APValue, 4> Elts;
8102
0
        for (unsigned I = 0; I < Indices.size(); ++I) {
8103
0
          Elts.push_back(Val.getVectorElt(Indices[I]));
8104
0
        }
8105
0
        APValue VecResult(Elts.data(), Indices.size());
8106
0
        return DerivedSuccess(VecResult, E);
8107
0
      }
8108
10
    }
8109
8110
0
    return false;
8111
10
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
8112
8113
8.97M
  bool VisitCastExpr(const CastExpr *E) {
8114
8.97M
    switch (E->getCastKind()) {
8115
279k
    default:
8116
279k
      break;
8117
8118
279k
    case CK_AtomicToNonAtomic: {
8119
338
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
338
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
304
        return false;
8125
34
      return DerivedSuccess(AtomicVal, E);
8126
338
    }
8127
8128
527k
    case CK_NoOp:
8129
533k
    case CK_UserDefinedConversion:
8130
533k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
8.16M
    case CK_LValueToRValue: {
8133
8.16M
      LValue LVal;
8134
8.16M
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
378k
        return false;
8136
7.78M
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
7.78M
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
7.78M
                                          LVal, RVal))
8140
5.34M
        return false;
8141
2.44M
      return DerivedSuccess(RVal, E);
8142
7.78M
    }
8143
576
    case CK_LValueToRValueBitCast: {
8144
576
      APValue DestValue, SourceValue;
8145
576
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
25
        return false;
8147
551
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
206
        return false;
8149
345
      return DerivedSuccess(DestValue, E);
8150
551
    }
8151
8152
25
    case CK_AddressSpaceConversion: {
8153
25
      APValue Value;
8154
25
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
4
        return false;
8156
21
      return DerivedSuccess(Value, E);
8157
25
    }
8158
8.97M
    }
8159
8160
279k
    return Error(E);
8161
8.97M
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
1.23k
  bool VisitCastExpr(const CastExpr *E) {
8114
1.23k
    switch (E->getCastKind()) {
8115
53
    default:
8116
53
      break;
8117
8118
53
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
193
    case CK_NoOp:
8129
223
    case CK_UserDefinedConversion:
8130
223
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
959
    case CK_LValueToRValue: {
8133
959
      LValue LVal;
8134
959
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
74
        return false;
8136
885
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
885
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
885
                                          LVal, RVal))
8140
623
        return false;
8141
262
      return DerivedSuccess(RVal, E);
8142
885
    }
8143
0
    case CK_LValueToRValueBitCast: {
8144
0
      APValue DestValue, SourceValue;
8145
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
1.23k
    }
8159
8160
53
    return Error(E);
8161
1.23k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
89.8k
  bool VisitCastExpr(const CastExpr *E) {
8114
89.8k
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
12
    case CK_AtomicToNonAtomic: {
8119
12
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
12
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
12
      return DerivedSuccess(AtomicVal, E);
8126
12
    }
8127
8128
89.3k
    case CK_NoOp:
8129
89.8k
    case CK_UserDefinedConversion:
8130
89.8k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
0
    case CK_LValueToRValue: {
8133
0
      LValue LVal;
8134
0
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
0
        return false;
8136
0
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
0
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
0
                                          LVal, RVal))
8140
0
        return false;
8141
0
      return DerivedSuccess(RVal, E);
8142
0
    }
8143
0
    case CK_LValueToRValueBitCast: {
8144
0
      APValue DestValue, SourceValue;
8145
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
25
    case CK_AddressSpaceConversion: {
8153
25
      APValue Value;
8154
25
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
4
        return false;
8156
21
      return DerivedSuccess(Value, E);
8157
25
    }
8158
89.8k
    }
8159
8160
0
    return Error(E);
8161
89.8k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
111
  bool VisitCastExpr(const CastExpr *E) {
8114
111
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
0
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
2
    case CK_NoOp:
8129
2
    case CK_UserDefinedConversion:
8130
2
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
109
    case CK_LValueToRValue: {
8133
109
      LValue LVal;
8134
109
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
0
        return false;
8136
109
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
109
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
109
                                          LVal, RVal))
8140
109
        return false;
8141
0
      return DerivedSuccess(RVal, E);
8142
109
    }
8143
0
    case CK_LValueToRValueBitCast: {
8144
0
      APValue DestValue, SourceValue;
8145
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
111
    }
8159
8160
0
    return Error(E);
8161
111
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
152k
  bool VisitCastExpr(const CastExpr *E) {
8114
152k
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
18
    case CK_AtomicToNonAtomic: {
8119
18
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
18
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
9
        return false;
8125
9
      return DerivedSuccess(AtomicVal, E);
8126
18
    }
8127
8128
3.39k
    case CK_NoOp:
8129
3.53k
    case CK_UserDefinedConversion:
8130
3.53k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
148k
    case CK_LValueToRValue: {
8133
148k
      LValue LVal;
8134
148k
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
18.1k
        return false;
8136
130k
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
130k
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
130k
                                          LVal, RVal))
8140
121k
        return false;
8141
8.42k
      return DerivedSuccess(RVal, E);
8142
130k
    }
8143
82
    case CK_LValueToRValueBitCast: {
8144
82
      APValue DestValue, SourceValue;
8145
82
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
10
        return false;
8147
72
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
59
        return false;
8149
13
      return DerivedSuccess(DestValue, E);
8150
72
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
152k
    }
8159
8160
0
    return Error(E);
8161
152k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
1.78k
  bool VisitCastExpr(const CastExpr *E) {
8114
1.78k
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
0
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
3
    case CK_NoOp:
8129
3
    case CK_UserDefinedConversion:
8130
3
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
1.78k
    case CK_LValueToRValue: {
8133
1.78k
      LValue LVal;
8134
1.78k
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
37
        return false;
8136
1.74k
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
1.74k
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
1.74k
                                          LVal, RVal))
8140
1.71k
        return false;
8141
35
      return DerivedSuccess(RVal, E);
8142
1.74k
    }
8143
1
    case CK_LValueToRValueBitCast: {
8144
1
      APValue DestValue, SourceValue;
8145
1
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
1
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
1.78k
    }
8159
8160
0
    return Error(E);
8161
1.78k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
10.6k
  bool VisitCastExpr(const CastExpr *E) {
8114
10.6k
    switch (E->getCastKind()) {
8115
6
    default:
8116
6
      break;
8117
8118
6
    case CK_AtomicToNonAtomic: {
8119
5
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
5
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
5
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
5
    }
8127
8128
7.43k
    case CK_NoOp:
8129
7.59k
    case CK_UserDefinedConversion:
8130
7.59k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
2.85k
    case CK_LValueToRValue: {
8133
2.85k
      LValue LVal;
8134
2.85k
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
36
        return false;
8136
2.82k
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
2.82k
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
2.82k
                                          LVal, RVal))
8140
2.32k
        return false;
8141
492
      return DerivedSuccess(RVal, E);
8142
2.82k
    }
8143
183
    case CK_LValueToRValueBitCast: {
8144
183
      APValue DestValue, SourceValue;
8145
183
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
3
        return false;
8147
180
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
33
        return false;
8149
147
      return DerivedSuccess(DestValue, E);
8150
180
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
10.6k
    }
8159
8160
6
    return Error(E);
8161
10.6k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
16
  bool VisitCastExpr(const CastExpr *E) {
8114
16
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
0
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
1
    case CK_NoOp:
8129
1
    case CK_UserDefinedConversion:
8130
1
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
0
    case CK_LValueToRValue: {
8133
0
      LValue LVal;
8134
0
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
0
        return false;
8136
0
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
0
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
0
                                          LVal, RVal))
8140
0
        return false;
8141
0
      return DerivedSuccess(RVal, E);
8142
0
    }
8143
15
    case CK_LValueToRValueBitCast: {
8144
15
      APValue DestValue, SourceValue;
8145
15
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
15
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
5
        return false;
8149
10
      return DerivedSuccess(DestValue, E);
8150
15
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
16
    }
8159
8160
0
    return Error(E);
8161
16
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
317
  bool VisitCastExpr(const CastExpr *E) {
8114
317
    switch (E->getCastKind()) {
8115
4
    default:
8116
4
      break;
8117
8118
4
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
0
    case CK_NoOp:
8129
0
    case CK_UserDefinedConversion:
8130
0
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
313
    case CK_LValueToRValue: {
8133
313
      LValue LVal;
8134
313
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
22
        return false;
8136
291
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
291
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
291
                                          LVal, RVal))
8140
270
        return false;
8141
21
      return DerivedSuccess(RVal, E);
8142
291
    }
8143
0
    case CK_LValueToRValueBitCast: {
8144
0
      APValue DestValue, SourceValue;
8145
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
317
    }
8159
8160
4
    return Error(E);
8161
317
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
683k
  bool VisitCastExpr(const CastExpr *E) {
8114
683k
    switch (E->getCastKind()) {
8115
359
    default:
8116
359
      break;
8117
8118
359
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
54.0k
    case CK_NoOp:
8129
54.5k
    case CK_UserDefinedConversion:
8130
54.5k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
628k
    case CK_LValueToRValue: {
8133
628k
      LValue LVal;
8134
628k
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
2.20k
        return false;
8136
626k
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
626k
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
626k
                                          LVal, RVal))
8140
626k
        return false;
8141
650
      return DerivedSuccess(RVal, E);
8142
626k
    }
8143
32
    case CK_LValueToRValueBitCast: {
8144
32
      APValue DestValue, SourceValue;
8145
32
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
32
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
8
        return false;
8149
24
      return DerivedSuccess(DestValue, E);
8150
32
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
683k
    }
8159
8160
359
    return Error(E);
8161
683k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
7.72M
  bool VisitCastExpr(const CastExpr *E) {
8114
7.72M
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
290
    case CK_AtomicToNonAtomic: {
8119
290
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
290
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
277
        return false;
8125
13
      return DerivedSuccess(AtomicVal, E);
8126
290
    }
8127
8128
341k
    case CK_NoOp:
8129
345k
    case CK_UserDefinedConversion:
8130
345k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
7.38M
    case CK_LValueToRValue: {
8133
7.38M
      LValue LVal;
8134
7.38M
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
358k
        return false;
8136
7.02M
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
7.02M
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
7.02M
                                          LVal, RVal))
8140
4.59M
        return false;
8141
2.43M
      return DerivedSuccess(RVal, E);
8142
7.02M
    }
8143
245
    case CK_LValueToRValueBitCast: {
8144
245
      APValue DestValue, SourceValue;
8145
245
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
11
        return false;
8147
234
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
95
        return false;
8149
139
      return DerivedSuccess(DestValue, E);
8150
234
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
7.72M
    }
8159
8160
0
    return Error(E);
8161
7.72M
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
6
  bool VisitCastExpr(const CastExpr *E) {
8114
6
    switch (E->getCastKind()) {
8115
0
    default:
8116
0
      break;
8117
8118
0
    case CK_AtomicToNonAtomic: {
8119
0
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
0
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
0
    }
8127
8128
6
    case CK_NoOp:
8129
6
    case CK_UserDefinedConversion:
8130
6
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
0
    case CK_LValueToRValue: {
8133
0
      LValue LVal;
8134
0
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
0
        return false;
8136
0
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
0
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
0
                                          LVal, RVal))
8140
0
        return false;
8141
0
      return DerivedSuccess(RVal, E);
8142
0
    }
8143
0
    case CK_LValueToRValueBitCast: {
8144
0
      APValue DestValue, SourceValue;
8145
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
0
        return false;
8149
0
      return DerivedSuccess(DestValue, E);
8150
0
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
6
    }
8159
8160
0
    return Error(E);
8161
6
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8113
311k
  bool VisitCastExpr(const CastExpr *E) {
8114
311k
    switch (E->getCastKind()) {
8115
279k
    default:
8116
279k
      break;
8117
8118
279k
    case CK_AtomicToNonAtomic: {
8119
13
      APValue AtomicVal;
8120
      // This does not need to be done in place even for class/array types:
8121
      // atomic-to-non-atomic conversion implies copying the object
8122
      // representation.
8123
13
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8124
13
        return false;
8125
0
      return DerivedSuccess(AtomicVal, E);
8126
13
    }
8127
8128
32.2k
    case CK_NoOp:
8129
32.6k
    case CK_UserDefinedConversion:
8130
32.6k
      return StmtVisitorTy::Visit(E->getSubExpr());
8131
8132
0
    case CK_LValueToRValue: {
8133
0
      LValue LVal;
8134
0
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8135
0
        return false;
8136
0
      APValue RVal;
8137
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138
0
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8139
0
                                          LVal, RVal))
8140
0
        return false;
8141
0
      return DerivedSuccess(RVal, E);
8142
0
    }
8143
18
    case CK_LValueToRValueBitCast: {
8144
18
      APValue DestValue, SourceValue;
8145
18
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8146
0
        return false;
8147
18
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8148
6
        return false;
8149
12
      return DerivedSuccess(DestValue, E);
8150
18
    }
8151
8152
0
    case CK_AddressSpaceConversion: {
8153
0
      APValue Value;
8154
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8155
0
        return false;
8156
0
      return DerivedSuccess(Value, E);
8157
0
    }
8158
311k
    }
8159
8160
279k
    return Error(E);
8161
311k
  }
8162
8163
82.9k
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
82.9k
    return VisitUnaryPostIncDec(UO);
8165
82.9k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
24
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
24
    return VisitUnaryPostIncDec(UO);
8165
24
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
1.16k
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
1.16k
    return VisitUnaryPostIncDec(UO);
8165
1.16k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
3
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
3
    return VisitUnaryPostIncDec(UO);
8165
3
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
53
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
53
    return VisitUnaryPostIncDec(UO);
8165
53
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
71.4k
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
71.4k
    return VisitUnaryPostIncDec(UO);
8165
71.4k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Line
Count
Source
8163
10.2k
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8164
10.2k
    return VisitUnaryPostIncDec(UO);
8165
10.2k
  }
8166
1.11k
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
1.11k
    return VisitUnaryPostIncDec(UO);
8168
1.11k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
24
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
24
    return VisitUnaryPostIncDec(UO);
8168
24
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
38
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
38
    return VisitUnaryPostIncDec(UO);
8168
38
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
2
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
2
    return VisitUnaryPostIncDec(UO);
8168
2
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
23
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
23
    return VisitUnaryPostIncDec(UO);
8168
23
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
929
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
929
    return VisitUnaryPostIncDec(UO);
8168
929
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Line
Count
Source
8166
95
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8167
95
    return VisitUnaryPostIncDec(UO);
8168
95
  }
8169
84.0k
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
84.0k
    if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()54.3k
)
8171
616
      return Error(UO);
8172
8173
83.4k
    LValue LVal;
8174
83.4k
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
7.68k
      return false;
8176
75.7k
    APValue RVal;
8177
75.7k
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
75.7k
                      UO->isIncrementOp(), &RVal))
8179
72.6k
      return false;
8180
3.15k
    return DerivedSuccess(RVal, UO);
8181
75.7k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
48
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
48
    if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8171
0
      return Error(UO);
8172
8173
48
    LValue LVal;
8174
48
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
0
      return false;
8176
48
    APValue RVal;
8177
48
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
48
                      UO->isIncrementOp(), &RVal))
8179
48
      return false;
8180
0
    return DerivedSuccess(RVal, UO);
8181
48
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
1.20k
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
1.20k
    if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()915
)
8171
21
      return Error(UO);
8172
8173
1.18k
    LValue LVal;
8174
1.18k
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
551
      return false;
8176
631
    APValue RVal;
8177
631
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
631
                      UO->isIncrementOp(), &RVal))
8179
617
      return false;
8180
14
    return DerivedSuccess(RVal, UO);
8181
631
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
5
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
5
    if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8171
0
      return Error(UO);
8172
8173
5
    LValue LVal;
8174
5
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
1
      return false;
8176
4
    APValue RVal;
8177
4
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
4
                      UO->isIncrementOp(), &RVal))
8179
4
      return false;
8180
0
    return DerivedSuccess(RVal, UO);
8181
4
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
76
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
76
    if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()68
)
8171
0
      return Error(UO);
8172
8173
76
    LValue LVal;
8174
76
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
0
      return false;
8176
76
    APValue RVal;
8177
76
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
76
                      UO->isIncrementOp(), &RVal))
8179
76
      return false;
8180
0
    return DerivedSuccess(RVal, UO);
8181
76
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
72.3k
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
72.3k
    if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()44.9k
)
8171
458
      return Error(UO);
8172
8173
71.9k
    LValue LVal;
8174
71.9k
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
1.32k
      return false;
8176
70.6k
    APValue RVal;
8177
70.6k
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
70.6k
                      UO->isIncrementOp(), &RVal))
8179
68.0k
      return false;
8180
2.50k
    return DerivedSuccess(RVal, UO);
8181
70.6k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Line
Count
Source
8169
10.3k
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8170
10.3k
    if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()8.39k
)
8171
137
      return Error(UO);
8172
8173
10.2k
    LValue LVal;
8174
10.2k
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8175
5.81k
      return false;
8176
4.41k
    APValue RVal;
8177
4.41k
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8178
4.41k
                      UO->isIncrementOp(), &RVal))
8179
3.78k
      return false;
8180
632
    return DerivedSuccess(RVal, UO);
8181
4.41k
  }
8182
8183
4.79k
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
4.79k
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
4.79k
                                          false);
8188
8189
4.79k
    const CompoundStmt *CS = E->getSubStmt();
8190
4.79k
    if (CS->body_empty())
8191
4
      return true;
8192
8193
4.79k
    BlockScopeRAII Scope(Info);
8194
4.79k
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
4.79k
                                           BE = CS->body_end();
8196
9.96k
         /**/; 
++BI5.16k
) {
8197
9.96k
      if (BI + 1 == BE) {
8198
956
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
956
        if (!FinalExpr) {
8200
29
          Info.FFDiag((*BI)->getBeginLoc(),
8201
29
                      diag::note_constexpr_stmt_expr_unsupported);
8202
29
          return false;
8203
29
        }
8204
927
        return this->Visit(FinalExpr) && 
Scope.destroy()96
;
8205
956
      }
8206
8207
9.00k
      APValue ReturnValue;
8208
9.00k
      StmtResult Result = { ReturnValue, nullptr };
8209
9.00k
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
9.00k
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
3.83k
        if (ESR != ESR_Failed)
8215
5
          Info.FFDiag((*BI)->getBeginLoc(),
8216
5
                      diag::note_constexpr_stmt_expr_unsupported);
8217
3.83k
        return false;
8218
3.83k
      }
8219
9.00k
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
396
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
396
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
396
                                          false);
8188
8189
396
    const CompoundStmt *CS = E->getSubStmt();
8190
396
    if (CS->body_empty())
8191
0
      return true;
8192
8193
396
    BlockScopeRAII Scope(Info);
8194
396
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
396
                                           BE = CS->body_end();
8196
792
         /**/; 
++BI396
) {
8197
792
      if (BI + 1 == BE) {
8198
142
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
142
        if (!FinalExpr) {
8200
0
          Info.FFDiag((*BI)->getBeginLoc(),
8201
0
                      diag::note_constexpr_stmt_expr_unsupported);
8202
0
          return false;
8203
0
        }
8204
142
        return this->Visit(FinalExpr) && 
Scope.destroy()0
;
8205
142
      }
8206
8207
650
      APValue ReturnValue;
8208
650
      StmtResult Result = { ReturnValue, nullptr };
8209
650
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
650
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
254
        if (ESR != ESR_Failed)
8215
0
          Info.FFDiag((*BI)->getBeginLoc(),
8216
0
                      diag::note_constexpr_stmt_expr_unsupported);
8217
254
        return false;
8218
254
      }
8219
650
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
514
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
514
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
514
                                          false);
8188
8189
514
    const CompoundStmt *CS = E->getSubStmt();
8190
514
    if (CS->body_empty())
8191
0
      return true;
8192
8193
514
    BlockScopeRAII Scope(Info);
8194
514
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
514
                                           BE = CS->body_end();
8196
1.38k
         /**/; 
++BI867
) {
8197
1.38k
      if (BI + 1 == BE) {
8198
367
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
367
        if (!FinalExpr) {
8200
0
          Info.FFDiag((*BI)->getBeginLoc(),
8201
0
                      diag::note_constexpr_stmt_expr_unsupported);
8202
0
          return false;
8203
0
        }
8204
367
        return this->Visit(FinalExpr) && 
Scope.destroy()5
;
8205
367
      }
8206
8207
1.01k
      APValue ReturnValue;
8208
1.01k
      StmtResult Result = { ReturnValue, nullptr };
8209
1.01k
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
1.01k
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
147
        if (ESR != ESR_Failed)
8215
0
          Info.FFDiag((*BI)->getBeginLoc(),
8216
0
                      diag::note_constexpr_stmt_expr_unsupported);
8217
147
        return false;
8218
147
      }
8219
1.01k
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
3.24k
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
3.24k
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
3.24k
                                          false);
8188
8189
3.24k
    const CompoundStmt *CS = E->getSubStmt();
8190
3.24k
    if (CS->body_empty())
8191
0
      return true;
8192
8193
3.24k
    BlockScopeRAII Scope(Info);
8194
3.24k
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
3.24k
                                           BE = CS->body_end();
8196
6.62k
         /**/; 
++BI3.37k
) {
8197
6.62k
      if (BI + 1 == BE) {
8198
132
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
132
        if (!FinalExpr) {
8200
0
          Info.FFDiag((*BI)->getBeginLoc(),
8201
0
                      diag::note_constexpr_stmt_expr_unsupported);
8202
0
          return false;
8203
0
        }
8204
132
        return this->Visit(FinalExpr) && 
Scope.destroy()0
;
8205
132
      }
8206
8207
6.49k
      APValue ReturnValue;
8208
6.49k
      StmtResult Result = { ReturnValue, nullptr };
8209
6.49k
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
6.49k
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
3.11k
        if (ESR != ESR_Failed)
8215
0
          Info.FFDiag((*BI)->getBeginLoc(),
8216
0
                      diag::note_constexpr_stmt_expr_unsupported);
8217
3.11k
        return false;
8218
3.11k
      }
8219
6.49k
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
550
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
550
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
550
                                          false);
8188
8189
550
    const CompoundStmt *CS = E->getSubStmt();
8190
550
    if (CS->body_empty())
8191
0
      return true;
8192
8193
550
    BlockScopeRAII Scope(Info);
8194
550
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
550
                                           BE = CS->body_end();
8196
1.05k
         /**/; 
++BI501
) {
8197
1.05k
      if (BI + 1 == BE) {
8198
236
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
236
        if (!FinalExpr) {
8200
5
          Info.FFDiag((*BI)->getBeginLoc(),
8201
5
                      diag::note_constexpr_stmt_expr_unsupported);
8202
5
          return false;
8203
5
        }
8204
231
        return this->Visit(FinalExpr) && 
Scope.destroy()37
;
8205
236
      }
8206
8207
815
      APValue ReturnValue;
8208
815
      StmtResult Result = { ReturnValue, nullptr };
8209
815
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
815
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
314
        if (ESR != ESR_Failed)
8215
5
          Info.FFDiag((*BI)->getBeginLoc(),
8216
5
                      diag::note_constexpr_stmt_expr_unsupported);
8217
314
        return false;
8218
314
      }
8219
815
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
37
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
37
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
37
                                          false);
8188
8189
37
    const CompoundStmt *CS = E->getSubStmt();
8190
37
    if (CS->body_empty())
8191
4
      return true;
8192
8193
33
    BlockScopeRAII Scope(Info);
8194
33
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
33
                                           BE = CS->body_end();
8196
33
         /**/; 
++BI0
) {
8197
33
      if (BI + 1 == BE) {
8198
24
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
24
        if (!FinalExpr) {
8200
24
          Info.FFDiag((*BI)->getBeginLoc(),
8201
24
                      diag::note_constexpr_stmt_expr_unsupported);
8202
24
          return false;
8203
24
        }
8204
0
        return this->Visit(FinalExpr) && Scope.destroy();
8205
24
      }
8206
8207
9
      APValue ReturnValue;
8208
9
      StmtResult Result = { ReturnValue, nullptr };
8209
9
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
9
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
9
        if (ESR != ESR_Failed)
8215
0
          Info.FFDiag((*BI)->getBeginLoc(),
8216
0
                      diag::note_constexpr_stmt_expr_unsupported);
8217
9
        return false;
8218
9
      }
8219
9
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Line
Count
Source
8183
58
  bool VisitStmtExpr(const StmtExpr *E) {
8184
    // We will have checked the full-expressions inside the statement expression
8185
    // when they were completed, and don't need to check them again now.
8186
58
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8187
58
                                          false);
8188
8189
58
    const CompoundStmt *CS = E->getSubStmt();
8190
58
    if (CS->body_empty())
8191
0
      return true;
8192
8193
58
    BlockScopeRAII Scope(Info);
8194
58
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8195
58
                                           BE = CS->body_end();
8196
84
         /**/; 
++BI26
) {
8197
84
      if (BI + 1 == BE) {
8198
55
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8199
55
        if (!FinalExpr) {
8200
0
          Info.FFDiag((*BI)->getBeginLoc(),
8201
0
                      diag::note_constexpr_stmt_expr_unsupported);
8202
0
          return false;
8203
0
        }
8204
55
        return this->Visit(FinalExpr) && 
Scope.destroy()54
;
8205
55
      }
8206
8207
29
      APValue ReturnValue;
8208
29
      StmtResult Result = { ReturnValue, nullptr };
8209
29
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8210
29
      if (ESR != ESR_Succeeded) {
8211
        // FIXME: If the statement-expression terminated due to 'return',
8212
        // 'break', or 'continue', it would be nice to propagate that to
8213
        // the outer statement evaluation rather than bailing out.
8214
3
        if (ESR != ESR_Failed)
8215
0
          Info.FFDiag((*BI)->getBeginLoc(),
8216
0
                      diag::note_constexpr_stmt_expr_unsupported);
8217
3
        return false;
8218
3
      }
8219
29
    }
8220
8221
0
    llvm_unreachable("Return from function from the loop above.");
8222
0
  }
8223
8224
  /// Visit a value which is evaluated, but whose value is ignored.
8225
39.4k
  void VisitIgnoredValue(const Expr *E) {
8226
39.4k
    EvaluateIgnoredValue(Info, E);
8227
39.4k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
6.09k
  void VisitIgnoredValue(const Expr *E) {
8226
6.09k
    EvaluateIgnoredValue(Info, E);
8227
6.09k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
505
  void VisitIgnoredValue(const Expr *E) {
8226
505
    EvaluateIgnoredValue(Info, E);
8227
505
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
3
  void VisitIgnoredValue(const Expr *E) {
8226
3
    EvaluateIgnoredValue(Info, E);
8227
3
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
27
  void VisitIgnoredValue(const Expr *E) {
8226
27
    EvaluateIgnoredValue(Info, E);
8227
27
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
4
  void VisitIgnoredValue(const Expr *E) {
8226
4
    EvaluateIgnoredValue(Info, E);
8227
4
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
60
  void VisitIgnoredValue(const Expr *E) {
8226
60
    EvaluateIgnoredValue(Info, E);
8227
60
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
1
  void VisitIgnoredValue(const Expr *E) {
8226
1
    EvaluateIgnoredValue(Info, E);
8227
1
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
144
  void VisitIgnoredValue(const Expr *E) {
8226
144
    EvaluateIgnoredValue(Info, E);
8227
144
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
2.80k
  void VisitIgnoredValue(const Expr *E) {
8226
2.80k
    EvaluateIgnoredValue(Info, E);
8227
2.80k
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Line
Count
Source
8225
29.8k
  void VisitIgnoredValue(const Expr *E) {
8226
29.8k
    EvaluateIgnoredValue(Info, E);
8227
29.8k
  }
8228
8229
  /// Potentially visit a MemberExpr's base expression.
8230
929
  void VisitIgnoredBaseExpression(const Expr *E) {
8231
    // While MSVC doesn't evaluate the base expression, it does diagnose the
8232
    // presence of side-effecting behavior.
8233
929
    if (Info.getLangOpts().MSVCCompat && 
!E->HasSideEffects(Info.Ctx)7
)
8234
4
      return;
8235
925
    VisitIgnoredValue(E);
8236
925
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitIgnoredBaseExpression(clang::Expr const*)
Line
Count
Source
8230
820
  void VisitIgnoredBaseExpression(const Expr *E) {
8231
    // While MSVC doesn't evaluate the base expression, it does diagnose the
8232
    // presence of side-effecting behavior.
8233
820
    if (Info.getLangOpts().MSVCCompat && 
!E->HasSideEffects(Info.Ctx)1
)
8234
1
      return;
8235
819
    VisitIgnoredValue(E);
8236
819
  }
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitIgnoredBaseExpression(clang::Expr const*)
Line
Count
Source
8230
109
  void VisitIgnoredBaseExpression(const Expr *E) {
8231
    // While MSVC doesn't evaluate the base expression, it does diagnose the
8232
    // presence of side-effecting behavior.
8233
109
    if (Info.getLangOpts().MSVCCompat && 
!E->HasSideEffects(Info.Ctx)6
)
8234
3
      return;
8235
106
    VisitIgnoredValue(E);
8236
106
  }
8237
};
8238
8239
} // namespace
8240
8241
//===----------------------------------------------------------------------===//
8242
// Common base class for lvalue and temporary evaluation.
8243
//===----------------------------------------------------------------------===//
8244
namespace {
8245
template<class Derived>
8246
class LValueExprEvaluatorBase
8247
  : public ExprEvaluatorBase<Derived> {
8248
protected:
8249
  LValue &Result;
8250
  bool InvalidBaseOK;
8251
  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8252
  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8253
8254
12.2M
  bool Success(APValue::LValueBase B) {
8255
12.2M
    Result.set(B);
8256
12.2M
    return true;
8257
12.2M
  }
8258
8259
1.11M
  bool evaluatePointer(const Expr *E, LValue &Result) {
8260
1.11M
    return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8261
1.11M
  }
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::evaluatePointer(clang::Expr const*, (anonymous namespace)::LValue&)
Line
Count
Source
8259
1.11M
  bool evaluatePointer(const Expr *E, LValue &Result) {
8260
1.11M
    return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8261
1.11M
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::evaluatePointer(clang::Expr const*, (anonymous namespace)::LValue&)
8262
8263
public:
8264
  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8265
14.1M
      : ExprEvaluatorBaseTy(Info), Result(Result),
8266
14.1M
        InvalidBaseOK(InvalidBaseOK) {}
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::LValueExprEvaluatorBase((anonymous namespace)::EvalInfo&, (anonymous namespace)::LValue&, bool)
Line
Count
Source
8265
14.1M
      : ExprEvaluatorBaseTy(Info), Result(Result),
8266
14.1M
        InvalidBaseOK(InvalidBaseOK) {}
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::LValueExprEvaluatorBase((anonymous namespace)::EvalInfo&, (anonymous namespace)::LValue&, bool)
Line
Count
Source
8265
5
      : ExprEvaluatorBaseTy(Info), Result(Result),
8266
5
        InvalidBaseOK(InvalidBaseOK) {}
8267
8268
47.3k
  bool Success(const APValue &V, const Expr *E) {
8269
47.3k
    Result.setFrom(this->Info.Ctx, V);
8270
47.3k
    return true;
8271
47.3k
  }
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Success(clang::APValue const&, clang::Expr const*)
Line
Count
Source
8268
47.3k
  bool Success(const APValue &V, const Expr *E) {
8269
47.3k
    Result.setFrom(this->Info.Ctx, V);
8270
47.3k
    return true;
8271
47.3k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Success(clang::APValue const&, clang::Expr const*)
8272
8273
561k
  bool VisitMemberExpr(const MemberExpr *E) {
8274
    // Handle non-static data members.
8275
561k
    QualType BaseTy;
8276
561k
    bool EvalOK;
8277
561k
    if (E->isArrow()) {
8278
328k
      EvalOK = evaluatePointer(E->getBase(), Result);
8279
328k
      BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8280
328k
    } else 
if (232k
E->getBase()->isPRValue()232k
) {
8281
3
      assert(E->getBase()->getType()->isRecordType());
8282
3
      EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8283
3
      BaseTy = E->getBase()->getType();
8284
232k
    } else {
8285
232k
      EvalOK = this->Visit(E->getBase());
8286
232k
      BaseTy = E->getBase()->getType();
8287
232k
    }
8288
561k
    if (!EvalOK) {
8289
403k
      if (!InvalidBaseOK)
8290
402k
        return false;
8291
872
      Result.setInvalid(E);
8292
872
      return true;
8293
403k
    }
8294
8295
158k
    const ValueDecl *MD = E->getMemberDecl();
8296
158k
    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8297
158k
      assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8298
158k
             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8299
158k
      (void)BaseTy;
8300
158k
      if (!HandleLValueMember(this->Info, E, Result, FD))
8301
4
        return false;
8302
158k
    } else 
if (const IndirectFieldDecl *0
IFD0
= dyn_cast<IndirectFieldDecl>(MD)) {
8303
0
      if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8304
0
        return false;
8305
0
    } else
8306
0
      return this->Error(E);
8307
8308
158k
    if (MD->getType()->isReferenceType()) {
8309
501
      APValue RefValue;
8310
501
      if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8311
501
                                          RefValue))
8312
168
        return false;
8313
333
      return Success(RefValue, E);
8314
501
    }
8315
157k
    return true;
8316
158k
  }
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Line
Count
Source
8273
561k
  bool VisitMemberExpr(const MemberExpr *E) {
8274
    // Handle non-static data members.
8275
561k
    QualType BaseTy;
8276
561k
    bool EvalOK;
8277
561k
    if (E->isArrow()) {
8278
328k
      EvalOK = evaluatePointer(E->getBase(), Result);
8279
328k
      BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8280
328k
    } else 
if (232k
E->getBase()->isPRValue()232k
) {
8281
3
      assert(E->getBase()->getType()->isRecordType());
8282
3
      EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8283
3
      BaseTy = E->getBase()->getType();
8284
232k
    } else {
8285
232k
      EvalOK = this->Visit(E->getBase());
8286
232k
      BaseTy = E->getBase()->getType();
8287
232k
    }
8288
561k
    if (!EvalOK) {
8289
403k
      if (!InvalidBaseOK)
8290
402k
        return false;
8291
872
      Result.setInvalid(E);
8292
872
      return true;
8293
403k
    }
8294
8295
158k
    const ValueDecl *MD = E->getMemberDecl();
8296
158k
    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8297
158k
      assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8298
158k
             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8299
158k
      (void)BaseTy;
8300
158k
      if (!HandleLValueMember(this->Info, E, Result, FD))
8301
4
        return false;
8302
158k
    } else 
if (const IndirectFieldDecl *0
IFD0
= dyn_cast<IndirectFieldDecl>(MD)) {
8303
0
      if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8304
0
        return false;
8305
0
    } else
8306
0
      return this->Error(E);
8307
8308
158k
    if (MD->getType()->isReferenceType()) {
8309
501
      APValue RefValue;
8310
501
      if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8311
501
                                          RefValue))
8312
168
        return false;
8313
333
      return Success(RefValue, E);
8314
501
    }
8315
157k
    return true;
8316
158k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
8317
8318
5.81k
  bool VisitBinaryOperator(const BinaryOperator *E) {
8319
5.81k
    switch (E->getOpcode()) {
8320
5.28k
    default:
8321
5.28k
      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8322
8323
316
    case BO_PtrMemD:
8324
532
    case BO_PtrMemI:
8325
532
      return HandleMemberPointerAccess(this->Info, E, Result);
8326
5.81k
    }
8327
5.81k
  }
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
8318
5.81k
  bool VisitBinaryOperator(const BinaryOperator *E) {
8319
5.81k
    switch (E->getOpcode()) {
8320
5.28k
    default:
8321
5.28k
      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8322
8323
316
    case BO_PtrMemD:
8324
532
    case BO_PtrMemI:
8325
532
      return HandleMemberPointerAccess(this->Info, E, Result);
8326
5.81k
    }
8327
5.81k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
8328
8329
103k
  bool VisitCastExpr(const CastExpr *E) {
8330
103k
    switch (E->getCastKind()) {
8331
89.8k
    default:
8332
89.8k
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
8333
8334
7.76k
    case CK_DerivedToBase:
8335
13.6k
    case CK_UncheckedDerivedToBase:
8336
13.6k
      if (!this->Visit(E->getSubExpr()))
8337
8.12k
        return false;
8338
8339
      // Now figure out the necessary offset to add to the base LV to get from
8340
      // the derived class to the base class.
8341
5.53k
      return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8342
5.53k
                                  Result);
8343
103k
    }
8344
103k
  }
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8329
103k
  bool VisitCastExpr(const CastExpr *E) {
8330
103k
    switch (E->getCastKind()) {
8331
89.8k
    default:
8332
89.8k
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
8333
8334
7.76k
    case CK_DerivedToBase:
8335
13.6k
    case CK_UncheckedDerivedToBase:
8336
13.6k
      if (!this->Visit(E->getSubExpr()))
8337
8.12k
        return false;
8338
8339
      // Now figure out the necessary offset to add to the base LV to get from
8340
      // the derived class to the base class.
8341
5.53k
      return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8342
5.53k
                                  Result);
8343
103k
    }
8344
103k
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
8345
};
8346
}
8347
8348
//===----------------------------------------------------------------------===//
8349
// LValue Evaluation
8350
//
8351
// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8352
// function designators (in C), decl references to void objects (in C), and
8353
// temporaries (if building with -Wno-address-of-temporary).
8354
//
8355
// LValue evaluation produces values comprising a base expression of one of the
8356
// following types:
8357
// - Declarations
8358
//  * VarDecl
8359
//  * FunctionDecl
8360
// - Literals
8361
//  * CompoundLiteralExpr in C (and in global scope in C++)
8362
//  * StringLiteral
8363
//  * PredefinedExpr
8364
//  * ObjCStringLiteralExpr
8365
//  * ObjCEncodeExpr
8366
//  * AddrLabelExpr
8367
//  * BlockExpr
8368
//  * CallExpr for a MakeStringConstant builtin
8369
// - typeid(T) expressions, as TypeInfoLValues
8370
// - Locals and temporaries
8371
//  * MaterializeTemporaryExpr
8372
//  * Any Expr, with a CallIndex indicating the function in which the temporary
8373
//    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8374
//    from the AST (FIXME).
8375
//  * A MaterializeTemporaryExpr that has static storage duration, with no
8376
//    CallIndex, for a lifetime-extended temporary.
8377
//  * The ConstantExpr that is currently being evaluated during evaluation of an
8378
//    immediate invocation.
8379
// plus an offset in bytes.
8380
//===----------------------------------------------------------------------===//
8381
namespace {
8382
class LValueExprEvaluator
8383
  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8384
public:
8385
  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8386
14.1M
    LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8387
8388
  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8389
  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8390
8391
  bool VisitCallExpr(const CallExpr *E);
8392
  bool VisitDeclRefExpr(const DeclRefExpr *E);
8393
372
  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8394
  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8395
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8396
  bool VisitMemberExpr(const MemberExpr *E);
8397
18.9k
  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8398
122
  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8399
  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8400
  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8401
  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8402
  bool VisitUnaryDeref(const UnaryOperator *E);
8403
  bool VisitUnaryReal(const UnaryOperator *E);
8404
  bool VisitUnaryImag(const UnaryOperator *E);
8405
319k
  bool VisitUnaryPreInc(const UnaryOperator *UO) {
8406
319k
    return VisitUnaryPreIncDec(UO);
8407
319k
  }
8408
17.8k
  bool VisitUnaryPreDec(const UnaryOperator *UO) {
8409
17.8k
    return VisitUnaryPreIncDec(UO);
8410
17.8k
  }
8411
  bool VisitBinAssign(const BinaryOperator *BO);
8412
  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8413
8414
103k
  bool VisitCastExpr(const CastExpr *E) {
8415
103k
    switch (E->getCastKind()) {
8416
103k
    default:
8417
103k
      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8418
8419
141
    case CK_LValueBitCast:
8420
141
      this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8421
141
          << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8422
141
      if (!Visit(E->getSubExpr()))
8423
39
        return false;
8424
102
      Result.Designator.setInvalid();
8425
102
      return true;
8426
8427
123
    case CK_BaseToDerived:
8428
123
      if (!Visit(E->getSubExpr()))
8429
73
        return false;
8430
50
      return HandleBaseToDerivedCast(Info, E, Result);
8431
8432
63
    case CK_Dynamic:
8433
63
      if (!Visit(E->getSubExpr()))
8434
46
        return false;
8435
17
      return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8436
103k
    }
8437
103k
  }
8438
};
8439
} // end anonymous namespace
8440
8441
/// Evaluate an expression as an lvalue. This can be legitimately called on
8442
/// expressions which are not glvalues, in three cases:
8443
///  * function designators in C, and
8444
///  * "extern void" objects
8445
///  * @selector() expressions in Objective-C
8446
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8447
14.1M
                           bool InvalidBaseOK) {
8448
14.1M
  assert(!E->isValueDependent());
8449
14.1M
  assert(E->isGLValue() || E->getType()->isFunctionType() ||
8450
14.1M
         E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8451
14.1M
  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8452
14.1M
}
8453
8454
12.8M
bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8455
12.8M
  const NamedDecl *D = E->getDecl();
8456
12.8M
  if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8457
12.8M
          UnnamedGlobalConstantDecl>(D))
8458
736k
    return Success(cast<ValueDecl>(D));
8459
12.1M
  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8460
12.1M
    return VisitVarDecl(E, VD);
8461
3.42k
  if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8462
2.70k
    return Visit(BD->getBinding());
8463
725
  return Error(E);
8464
3.42k
}
8465
8466
8467
12.1M
bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8468
8469
  // If we are within a lambda's call operator, check whether the 'VD' referred
8470
  // to within 'E' actually represents a lambda-capture that maps to a
8471
  // data-member/field within the closure object, and if so, evaluate to the
8472
  // field or what the field refers to.
8473
12.1M
  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8474
12.1M
      
isa<DeclRefExpr>(E)1.76k
&&
8475
12.1M
      
cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()1.76k
) {
8476
    // We don't always have a complete capture-map when checking or inferring if
8477
    // the function call operator meets the requirements of a constexpr function
8478
    // - but we don't need to evaluate the captures to determine constexprness
8479
    // (dcl.constexpr C++17).
8480
332
    if (Info.checkingPotentialConstantExpression())
8481
4
      return false;
8482
8483
328
    if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8484
      // Start with 'Result' referring to the complete closure object...
8485
328
      if (auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8486
328
          MD->isExplicitObjectMemberFunction()) {
8487
3
        APValue *RefValue =
8488
3
            Info.getParamSlot(Info.CurrentCall->Arguments, MD->getParamDecl(0));
8489
3
        Result.setFrom(Info.Ctx, *RefValue);
8490
3
      } else
8491
325
        Result = *Info.CurrentCall->This;
8492
      // ... then update it to refer to the field of the closure object
8493
      // that represents the capture.
8494
328
      if (!HandleLValueMember(Info, E, Result, FD))
8495
0
        return false;
8496
      // And if the field is of reference type, update 'Result' to refer to what
8497
      // the field refers to.
8498
328
      if (FD->getType()->isReferenceType()) {
8499
76
        APValue RVal;
8500
76
        if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8501
76
                                            RVal))
8502
25
          return false;
8503
51
        Result.setFrom(Info.Ctx, RVal);
8504
51
      }
8505
303
      return true;
8506
328
    }
8507
328
  }
8508
8509
12.1M
  CallStackFrame *Frame = nullptr;
8510
12.1M
  unsigned Version = 0;
8511
12.1M
  if (VD->hasLocalStorage()) {
8512
    // Only if a local variable was declared in the function currently being
8513
    // evaluated, do we expect to be able to find its value in the current
8514
    // frame. (Otherwise it was likely declared in an enclosing context and
8515
    // could either have a valid evaluatable value (for e.g. a constexpr
8516
    // variable) or be ill-formed (and trigger an appropriate evaluation
8517
    // diagnostic)).
8518
9.83M
    CallStackFrame *CurrFrame = Info.CurrentCall;
8519
9.83M
    if (CurrFrame->Callee && 
CurrFrame->Callee->Equals(VD->getDeclContext())459k
) {
8520
      // Function parameters are stored in some caller's frame. (Usually the
8521
      // immediate caller, but for an inherited constructor they may be more
8522
      // distant.)
8523
459k
      if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8524
334k
        if (CurrFrame->Arguments) {
8525
267k
          VD = CurrFrame->Arguments.getOrigParam(PVD);
8526
267k
          Frame =
8527
267k
              Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8528
267k
          Version = CurrFrame->Arguments.Version;
8529
267k
        }
8530
334k
      } else {
8531
124k
        Frame = CurrFrame;
8532
124k
        Version = CurrFrame->getCurrentTemporaryVersion(VD);
8533
124k
      }
8534
459k
    }
8535
9.83M
  }
8536
8537
12.1M
  if (!VD->getType()->isReferenceType()) {
8538
11.8M
    if (Frame) {
8539
349k
      Result.set({VD, Frame->Index, Version});
8540
349k
      return true;
8541
349k
    }
8542
11.5M
    return Success(VD);
8543
11.8M
  }
8544
8545
278k
  if (!Info.getLangOpts().CPlusPlus11) {
8546
3.63k
    Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8547
3.63k
        << VD << VD->getType();
8548
3.63k
    Info.Note(VD->getLocation(), diag::note_declared_at);
8549
3.63k
  }
8550
8551
278k
  APValue *V;
8552
278k
  if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8553
235k
    return false;
8554
43.3k
  if (!V->hasValue()) {
8555
    // FIXME: Is it possible for V to be indeterminate here? If so, we should
8556
    // adjust the diagnostic to say that.
8557
80
    if (!Info.checkingPotentialConstantExpression())
8558
46
      Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8559
80
    return false;
8560
80
  }
8561
43.2k
  return Success(*V, E);
8562
43.3k
}
8563
8564
59.1k
bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8565
59.1k
  if (!IsConstantEvaluatedBuiltinCall(E))
8566
53.5k
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
8567
8568
5.53k
  switch (E->getBuiltinCallee()) {
8569
0
  default:
8570
0
    return false;
8571
14
  case Builtin::BIas_const:
8572
1.98k
  case Builtin::BIforward:
8573
1.99k
  case Builtin::BIforward_like:
8574
5.52k
  case Builtin::BImove:
8575
5.53k
  case Builtin::BImove_if_noexcept:
8576
5.53k
    if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8577
5.43k
      return Visit(E->getArg(0));
8578
97
    break;
8579
5.53k
  }
8580
8581
97
  return ExprEvaluatorBaseTy::VisitCallExpr(E);
8582
5.53k
}
8583
8584
bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8585
45.3k
    const MaterializeTemporaryExpr *E) {
8586
  // Walk through the expression to find the materialized temporary itself.
8587
45.3k
  SmallVector<const Expr *, 2> CommaLHSs;
8588
45.3k
  SmallVector<SubobjectAdjustment, 2> Adjustments;
8589
45.3k
  const Expr *Inner =
8590
45.3k
      E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8591
8592
  // If we passed any comma operators, evaluate their LHSs.
8593
45.3k
  for (const Expr *E : CommaLHSs)
8594
49
    if (!EvaluateIgnoredValue(Info, E))
8595
6
      return false;
8596
8597
  // A materialized temporary with static storage duration can appear within the
8598
  // result of a constant expression evaluation, so we need to preserve its
8599
  // value for use outside this evaluation.
8600
45.3k
  APValue *Value;
8601
45.3k
  if (E->getStorageDuration() == SD_Static) {
8602
979
    if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8603
97
      return false;
8604
    // FIXME: What about SD_Thread?
8605
882
    Value = E->getOrCreateValue(true);
8606
882
    *Value = APValue();
8607
882
    Result.set(E);
8608
44.3k
  } else {
8609
44.3k
    Value = &Info.CurrentCall->createTemporary(
8610
44.3k
        E, E->getType(),
8611
44.3k
        E->getStorageDuration() == SD_FullExpression ? 
ScopeKind::FullExpression41.8k
8612
44.3k
                                                     : 
ScopeKind::Block2.50k
,
8613
44.3k
        Result);
8614
44.3k
  }
8615
8616
45.2k
  QualType Type = Inner->getType();
8617
8618
  // Materialize the temporary itself.
8619
45.2k
  if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8620
19.0k
    *Value = APValue();
8621
19.0k
    return false;
8622
19.0k
  }
8623
8624
  // Adjust our lvalue to refer to the desired subobject.
8625
26.1k
  
for (unsigned I = Adjustments.size(); 26.1k
I != 0; /**/) {
8626
1
    --I;
8627
1
    switch (Adjustments[I].Kind) {
8628
0
    case SubobjectAdjustment::DerivedToBaseAdjustment:
8629
0
      if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8630
0
                                Type, Result))
8631
0
        return false;
8632
0
      Type = Adjustments[I].DerivedToBase.BasePath->getType();
8633
0
      break;
8634
8635
1
    case SubobjectAdjustment::FieldAdjustment:
8636
1
      if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8637
0
        return false;
8638
1
      Type = Adjustments[I].Field->getType();
8639
1
      break;
8640
8641
0
    case SubobjectAdjustment::MemberPointerAdjustment:
8642
0
      if (!HandleMemberPointerAccess(this->Info, Type, Result,
8643
0
                                     Adjustments[I].Ptr.RHS))
8644
0
        return false;
8645
0
      Type = Adjustments[I].Ptr.MPT->getPointeeType();
8646
0
      break;
8647
1
    }
8648
1
  }
8649
8650
26.1k
  return true;
8651
26.1k
}
8652
8653
bool
8654
21.5k
LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8655
21.5k
  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8656
21.5k
         "lvalue compound literal in c++?");
8657
  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8658
  // only see this when folding in C, so there's no standard to follow here.
8659
21.5k
  return Success(E);
8660
21.5k
}
8661
8662
1.52k
bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8663
1.52k
  TypeInfoLValue TypeInfo;
8664
8665
1.52k
  if (!E->isPotentiallyEvaluated()) {
8666
1.44k
    if (E->isTypeOperand())
8667
1.32k
      TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8668
126
    else
8669
126
      TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8670
1.44k
  } else {
8671
82
    if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8672
57
      Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8673
57
        << E->getExprOperand()->getType()
8674
57
        << E->getExprOperand()->getSourceRange();
8675
57
    }
8676
8677
82
    if (!Visit(E->getExprOperand()))
8678
53
      return false;
8679
8680
29
    std::optional<DynamicType> DynType =
8681
29
        ComputeDynamicType(Info, E, Result, AK_TypeId);
8682
29
    if (!DynType)
8683
13
      return false;
8684
8685
16
    TypeInfo =
8686
16
        TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8687
16
  }
8688
8689
1.46k
  return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8690
1.52k
}
8691
8692
211
bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8693
211
  return Success(E->getGuidDecl());
8694
211
}
8695
8696
562k
bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8697
  // Handle static data members.
8698
562k
  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8699
444
    VisitIgnoredBaseExpression(E->getBase());
8700
444
    return VisitVarDecl(E, VD);
8701
444
  }
8702
8703
  // Handle static member functions.
8704
562k
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8705
376
    if (MD->isStatic()) {
8706
376
      VisitIgnoredBaseExpression(E->getBase());
8707
376
      return Success(MD);
8708
376
    }
8709
376
  }
8710
8711
  // Handle non-static data members.
8712
561k
  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8713
562k
}
8714
8715
513k
bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8716
  // FIXME: Deal with vectors as array subscript bases.
8717
513k
  if (E->getBase()->getType()->isVectorType() ||
8718
513k
      
E->getBase()->getType()->isSveVLSBuiltinType()510k
)
8719
3.29k
    return Error(E);
8720
8721
510k
  APSInt Index;
8722
510k
  bool Success = true;
8723
8724
  // C++17's rules require us to evaluate the LHS first, regardless of which
8725
  // side is the base.
8726
706k
  for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8727
706k
    if (SubExpr == E->getBase() ? 
!evaluatePointer(SubExpr, Result)510k
8728
706k
                                : 
!EvaluateInteger(SubExpr, Index, Info)196k
) {
8729
543k
      if (!Info.noteFailure())
8730
325k
        return false;
8731
217k
      Success = false;
8732
217k
    }
8733
706k
  }
8734
8735
185k
  return Success &&
8736
185k
         
HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index)37.1k
;
8737
510k
}
8738
8739
271k
bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8740
271k
  return evaluatePointer(E->getSubExpr(), Result);
8741
271k
}
8742
8743
256
bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8744
256
  if (!Visit(E->getSubExpr()))
8745
12
    return false;
8746
  // __real is a no-op on scalar lvalues.
8747
244
  if (E->getSubExpr()->getType()->isAnyComplexType())
8748
202
    HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8749
244
  return true;
8750
256
}
8751
8752
187
bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8753
187
  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8754
187
         "lvalue __imag__ on scalar?");
8755
187
  if (!Visit(E->getSubExpr()))
8756
6
    return false;
8757
181
  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8758
181
  return true;
8759
187
}
8760
8761
337k
bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8762
337k
  if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()143k
)
8763
9.64k
    return Error(UO);
8764
8765
328k
  if (!this->Visit(UO->getSubExpr()))
8766
7.82k
    return false;
8767
8768
320k
  return handleIncDec(
8769
320k
      this->Info, UO, Result, UO->getSubExpr()->getType(),
8770
320k
      UO->isIncrementOp(), nullptr);
8771
328k
}
8772
8773
bool LValueExprEvaluator::VisitCompoundAssignOperator(
8774
93.4k
    const CompoundAssignOperator *CAO) {
8775
93.4k
  if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()64.9k
)
8776
1.01k
    return Error(CAO);
8777
8778
92.4k
  bool Success = true;
8779
8780
  // C++17 onwards require that we evaluate the RHS first.
8781
92.4k
  APValue RHS;
8782
92.4k
  if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8783
23.6k
    if (!Info.noteFailure())
8784
186
      return false;
8785
23.4k
    Success = false;
8786
23.4k
  }
8787
8788
  // The overall lvalue result is the result of evaluating the LHS.
8789
92.2k
  if (!this->Visit(CAO->getLHS()) || 
!Success69.0k
)
8790
39.5k
    return false;
8791
8792
52.7k
  return handleCompoundAssignment(
8793
52.7k
      this->Info, CAO,
8794
52.7k
      Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8795
52.7k
      CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8796
92.2k
}
8797
8798
1.33M
bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8799
1.33M
  if (!Info.getLangOpts().CPlusPlus14 && 
!Info.keepEvaluatingAfterFailure()660k
)
8800
2.76k
    return Error(E);
8801
8802
1.33M
  bool Success = true;
8803
8804
  // C++17 onwards require that we evaluate the RHS first.
8805
1.33M
  APValue NewVal;
8806
1.33M
  if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8807
1.21M
    if (!Info.noteFailure())
8808
818
      return false;
8809
1.21M
    Success = false;
8810
1.21M
  }
8811
8812
1.33M
  if (!this->Visit(E->getLHS()) || 
!Success1.19M
)
8813
1.25M
    return false;
8814
8815
78.6k
  if (Info.getLangOpts().CPlusPlus20 &&
8816
78.6k
      
!MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result)5.14k
)
8817
94
    return false;
8818
8819
78.5k
  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8820
78.5k
                          NewVal);
8821
78.6k
}
8822
8823
//===----------------------------------------------------------------------===//
8824
// Pointer Evaluation
8825
//===----------------------------------------------------------------------===//
8826
8827
/// Attempts to compute the number of bytes available at the pointer
8828
/// returned by a function with the alloc_size attribute. Returns true if we
8829
/// were successful. Places an unsigned number into `Result`.
8830
///
8831
/// This expects the given CallExpr to be a call to a function with an
8832
/// alloc_size attribute.
8833
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8834
                                            const CallExpr *Call,
8835
911
                                            llvm::APInt &Result) {
8836
911
  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8837
8838
911
  assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8839
911
  unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8840
911
  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8841
911
  if (Call->getNumArgs() <= SizeArgNo)
8842
0
    return false;
8843
8844
1.41k
  
auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) 911
{
8845
1.41k
    Expr::EvalResult ExprResult;
8846
1.41k
    if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8847
24
      return false;
8848
1.39k
    Into = ExprResult.Val.getInt();
8849
1.39k
    if (Into.isNegative() || 
!Into.isIntN(BitsInSizeT)1.34k
)
8850
48
      return false;
8851
1.34k
    Into = Into.zext(BitsInSizeT);
8852
1.34k
    return true;
8853
1.39k
  };
8854
8855
911
  APSInt SizeOfElem;
8856
911
  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8857
48
    return false;
8858
8859
863
  if (!AllocSize->getNumElemsParam().isValid()) {
8860
358
    Result = std::move(SizeOfElem);
8861
358
    return true;
8862
358
  }
8863
8864
505
  APSInt NumberOfElems;
8865
505
  unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8866
505
  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8867
24
    return false;
8868
8869
481
  bool Overflow;
8870
481
  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8871
481
  if (Overflow)
8872
32
    return false;
8873
8874
449
  Result = std::move(BytesAvailable);
8875
449
  return true;
8876
481
}
8877
8878
/// Convenience function. LVal's base must be a call to an alloc_size
8879
/// function.
8880
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8881
                                            const LValue &LVal,
8882
911
                                            llvm::APInt &Result) {
8883
911
  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8884
911
         "Can't get the size of a non alloc_size function");
8885
911
  const auto *Base = LVal.getLValueBase().get<const Expr *>();
8886
911
  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8887
911
  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8888
911
}
8889
8890
/// Attempts to evaluate the given LValueBase as the result of a call to
8891
/// a function with the alloc_size attribute. If it was possible to do so, this
8892
/// function will return true, make Result's Base point to said function call,
8893
/// and mark Result's Base as invalid.
8894
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8895
6.30k
                                      LValue &Result) {
8896
6.30k
  if (Base.isNull())
8897
0
    return false;
8898
8899
  // Because we do no form of static analysis, we only support const variables.
8900
  //
8901
  // Additionally, we can't support parameters, nor can we support static
8902
  // variables (in the latter case, use-before-assign isn't UB; in the former,
8903
  // we have no clue what they'll be assigned to).
8904
6.30k
  const auto *VD =
8905
6.30k
      dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8906
6.30k
  if (!VD || 
!VD->isLocalVarDecl()6.30k
||
!VD->getType().isConstQualified()1.55k
)
8907
5.62k
    return false;
8908
8909
683
  const Expr *Init = VD->getAnyInitializer();
8910
683
  if (!Init || Init->getType().isNull())
8911
8
    return false;
8912
8913
675
  const Expr *E = Init->IgnoreParens();
8914
675
  if (!tryUnwrapAllocSizeCall(E))
8915
0
    return false;
8916
8917
  // Store E instead of E unwrapped so that the type of the LValue's base is
8918
  // what the user wanted.
8919
675
  Result.setInvalid(E);
8920
8921
675
  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8922
675
  Result.addUnsizedArray(Info, E, Pointee);
8923
675
  return true;
8924
675
}
8925
8926
namespace {
8927
class PointerExprEvaluator
8928
  : public ExprEvaluatorBase<PointerExprEvaluator> {
8929
  LValue &Result;
8930
  bool InvalidBaseOK;
8931
8932
3.62k
  bool Success(const Expr *E) {
8933
3.62k
    Result.set(E);
8934
3.62k
    return true;
8935
3.62k
  }
8936
8937
2.11M
  bool evaluateLValue(const Expr *E, LValue &Result) {
8938
2.11M
    return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8939
2.11M
  }
8940
8941
93.7k
  bool evaluatePointer(const Expr *E, LValue &Result) {
8942
93.7k
    return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8943
93.7k
  }
8944
8945
  bool visitNonBuiltinCallExpr(const CallExpr *E);
8946
public:
8947
8948
  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8949
2.81M
      : ExprEvaluatorBaseTy(info), Result(Result),
8950
2.81M
        InvalidBaseOK(InvalidBaseOK) {}
8951
8952
89.6k
  bool Success(const APValue &V, const Expr *E) {
8953
89.6k
    Result.setFrom(Info.Ctx, V);
8954
89.6k
    return true;
8955
89.6k
  }
8956
42.2k
  bool ZeroInitialization(const Expr *E) {
8957
42.2k
    Result.setNull(Info.Ctx, E->getType());
8958
42.2k
    return true;
8959
42.2k
  }
8960
8961
  bool VisitBinaryOperator(const BinaryOperator *E);
8962
  bool VisitCastExpr(const CastExpr* E);
8963
  bool VisitUnaryAddrOf(const UnaryOperator *E);
8964
  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8965
2.52k
      { return Success(E); }
8966
706
  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8967
706
    if (E->isExpressibleAsConstantInitializer())
8968
9
      return Success(E);
8969
697
    if (Info.noteFailure())
8970
611
      EvaluateIgnoredValue(Info, E->getSubExpr());
8971
697
    return Error(E);
8972
706
  }
8973
  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8974
260
      { return Success(E); }
8975
  bool VisitCallExpr(const CallExpr *E);
8976
  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8977
499
  bool VisitBlockExpr(const BlockExpr *E) {
8978
499
    if (!E->getBlockDecl()->hasCaptures())
8979
289
      return Success(E);
8980
210
    return Error(E);
8981
499
  }
8982
217k
  bool VisitCXXThisExpr(const CXXThisExpr *E) {
8983
    // Can't look at 'this' when checking a potential constant expression.
8984
217k
    if (Info.checkingPotentialConstantExpression())
8985
1.27k
      return false;
8986
216k
    if (!Info.CurrentCall->This) {
8987
178k
      if (Info.getLangOpts().CPlusPlus11)
8988
175k
        Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8989
3.15k
      else
8990
3.15k
        Info.FFDiag(E);
8991
178k
      return false;
8992
178k
    }
8993
38.1k
    Result = *Info.CurrentCall->This;
8994
8995
38.1k
    if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8996
      // Ensure we actually have captured 'this'. If something was wrong with
8997
      // 'this' capture, the error would have been previously reported.
8998
      // Otherwise we can be inside of a default initialization of an object
8999
      // declared by lambda's body, so no need to return false.
9000
16
      if (!Info.CurrentCall->LambdaThisCaptureField)
9001
1
        return true;
9002
9003
      // If we have captured 'this',  the 'this' expression refers
9004
      // to the enclosing '*this' object (either by value or reference) which is
9005
      // either copied into the closure object's field that represents the
9006
      // '*this' or refers to '*this'.
9007
      // Update 'Result' to refer to the data member/field of the closure object
9008
      // that represents the '*this' capture.
9009
15
      if (!HandleLValueMember(Info, E, Result,
9010
15
                             Info.CurrentCall->LambdaThisCaptureField))
9011
0
        return false;
9012
      // If we captured '*this' by reference, replace the field with its referent.
9013
15
      if (Info.CurrentCall->LambdaThisCaptureField->getType()
9014
15
              ->isPointerType()) {
9015
9
        APValue RVal;
9016
9
        if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
9017
9
                                            RVal))
9018
0
          return false;
9019
9020
9
        Result.setFrom(Info.Ctx, RVal);
9021
9
      }
9022
15
    }
9023
38.1k
    return true;
9024
38.1k
  }
9025
9026
  bool VisitCXXNewExpr(const CXXNewExpr *E);
9027
9028
1.12k
  bool VisitSourceLocExpr(const SourceLocExpr *E) {
9029
1.12k
    assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9030
1.12k
    APValue LValResult = E->EvaluateInContext(
9031
1.12k
        Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9032
1.12k
    Result.setFrom(Info.Ctx, LValResult);
9033
1.12k
    return true;
9034
1.12k
  }
9035
9036
22
  bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9037
22
    std::string ResultStr = E->ComputeName(Info.Ctx);
9038
9039
22
    QualType CharTy = Info.Ctx.CharTy.withConst();
9040
22
    APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9041
22
               ResultStr.size() + 1);
9042
22
    QualType ArrayTy = Info.Ctx.getConstantArrayType(
9043
22
        CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9044
9045
22
    StringLiteral *SL =
9046
22
        StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9047
22
                              /*Pascal*/ false, ArrayTy, E->getLocation());
9048
9049
22
    evaluateLValue(SL, Result);
9050
22
    Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9051
22
    return true;
9052
22
  }
9053
9054
  // FIXME: Missing: @protocol, @selector
9055
};
9056
} // end anonymous namespace
9057
9058
static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9059
2.81M
                            bool InvalidBaseOK) {
9060
2.81M
  assert(!E->isValueDependent());
9061
2.81M
  assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9062
2.81M
  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9063
2.81M
}
9064
9065
85.8k
bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9066
85.8k
  if (E->getOpcode() != BO_Add &&
9067
85.8k
      
E->getOpcode() != BO_Sub17.4k
)
9068
5.27k
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9069
9070
80.5k
  const Expr *PExp = E->getLHS();
9071
80.5k
  const Expr *IExp = E->getRHS();
9072
80.5k
  if (IExp->getType()->isPointerType())
9073
220
    std::swap(PExp, IExp);
9074
9075
80.5k
  bool EvalPtrOK = evaluatePointer(PExp, Result);
9076
80.5k
  if (!EvalPtrOK && 
!Info.noteFailure()71.4k
)
9077
15.2k
    return false;
9078
9079
65.2k
  llvm::APSInt Offset;
9080
65.2k
  if (!EvaluateInteger(IExp, Offset, Info) || 
!EvalPtrOK27.9k
)
9081
57.4k
    return false;
9082
9083
7.84k
  if (E->getOpcode() == BO_Sub)
9084
333
    negateAsSigned(Offset);
9085
9086
7.84k
  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9087
7.84k
  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9088
65.2k
}
9089
9090
117k
bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9091
117k
  return evaluateLValue(E->getSubExpr(), Result);
9092
117k
}
9093
9094
// Is the provided decl 'std::source_location::current'?
9095
183
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9096
183
  if (!FD)
9097
131
    return false;
9098
52
  const IdentifierInfo *FnII = FD->getIdentifier();
9099
52
  if (!FnII || !FnII->isStr("current"))
9100
22
    return false;
9101
9102
30
  const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9103
30
  if (!RD)
9104
0
    return false;
9105
9106
30
  const IdentifierInfo *ClassII = RD->getIdentifier();
9107
30
  return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9108
30
}
9109
9110
2.43M
bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9111
2.43M
  const Expr *SubExpr = E->getSubExpr();
9112
9113
2.43M
  switch (E->getCastKind()) {
9114
308k
  default:
9115
308k
    break;
9116
308k
  case CK_BitCast:
9117
82.9k
  case CK_CPointerToObjCPointerCast:
9118
82.9k
  case CK_BlockPointerToObjCPointerCast:
9119
82.9k
  case CK_AnyPointerToBlockPointerCast:
9120
83.9k
  case CK_AddressSpaceConversion:
9121
83.9k
    if (!Visit(SubExpr))
9122
66.3k
      return false;
9123
    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9124
    // permitted in constant expressions in C++11. Bitcasts from cv void* are
9125
    // also static_casts, but we disallow them as a resolution to DR1312.
9126
17.5k
    if (!E->getType()->isVoidPointerType()) {
9127
      // In some circumstances, we permit casting from void* to cv1 T*, when the
9128
      // actual pointee object is actually a cv2 T.
9129
6.10k
      bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9130
6.10k
                            
!Result.IsNullPtr6.06k
;
9131
6.10k
      bool VoidPtrCastMaybeOK =
9132
6.10k
          HasValidResult &&
9133
6.10k
          Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
9134
4.67k
                                          E->getType()->getPointeeType());
9135
      // 1. We'll allow it in std::allocator::allocate, and anything which that
9136
      //    calls.
9137
      // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9138
      //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9139
      //    We'll allow it in the body of std::source_location::current.  GCC's
9140
      //    implementation had a parameter of type `void*`, and casts from
9141
      //    that back to `const __impl*` in its body.
9142
6.10k
      if (VoidPtrCastMaybeOK &&
9143
6.10k
          
(227
Info.getStdAllocatorCaller("allocate")227
||
9144
227
           
IsDeclSourceLocationCurrent(Info.CurrentCall->Callee)183
||
9145
227
           
Info.getLangOpts().CPlusPlus26153
)) {
9146
        // Permitted.
9147
6.02k
      } else {
9148
6.02k
        if (SubExpr->getType()->isVoidPointerType()) {
9149
1.06k
          if (HasValidResult)
9150
94
            CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9151
94
                << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9152
94
                << Result.Designator.getType(Info.Ctx).getCanonicalType()
9153
94
                << E->getType()->getPointeeType();
9154
969
          else
9155
969
            CCEDiag(E, diag::note_constexpr_invalid_cast)
9156
969
                << 3 << SubExpr->getType();
9157
1.06k
        } else
9158
4.95k
          CCEDiag(E, diag::note_constexpr_invalid_cast)
9159
4.95k
              << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9160
6.02k
        Result.Designator.setInvalid();
9161
6.02k
      }
9162
6.10k
    }
9163
17.5k
    if (E->getCastKind() == CK_AddressSpaceConversion && 
Result.IsNullPtr810
)
9164
682
      ZeroInitialization(E);
9165
17.5k
    return true;
9166
9167
6.16k
  case CK_DerivedToBase:
9168
12.9k
  case CK_UncheckedDerivedToBase:
9169
12.9k
    if (!evaluatePointer(E->getSubExpr(), Result))
9170
12.2k
      return false;
9171
733
    if (!Result.Base && 
Result.Offset.isZero()15
)
9172
11
      return true;
9173
9174
    // Now figure out the necessary offset to add to the base LV to get from
9175
    // the derived class to the base class.
9176
722
    return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9177
722
                                  castAs<PointerType>()->getPointeeType(),
9178
722
                                Result);
9179
9180
508
  case CK_BaseToDerived:
9181
508
    if (!Visit(E->getSubExpr()))
9182
362
      return false;
9183
146
    if (!Result.Base && 
Result.Offset.isZero()8
)
9184
8
      return true;
9185
138
    return HandleBaseToDerivedCast(Info, E, Result);
9186
9187
116
  case CK_Dynamic:
9188
116
    if (!Visit(E->getSubExpr()))
9189
64
      return false;
9190
52
    return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9191
9192
29.6k
  case CK_NullToPointer:
9193
29.6k
    VisitIgnoredValue(E->getSubExpr());
9194
29.6k
    return ZeroInitialization(E);
9195
9196
4.08k
  case CK_IntegralToPointer: {
9197
4.08k
    CCEDiag(E, diag::note_constexpr_invalid_cast)
9198
4.08k
        << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9199
9200
4.08k
    APValue Value;
9201
4.08k
    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9202
2.98k
      break;
9203
9204
1.09k
    if (Value.isInt()) {
9205
1.06k
      unsigned Size = Info.Ctx.getTypeSize(E->getType());
9206
1.06k
      uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9207
1.06k
      Result.Base = (Expr*)nullptr;
9208
1.06k
      Result.InvalidBase = false;
9209
1.06k
      Result.Offset = CharUnits::fromQuantity(N);
9210
1.06k
      Result.Designator.setInvalid();
9211
1.06k
      Result.IsNullPtr = false;
9212
1.06k
      return true;
9213
1.06k
    } else {
9214
      // Cast is of an lvalue, no need to change value.
9215
35
      Result.setFrom(Info.Ctx, Value);
9216
35
      return true;
9217
35
    }
9218
1.09k
  }
9219
9220
120k
  case CK_ArrayToPointerDecay: {
9221
120k
    if (SubExpr->isGLValue()) {
9222
120k
      if (!evaluateLValue(SubExpr, Result))
9223
16.8k
        return false;
9224
120k
    } else {
9225
6
      APValue &Value = Info.CurrentCall->createTemporary(
9226
6
          SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9227
6
      if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9228
6
        return false;
9229
6
    }
9230
    // The result is a pointer to the first element of the array.
9231
103k
    auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9232
103k
    if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9233
98.8k
      Result.addArray(Info, E, CAT);
9234
4.31k
    else
9235
4.31k
      Result.addUnsizedArray(Info, E, AT->getElementType());
9236
103k
    return true;
9237
120k
  }
9238
9239
725k
  case CK_FunctionToPointerDecay:
9240
725k
    return evaluateLValue(SubExpr, Result);
9241
9242
1.14M
  case CK_LValueToRValue: {
9243
1.14M
    LValue LVal;
9244
1.14M
    if (!evaluateLValue(E->getSubExpr(), LVal))
9245
243k
      return false;
9246
9247
902k
    APValue RVal;
9248
    // Note, we use the subexpression's type in order to retain cv-qualifiers.
9249
902k
    if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9250
902k
                                        LVal, RVal))
9251
816k
      return InvalidBaseOK &&
9252
816k
             
evaluateLValueAsAllocSize(Info, LVal.Base, Result)6.30k
;
9253
85.8k
    return Success(RVal, E);
9254
902k
  }
9255
2.43M
  }
9256
9257
311k
  return ExprEvaluatorBaseTy::VisitCastExpr(E);
9258
2.43M
}
9259
9260
static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9261
13.5k
                                UnaryExprOrTypeTrait ExprKind) {
9262
  // C++ [expr.alignof]p3:
9263
  //     When alignof is applied to a reference type, the result is the
9264
  //     alignment of the referenced type.
9265
13.5k
  T = T.getNonReferenceType();
9266
9267
13.5k
  if (T.getQualifiers().hasUnaligned())
9268
6
    return CharUnits::One();
9269
9270
13.4k
  const bool AlignOfReturnsPreferred =
9271
13.4k
      Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9272
9273
  // __alignof is defined to return the preferred alignment.
9274
  // Before 8, clang returned the preferred alignment for alignof and _Alignof
9275
  // as well.
9276
13.4k
  if (ExprKind == UETT_PreferredAlignOf || 
AlignOfReturnsPreferred4.83k
)
9277
8.70k
    return Info.Ctx.toCharUnitsFromBits(
9278
8.70k
      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9279
  // alignof and _Alignof are defined to return the ABI alignment.
9280
4.79k
  else if (ExprKind == UETT_AlignOf)
9281
4.79k
    return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9282
0
  else
9283
0
    llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9284
13.4k
}
9285
9286
static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9287
321
                                UnaryExprOrTypeTrait ExprKind) {
9288
321
  E = E->IgnoreParens();
9289
9290
  // The kinds of expressions that we have special-case logic here for
9291
  // should be kept up to date with the special checks for those
9292
  // expressions in Sema.
9293
9294
  // alignof decl is always accepted, even if it doesn't make sense: we default
9295
  // to 1 in those cases.
9296
321
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9297
228
    return Info.Ctx.getDeclAlign(DRE->getDecl(),
9298
228
                                 /*RefAsPointee*/true);
9299
9300
93
  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9301
57
    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9302
57
                                 /*RefAsPointee*/true);
9303
9304
36
  return GetAlignOfType(Info, E->getType(), ExprKind);
9305
93
}
9306
9307
64
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9308
64
  if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9309
64
    return Info.Ctx.getDeclAlign(VD);
9310
0
  if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9311
0
    return GetAlignOfExpr(Info, E, UETT_AlignOf);
9312
0
  return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9313
0
}
9314
9315
/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9316
/// __builtin_is_aligned and __builtin_assume_aligned.
9317
static bool getAlignmentArgument(const Expr *E, QualType ForType,
9318
238
                                 EvalInfo &Info, APSInt &Alignment) {
9319
238
  if (!EvaluateInteger(E, Alignment, Info))
9320
29
    return false;
9321
209
  if (Alignment < 0 || 
!Alignment.isPowerOf2()206
) {
9322
6
    Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9323
6
    return false;
9324
6
  }
9325
203
  unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9326
203
  APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9327
203
  if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9328
3
    Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9329
3
        << MaxValue << ForType << Alignment;
9330
3
    return false;
9331
3
  }
9332
  // Ensure both alignment and source value have the same bit width so that we
9333
  // don't assert when computing the resulting value.
9334
200
  APSInt ExtAlignment =
9335
200
      APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9336
200
  assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9337
200
         "Alignment should not be changed by ext/trunc");
9338
200
  Alignment = ExtAlignment;
9339
200
  assert(Alignment.getBitWidth() == SrcWidth);
9340
200
  return true;
9341
200
}
9342
9343
// To be clear: this happily visits unsupported builtins. Better name welcomed.
9344
40.5k
bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9345
40.5k
  if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9346
3.05k
    return true;
9347
9348
37.4k
  if (!(InvalidBaseOK && 
getAllocSizeAttr(E)274
))
9349
37.1k
    return false;
9350
9351
272
  Result.setInvalid(E);
9352
272
  QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9353
272
  Result.addUnsizedArray(Info, E, PointeeTy);
9354
272
  return true;
9355
37.4k
}
9356
9357
50.9k
bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9358
50.9k
  if (!IsConstantEvaluatedBuiltinCall(E))
9359
40.5k
    return visitNonBuiltinCallExpr(E);
9360
10.4k
  return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9361
50.9k
}
9362
9363
// Determine if T is a character type for which we guarantee that
9364
// sizeof(T) == 1.
9365
2.92k
static bool isOneByteCharacterType(QualType T) {
9366
2.92k
  return T->isCharType() || 
T->isChar8Type()1.11k
;
9367
2.92k
}
9368
9369
bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9370
10.4k
                                                unsigned BuiltinOp) {
9371
10.4k
  if (IsNoOpCall(E))
9372
542
    return Success(E);
9373
9374
9.86k
  switch (BuiltinOp) {
9375
6.20k
  case Builtin::BIaddressof:
9376
6.21k
  case Builtin::BI__addressof:
9377
6.30k
  case Builtin::BI__builtin_addressof:
9378
6.30k
    return evaluateLValue(E->getArg(0), Result);
9379
77
  case Builtin::BI__builtin_assume_aligned: {
9380
    // We need to be very careful here because: if the pointer does not have the
9381
    // asserted alignment, then the behavior is undefined, and undefined
9382
    // behavior is non-constant.
9383
77
    if (!evaluatePointer(E->getArg(0), Result))
9384
51
      return false;
9385
9386
26
    LValue OffsetResult(Result);
9387
26
    APSInt Alignment;
9388
26
    if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9389
26
                              Alignment))
9390
0
      return false;
9391
26
    CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9392
9393
26
    if (E->getNumArgs() > 2) {
9394
10
      APSInt Offset;
9395
10
      if (!EvaluateInteger(E->getArg(2), Offset, Info))
9396
2
        return false;
9397
9398
8
      int64_t AdditionalOffset = -Offset.getZExtValue();
9399
8
      OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9400
8
    }
9401
9402
    // If there is a base object, then it must have the correct alignment.
9403
24
    if (OffsetResult.Base) {
9404
19
      CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9405
9406
19
      if (BaseAlignment < Align) {
9407
2
        Result.Designator.setInvalid();
9408
        // FIXME: Add support to Diagnostic for long / long long.
9409
2
        CCEDiag(E->getArg(0),
9410
2
                diag::note_constexpr_baa_insufficient_alignment) << 0
9411
2
          << (unsigned)BaseAlignment.getQuantity()
9412
2
          << (unsigned)Align.getQuantity();
9413
2
        return false;
9414
2
      }
9415
19
    }
9416
9417
    // The offset must also have the correct alignment.
9418
22
    if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9419
6
      Result.Designator.setInvalid();
9420
9421
6
      (OffsetResult.Base
9422
6
           ? CCEDiag(E->getArg(0),
9423
4
                     diag::note_constexpr_baa_insufficient_alignment) << 1
9424
6
           : CCEDiag(E->getArg(0),
9425
2
                     diag::note_constexpr_baa_value_insufficient_alignment))
9426
6
        << (int)OffsetResult.Offset.getQuantity()
9427
6
        << (unsigned)Align.getQuantity();
9428
6
      return false;
9429
6
    }
9430
9431
16
    return true;
9432
22
  }
9433
24
  case Builtin::BI__builtin_align_up:
9434
42
  case Builtin::BI__builtin_align_down: {
9435
42
    if (!evaluatePointer(E->getArg(0), Result))
9436
11
      return false;
9437
31
    APSInt Alignment;
9438
31
    if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9439
31
                              Alignment))
9440
0
      return false;
9441
31
    CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9442
31
    CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9443
    // For align_up/align_down, we can return the same value if the alignment
9444
    // is known to be greater or equal to the requested value.
9445
31
    if (PtrAlign.getQuantity() >= Alignment)
9446
12
      return true;
9447
9448
    // The alignment could be greater than the minimum at run-time, so we cannot
9449
    // infer much about the resulting pointer value. One case is possible:
9450
    // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9451
    // can infer the correct index if the requested alignment is smaller than
9452
    // the base alignment so we can perform the computation on the offset.
9453
19
    if (BaseAlignment.getQuantity() >= Alignment) {
9454
14
      assert(Alignment.getBitWidth() <= 64 &&
9455
14
             "Cannot handle > 64-bit address-space");
9456
14
      uint64_t Alignment64 = Alignment.getZExtValue();
9457
14
      CharUnits NewOffset = CharUnits::fromQuantity(
9458
14
          BuiltinOp == Builtin::BI__builtin_align_down
9459
14
              ? 
llvm::alignDown(Result.Offset.getQuantity(), Alignment64)8
9460
14
              : 
llvm::alignTo(Result.Offset.getQuantity(), Alignment64)6
);
9461
14
      Result.adjustOffset(NewOffset - Result.Offset);
9462
      // TODO: diagnose out-of-bounds values/only allow for arrays?
9463
14
      return true;
9464
14
    }
9465
    // Otherwise, we cannot constant-evaluate the result.
9466
5
    Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9467
5
        << Alignment;
9468
5
    return false;
9469
19
  }
9470
518
  case Builtin::BI__builtin_operator_new:
9471
518
    return HandleOperatorNewCall(Info, E, Result);
9472
66
  case Builtin::BI__builtin_launder:
9473
66
    return evaluatePointer(E->getArg(0), Result);
9474
18
  case Builtin::BIstrchr:
9475
34
  case Builtin::BIwcschr:
9476
50
  case Builtin::BImemchr:
9477
66
  case Builtin::BIwmemchr:
9478
66
    if (Info.getLangOpts().CPlusPlus11)
9479
64
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9480
64
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9481
64
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9482
2
    else
9483
2
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9484
66
    [[fallthrough]];
9485
373
  case Builtin::BI__builtin_strchr:
9486
469
  case Builtin::BI__builtin_wcschr:
9487
882
  case Builtin::BI__builtin_memchr:
9488
1.04k
  case Builtin::BI__builtin_char_memchr:
9489
1.12k
  case Builtin::BI__builtin_wmemchr: {
9490
1.12k
    if (!Visit(E->getArg(0)))
9491
136
      return false;
9492
984
    APSInt Desired;
9493
984
    if (!EvaluateInteger(E->getArg(1), Desired, Info))
9494
13
      return false;
9495
971
    uint64_t MaxLength = uint64_t(-1);
9496
971
    if (BuiltinOp != Builtin::BIstrchr &&
9497
971
        
BuiltinOp != Builtin::BIwcschr953
&&
9498
971
        
BuiltinOp != Builtin::BI__builtin_strchr937
&&
9499
971
        
BuiltinOp != Builtin::BI__builtin_wcschr643
) {
9500
547
      APSInt N;
9501
547
      if (!EvaluateInteger(E->getArg(2), N, Info))
9502
16
        return false;
9503
531
      MaxLength = N.getZExtValue();
9504
531
    }
9505
    // We cannot find the value if there are no candidates to match against.
9506
955
    if (MaxLength == 0u)
9507
72
      return ZeroInitialization(E);
9508
883
    if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9509
883
        
Result.Designator.Invalid835
)
9510
48
      return false;
9511
835
    QualType CharTy = Result.Designator.getType(Info.Ctx);
9512
835
    bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9513
835
                     
BuiltinOp == Builtin::BI__builtin_memchr819
;
9514
835
    assert(IsRawByte ||
9515
835
           Info.Ctx.hasSameUnqualifiedType(
9516
835
               CharTy, E->getArg(0)->getType()->getPointeeType()));
9517
    // Pointers to const void may point to objects of incomplete type.
9518
835
    if (IsRawByte && 
CharTy->isIncompleteType()224
) {
9519
8
      Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9520
8
      return false;
9521
8
    }
9522
    // Give up on byte-oriented matching against multibyte elements.
9523
    // FIXME: We can compare the bytes in the correct order.
9524
827
    if (IsRawByte && 
!isOneByteCharacterType(CharTy)216
) {
9525
56
      Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9526
56
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9527
56
          << CharTy;
9528
56
      return false;
9529
56
    }
9530
    // Figure out what value we're actually looking for (after converting to
9531
    // the corresponding unsigned type if necessary).
9532
771
    uint64_t DesiredVal;
9533
771
    bool StopAtNull = false;
9534
771
    switch (BuiltinOp) {
9535
18
    case Builtin::BIstrchr:
9536
304
    case Builtin::BI__builtin_strchr:
9537
      // strchr compares directly to the passed integer, and therefore
9538
      // always fails if given an int that is not a char.
9539
304
      if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9540
304
                                                  E->getArg(1)->getType(),
9541
304
                                                  Desired),
9542
304
                               Desired))
9543
32
        return ZeroInitialization(E);
9544
272
      StopAtNull = true;
9545
272
      [[fallthrough]];
9546
288
    case Builtin::BImemchr:
9547
432
    case Builtin::BI__builtin_memchr:
9548
571
    case Builtin::BI__builtin_char_memchr:
9549
      // memchr compares by converting both sides to unsigned char. That's also
9550
      // correct for strchr if we get this far (to cope with plain char being
9551
      // unsigned in the strchr case).
9552
571
      DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9553
571
      break;
9554
9555
16
    case Builtin::BIwcschr:
9556
104
    case Builtin::BI__builtin_wcschr:
9557
104
      StopAtNull = true;
9558
104
      [[fallthrough]];
9559
120
    case Builtin::BIwmemchr:
9560
168
    case Builtin::BI__builtin_wmemchr:
9561
      // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9562
168
      DesiredVal = Desired.getZExtValue();
9563
168
      break;
9564
771
    }
9565
9566
3.69k
    
for (; 739
MaxLength;
--MaxLength2.95k
) {
9567
3.62k
      APValue Char;
9568
3.62k
      if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9569
3.62k
          
!Char.isInt()3.56k
)
9570
67
        return false;
9571
3.56k
      if (Char.getInt().getZExtValue() == DesiredVal)
9572
484
        return true;
9573
3.07k
      if (StopAtNull && 
!Char.getInt()2.11k
)
9574
124
        break;
9575
2.95k
      if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9576
0
        return false;
9577
2.95k
    }
9578
    // Not found: return nullptr.
9579
188
    return ZeroInitialization(E);
9580
739
  }
9581
9582
62
  case Builtin::BImemcpy:
9583
82
  case Builtin::BImemmove:
9584
88
  case Builtin::BIwmemcpy:
9585
91
  case Builtin::BIwmemmove:
9586
91
    if (Info.getLangOpts().CPlusPlus11)
9587
33
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9588
33
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9589
33
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9590
58
    else
9591
58
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9592
91
    [[fallthrough]];
9593
996
  case Builtin::BI__builtin_memcpy:
9594
1.36k
  case Builtin::BI__builtin_memmove:
9595
1.55k
  case Builtin::BI__builtin_wmemcpy:
9596
1.73k
  case Builtin::BI__builtin_wmemmove: {
9597
1.73k
    bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9598
1.73k
                 
BuiltinOp == Builtin::BIwmemmove1.72k
||
9599
1.73k
                 
BuiltinOp == Builtin::BI__builtin_wmemcpy1.72k
||
9600
1.73k
                 
BuiltinOp == Builtin::BI__builtin_wmemmove1.53k
;
9601
1.73k
    bool Move = BuiltinOp == Builtin::BImemmove ||
9602
1.73k
                
BuiltinOp == Builtin::BIwmemmove1.71k
||
9603
1.73k
                
BuiltinOp == Builtin::BI__builtin_memmove1.70k
||
9604
1.73k
                
BuiltinOp == Builtin::BI__builtin_wmemmove1.33k
;
9605
9606
    // The result of mem* is the first argument.
9607
1.73k
    if (!Visit(E->getArg(0)))
9608
145
      return false;
9609
1.58k
    LValue Dest = Result;
9610
9611
1.58k
    LValue Src;
9612
1.58k
    if (!EvaluatePointer(E->getArg(1), Src, Info))
9613
21
      return false;
9614
9615
1.56k
    APSInt N;
9616
1.56k
    if (!EvaluateInteger(E->getArg(2), N, Info))
9617
20
      return false;
9618
1.54k
    assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9619
9620
    // If the size is zero, we treat this as always being a valid no-op.
9621
    // (Even if one of the src and dest pointers is null.)
9622
1.54k
    if (!N)
9623
61
      return true;
9624
9625
    // Otherwise, if either of the operands is null, we can't proceed. Don't
9626
    // try to determine the type of the copied objects, because there aren't
9627
    // any.
9628
1.48k
    if (!Src.Base || 
!Dest.Base1.43k
) {
9629
88
      APValue Val;
9630
88
      (!Src.Base ? 
Src48
:
Dest40
).moveInto(Val);
9631
88
      Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9632
88
          << Move << WChar << !!Src.Base
9633
88
          << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9634
88
      return false;
9635
88
    }
9636
1.39k
    if (Src.Designator.Invalid || 
Dest.Designator.Invalid1.39k
)
9637
2
      return false;
9638
9639
    // We require that Src and Dest are both pointers to arrays of
9640
    // trivially-copyable type. (For the wide version, the designator will be
9641
    // invalid if the designated object is not a wchar_t.)
9642
1.39k
    QualType T = Dest.Designator.getType(Info.Ctx);
9643
1.39k
    QualType SrcT = Src.Designator.getType(Info.Ctx);
9644
1.39k
    if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9645
      // FIXME: Consider using our bit_cast implementation to support this.
9646
19
      Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9647
19
      return false;
9648
19
    }
9649
1.37k
    if (T->isIncompleteType()) {
9650
49
      Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9651
49
      return false;
9652
49
    }
9653
1.32k
    if (!T.isTriviallyCopyableType(Info.Ctx)) {
9654
32
      Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9655
32
      return false;
9656
32
    }
9657
9658
    // Figure out how many T's we're copying.
9659
1.29k
    uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9660
1.29k
    if (TSize == 0)
9661
0
      return false;
9662
1.29k
    if (!WChar) {
9663
975
      uint64_t Remainder;
9664
975
      llvm::APInt OrigN = N;
9665
975
      llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9666
975
      if (Remainder) {
9667
48
        Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9668
48
            << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9669
48
            << (unsigned)TSize;
9670
48
        return false;
9671
48
      }
9672
975
    }
9673
9674
    // Check that the copying will remain within the arrays, just so that we
9675
    // can give a more meaningful diagnostic. This implicitly also checks that
9676
    // N fits into 64 bits.
9677
1.24k
    uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9678
1.24k
    uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9679
1.24k
    if (N.ugt(RemainingSrcSize) || 
N.ugt(RemainingDestSize)1.09k
) {
9680
256
      Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9681
256
          << Move << WChar << (N.ugt(RemainingSrcSize) ? 
1154
:
2102
) << T
9682
256
          << toString(N, 10, /*Signed*/false);
9683
256
      return false;
9684
256
    }
9685
989
    uint64_t NElems = N.getZExtValue();
9686
989
    uint64_t NBytes = NElems * TSize;
9687
9688
    // Check for overlap.
9689
989
    int Direction = 1;
9690
989
    if (HasSameBase(Src, Dest)) {
9691
459
      uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9692
459
      uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9693
459
      if (DestOffset >= SrcOffset && 
DestOffset - SrcOffset < NBytes187
) {
9694
        // Dest is inside the source region.
9695
120
        if (!Move) {
9696
48
          Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9697
48
          return false;
9698
48
        }
9699
        // For memmove and friends, copy backwards.
9700
72
        if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9701
72
            !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9702
0
          return false;
9703
72
        Direction = -1;
9704
339
      } else if (!Move && 
SrcOffset >= DestOffset195
&&
9705
339
                 
SrcOffset - DestOffset < NBytes160
) {
9706
        // Src is inside the destination region for memcpy: invalid.
9707
48
        Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9708
48
        return false;
9709
48
      }
9710
459
    }
9711
9712
15.3k
    
while (893
true) {
9713
15.3k
      APValue Val;
9714
      // FIXME: Set WantObjectRepresentation to true if we're copying a
9715
      // char-like type?
9716
15.3k
      if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9717
15.3k
          
!handleAssignment(Info, E, Dest, T, Val)15.2k
)
9718
95
        return false;
9719
      // Do not iterate past the last element; if we're copying backwards, that
9720
      // might take us off the start of the array.
9721
15.2k
      if (--NElems == 0)
9722
798
        return true;
9723
14.4k
      if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9724
14.4k
          !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9725
0
        return false;
9726
14.4k
    }
9727
893
  }
9728
9729
0
  default:
9730
0
    return false;
9731
9.86k
  }
9732
9.86k
}
9733
9734
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9735
                                     APValue &Result, const InitListExpr *ILE,
9736
                                     QualType AllocType);
9737
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9738
                                          APValue &Result,
9739
                                          const CXXConstructExpr *CCE,
9740
                                          QualType AllocType);
9741
9742
2.56k
bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9743
2.56k
  if (!Info.getLangOpts().CPlusPlus20)
9744
1.04k
    Info.CCEDiag(E, diag::note_constexpr_new);
9745
9746
  // We cannot speculatively evaluate a delete expression.
9747
2.56k
  if (Info.SpeculativeEvaluationDepth)
9748
0
    return false;
9749
9750
2.56k
  FunctionDecl *OperatorNew = E->getOperatorNew();
9751
9752
2.56k
  bool IsNothrow = false;
9753
2.56k
  bool IsPlacement = false;
9754
2.56k
  if (OperatorNew->isReservedGlobalPlacementOperator() &&
9755
2.56k
      
Info.CurrentCall->isStdFunction()1.05k
&&
!E->isArray()839
) {
9756
    // FIXME Support array placement new.
9757
839
    assert(E->getNumPlacementArgs() == 1);
9758
839
    if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9759
1
      return false;
9760
838
    if (Result.Designator.Invalid)
9761
0
      return false;
9762
838
    IsPlacement = true;
9763
1.73k
  } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9764
378
    Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9765
378
        << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9766
378
    return false;
9767
1.35k
  } else if (E->getNumPlacementArgs()) {
9768
    // The only new-placement list we support is of the form (std::nothrow).
9769
    //
9770
    // FIXME: There is no restriction on this, but it's not clear that any
9771
    // other form makes any sense. We get here for cases such as:
9772
    //
9773
    //   new (std::align_val_t{N}) X(int)
9774
    //
9775
    // (which should presumably be valid only if N is a multiple of
9776
    // alignof(int), and in any case can't be deallocated unless N is
9777
    // alignof(X) and X has new-extended alignment).
9778
100
    if (E->getNumPlacementArgs() != 1 ||
9779
100
        !E->getPlacementArg(0)->getType()->isNothrowT())
9780
32
      return Error(E, diag::note_constexpr_new_placement);
9781
9782
68
    LValue Nothrow;
9783
68
    if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9784
0
      return false;
9785
68
    IsNothrow = true;
9786
68
  }
9787
9788
2.15k
  const Expr *Init = E->getInitializer();
9789
2.15k
  const InitListExpr *ResizedArrayILE = nullptr;
9790
2.15k
  const CXXConstructExpr *ResizedArrayCCE = nullptr;
9791
2.15k
  bool ValueInit = false;
9792
9793
2.15k
  QualType AllocType = E->getAllocatedType();
9794
2.15k
  if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9795
639
    const Expr *Stripped = *ArraySize;
9796
889
    for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9797
639
         
Stripped = ICE->getSubExpr()250
)
9798
445
      if (ICE->getCastKind() != CK_NoOp &&
9799
445
          ICE->getCastKind() != CK_IntegralCast)
9800
195
        break;
9801
9802
639
    llvm::APSInt ArrayBound;
9803
639
    if (!EvaluateInteger(Stripped, ArrayBound, Info))
9804
128
      return false;
9805
9806
    // C++ [expr.new]p9:
9807
    //   The expression is erroneous if:
9808
    //   -- [...] its value before converting to size_t [or] applying the
9809
    //      second standard conversion sequence is less than zero
9810
511
    if (ArrayBound.isSigned() && 
ArrayBound.isNegative()221
) {
9811
2
      if (IsNothrow)
9812
1
        return ZeroInitialization(E);
9813
9814
1
      Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9815
1
          << ArrayBound << (*ArraySize)->getSourceRange();
9816
1
      return false;
9817
2
    }
9818
9819
    //   -- its value is such that the size of the allocated object would
9820
    //      exceed the implementation-defined limit
9821
509
    if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9822
509
                             ConstantArrayType::getNumAddressingBits(
9823
509
                                 Info.Ctx, AllocType, ArrayBound),
9824
509
                             ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9825
2
      if (IsNothrow)
9826
1
        return ZeroInitialization(E);
9827
1
      return false;
9828
2
    }
9829
9830
    //   -- the new-initializer is a braced-init-list and the number of
9831
    //      array elements for which initializers are provided [...]
9832
    //      exceeds the number of elements to initialize
9833
507
    if (!Init) {
9834
      // No initialization is performed.
9835
348
    } else 
if (159
isa<CXXScalarValueInitExpr>(Init)159
||
9836
159
               isa<ImplicitValueInitExpr>(Init)) {
9837
5
      ValueInit = true;
9838
154
    } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9839
72
      ResizedArrayCCE = CCE;
9840
82
    } else {
9841
82
      auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9842
82
      assert(CAT && "unexpected type for array initializer");
9843
9844
82
      unsigned Bits =
9845
82
          std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9846
82
      llvm::APInt InitBound = CAT->getSize().zext(Bits);
9847
82
      llvm::APInt AllocBound = ArrayBound.zext(Bits);
9848
82
      if (InitBound.ugt(AllocBound)) {
9849
7
        if (IsNothrow)
9850
0
          return ZeroInitialization(E);
9851
9852
7
        Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9853
7
            << toString(AllocBound, 10, /*Signed=*/false)
9854
7
            << toString(InitBound, 10, /*Signed=*/false)
9855
7
            << (*ArraySize)->getSourceRange();
9856
7
        return false;
9857
7
      }
9858
9859
      // If the sizes differ, we must have an initializer list, and we need
9860
      // special handling for this case when we initialize.
9861
75
      if (InitBound != AllocBound)
9862
30
        ResizedArrayILE = cast<InitListExpr>(Init);
9863
75
    }
9864
9865
500
    AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9866
500
                                              ArraySizeModifier::Normal, 0);
9867
1.51k
  } else {
9868
1.51k
    assert(!AllocType->isArrayType() &&
9869
1.51k
           "array allocation with non-array new");
9870
1.51k
  }
9871
9872
2.01k
  APValue *Val;
9873
2.01k
  if (IsPlacement) {
9874
838
    AccessKinds AK = AK_Construct;
9875
838
    struct FindObjectHandler {
9876
838
      EvalInfo &Info;
9877
838
      const Expr *E;
9878
838
      QualType AllocType;
9879
838
      const AccessKinds AccessKind;
9880
838
      APValue *Value;
9881
9882
838
      typedef bool result_type;
9883
838
      bool failed() 
{ return false; }6
9884
838
      bool found(APValue &Subobj, QualType SubobjType) {
9885
        // FIXME: Reject the cases where [basic.life]p8 would not permit the
9886
        // old name of the object to be used to name the new object.
9887
822
        if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9888
3
          Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9889
3
            SubobjType << AllocType;
9890
3
          return false;
9891
3
        }
9892
819
        Value = &Subobj;
9893
819
        return true;
9894
822
      }
9895
838
      bool found(APSInt &Value, QualType SubobjType) {
9896
0
        Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9897
0
        return false;
9898
0
      }
9899
838
      bool found(APFloat &Value, QualType SubobjType) {
9900
0
        Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9901
0
        return false;
9902
0
      }
9903
838
    } Handler = {Info, E, AllocType, AK, nullptr};
9904
9905
838
    CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9906
838
    if (!Obj || 
!findSubobject(Info, E, Obj, Result.Designator, Handler)828
)
9907
19
      return false;
9908
9909
819
    Val = Handler.Value;
9910
9911
    // [basic.life]p1:
9912
    //   The lifetime of an object o of type T ends when [...] the storage
9913
    //   which the object occupies is [...] reused by an object that is not
9914
    //   nested within o (6.6.2).
9915
819
    *Val = APValue();
9916
1.18k
  } else {
9917
    // Perform the allocation and obtain a pointer to the resulting object.
9918
1.18k
    Val = Info.createHeapAlloc(E, AllocType, Result);
9919
1.18k
    if (!Val)
9920
0
      return false;
9921
1.18k
  }
9922
9923
2.00k
  if (ValueInit) {
9924
5
    ImplicitValueInitExpr VIE(AllocType);
9925
5
    if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9926
0
      return false;
9927
1.99k
  } else if (ResizedArrayILE) {
9928
30
    if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9929
30
                                  AllocType))
9930
0
      return false;
9931
1.96k
  } else if (ResizedArrayCCE) {
9932
72
    if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9933
72
                                       AllocType))
9934
28
      return false;
9935
1.89k
  } else if (Init) {
9936
1.43k
    if (!EvaluateInPlace(*Val, Info, Result, Init))
9937
231
      return false;
9938
1.43k
  } else 
if (463
!handleDefaultInitValue(AllocType, *Val)463
) {
9939
0
    return false;
9940
0
  }
9941
9942
  // Array new returns a pointer to the first element, not a pointer to the
9943
  // array.
9944
1.74k
  if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9945
468
    Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9946
9947
1.74k
  return true;
9948
2.00k
}
9949
//===----------------------------------------------------------------------===//
9950
// Member Pointer Evaluation
9951
//===----------------------------------------------------------------------===//
9952
9953
namespace {
9954
class MemberPointerExprEvaluator
9955
  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9956
  MemberPtr &Result;
9957
9958
3.98k
  bool Success(const ValueDecl *D) {
9959
3.98k
    Result = MemberPtr(D);
9960
3.98k
    return true;
9961
3.98k
  }
9962
public:
9963
9964
  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9965
5.04k
    : ExprEvaluatorBaseTy(Info), Result(Result) {}
9966
9967
268
  bool Success(const APValue &V, const Expr *E) {
9968
268
    Result.setFrom(V);
9969
268
    return true;
9970
268
  }
9971
537
  bool ZeroInitialization(const Expr *E) {
9972
537
    return Success((const ValueDecl*)nullptr);
9973
537
  }
9974
9975
  bool VisitCastExpr(const CastExpr *E);
9976
  bool VisitUnaryAddrOf(const UnaryOperator *E);
9977
};
9978
} // end anonymous namespace
9979
9980
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9981
5.04k
                                  EvalInfo &Info) {
9982
5.04k
  assert(!E->isValueDependent());
9983
5.04k
  assert(E->isPRValue() && E->getType()->isMemberPointerType());
9984
5.04k
  return MemberPointerExprEvaluator(Info, Result).Visit(E);
9985
5.04k
}
9986
9987
2.24k
bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9988
2.24k
  switch (E->getCastKind()) {
9989
1.23k
  default:
9990
1.23k
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
9991
9992
505
  case CK_NullToMemberPointer:
9993
505
    VisitIgnoredValue(E->getSubExpr());
9994
505
    return ZeroInitialization(E);
9995
9996
370
  case CK_BaseToDerivedMemberPointer: {
9997
370
    if (!Visit(E->getSubExpr()))
9998
34
      return false;
9999
336
    if (E->path_empty())
10000
0
      return true;
10001
    // Base-to-derived member pointer casts store the path in derived-to-base
10002
    // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10003
    // the wrong end of the derived->base arc, so stagger the path by one class.
10004
336
    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10005
336
    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10006
541
         PathI != PathE; 
++PathI205
) {
10007
205
      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10008
205
      const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10009
205
      if (!Result.castToDerived(Derived))
10010
0
        return Error(E);
10011
205
    }
10012
336
    const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10013
336
    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10014
0
      return Error(E);
10015
336
    return true;
10016
336
  }
10017
10018
138
  case CK_DerivedToBaseMemberPointer:
10019
138
    if (!Visit(E->getSubExpr()))
10020
14
      return false;
10021
124
    for (CastExpr::path_const_iterator PathI = E->path_begin(),
10022
485
         PathE = E->path_end(); PathI != PathE; 
++PathI361
) {
10023
361
      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10024
361
      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10025
361
      if (!Result.castToBase(Base))
10026
0
        return Error(E);
10027
361
    }
10028
124
    return true;
10029
2.24k
  }
10030
2.24k
}
10031
10032
3.45k
bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10033
  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10034
  // member can be formed.
10035
3.45k
  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10036
3.45k
}
10037
10038
//===----------------------------------------------------------------------===//
10039
// Record Evaluation
10040
//===----------------------------------------------------------------------===//
10041
10042
namespace {
10043
  class RecordExprEvaluator
10044
  : public ExprEvaluatorBase<RecordExprEvaluator> {
10045
    const LValue &This;
10046
    APValue &Result;
10047
  public:
10048
10049
    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10050
120k
      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10051
10052
819
    bool Success(const APValue &V, const Expr *E) {
10053
819
      Result = V;
10054
819
      return true;
10055
819
    }
10056
488
    bool ZeroInitialization(const Expr *E) {
10057
488
      return ZeroInitialization(E, E->getType());
10058
488
    }
10059
    bool ZeroInitialization(const Expr *E, QualType T);
10060
10061
15.0k
    bool VisitCallExpr(const CallExpr *E) {
10062
15.0k
      return handleCallExpr(E, Result, &This);
10063
15.0k
    }
10064
    bool VisitCastExpr(const CastExpr *E);
10065
    bool VisitInitListExpr(const InitListExpr *E);
10066
97.4k
    bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10067
97.4k
      return VisitCXXConstructExpr(E, E->getType());
10068
97.4k
    }
10069
    bool VisitLambdaExpr(const LambdaExpr *E);
10070
    bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10071
    bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10072
    bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10073
    bool VisitBinCmp(const BinaryOperator *E);
10074
    bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10075
    bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10076
                                         ArrayRef<Expr *> Args);
10077
  };
10078
}
10079
10080
/// Perform zero-initialization on an object of non-union class type.
10081
/// C++11 [dcl.init]p5:
10082
///  To zero-initialize an object or reference of type T means:
10083
///    [...]
10084
///    -- if T is a (possibly cv-qualified) non-union class type,
10085
///       each non-static data member and each base-class subobject is
10086
///       zero-initialized
10087
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10088
                                          const RecordDecl *RD,
10089
19.2k
                                          const LValue &This, APValue &Result) {
10090
19.2k
  assert(!RD->isUnion() && "Expected non-union class type");
10091
19.2k
  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10092
19.2k
  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 
00
,
10093
19.2k
                   std::distance(RD->field_begin(), RD->field_end()));
10094
10095
19.2k
  if (RD->isInvalidDecl()) 
return false0
;
10096
19.2k
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10097
10098
19.2k
  if (CD) {
10099
19.2k
    unsigned Index = 0;
10100
19.2k
    for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10101
20.9k
           End = CD->bases_end(); I != End; 
++I, ++Index1.74k
) {
10102
1.74k
      const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10103
1.74k
      LValue Subobject = This;
10104
1.74k
      if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10105
0
        return false;
10106
1.74k
      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10107
1.74k
                                         Result.getStructBase(Index)))
10108
0
        return false;
10109
1.74k
    }
10110
19.2k
  }
10111
10112
19.2k
  for (const auto *I : RD->fields()) {
10113
    // -- if T is a reference type, no initialization is performed.
10114
2.26k
    if (I->isUnnamedBitfield() || 
I->getType()->isReferenceType()2.25k
)
10115
22
      continue;
10116
10117
2.24k
    LValue Subobject = This;
10118
2.24k
    if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10119
0
      return false;
10120
10121
2.24k
    ImplicitValueInitExpr VIE(I->getType());
10122
2.24k
    if (!EvaluateInPlace(
10123
2.24k
          Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10124
0
      return false;
10125
2.24k
  }
10126
10127
19.2k
  return true;
10128
19.2k
}
10129
10130
17.7k
bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10131
17.7k
  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10132
17.7k
  if (RD->isInvalidDecl()) 
return false0
;
10133
17.7k
  if (RD->isUnion()) {
10134
    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10135
    // object's first non-static named data member is zero-initialized
10136
227
    RecordDecl::field_iterator I = RD->field_begin();
10137
233
    while (I != RD->field_end() && 
(*I)->isUnnamedBitfield()205
)
10138
6
      ++I;
10139
227
    if (I == RD->field_end()) {
10140
28
      Result = APValue((const FieldDecl*)nullptr);
10141
28
      return true;
10142
28
    }
10143
10144
199
    LValue Subobject = This;
10145
199
    if (!HandleLValueMember(Info, E, Subobject, *I))
10146
0
      return false;
10147
199
    Result = APValue(*I);
10148
199
    ImplicitValueInitExpr VIE(I->getType());
10149
199
    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10150
199
  }
10151
10152
17.5k
  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10153
0
    Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10154
0
    return false;
10155
0
  }
10156
10157
17.5k
  return HandleClassZeroInitialization(Info, E, RD, This, Result);
10158
17.5k
}
10159
10160
22.6k
bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10161
22.6k
  switch (E->getCastKind()) {
10162
10.6k
  default:
10163
10.6k
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
10164
10165
12.0k
  case CK_ConstructorConversion:
10166
12.0k
    return Visit(E->getSubExpr());
10167
10168
0
  case CK_DerivedToBase:
10169
48
  case CK_UncheckedDerivedToBase: {
10170
48
    APValue DerivedObject;
10171
48
    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10172
4
      return false;
10173
44
    if (!DerivedObject.isStruct())
10174
0
      return Error(E->getSubExpr());
10175
10176
    // Derived-to-base rvalue conversion: just slice off the derived part.
10177
44
    APValue *Value = &DerivedObject;
10178
44
    const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10179
44
    for (CastExpr::path_const_iterator PathI = E->path_begin(),
10180
88
         PathE = E->path_end(); PathI != PathE; 
++PathI44
) {
10181
44
      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10182
44
      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10183
44
      Value = &Value->getStructBase(getBaseIndex(RD, Base));
10184
44
      RD = Base;
10185
44
    }
10186
44
    Result = *Value;
10187
44
    return true;
10188
44
  }
10189
22.6k
  }
10190
22.6k
}
10191
10192
9.83k
bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10193
9.83k
  if (E->isTransparent())
10194
33
    return Visit(E->getInit(0));
10195
9.80k
  return VisitCXXParenListOrInitListExpr(E, E->inits());
10196
9.83k
}
10197
10198
bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10199
9.86k
    const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10200
9.86k
  const RecordDecl *RD =
10201
9.86k
      ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10202
9.86k
  if (RD->isInvalidDecl()) 
return false0
;
10203
9.86k
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10204
9.86k
  auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10205
10206
9.86k
  EvalInfo::EvaluatingConstructorRAII EvalObj(
10207
9.86k
      Info,
10208
9.86k
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10209
9.86k
      CXXRD && 
CXXRD->getNumBases()9.03k
);
10210
10211
9.86k
  if (RD->isUnion()) {
10212
549
    const FieldDecl *Field;
10213
549
    if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10214
545
      Field = ILE->getInitializedFieldInUnion();
10215
545
    } else 
if (auto *4
PLIE4
= dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10216
4
      Field = PLIE->getInitializedFieldInUnion();
10217
4
    } else {
10218
0
      llvm_unreachable(
10219
0
          "Expression is neither an init list nor a C++ paren list");
10220
0
    }
10221
10222
549
    Result = APValue(Field);
10223
549
    if (!Field)
10224
69
      return true;
10225
10226
    // If the initializer list for a union does not contain any elements, the
10227
    // first element of the union is value-initialized.
10228
    // FIXME: The element should be initialized from an initializer list.
10229
    //        Is this difference ever observable for initializer lists which
10230
    //        we don't build?
10231
480
    ImplicitValueInitExpr VIE(Field->getType());
10232
480
    const Expr *InitExpr = Args.empty() ? 
&VIE51
:
Args[0]429
;
10233
10234
480
    LValue Subobject = This;
10235
480
    if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10236
0
      return false;
10237
10238
    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10239
480
    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10240
480
                                  isa<CXXDefaultInitExpr>(InitExpr));
10241
10242
480
    if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10243
457
      if (Field->isBitField())
10244
40
        return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10245
40
                                     Field);
10246
417
      return true;
10247
457
    }
10248
10249
23
    return false;
10250
480
  }
10251
10252
9.31k
  if (!Result.hasValue())
10253
9.31k
    Result = APValue(APValue::UninitStruct(), CXXRD ? 
CXXRD->getNumBases()8.57k
:
0740
,
10254
9.31k
                     std::distance(RD->field_begin(), RD->field_end()));
10255
9.31k
  unsigned ElementNo = 0;
10256
9.31k
  bool Success = true;
10257
10258
  // Initialize base classes.
10259
9.31k
  if (CXXRD && 
CXXRD->getNumBases()8.57k
) {
10260
398
    for (const auto &Base : CXXRD->bases()) {
10261
398
      assert(ElementNo < Args.size() && "missing init for base class");
10262
398
      const Expr *Init = Args[ElementNo];
10263
10264
398
      LValue Subobject = This;
10265
398
      if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10266
0
        return false;
10267
10268
398
      APValue &FieldVal = Result.getStructBase(ElementNo);
10269
398
      if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10270
27
        if (!Info.noteFailure())
10271
26
          return false;
10272
1
        Success = false;
10273
1
      }
10274
372
      ++ElementNo;
10275
372
    }
10276
10277
317
    EvalObj.finishedConstructingBases();
10278
317
  }
10279
10280
  // Initialize members.
10281
16.7k
  
for (const auto *Field : RD->fields())9.28k
{
10282
    // Anonymous bit-fields are not considered members of the class for
10283
    // purposes of aggregate initialization.
10284
16.7k
    if (Field->isUnnamedBitfield())
10285
150
      continue;
10286
10287
16.5k
    LValue Subobject = This;
10288
10289
16.5k
    bool HaveInit = ElementNo < Args.size();
10290
10291
    // FIXME: Diagnostics here should point to the end of the initializer
10292
    // list, not the start.
10293
16.5k
    if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : 
ExprToVisit0
,
10294
16.5k
                            Subobject, Field, &Layout))
10295
0
      return false;
10296
10297
    // Perform an implicit value-initialization for members beyond the end of
10298
    // the initializer list.
10299
16.5k
    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : 
Field->getType()0
);
10300
16.5k
    const Expr *Init = HaveInit ? Args[ElementNo++] : 
&VIE0
;
10301
10302
16.5k
    if (Field->getType()->isIncompleteArrayType()) {
10303
48
      if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10304
26
        if (!CAT->getSize().isZero()) {
10305
          // Bail out for now. This might sort of "work", but the rest of the
10306
          // code isn't really prepared to handle it.
10307
23
          Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10308
23
          return false;
10309
23
        }
10310
26
      }
10311
48
    }
10312
10313
    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10314
16.5k
    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10315
16.5k
                                  isa<CXXDefaultInitExpr>(Init));
10316
10317
16.5k
    APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10318
16.5k
    if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10319
16.5k
        
(15.8k
Field->isBitField()15.8k
&& !truncateBitfieldValue(Info, Init,
10320
744
                                                       FieldVal, Field))) {
10321
717
      if (!Info.noteFailure())
10322
576
        return false;
10323
141
      Success = false;
10324
141
    }
10325
16.5k
  }
10326
10327
8.69k
  EvalObj.finishedConstructingFields();
10328
10329
8.69k
  return Success;
10330
9.28k
}
10331
10332
bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10333
104k
                                                QualType T) {
10334
  // Note that E's type is not necessarily the type of our class here; we might
10335
  // be initializing an array element instead.
10336
104k
  const CXXConstructorDecl *FD = E->getConstructor();
10337
104k
  if (FD->isInvalidDecl() || 
FD->getParent()->isInvalidDecl()104k
)
return false44
;
10338
10339
104k
  bool ZeroInit = E->requiresZeroInitialization();
10340
104k
  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10341
    // If we've already performed zero-initialization, we're already done.
10342
24.3k
    if (Result.hasValue())
10343
18
      return true;
10344
10345
24.3k
    if (ZeroInit)
10346
16.8k
      return ZeroInitialization(E, T);
10347
10348
7.48k
    return handleDefaultInitValue(T, Result);
10349
24.3k
  }
10350
10351
79.6k
  const FunctionDecl *Definition = nullptr;
10352
79.6k
  auto Body = FD->getBody(Definition);
10353
10354
79.6k
  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10355
27.6k
    return false;
10356
10357
  // Avoid materializing a temporary for an elidable copy/move constructor.
10358
51.9k
  if (E->isElidable() && 
!ZeroInit16.7k
) {
10359
    // FIXME: This only handles the simplest case, where the source object
10360
    //        is passed directly as the first argument to the constructor.
10361
    //        This should also handle stepping though implicit casts and
10362
    //        and conversion sequences which involve two steps, with a
10363
    //        conversion operator followed by a converting constructor.
10364
16.7k
    const Expr *SrcObj = E->getArg(0);
10365
16.7k
    assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10366
16.7k
    assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10367
16.7k
    if (const MaterializeTemporaryExpr *ME =
10368
16.7k
            dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10369
16.7k
      return Visit(ME->getSubExpr());
10370
16.7k
  }
10371
10372
35.1k
  if (ZeroInit && 
!ZeroInitialization(E, T)401
)
10373
0
    return false;
10374
10375
35.1k
  auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10376
35.1k
  return HandleConstructorCall(E, This, Args,
10377
35.1k
                               cast<CXXConstructorDecl>(Definition), Info,
10378
35.1k
                               Result);
10379
35.1k
}
10380
10381
bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10382
35
    const CXXInheritedCtorInitExpr *E) {
10383
35
  if (!Info.CurrentCall) {
10384
0
    assert(Info.checkingPotentialConstantExpression());
10385
0
    return false;
10386
0
  }
10387
10388
35
  const CXXConstructorDecl *FD = E->getConstructor();
10389
35
  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10390
0
    return false;
10391
10392
35
  const FunctionDecl *Definition = nullptr;
10393
35
  auto Body = FD->getBody(Definition);
10394
10395
35
  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10396
0
    return false;
10397
10398
35
  return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10399
35
                               cast<CXXConstructorDecl>(Definition), Info,
10400
35
                               Result);
10401
35
}
10402
10403
bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10404
175
    const CXXStdInitializerListExpr *E) {
10405
175
  const ConstantArrayType *ArrayType =
10406
175
      Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10407
10408
175
  LValue Array;
10409
175
  if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10410
14
    return false;
10411
10412
161
  assert(ArrayType && "unexpected type for array initializer");
10413
10414
  // Get a pointer to the first element of the array.
10415
161
  Array.addArray(Info, E, ArrayType);
10416
10417
161
  auto InvalidType = [&] {
10418
8
    Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10419
8
      << E->getType();
10420
8
    return false;
10421
8
  };
10422
10423
  // FIXME: Perform the checks on the field types in SemaInit.
10424
161
  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10425
161
  RecordDecl::field_iterator Field = Record->field_begin();
10426
161
  if (Field == Record->field_end())
10427
6
    return InvalidType();
10428
10429
  // Start pointer.
10430
155
  if (!Field->getType()->isPointerType() ||
10431
155
      !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10432
153
                            ArrayType->getElementType()))
10433
2
    return InvalidType();
10434
10435
  // FIXME: What if the initializer_list type has base classes, etc?
10436
153
  Result = APValue(APValue::UninitStruct(), 0, 2);
10437
153
  Array.moveInto(Result.getStructField(0));
10438
10439
153
  if (++Field == Record->field_end())
10440
0
    return InvalidType();
10441
10442
153
  if (Field->getType()->isPointerType() &&
10443
153
      Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10444
8
                           ArrayType->getElementType())) {
10445
    // End pointer.
10446
8
    if (!HandleLValueArrayAdjustment(Info, E, Array,
10447
8
                                     ArrayType->getElementType(),
10448
8
                                     ArrayType->getSize().getZExtValue()))
10449
0
      return false;
10450
8
    Array.moveInto(Result.getStructField(1));
10451
145
  } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10452
    // Length.
10453
145
    Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10454
0
  else
10455
0
    return InvalidType();
10456
10457
153
  if (++Field != Record->field_end())
10458
0
    return InvalidType();
10459
10460
153
  return true;
10461
153
}
10462
10463
1.47k
bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10464
1.47k
  const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10465
1.47k
  if (ClosureClass->isInvalidDecl())
10466
0
    return false;
10467
10468
1.47k
  const size_t NumFields =
10469
1.47k
      std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10470
10471
1.47k
  assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10472
1.47k
                                            E->capture_init_end()) &&
10473
1.47k
         "The number of lambda capture initializers should equal the number of "
10474
1.47k
         "fields within the closure type");
10475
10476
1.47k
  Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10477
  // Iterate through all the lambda's closure object's fields and initialize
10478
  // them.
10479
1.47k
  auto *CaptureInitIt = E->capture_init_begin();
10480
1.47k
  bool Success = true;
10481
1.47k
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10482
1.47k
  for (const auto *Field : ClosureClass->fields()) {
10483
347
    assert(CaptureInitIt != E->capture_init_end());
10484
    // Get the initializer for this field
10485
347
    Expr *const CurFieldInit = *CaptureInitIt++;
10486
10487
    // If there is no initializer, either this is a VLA or an error has
10488
    // occurred.
10489
347
    if (!CurFieldInit)
10490
4
      return Error(E);
10491
10492
343
    LValue Subobject = This;
10493
10494
343
    if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10495
0
      return false;
10496
10497
343
    APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10498
343
    if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10499
84
      if (!Info.keepEvaluatingAfterFailure())
10500
23
        return false;
10501
61
      Success = false;
10502
61
    }
10503
343
  }
10504
1.44k
  return Success;
10505
1.47k
}
10506
10507
static bool EvaluateRecord(const Expr *E, const LValue &This,
10508
114k
                           APValue &Result, EvalInfo &Info) {
10509
114k
  assert(!E->isValueDependent());
10510
114k
  assert(E->isPRValue() && E->getType()->isRecordType() &&
10511
114k
         "can't evaluate expression as a record rvalue");
10512
114k
  return RecordExprEvaluator(Info, This, Result).Visit(E);
10513
114k
}
10514
10515
//===----------------------------------------------------------------------===//
10516
// Temporary Evaluation
10517
//
10518
// Temporaries are represented in the AST as rvalues, but generally behave like
10519
// lvalues. The full-object of which the temporary is a subobject is implicitly
10520
// materialized so that a reference can bind to it.
10521
//===----------------------------------------------------------------------===//
10522
namespace {
10523
class TemporaryExprEvaluator
10524
  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10525
public:
10526
  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10527
5
    LValueExprEvaluatorBaseTy(Info, Result, false) {}
10528
10529
  /// Visit an expression which constructs the value of this temporary.
10530
5
  bool VisitConstructExpr(const Expr *E) {
10531
5
    APValue &Value = Info.CurrentCall->createTemporary(
10532
5
        E, E->getType(), ScopeKind::FullExpression, Result);
10533
5
    return EvaluateInPlace(Value, Info, Result, E);
10534
5
  }
10535
10536
0
  bool VisitCastExpr(const CastExpr *E) {
10537
0
    switch (E->getCastKind()) {
10538
0
    default:
10539
0
      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10540
10541
0
    case CK_ConstructorConversion:
10542
0
      return VisitConstructExpr(E->getSubExpr());
10543
0
    }
10544
0
  }
10545
0
  bool VisitInitListExpr(const InitListExpr *E) {
10546
0
    return VisitConstructExpr(E);
10547
0
  }
10548
5
  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10549
5
    return VisitConstructExpr(E);
10550
5
  }
10551
0
  bool VisitCallExpr(const CallExpr *E) {
10552
0
    return VisitConstructExpr(E);
10553
0
  }
10554
0
  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10555
0
    return VisitConstructExpr(E);
10556
0
  }
10557
0
  bool VisitLambdaExpr(const LambdaExpr *E) {
10558
0
    return VisitConstructExpr(E);
10559
0
  }
10560
};
10561
} // end anonymous namespace
10562
10563
/// Evaluate an expression of record type as a temporary.
10564
5
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10565
5
  assert(!E->isValueDependent());
10566
5
  assert(E->isPRValue() && E->getType()->isRecordType());
10567
5
  return TemporaryExprEvaluator(Info, Result).Visit(E);
10568
5
}
10569
10570
//===----------------------------------------------------------------------===//
10571
// Vector Evaluation
10572
//===----------------------------------------------------------------------===//
10573
10574
namespace {
10575
  class VectorExprEvaluator
10576
  : public ExprEvaluatorBase<VectorExprEvaluator> {
10577
    APValue &Result;
10578
  public:
10579
10580
    VectorExprEvaluator(EvalInfo &info, APValue &Result)
10581
2.32M
      : ExprEvaluatorBaseTy(info), Result(Result) {}
10582
10583
2.34k
    bool Success(ArrayRef<APValue> V, const Expr *E) {
10584
2.34k
      assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10585
      // FIXME: remove this APValue copy.
10586
2.34k
      Result = APValue(V.data(), V.size());
10587
2.34k
      return true;
10588
2.34k
    }
10589
932
    bool Success(const APValue &V, const Expr *E) {
10590
932
      assert(V.isVector());
10591
932
      Result = V;
10592
932
      return true;
10593
932
    }
10594
    bool ZeroInitialization(const Expr *E);
10595
10596
    bool VisitUnaryReal(const UnaryOperator *E)
10597
0
      { return Visit(E->getSubExpr()); }
10598
    bool VisitCastExpr(const CastExpr* E);
10599
    bool VisitInitListExpr(const InitListExpr *E);
10600
    bool VisitUnaryImag(const UnaryOperator *E);
10601
    bool VisitBinaryOperator(const BinaryOperator *E);
10602
    bool VisitUnaryOperator(const UnaryOperator *E);
10603
    // FIXME: Missing: conditional operator (for GNU
10604
    //                 conditional select), shufflevector, ExtVectorElementExpr
10605
  };
10606
} // end anonymous namespace
10607
10608
2.32M
static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10609
2.32M
  assert(E->isPRValue() && E->getType()->isVectorType() &&
10610
2.32M
         "not a vector prvalue");
10611
2.32M
  return VectorExprEvaluator(Info, Result).Visit(E);
10612
2.32M
}
10613
10614
1.16M
bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10615
1.16M
  const VectorType *VTy = E->getType()->castAs<VectorType>();
10616
1.16M
  unsigned NElts = VTy->getNumElements();
10617
10618
1.16M
  const Expr *SE = E->getSubExpr();
10619
1.16M
  QualType SETy = SE->getType();
10620
10621
1.16M
  switch (E->getCastKind()) {
10622
2.26k
  case CK_VectorSplat: {
10623
2.26k
    APValue Val = APValue();
10624
2.26k
    if (SETy->isIntegerType()) {
10625
1.66k
      APSInt IntResult;
10626
1.66k
      if (!EvaluateInteger(SE, IntResult, Info))
10627
812
        return false;
10628
848
      Val = APValue(std::move(IntResult));
10629
848
    } else 
if (605
SETy->isRealFloatingType()605
) {
10630
605
      APFloat FloatResult(0.0);
10631
605
      if (!EvaluateFloat(SE, FloatResult, Info))
10632
289
        return false;
10633
316
      Val = APValue(std::move(FloatResult));
10634
316
    } else {
10635
0
      return Error(E);
10636
0
    }
10637
10638
    // Splat and create vector APValue.
10639
1.16k
    SmallVector<APValue, 4> Elts(NElts, Val);
10640
1.16k
    return Success(Elts, E);
10641
2.26k
  }
10642
481k
  case CK_BitCast: {
10643
481k
    APValue SVal;
10644
481k
    if (!Evaluate(SVal, Info, SE))
10645
481k
      return false;
10646
10647
296
    if (!SVal.isInt() && 
!SVal.isFloat()223
&&
!SVal.isVector()223
) {
10648
      // Give up if the input isn't an int, float, or vector.  For example, we
10649
      // reject "(v4i16)(intptr_t)&a".
10650
0
      Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10651
0
          << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10652
0
      return false;
10653
0
    }
10654
10655
296
    if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10656
2
      return false;
10657
10658
294
    return true;
10659
296
  }
10660
683k
  default:
10661
683k
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
10662
1.16M
  }
10663
1.16M
}
10664
10665
bool
10666
24.5k
VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10667
24.5k
  const VectorType *VT = E->getType()->castAs<VectorType>();
10668
24.5k
  unsigned NumInits = E->getNumInits();
10669
24.5k
  unsigned NumElements = VT->getNumElements();
10670
10671
24.5k
  QualType EltTy = VT->getElementType();
10672
24.5k
  SmallVector<APValue, 4> Elements;
10673
10674
  // The number of initializers can be less than the number of
10675
  // vector elements. For OpenCL, this can be due to nested vector
10676
  // initialization. For GCC compatibility, missing trailing elements
10677
  // should be initialized with zeroes.
10678
24.5k
  unsigned CountInits = 0, CountElts = 0;
10679
30.5k
  while (CountElts < NumElements) {
10680
    // Handle nested vector initialization.
10681
29.3k
    if (CountInits < NumInits
10682
29.3k
        && 
E->getInit(CountInits)->getType()->isVectorType()28.5k
) {
10683
20
      APValue v;
10684
20
      if (!EvaluateVector(E->getInit(CountInits), v, Info))
10685
5
        return Error(E);
10686
15
      unsigned vlen = v.getVectorLength();
10687
49
      for (unsigned j = 0; j < vlen; 
j++34
)
10688
34
        Elements.push_back(v.getVectorElt(j));
10689
15
      CountElts += vlen;
10690
29.3k
    } else if (EltTy->isIntegerType()) {
10691
22.9k
      llvm::APSInt sInt(32);
10692
22.9k
      if (CountInits < NumInits) {
10693
22.1k
        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10694
18.9k
          return false;
10695
22.1k
      } else // trailing integer zero.
10696
823
        sInt = Info.Ctx.MakeIntValue(0, EltTy);
10697
4.02k
      Elements.push_back(APValue(sInt));
10698
4.02k
      CountElts++;
10699
6.44k
    } else {
10700
6.44k
      llvm::APFloat f(0.0);
10701
6.44k
      if (CountInits < NumInits) {
10702
6.43k
        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10703
4.45k
          return false;
10704
6.43k
      } else // trailing float zero.
10705
6
        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10706
1.99k
      Elements.push_back(APValue(f));
10707
1.99k
      CountElts++;
10708
1.99k
    }
10709
6.02k
    CountInits++;
10710
6.02k
  }
10711
1.16k
  return Success(Elements, E);
10712
24.5k
}
10713
10714
bool
10715
10
VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10716
10
  const auto *VT = E->getType()->castAs<VectorType>();
10717
10
  QualType EltTy = VT->getElementType();
10718
10
  APValue ZeroElement;
10719
10
  if (EltTy->isIntegerType())
10720
6
    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10721
4
  else
10722
4
    ZeroElement =
10723
4
        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10724
10725
10
  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10726
10
  return Success(Elements, E);
10727
10
}
10728
10729
0
bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10730
0
  VisitIgnoredValue(E->getSubExpr());
10731
0
  return ZeroInitialization(E);
10732
0
}
10733
10734
632k
bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10735
632k
  BinaryOperatorKind Op = E->getOpcode();
10736
632k
  assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10737
632k
         "Operation not supported on vector types");
10738
10739
632k
  if (Op == BO_Comma)
10740
1
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10741
10742
632k
  Expr *LHS = E->getLHS();
10743
632k
  Expr *RHS = E->getRHS();
10744
10745
632k
  assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10746
632k
         "Must both be vector types");
10747
  // Checking JUST the types are the same would be fine, except shifts don't
10748
  // need to have their types be the same (since you always shift by an int).
10749
632k
  assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10750
632k
             E->getType()->castAs<VectorType>()->getNumElements() &&
10751
632k
         RHS->getType()->castAs<VectorType>()->getNumElements() ==
10752
632k
             E->getType()->castAs<VectorType>()->getNumElements() &&
10753
632k
         "All operands must be the same size.");
10754
10755
632k
  APValue LHSValue;
10756
632k
  APValue RHSValue;
10757
632k
  bool LHSOK = Evaluate(LHSValue, Info, LHS);
10758
632k
  if (!LHSOK && 
!Info.noteFailure()179k
)
10759
1.42k
    return false;
10760
630k
  if (!Evaluate(RHSValue, Info, RHS) || 
!LHSOK1.09k
)
10761
630k
    return false;
10762
10763
531
  if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10764
362
    return false;
10765
10766
169
  return Success(LHSValue, E);
10767
531
}
10768
10769
static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10770
                                                        QualType ResultTy,
10771
                                                        UnaryOperatorKind Op,
10772
112
                                                        APValue Elt) {
10773
112
  switch (Op) {
10774
0
  case UO_Plus:
10775
    // Nothing to do here.
10776
0
    return Elt;
10777
16
  case UO_Minus:
10778
16
    if (Elt.getKind() == APValue::Int) {
10779
8
      Elt.getInt().negate();
10780
8
    } else {
10781
8
      assert(Elt.getKind() == APValue::Float &&
10782
8
             "Vector can only be int or float type");
10783
8
      Elt.getFloat().changeSign();
10784
8
    }
10785
16
    return Elt;
10786
20
  case UO_Not:
10787
    // This is only valid for integral types anyway, so we don't have to handle
10788
    // float here.
10789
20
    assert(Elt.getKind() == APValue::Int &&
10790
20
           "Vector operator ~ can only be int");
10791
20
    Elt.getInt().flipAllBits();
10792
20
    return Elt;
10793
76
  case UO_LNot: {
10794
76
    if (Elt.getKind() == APValue::Int) {
10795
20
      Elt.getInt() = !Elt.getInt();
10796
      // operator ! on vectors returns -1 for 'truth', so negate it.
10797
20
      Elt.getInt().negate();
10798
20
      return Elt;
10799
20
    }
10800
56
    assert(Elt.getKind() == APValue::Float &&
10801
56
           "Vector can only be int or float type");
10802
    // Float types result in an int of the same size, but -1 for true, or 0 for
10803
    // false.
10804
56
    APSInt EltResult{Ctx.getIntWidth(ResultTy),
10805
56
                     ResultTy->isUnsignedIntegerType()};
10806
56
    if (Elt.getFloat().isZero())
10807
26
      EltResult.setAllBits();
10808
30
    else
10809
30
      EltResult.clearAllBits();
10810
10811
56
    return APValue{EltResult};
10812
56
  }
10813
0
  default:
10814
    // FIXME: Implement the rest of the unary operators.
10815
0
    return std::nullopt;
10816
112
  }
10817
112
}
10818
10819
91.0k
bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10820
91.0k
  Expr *SubExpr = E->getSubExpr();
10821
91.0k
  const auto *VD = SubExpr->getType()->castAs<VectorType>();
10822
  // This result element type differs in the case of negating a floating point
10823
  // vector, since the result type is the a vector of the equivilant sized
10824
  // integer.
10825
91.0k
  const QualType ResultEltTy = VD->getElementType();
10826
91.0k
  UnaryOperatorKind Op = E->getOpcode();
10827
10828
91.0k
  APValue SubExprValue;
10829
91.0k
  if (!Evaluate(SubExprValue, Info, SubExpr))
10830
90.9k
    return false;
10831
10832
  // FIXME: This vector evaluator someday needs to be changed to be LValue
10833
  // aware/keep LValue information around, rather than dealing with just vector
10834
  // types directly. Until then, we cannot handle cases where the operand to
10835
  // these unary operators is an LValue. The only case I've been able to see
10836
  // cause this is operator++ assigning to a member expression (only valid in
10837
  // altivec compilations) in C mode, so this shouldn't limit us too much.
10838
83
  if (SubExprValue.isLValue())
10839
55
    return false;
10840
10841
28
  assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10842
28
         "Vector length doesn't match type?");
10843
10844
28
  SmallVector<APValue, 4> ResultElements;
10845
140
  for (unsigned EltNum = 0; EltNum < VD->getNumElements(); 
++EltNum112
) {
10846
112
    std::optional<APValue> Elt = handleVectorUnaryOperator(
10847
112
        Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10848
112
    if (!Elt)
10849
0
      return false;
10850
112
    ResultElements.push_back(*Elt);
10851
112
  }
10852
28
  return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10853
28
}
10854
10855
//===----------------------------------------------------------------------===//
10856
// Array Evaluation
10857
//===----------------------------------------------------------------------===//
10858
10859
namespace {
10860
  class ArrayExprEvaluator
10861
  : public ExprEvaluatorBase<ArrayExprEvaluator> {
10862
    const LValue &This;
10863
    APValue &Result;
10864
  public:
10865
10866
    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10867
13.6k
      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10868
10869
10
    bool Success(const APValue &V, const Expr *E) {
10870
10
      assert(V.isArray() && "expected array");
10871
10
      Result = V;
10872
10
      return true;
10873
10
    }
10874
10875
371
    bool ZeroInitialization(const Expr *E) {
10876
371
      const ConstantArrayType *CAT =
10877
371
          Info.Ctx.getAsConstantArrayType(E->getType());
10878
371
      if (!CAT) {
10879
23
        if (E->getType()->isIncompleteArrayType()) {
10880
          // We can be asked to zero-initialize a flexible array member; this
10881
          // is represented as an ImplicitValueInitExpr of incomplete array
10882
          // type. In this case, the array has zero elements.
10883
23
          Result = APValue(APValue::UninitArray(), 0, 0);
10884
23
          return true;
10885
23
        }
10886
        // FIXME: We could handle VLAs here.
10887
0
        return Error(E);
10888
23
      }
10889
10890
348
      Result = APValue(APValue::UninitArray(), 0,
10891
348
                       CAT->getSize().getZExtValue());
10892
348
      if (!Result.hasArrayFiller())
10893
92
        return true;
10894
10895
      // Zero-initialize all elements.
10896
256
      LValue Subobject = This;
10897
256
      Subobject.addArray(Info, E, CAT);
10898
256
      ImplicitValueInitExpr VIE(CAT->getElementType());
10899
256
      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10900
348
    }
10901
10902
0
    bool VisitCallExpr(const CallExpr *E) {
10903
0
      return handleCallExpr(E, Result, &This);
10904
0
    }
10905
    bool VisitInitListExpr(const InitListExpr *E,
10906
                           QualType AllocType = QualType());
10907
    bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10908
    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10909
    bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10910
                               const LValue &Subobject,
10911
                               APValue *Value, QualType Type);
10912
    bool VisitStringLiteral(const StringLiteral *E,
10913
1.29k
                            QualType AllocType = QualType()) {
10914
1.29k
      expandStringLiteral(Info, E, Result, AllocType);
10915
1.29k
      return true;
10916
1.29k
    }
10917
    bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10918
    bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10919
                                         ArrayRef<Expr *> Args,
10920
                                         const Expr *ArrayFiller,
10921
                                         QualType AllocType = QualType());
10922
  };
10923
} // end anonymous namespace
10924
10925
static bool EvaluateArray(const Expr *E, const LValue &This,
10926
13.5k
                          APValue &Result, EvalInfo &Info) {
10927
13.5k
  assert(!E->isValueDependent());
10928
13.5k
  assert(E->isPRValue() && E->getType()->isArrayType() &&
10929
13.5k
         "not an array prvalue");
10930
13.5k
  return ArrayExprEvaluator(Info, This, Result).Visit(E);
10931
13.5k
}
10932
10933
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10934
                                     APValue &Result, const InitListExpr *ILE,
10935
30
                                     QualType AllocType) {
10936
30
  assert(!ILE->isValueDependent());
10937
30
  assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10938
30
         "not an array prvalue");
10939
30
  return ArrayExprEvaluator(Info, This, Result)
10940
30
      .VisitInitListExpr(ILE, AllocType);
10941
30
}
10942
10943
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10944
                                          APValue &Result,
10945
                                          const CXXConstructExpr *CCE,
10946
72
                                          QualType AllocType) {
10947
72
  assert(!CCE->isValueDependent());
10948
72
  assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10949
72
         "not an array prvalue");
10950
72
  return ArrayExprEvaluator(Info, This, Result)
10951
72
      .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10952
72
}
10953
10954
// Return true iff the given array filler may depend on the element index.
10955
1.00k
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10956
  // For now, just allow non-class value-initialization and initialization
10957
  // lists comprised of them.
10958
1.00k
  if (isa<ImplicitValueInitExpr>(FillerExpr))
10959
745
    return false;
10960
261
  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10961
282
    for (unsigned I = 0, E = ILE->getNumInits(); I != E; 
++I123
) {
10962
135
      if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10963
12
        return true;
10964
135
    }
10965
10966
147
    if (ILE->hasArrayFiller() &&
10967
147
        
MaybeElementDependentArrayFiller(ILE->getArrayFiller())27
)
10968
15
      return true;
10969
10970
132
    return false;
10971
147
  }
10972
102
  return true;
10973
261
}
10974
10975
bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10976
5.62k
                                           QualType AllocType) {
10977
5.62k
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10978
5.62k
      AllocType.isNull() ? 
E->getType()5.59k
:
AllocType30
);
10979
5.62k
  if (!CAT)
10980
0
    return Error(E);
10981
10982
  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10983
  // an appropriately-typed string literal enclosed in braces.
10984
5.62k
  if (E->isStringLiteralInit()) {
10985
112
    auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10986
    // FIXME: Support ObjCEncodeExpr here once we support it in
10987
    // ArrayExprEvaluator generally.
10988
112
    if (!SL)
10989
0
      return Error(E);
10990
112
    return VisitStringLiteral(SL, AllocType);
10991
112
  }
10992
  // Any other transparent list init will need proper handling of the
10993
  // AllocType; we can't just recurse to the inner initializer.
10994
5.51k
  assert(!E->isTransparent() &&
10995
5.51k
         "transparent array list initialization is not string literal init?");
10996
10997
5.51k
  return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10998
5.51k
                                         AllocType);
10999
5.51k
}
11000
11001
bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11002
    const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11003
5.52k
    QualType AllocType) {
11004
5.52k
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11005
5.52k
      AllocType.isNull() ? 
ExprToVisit->getType()5.51k
:
AllocType11
);
11006
11007
5.52k
  bool Success = true;
11008
11009
5.52k
  assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11010
5.52k
         "zero-initialized array shouldn't have any initialized elts");
11011
5.52k
  APValue Filler;
11012
5.52k
  if (Result.isArray() && 
Result.hasArrayFiller()3
)
11013
3
    Filler = Result.getArrayFiller();
11014
11015
5.52k
  unsigned NumEltsToInit = Args.size();
11016
5.52k
  unsigned NumElts = CAT->getSize().getZExtValue();
11017
11018
  // If the initializer might depend on the array index, run it for each
11019
  // array element.
11020
5.52k
  if (NumEltsToInit != NumElts && 
MaybeElementDependentArrayFiller(ArrayFiller)844
)
11021
102
    NumEltsToInit = NumElts;
11022
11023
5.52k
  LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11024
5.52k
                          << NumEltsToInit << ".\n");
11025
11026
5.52k
  Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11027
11028
  // If the array was previously zero-initialized, preserve the
11029
  // zero-initialized values.
11030
5.52k
  if (Filler.hasValue()) {
11031
12
    for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; 
++I9
)
11032
9
      Result.getArrayInitializedElt(I) = Filler;
11033
3
    if (Result.hasArrayFiller())
11034
0
      Result.getArrayFiller() = Filler;
11035
3
  }
11036
11037
5.52k
  LValue Subobject = This;
11038
5.52k
  Subobject.addArray(Info, ExprToVisit, CAT);
11039
51.8k
  for (unsigned Index = 0; Index != NumEltsToInit; 
++Index46.3k
) {
11040
47.1k
    const Expr *Init = Index < Args.size() ? 
Args[Index]46.8k
:
ArrayFiller285
;
11041
47.1k
    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11042
47.1k
                         Info, Subobject, Init) ||
11043
47.1k
        !HandleLValueArrayAdjustment(Info, Init, Subobject,
11044
46.1k
                                     CAT->getElementType(), 1)) {
11045
1.00k
      if (!Info.noteFailure())
11046
853
        return false;
11047
154
      Success = false;
11048
154
    }
11049
47.1k
  }
11050
11051
4.66k
  if (!Result.hasArrayFiller())
11052
3.94k
    return Success;
11053
11054
  // If we get here, we have a trivial filler, which we can just evaluate
11055
  // once and splat over the rest of the array elements.
11056
728
  assert(ArrayFiller && "no array filler for incomplete init list");
11057
728
  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11058
728
                         ArrayFiller) &&
11059
728
         Success;
11060
728
}
11061
11062
43
bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11063
43
  LValue CommonLV;
11064
43
  if (E->getCommonExpr() &&
11065
43
      !Evaluate(Info.CurrentCall->createTemporary(
11066
43
                    E->getCommonExpr(),
11067
43
                    getStorageType(Info.Ctx, E->getCommonExpr()),
11068
43
                    ScopeKind::FullExpression, CommonLV),
11069
43
                Info, E->getCommonExpr()->getSourceExpr()))
11070
2
    return false;
11071
11072
41
  auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11073
11074
41
  uint64_t Elements = CAT->getSize().getZExtValue();
11075
41
  Result = APValue(APValue::UninitArray(), Elements, Elements);
11076
11077
41
  LValue Subobject = This;
11078
41
  Subobject.addArray(Info, E, CAT);
11079
11080
41
  bool Success = true;
11081
163
  for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; 
++Index122
) {
11082
    // C++ [class.temporary]/5
11083
    // There are four contexts in which temporaries are destroyed at a different
11084
    // point than the end of the full-expression. [...] The second context is
11085
    // when a copy constructor is called to copy an element of an array while
11086
    // the entire array is copied [...]. In either case, if the constructor has
11087
    // one or more default arguments, the destruction of every temporary created
11088
    // in a default argument is sequenced before the construction of the next
11089
    // array element, if any.
11090
132
    FullExpressionRAII Scope(Info);
11091
11092
132
    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11093
132
                         Info, Subobject, E->getSubExpr()) ||
11094
132
        !HandleLValueArrayAdjustment(Info, E, Subobject,
11095
68
                                     CAT->getElementType(), 1)) {
11096
68
      if (!Info.noteFailure())
11097
10
        return false;
11098
58
      Success = false;
11099
58
    }
11100
11101
    // Make sure we run the destructors too.
11102
122
    Scope.destroy();
11103
122
  }
11104
11105
31
  return Success;
11106
41
}
11107
11108
6.28k
bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11109
6.28k
  return VisitCXXConstructExpr(E, This, &Result, E->getType());
11110
6.28k
}
11111
11112
bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11113
                                               const LValue &Subobject,
11114
                                               APValue *Value,
11115
13.0k
                                               QualType Type) {
11116
13.0k
  bool HadZeroInit = Value->hasValue();
11117
11118
13.0k
  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11119
6.39k
    unsigned FinalSize = CAT->getSize().getZExtValue();
11120
11121
    // Preserve the array filler if we had prior zero-initialization.
11122
6.39k
    APValue Filler =
11123
6.39k
      HadZeroInit && 
Value->hasArrayFiller()1
?
Value->getArrayFiller()1
11124
6.39k
                                             : 
APValue()6.38k
;
11125
11126
6.39k
    *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11127
6.39k
    if (FinalSize == 0)
11128
2
      return true;
11129
11130
6.38k
    bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11131
6.38k
        Info, E->getExprLoc(), E->getConstructor(),
11132
6.38k
        E->requiresZeroInitialization());
11133
6.38k
    LValue ArrayElt = Subobject;
11134
6.38k
    ArrayElt.addArray(Info, E, CAT);
11135
    // We do the whole initialization in two passes, first for just one element,
11136
    // then for the whole array. It's possible we may find out we can't do const
11137
    // init in the first pass, in which case we avoid allocating a potentially
11138
    // large array. We don't do more passes because expanding array requires
11139
    // copying the data, which is wasteful.
11140
6.59k
    for (const unsigned N : {1u, FinalSize}) {
11141
6.59k
      unsigned OldElts = Value->getArrayInitializedElts();
11142
6.59k
      if (OldElts == N)
11143
5
        break;
11144
11145
      // Expand the array to appropriate size.
11146
6.59k
      APValue NewValue(APValue::UninitArray(), N, FinalSize);
11147
6.80k
      for (unsigned I = 0; I < OldElts; 
++I206
)
11148
206
        NewValue.getArrayInitializedElt(I).swap(
11149
206
            Value->getArrayInitializedElt(I));
11150
6.59k
      Value->swap(NewValue);
11151
11152
6.59k
      if (HadZeroInit)
11153
4
        
for (unsigned I = OldElts; 2
I < N;
++I2
)
11154
2
          Value->getArrayInitializedElt(I) = Filler;
11155
11156
6.59k
      if (HasTrivialConstructor && 
N == FinalSize355
&&
FinalSize != 1141
) {
11157
        // If we have a trivial constructor, only evaluate it once and copy
11158
        // the result into all the array elements.
11159
135
        APValue &FirstResult = Value->getArrayInitializedElt(0);
11160
970
        for (unsigned I = OldElts; I < FinalSize; 
++I835
)
11161
835
          Value->getArrayInitializedElt(I) = FirstResult;
11162
6.45k
      } else {
11163
6.95k
        for (unsigned I = OldElts; I < N; 
++I498
) {
11164
6.67k
          if (!VisitCXXConstructExpr(E, ArrayElt,
11165
6.67k
                                     &Value->getArrayInitializedElt(I),
11166
6.67k
                                     CAT->getElementType()) ||
11167
6.67k
              !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11168
572
                                           CAT->getElementType(), 1))
11169
6.10k
            return false;
11170
          // When checking for const initilization any diagnostic is considered
11171
          // an error.
11172
572
          if (Info.EvalStatus.Diag && 
!Info.EvalStatus.Diag->empty()535
&&
11173
572
              
!Info.keepEvaluatingAfterFailure()74
)
11174
74
            return false;
11175
572
        }
11176
6.45k
      }
11177
6.59k
    }
11178
11179
211
    return true;
11180
6.38k
  }
11181
11182
6.63k
  if (!Type->isRecordType())
11183
4
    return Error(E);
11184
11185
6.63k
  return RecordExprEvaluator(Info, Subobject, *Value)
11186
6.63k
             .VisitCXXConstructExpr(E, Type);
11187
6.63k
}
11188
11189
bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11190
10
    const CXXParenListInitExpr *E) {
11191
10
  assert(dyn_cast<ConstantArrayType>(E->getType()) &&
11192
10
         "Expression result is not a constant array type");
11193
11194
10
  return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11195
10
                                         E->getArrayFiller());
11196
10
}
11197
11198
//===----------------------------------------------------------------------===//
11199
// Integer Evaluation
11200
//
11201
// As a GNU extension, we support casting pointers to sufficiently-wide integer
11202
// types and back in constant folding. Integer values are thus represented
11203
// either as an integer-valued APValue, or as an lvalue-valued APValue.
11204
//===----------------------------------------------------------------------===//
11205
11206
namespace {
11207
class IntExprEvaluator
11208
        : public ExprEvaluatorBase<IntExprEvaluator> {
11209
  APValue &Result;
11210
public:
11211
  IntExprEvaluator(EvalInfo &info, APValue &result)
11212
30.5M
      : ExprEvaluatorBaseTy(info), Result(result) {}
11213
11214
12.1M
  bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11215
12.1M
    assert(E->getType()->isIntegralOrEnumerationType() &&
11216
12.1M
           "Invalid evaluation result.");
11217
12.1M
    assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11218
12.1M
           "Invalid evaluation result.");
11219
12.1M
    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11220
12.1M
           "Invalid evaluation result.");
11221
12.1M
    Result = APValue(SI);
11222
12.1M
    return true;
11223
12.1M
  }
11224
6.02M
  bool Success(const llvm::APSInt &SI, const Expr *E) {
11225
6.02M
    return Success(SI, E, Result);
11226
6.02M
  }
11227
11228
14.7M
  bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11229
14.7M
    assert(E->getType()->isIntegralOrEnumerationType() &&
11230
14.7M
           "Invalid evaluation result.");
11231
14.7M
    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11232
14.7M
           "Invalid evaluation result.");
11233
14.7M
    Result = APValue(APSInt(I));
11234
14.7M
    Result.getInt().setIsUnsigned(
11235
14.7M
                            E->getType()->isUnsignedIntegerOrEnumerationType());
11236
14.7M
    return true;
11237
14.7M
  }
11238
14.7M
  bool Success(const llvm::APInt &I, const Expr *E) {
11239
14.7M
    return Success(I, E, Result);
11240
14.7M
  }
11241
11242
2.89M
  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11243
2.89M
    assert(E->getType()->isIntegralOrEnumerationType() &&
11244
2.89M
           "Invalid evaluation result.");
11245
2.89M
    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11246
2.89M
    return true;
11247
2.89M
  }
11248
2.20M
  bool Success(uint64_t Value, const Expr *E) {
11249
2.20M
    return Success(Value, E, Result);
11250
2.20M
  }
11251
11252
191k
  bool Success(CharUnits Size, const Expr *E) {
11253
191k
    return Success(Size.getQuantity(), E);
11254
191k
  }
11255
11256
2.81M
  bool Success(const APValue &V, const Expr *E) {
11257
2.81M
    if (V.isLValue() || 
V.isAddrLabelDiff()2.81M
||
V.isIndeterminate()2.81M
) {
11258
54
      Result = V;
11259
54
      return true;
11260
54
    }
11261
2.81M
    return Success(V.getInt(), E);
11262
2.81M
  }
11263
11264
8.93k
  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11265
11266
  //===--------------------------------------------------------------------===//
11267
  //                            Visitor Methods
11268
  //===--------------------------------------------------------------------===//
11269
11270
14.7M
  bool VisitIntegerLiteral(const IntegerLiteral *E) {
11271
14.7M
    return Success(E->getValue(), E);
11272
14.7M
  }
11273
805k
  bool VisitCharacterLiteral(const CharacterLiteral *E) {
11274
805k
    return Success(E->getValue(), E);
11275
805k
  }
11276
11277
  bool CheckReferencedDecl(const Expr *E, const Decl *D);
11278
558k
  bool VisitDeclRefExpr(const DeclRefExpr *E) {
11279
558k
    if (CheckReferencedDecl(E, E->getDecl()))
11280
558k
      return true;
11281
11282
0
    return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11283
558k
  }
11284
261
  bool VisitMemberExpr(const MemberExpr *E) {
11285
261
    if (CheckReferencedDecl(E, E->getMemberDecl())) {
11286
109
      VisitIgnoredBaseExpression(E->getBase());
11287
109
      return true;
11288
109
    }
11289
11290
152
    return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11291
261
  }
11292
11293
  bool VisitCallExpr(const CallExpr *E);
11294
  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11295
  bool VisitBinaryOperator(const BinaryOperator *E);
11296
  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11297
  bool VisitUnaryOperator(const UnaryOperator *E);
11298
11299
  bool VisitCastExpr(const CastExpr* E);
11300
  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11301
11302
643k
  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11303
643k
    return Success(E->getValue(), E);
11304
643k
  }
11305
11306
370
  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11307
370
    return Success(E->getValue(), E);
11308
370
  }
11309
11310
252
  bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11311
252
    if (Info.ArrayInitIndex == uint64_t(-1)) {
11312
      // We were asked to evaluate this subexpression independent of the
11313
      // enclosing ArrayInitLoopExpr. We can't do that.
11314
120
      Info.FFDiag(E);
11315
120
      return false;
11316
120
    }
11317
132
    return Success(Info.ArrayInitIndex, E);
11318
252
  }
11319
11320
  // Note, GNU defines __null as an integer, not a pointer.
11321
1.62k
  bool VisitGNUNullExpr(const GNUNullExpr *E) {
11322
1.62k
    return ZeroInitialization(E);
11323
1.62k
  }
11324
11325
187k
  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11326
187k
    return Success(E->getValue(), E);
11327
187k
  }
11328
11329
29
  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11330
29
    return Success(E->getValue(), E);
11331
29
  }
11332
11333
433
  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11334
433
    return Success(E->getValue(), E);
11335
433
  }
11336
11337
  bool VisitUnaryReal(const UnaryOperator *E);
11338
  bool VisitUnaryImag(const UnaryOperator *E);
11339
11340
  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11341
  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11342
  bool VisitSourceLocExpr(const SourceLocExpr *E);
11343
  bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11344
  bool VisitRequiresExpr(const RequiresExpr *E);
11345
  // FIXME: Missing: array subscript of vector, member of vector
11346
};
11347
11348
class FixedPointExprEvaluator
11349
    : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11350
  APValue &Result;
11351
11352
 public:
11353
  FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11354
3.72k
      : ExprEvaluatorBaseTy(info), Result(result) {}
11355
11356
1.88k
  bool Success(const llvm::APInt &I, const Expr *E) {
11357
1.88k
    return Success(
11358
1.88k
        APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11359
1.88k
  }
11360
11361
0
  bool Success(uint64_t Value, const Expr *E) {
11362
0
    return Success(
11363
0
        APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11364
0
  }
11365
11366
0
  bool Success(const APValue &V, const Expr *E) {
11367
0
    return Success(V.getFixedPoint(), E);
11368
0
  }
11369
11370
3.29k
  bool Success(const APFixedPoint &V, const Expr *E) {
11371
3.29k
    assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11372
3.29k
    assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11373
3.29k
           "Invalid evaluation result.");
11374
3.29k
    Result = APValue(V);
11375
3.29k
    return true;
11376
3.29k
  }
11377
11378
  //===--------------------------------------------------------------------===//
11379
  //                            Visitor Methods
11380
  //===--------------------------------------------------------------------===//
11381
11382
1.88k
  bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11383
1.88k
    return Success(E->getValue(), E);
11384
1.88k
  }
11385
11386
  bool VisitCastExpr(const CastExpr *E);
11387
  bool VisitUnaryOperator(const UnaryOperator *E);
11388
  bool VisitBinaryOperator(const BinaryOperator *E);
11389
};
11390
} // end anonymous namespace
11391
11392
/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11393
/// produce either the integer value or a pointer.
11394
///
11395
/// GCC has a heinous extension which folds casts between pointer types and
11396
/// pointer-sized integral types. We support this by allowing the evaluation of
11397
/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11398
/// Some simple arithmetic on such values is supported (they are treated much
11399
/// like char*).
11400
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11401
342k
                                    EvalInfo &Info) {
11402
342k
  assert(!E->isValueDependent());
11403
342k
  assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11404
342k
  return IntExprEvaluator(Info, Result).Visit(E);
11405
342k
}
11406
11407
338k
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11408
338k
  assert(!E->isValueDependent());
11409
338k
  APValue Val;
11410
338k
  if (!EvaluateIntegerOrLValue(E, Val, Info))
11411
177k
    return false;
11412
161k
  if (!Val.isInt()) {
11413
    // FIXME: It would be better to produce the diagnostic for casting
11414
    //        a pointer to an integer.
11415
17
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11416
17
    return false;
11417
17
  }
11418
161k
  Result = Val.getInt();
11419
161k
  return true;
11420
161k
}
11421
11422
830
bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11423
830
  APValue Evaluated = E->EvaluateInContext(
11424
830
      Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11425
830
  return Success(Evaluated, E);
11426
830
}
11427
11428
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11429
1.87k
                               EvalInfo &Info) {
11430
1.87k
  assert(!E->isValueDependent());
11431
1.87k
  if (E->getType()->isFixedPointType()) {
11432
1.87k
    APValue Val;
11433
1.87k
    if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11434
109
      return false;
11435
1.76k
    if (!Val.isFixedPoint())
11436
0
      return false;
11437
11438
1.76k
    Result = Val.getFixedPoint();
11439
1.76k
    return true;
11440
1.76k
  }
11441
0
  return false;
11442
1.87k
}
11443
11444
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11445
1.95k
                                        EvalInfo &Info) {
11446
1.95k
  assert(!E->isValueDependent());
11447
1.95k
  if (E->getType()->isIntegerType()) {
11448
452
    auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11449
452
    APSInt Val;
11450
452
    if (!EvaluateInteger(E, Val, Info))
11451
32
      return false;
11452
420
    Result = APFixedPoint(Val, FXSema);
11453
420
    return true;
11454
1.50k
  } else if (E->getType()->isFixedPointType()) {
11455
1.50k
    return EvaluateFixedPoint(E, Result, Info);
11456
1.50k
  }
11457
0
  return false;
11458
1.95k
}
11459
11460
/// Check whether the given declaration can be directly converted to an integral
11461
/// rvalue. If not, no diagnostic is produced; there are other things we can
11462
/// try.
11463
558k
bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11464
  // Enums are integer constant exprs.
11465
558k
  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11466
    // Check for signedness/width mismatches between E type and ECD value.
11467
558k
    bool SameSign = (ECD->getInitVal().isSigned()
11468
558k
                     == E->getType()->isSignedIntegerOrEnumerationType());
11469
558k
    bool SameWidth = (ECD->getInitVal().getBitWidth()
11470
558k
                      == Info.Ctx.getIntWidth(E->getType()));
11471
558k
    if (SameSign && 
SameWidth558k
)
11472
558k
      return Success(ECD->getInitVal(), E);
11473
26
    else {
11474
      // Get rid of mismatch (otherwise Success assertions will fail)
11475
      // by computing a new value matching the type of E.
11476
26
      llvm::APSInt Val = ECD->getInitVal();
11477
26
      if (!SameSign)
11478
26
        Val.setIsSigned(!ECD->getInitVal().isSigned());
11479
26
      if (!SameWidth)
11480
0
        Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11481
26
      return Success(Val, E);
11482
26
    }
11483
558k
  }
11484
152
  return false;
11485
558k
}
11486
11487
/// Values returned by __builtin_classify_type, chosen to match the values
11488
/// produced by GCC's builtin.
11489
enum class GCCTypeClass {
11490
  None = -1,
11491
  Void = 0,
11492
  Integer = 1,
11493
  // GCC reserves 2 for character types, but instead classifies them as
11494
  // integers.
11495
  Enum = 3,
11496
  Bool = 4,
11497
  Pointer = 5,
11498
  // GCC reserves 6 for references, but appears to never use it (because
11499
  // expressions never have reference type, presumably).
11500
  PointerToDataMember = 7,
11501
  RealFloat = 8,
11502
  Complex = 9,
11503
  // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11504
  // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11505
  // GCC claims to reserve 11 for pointers to member functions, but *actually*
11506
  // uses 12 for that purpose, same as for a class or struct. Maybe it
11507
  // internally implements a pointer to member as a struct?  Who knows.
11508
  PointerToMemberFunction = 12, // Not a bug, see above.
11509
  ClassOrStruct = 12,
11510
  Union = 13,
11511
  // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11512
  // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11513
  // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11514
  // literals.
11515
};
11516
11517
/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11518
/// as GCC.
11519
static GCCTypeClass
11520
109
EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11521
109
  assert(!T->isDependentType() && "unexpected dependent type");
11522
11523
109
  QualType CanTy = T.getCanonicalType();
11524
11525
109
  switch (CanTy->getTypeClass()) {
11526
0
#define TYPE(ID, BASE)
11527
0
#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11528
0
#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11529
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11530
0
#include "clang/AST/TypeNodes.inc"
11531
0
  case Type::Auto:
11532
0
  case Type::DeducedTemplateSpecialization:
11533
0
      llvm_unreachable("unexpected non-canonical or dependent type");
11534
11535
48
  case Type::Builtin:
11536
48
      switch (cast<BuiltinType>(CanTy)->getKind()) {
11537
0
#define BUILTIN_TYPE(ID, SINGLETON_ID)
11538
0
#define SIGNED_TYPE(ID, SINGLETON_ID) \
11539
28
    case BuiltinType::ID: return GCCTypeClass::Integer;
11540
0
#define FLOATING_TYPE(ID, SINGLETON_ID) \
11541
13
    case BuiltinType::ID: return GCCTypeClass::RealFloat;
11542
0
#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11543
0
    case BuiltinType::ID: break;
11544
0
#include "clang/AST/BuiltinTypes.def"
11545
3
    case BuiltinType::Void:
11546
3
      return GCCTypeClass::Void;
11547
11548
1
    case BuiltinType::Bool:
11549
1
      return GCCTypeClass::Bool;
11550
11551
0
    case BuiltinType::Char_U:
11552
0
    case BuiltinType::UChar:
11553
0
    case BuiltinType::WChar_U:
11554
0
    case BuiltinType::Char8:
11555
0
    case BuiltinType::Char16:
11556
0
    case BuiltinType::Char32:
11557
0
    case BuiltinType::UShort:
11558
0
    case BuiltinType::UInt:
11559
0
    case BuiltinType::ULong:
11560
0
    case BuiltinType::ULongLong:
11561
0
    case BuiltinType::UInt128:
11562
0
      return GCCTypeClass::Integer;
11563
11564
0
    case BuiltinType::UShortAccum:
11565
0
    case BuiltinType::UAccum:
11566
0
    case BuiltinType::ULongAccum:
11567
0
    case BuiltinType::UShortFract:
11568
0
    case BuiltinType::UFract:
11569
0
    case BuiltinType::ULongFract:
11570
0
    case BuiltinType::SatUShortAccum:
11571
0
    case BuiltinType::SatUAccum:
11572
0
    case BuiltinType::SatULongAccum:
11573
0
    case BuiltinType::SatUShortFract:
11574
0
    case BuiltinType::SatUFract:
11575
0
    case BuiltinType::SatULongFract:
11576
0
      return GCCTypeClass::None;
11577
11578
0
    case BuiltinType::NullPtr:
11579
11580
0
    case BuiltinType::ObjCId:
11581
0
    case BuiltinType::ObjCClass:
11582
0
    case BuiltinType::ObjCSel:
11583
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11584
0
    case BuiltinType::Id:
11585
0
#include "clang/Basic/OpenCLImageTypes.def"
11586
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11587
0
    case BuiltinType::Id:
11588
0
#include "clang/Basic/OpenCLExtensionTypes.def"
11589
0
    case BuiltinType::OCLSampler:
11590
0
    case BuiltinType::OCLEvent:
11591
0
    case BuiltinType::OCLClkEvent:
11592
0
    case BuiltinType::OCLQueue:
11593
0
    case BuiltinType::OCLReserveID:
11594
0
#define SVE_TYPE(Name, Id, SingletonId) \
11595
0
    case BuiltinType::Id:
11596
0
#include "clang/Basic/AArch64SVEACLETypes.def"
11597
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
11598
0
    case BuiltinType::Id:
11599
0
#include "clang/Basic/PPCTypes.def"
11600
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11601
0
#include "clang/Basic/RISCVVTypes.def"
11602
0
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11603
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
11604
0
      return GCCTypeClass::None;
11605
11606
0
    case BuiltinType::Dependent:
11607
0
      llvm_unreachable("unexpected dependent type");
11608
48
    };
11609
0
    llvm_unreachable("unexpected placeholder type");
11610
11611
3
  case Type::Enum:
11612
3
    return LangOpts.CPlusPlus ? 
GCCTypeClass::Enum1
:
GCCTypeClass::Integer2
;
11613
11614
3
  case Type::Pointer:
11615
9
  case Type::ConstantArray:
11616
9
  case Type::VariableArray:
11617
9
  case Type::IncompleteArray:
11618
9
  case Type::FunctionNoProto:
11619
12
  case Type::FunctionProto:
11620
12
    return GCCTypeClass::Pointer;
11621
11622
2
  case Type::MemberPointer:
11623
2
    return CanTy->isMemberDataPointerType()
11624
2
               ? 
GCCTypeClass::PointerToDataMember1
11625
2
               : 
GCCTypeClass::PointerToMemberFunction1
;
11626
11627
16
  case Type::Complex:
11628
16
    return GCCTypeClass::Complex;
11629
11630
12
  case Type::Record:
11631
12
    return CanTy->isUnionType() ? 
GCCTypeClass::Union3
11632
12
                                : 
GCCTypeClass::ClassOrStruct9
;
11633
11634
6
  case Type::Atomic:
11635
    // GCC classifies _Atomic T the same as T.
11636
6
    return EvaluateBuiltinClassifyType(
11637
6
        CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11638
11639
4
  case Type::BlockPointer:
11640
7
  case Type::Vector:
11641
10
  case Type::ExtVector:
11642
10
  case Type::ConstantMatrix:
11643
10
  case Type::ObjCObject:
11644
10
  case Type::ObjCInterface:
11645
10
  case Type::ObjCObjectPointer:
11646
10
  case Type::Pipe:
11647
10
  case Type::BitInt:
11648
    // GCC classifies vectors as None. We follow its lead and classify all
11649
    // other types that don't fit into the regular classification the same way.
11650
10
    return GCCTypeClass::None;
11651
11652
0
  case Type::LValueReference:
11653
0
  case Type::RValueReference:
11654
0
    llvm_unreachable("invalid type for expression");
11655
109
  }
11656
11657
0
  llvm_unreachable("unexpected type class");
11658
0
}
11659
11660
/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11661
/// as GCC.
11662
static GCCTypeClass
11663
103
EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11664
  // If no argument was supplied, default to None. This isn't
11665
  // ideal, however it is what gcc does.
11666
103
  if (E->getNumArgs() == 0)
11667
0
    return GCCTypeClass::None;
11668
11669
  // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11670
  // being an ICE, but still folds it to a constant using the type of the first
11671
  // argument.
11672
103
  return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11673
103
}
11674
11675
/// EvaluateBuiltinConstantPForLValue - Determine the result of
11676
/// __builtin_constant_p when applied to the given pointer.
11677
///
11678
/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11679
/// or it points to the first character of a string literal.
11680
886
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11681
886
  APValue::LValueBase Base = LV.getLValueBase();
11682
886
  if (Base.isNull()) {
11683
    // A null base is acceptable.
11684
35
    return true;
11685
851
  } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11686
781
    if (!isa<StringLiteral>(E))
11687
0
      return false;
11688
781
    return LV.getLValueOffset().isZero();
11689
781
  } else 
if (70
Base.is<TypeInfoLValue>()70
) {
11690
    // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11691
    // evaluate to true.
11692
2
    return true;
11693
68
  } else {
11694
    // Any other base is not constant enough for GCC.
11695
68
    return false;
11696
68
  }
11697
886
}
11698
11699
/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11700
/// GCC as we can manage.
11701
6.01k
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11702
  // This evaluation is not permitted to have side-effects, so evaluate it in
11703
  // a speculative evaluation context.
11704
6.01k
  SpeculativeEvaluationRAII SpeculativeEval(Info);
11705
11706
  // Constant-folding is always enabled for the operand of __builtin_constant_p
11707
  // (even when the enclosing evaluation context otherwise requires a strict
11708
  // language-specific constant expression).
11709
6.01k
  FoldConstant Fold(Info, true);
11710
11711
6.01k
  QualType ArgType = Arg->getType();
11712
11713
  // __builtin_constant_p always has one operand. The rules which gcc follows
11714
  // are not precisely documented, but are as follows:
11715
  //
11716
  //  - If the operand is of integral, floating, complex or enumeration type,
11717
  //    and can be folded to a known value of that type, it returns 1.
11718
  //  - If the operand can be folded to a pointer to the first character
11719
  //    of a string literal (or such a pointer cast to an integral type)
11720
  //    or to a null pointer or an integer cast to a pointer, it returns 1.
11721
  //
11722
  // Otherwise, it returns 0.
11723
  //
11724
  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11725
  // its support for this did not work prior to GCC 9 and is not yet well
11726
  // understood.
11727
6.01k
  if (ArgType->isIntegralOrEnumerationType() || 
ArgType->isFloatingType()942
||
11728
6.01k
      
ArgType->isAnyComplexType()924
||
ArgType->isPointerType()922
||
11729
6.01k
      
ArgType->isNullPtrType()40
) {
11730
5.97k
    APValue V;
11731
5.97k
    if (!::EvaluateAsRValue(Info, Arg, V) || 
Info.EvalStatus.HasSideEffects1.36k
) {
11732
4.61k
      Fold.keepDiagnostics();
11733
4.61k
      return false;
11734
4.61k
    }
11735
11736
    // For a pointer (possibly cast to integer), there are special rules.
11737
1.35k
    if (V.getKind() == APValue::LValue)
11738
886
      return EvaluateBuiltinConstantPForLValue(V);
11739
11740
    // Otherwise, any constant value is good enough.
11741
473
    return V.hasValue();
11742
1.35k
  }
11743
11744
  // Anything else isn't considered to be sufficiently constant.
11745
36
  return false;
11746
6.01k
}
11747
11748
/// Retrieves the "underlying object type" of the given expression,
11749
/// as used by __builtin_object_size.
11750
5.33k
static QualType getObjectType(APValue::LValueBase B) {
11751
5.33k
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11752
5.20k
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11753
5.17k
      return VD->getType();
11754
5.20k
  } else 
if (const Expr *126
E126
= B.dyn_cast<const Expr*>()) {
11755
15
    if (isa<CompoundLiteralExpr>(E))
11756
4
      return E->getType();
11757
111
  } else if (B.is<TypeInfoLValue>()) {
11758
0
    return B.getTypeInfoType();
11759
111
  } else if (B.is<DynamicAllocLValue>()) {
11760
2
    return B.getDynamicAllocType();
11761
2
  }
11762
11763
155
  return QualType();
11764
5.33k
}
11765
11766
/// A more selective version of E->IgnoreParenCasts for
11767
/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11768
/// to change the type of E.
11769
/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11770
///
11771
/// Always returns an RValue with a pointer representation.
11772
22.0k
static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11773
22.0k
  assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11774
11775
22.0k
  auto *NoParens = E->IgnoreParens();
11776
22.0k
  auto *Cast = dyn_cast<CastExpr>(NoParens);
11777
22.0k
  if (Cast == nullptr)
11778
3.38k
    return NoParens;
11779
11780
  // We only conservatively allow a few kinds of casts, because this code is
11781
  // inherently a simple solution that seeks to support the common case.
11782
18.6k
  auto CastKind = Cast->getCastKind();
11783
18.6k
  if (CastKind != CK_NoOp && 
CastKind != CK_BitCast17.8k
&&
11784
18.6k
      
CastKind != CK_AddressSpaceConversion9.05k
)
11785
9.05k
    return NoParens;
11786
11787
9.63k
  auto *SubExpr = Cast->getSubExpr();
11788
9.63k
  if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11789
0
    return NoParens;
11790
9.63k
  return ignorePointerCastsAndParens(SubExpr);
11791
9.63k
}
11792
11793
/// Checks to see if the given LValue's Designator is at the end of the LValue's
11794
/// record layout. e.g.
11795
///   struct { struct { int a, b; } fst, snd; } obj;
11796
///   obj.fst   // no
11797
///   obj.snd   // yes
11798
///   obj.fst.a // no
11799
///   obj.fst.b // no
11800
///   obj.snd.a // no
11801
///   obj.snd.b // yes
11802
///
11803
/// Please note: this function is specialized for how __builtin_object_size
11804
/// views "objects".
11805
///
11806
/// If this encounters an invalid RecordDecl or otherwise cannot determine the
11807
/// correct result, it will always return true.
11808
388
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11809
388
  assert(!LVal.Designator.Invalid);
11810
11811
458
  
auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) 388
{
11812
458
    const RecordDecl *Parent = FD->getParent();
11813
458
    Invalid = Parent->isInvalidDecl();
11814
458
    if (Invalid || Parent->isUnion())
11815
28
      return true;
11816
430
    const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11817
430
    return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11818
458
  };
11819
11820
388
  auto &Base = LVal.getLValueBase();
11821
388
  if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11822
292
    if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11823
292
      bool Invalid;
11824
292
      if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11825
39
        return Invalid;
11826
292
    } else 
if (auto *0
IFD0
= dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11827
0
      for (auto *FD : IFD->chain()) {
11828
0
        bool Invalid;
11829
0
        if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11830
0
          return Invalid;
11831
0
      }
11832
0
    }
11833
292
  }
11834
11835
349
  unsigned I = 0;
11836
349
  QualType BaseType = getType(Base);
11837
349
  if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11838
    // If we don't know the array bound, conservatively assume we're looking at
11839
    // the final array element.
11840
102
    ++I;
11841
102
    if (BaseType->isIncompleteArrayType())
11842
6
      BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11843
96
    else
11844
96
      BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11845
102
  }
11846
11847
509
  for (unsigned E = LVal.Designator.Entries.size(); I != E; 
++I160
) {
11848
509
    const auto &Entry = LVal.Designator.Entries[I];
11849
509
    if (BaseType->isArrayType()) {
11850
      // Because __builtin_object_size treats arrays as objects, we can ignore
11851
      // the index iff this is the last array in the Designator.
11852
337
      if (I + 1 == E)
11853
295
        return true;
11854
42
      const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11855
42
      uint64_t Index = Entry.getAsArrayIndex();
11856
42
      if (Index + 1 != CAT->getSize())
11857
0
        return false;
11858
42
      BaseType = CAT->getElementType();
11859
172
    } else if (BaseType->isAnyComplexType()) {
11860
0
      const auto *CT = BaseType->castAs<ComplexType>();
11861
0
      uint64_t Index = Entry.getAsArrayIndex();
11862
0
      if (Index != 1)
11863
0
        return false;
11864
0
      BaseType = CT->getElementType();
11865
172
    } else if (auto *FD = getAsField(Entry)) {
11866
166
      bool Invalid;
11867
166
      if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11868
48
        return Invalid;
11869
118
      BaseType = FD->getType();
11870
118
    } else {
11871
6
      assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11872
6
      return false;
11873
6
    }
11874
509
  }
11875
0
  return true;
11876
349
}
11877
11878
/// Tests to see if the LValue has a user-specified designator (that isn't
11879
/// necessarily valid). Note that this always returns 'true' if the LValue has
11880
/// an unsized array as its first designator entry, because there's currently no
11881
/// way to tell if the user typed *foo or foo[0].
11882
7.34k
static bool refersToCompleteObject(const LValue &LVal) {
11883
7.34k
  if (LVal.Designator.Invalid)
11884
208
    return false;
11885
11886
7.13k
  if (!LVal.Designator.Entries.empty())
11887
4.88k
    return LVal.Designator.isMostDerivedAnUnsizedArray();
11888
11889
2.25k
  if (!LVal.InvalidBase)
11890
2.13k
    return true;
11891
11892
  // If `E` is a MemberExpr, then the first part of the designator is hiding in
11893
  // the LValueBase.
11894
114
  const auto *E = LVal.Base.dyn_cast<const Expr *>();
11895
114
  return !E || !isa<MemberExpr>(E);
11896
2.25k
}
11897
11898
/// Attempts to detect a user writing into a piece of memory that's impossible
11899
/// to figure out the size of by just using types.
11900
651
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11901
651
  const SubobjectDesignator &Designator = LVal.Designator;
11902
  // Notes:
11903
  // - Users can only write off of the end when we have an invalid base. Invalid
11904
  //   bases imply we don't know where the memory came from.
11905
  // - We used to be a bit more aggressive here; we'd only be conservative if
11906
  //   the array at the end was flexible, or if it had 0 or 1 elements. This
11907
  //   broke some common standard library extensions (PR30346), but was
11908
  //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11909
  //   with some sort of list. OTOH, it seems that GCC is always
11910
  //   conservative with the last element in structs (if it's an array), so our
11911
  //   current behavior is more compatible than an explicit list approach would
11912
  //   be.
11913
651
  auto isFlexibleArrayMember = [&] {
11914
442
    using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11915
442
    FAMKind StrictFlexArraysLevel =
11916
442
        Ctx.getLangOpts().getStrictFlexArraysLevel();
11917
11918
442
    if (Designator.isMostDerivedAnUnsizedArray())
11919
0
      return true;
11920
11921
442
    if (StrictFlexArraysLevel == FAMKind::Default)
11922
355
      return true;
11923
11924
87
    if (Designator.getMostDerivedArraySize() == 0 &&
11925
87
        
StrictFlexArraysLevel != FAMKind::IncompleteOnly31
)
11926
22
      return true;
11927
11928
65
    if (Designator.getMostDerivedArraySize() == 1 &&
11929
65
        
StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete29
)
11930
11
      return true;
11931
11932
54
    return false;
11933
65
  };
11934
11935
651
  return LVal.InvalidBase &&
11936
651
         
Designator.Entries.size() == Designator.MostDerivedPathLength472
&&
11937
651
         
Designator.MostDerivedIsArrayElement466
&&
isFlexibleArrayMember()442
&&
11938
651
         
isDesignatorAtObjectEnd(Ctx, LVal)388
;
11939
651
}
11940
11941
/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11942
/// Fails if the conversion would cause loss of precision.
11943
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11944
807
                                            CharUnits &Result) {
11945
807
  auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11946
807
  if (Int.ugt(CharUnitsMax))
11947
64
    return false;
11948
743
  Result = CharUnits::fromQuantity(Int.getZExtValue());
11949
743
  return true;
11950
807
}
11951
11952
/// If we're evaluating the object size of an instance of a struct that
11953
/// contains a flexible array member, add the size of the initializer.
11954
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
11955
5.33k
                                           const LValue &LV, CharUnits &Size) {
11956
5.33k
  if (!T.isNull() && 
T->isStructureType()5.17k
&&
11957
5.33k
      
T->getAsStructureType()->getDecl()->hasFlexibleArrayMember()203
)
11958
18
    if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
11959
14
      if (const auto *VD = dyn_cast<VarDecl>(V))
11960
14
        if (VD->hasInit())
11961
12
          Size += VD->getFlexibleArrayInitChars(Info.Ctx);
11962
5.33k
}
11963
11964
/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11965
/// determine how many bytes exist from the beginning of the object to either
11966
/// the end of the current subobject, or the end of the object itself, depending
11967
/// on what the LValue looks like + the value of Type.
11968
///
11969
/// If this returns false, the value of Result is undefined.
11970
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11971
                               unsigned Type, const LValue &LVal,
11972
7.34k
                               CharUnits &EndOffset) {
11973
7.34k
  bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11974
11975
7.34k
  auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11976
5.74k
    if (Ty.isNull() || 
Ty->isIncompleteType()5.59k
||
Ty->isFunctionType()5.53k
)
11977
212
      return false;
11978
5.53k
    return HandleSizeof(Info, ExprLoc, Ty, Result);
11979
5.74k
  };
11980
11981
  // We want to evaluate the size of the entire object. This is a valid fallback
11982
  // for when Type=1 and the designator is invalid, because we're asked for an
11983
  // upper-bound.
11984
7.34k
  if (!(Type & 1) || 
LVal.Designator.Invalid1.21k
||
DetermineForCompleteObject1.10k
) {
11985
    // Type=3 wants a lower bound, so we can't fall back to this.
11986
6.69k
    if (Type == 3 && 
!DetermineForCompleteObject210
)
11987
40
      return false;
11988
11989
6.65k
    llvm::APInt APEndOffset;
11990
6.65k
    if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11991
6.65k
        
getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)851
)
11992
747
      return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11993
11994
5.90k
    if (LVal.InvalidBase)
11995
575
      return false;
11996
11997
5.33k
    QualType BaseTy = getObjectType(LVal.getLValueBase());
11998
5.33k
    const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
11999
5.33k
    addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12000
5.33k
    return Ret;
12001
5.90k
  }
12002
12003
  // We want to evaluate the size of a subobject.
12004
651
  const SubobjectDesignator &Designator = LVal.Designator;
12005
12006
  // The following is a moderately common idiom in C:
12007
  //
12008
  // struct Foo { int a; char c[1]; };
12009
  // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12010
  // strcpy(&F->c[0], Bar);
12011
  //
12012
  // In order to not break too much legacy code, we need to support it.
12013
651
  if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12014
    // If we can resolve this to an alloc_size call, we can hand that back,
12015
    // because we know for certain how many bytes there are to write to.
12016
295
    llvm::APInt APEndOffset;
12017
295
    if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12018
295
        
getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)60
)
12019
60
      return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12020
12021
    // If we cannot determine the size of the initial allocation, then we can't
12022
    // given an accurate upper-bound. However, we are still able to give
12023
    // conservative lower-bounds for Type=3.
12024
235
    if (Type == 1)
12025
178
      return false;
12026
235
  }
12027
12028
413
  CharUnits BytesPerElem;
12029
413
  if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12030
0
    return false;
12031
12032
  // According to the GCC documentation, we want the size of the subobject
12033
  // denoted by the pointer. But that's not quite right -- what we actually
12034
  // want is the size of the immediately-enclosing array, if there is one.
12035
413
  int64_t ElemsRemaining;
12036
413
  if (Designator.MostDerivedIsArrayElement &&
12037
413
      
Designator.Entries.size() == Designator.MostDerivedPathLength349
) {
12038
343
    uint64_t ArraySize = Designator.getMostDerivedArraySize();
12039
343
    uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12040
343
    ElemsRemaining = ArraySize <= ArrayIndex ? 
051
:
ArraySize - ArrayIndex292
;
12041
343
  } else {
12042
70
    ElemsRemaining = Designator.isOnePastTheEnd() ? 
012
:
158
;
12043
70
  }
12044
12045
413
  EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12046
413
  return true;
12047
413
}
12048
12049
/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12050
/// returns true and stores the result in @p Size.
12051
///
12052
/// If @p WasError is non-null, this will report whether the failure to evaluate
12053
/// is to be treated as an Error in IntExprEvaluator.
12054
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12055
12.4k
                                         EvalInfo &Info, uint64_t &Size) {
12056
  // Determine the denoted object.
12057
12.4k
  LValue LVal;
12058
12.4k
  {
12059
    // The operand of __builtin_object_size is never evaluated for side-effects.
12060
    // If there are any, but we can determine the pointed-to object anyway, then
12061
    // ignore the side-effects.
12062
12.4k
    SpeculativeEvaluationRAII SpeculativeEval(Info);
12063
12.4k
    IgnoreSideEffectsRAII Fold(Info);
12064
12065
12.4k
    if (E->isGLValue()) {
12066
      // It's possible for us to be given GLValues if we're called via
12067
      // Expr::tryEvaluateObjectSize.
12068
0
      APValue RVal;
12069
0
      if (!EvaluateAsRValue(Info, E, RVal))
12070
0
        return false;
12071
0
      LVal.setFrom(Info.Ctx, RVal);
12072
12.4k
    } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12073
12.4k
                                /*InvalidBaseOK=*/true))
12074
5.07k
      return false;
12075
12.4k
  }
12076
12077
  // If we point to before the start of the object, there are no accessible
12078
  // bytes.
12079
7.36k
  if (LVal.getLValueOffset().isNegative()) {
12080
18
    Size = 0;
12081
18
    return true;
12082
18
  }
12083
12084
7.34k
  CharUnits EndOffset;
12085
7.34k
  if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12086
1.09k
    return false;
12087
12088
  // If we've fallen outside of the end offset, just pretend there's nothing to
12089
  // write to/read from.
12090
6.24k
  if (EndOffset <= LVal.getLValueOffset())
12091
286
    Size = 0;
12092
5.96k
  else
12093
5.96k
    Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12094
6.24k
  return true;
12095
7.34k
}
12096
12097
696k
bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12098
696k
  if (!IsConstantEvaluatedBuiltinCall(E))
12099
650k
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
12100
46.6k
  return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12101
696k
}
12102
12103
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12104
181
                                     APValue &Val, APSInt &Alignment) {
12105
181
  QualType SrcTy = E->getArg(0)->getType();
12106
181
  if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12107
38
    return false;
12108
  // Even though we are evaluating integer expressions we could get a pointer
12109
  // argument for the __builtin_is_aligned() case.
12110
143
  if (SrcTy->isPointerType()) {
12111
15
    LValue Ptr;
12112
15
    if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12113
1
      return false;
12114
14
    Ptr.moveInto(Val);
12115
128
  } else if (!SrcTy->isIntegralOrEnumerationType()) {
12116
0
    Info.FFDiag(E->getArg(0));
12117
0
    return false;
12118
128
  } else {
12119
128
    APSInt SrcInt;
12120
128
    if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12121
13
      return false;
12122
115
    assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12123
115
           "Bit widths must be the same");
12124
115
    Val = APValue(SrcInt);
12125
115
  }
12126
129
  assert(Val.hasValue());
12127
129
  return true;
12128
129
}
12129
12130
bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12131
46.6k
                                            unsigned BuiltinOp) {
12132
46.6k
  switch (BuiltinOp) {
12133
0
  default:
12134
0
    return false;
12135
12136
1.19k
  case Builtin::BI__builtin_dynamic_object_size:
12137
3.06k
  case Builtin::BI__builtin_object_size: {
12138
    // The type was checked when we built the expression.
12139
3.06k
    unsigned Type =
12140
3.06k
        E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12141
3.06k
    assert(Type <= 3 && "unexpected type");
12142
12143
3.06k
    uint64_t Size;
12144
3.06k
    if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12145
1.62k
      return Success(Size, E);
12146
12147
1.43k
    if (E->getArg(0)->HasSideEffects(Info.Ctx))
12148
174
      return Success((Type & 2) ? 
012
:
-1162
, E);
12149
12150
    // Expression had no side effects, but we couldn't statically determine the
12151
    // size of the referenced object.
12152
1.26k
    switch (Info.EvalMode) {
12153
3
    case EvalInfo::EM_ConstantExpression:
12154
3
    case EvalInfo::EM_ConstantFold:
12155
1.23k
    case EvalInfo::EM_IgnoreSideEffects:
12156
      // Leave it to IR generation.
12157
1.23k
      return Error(E);
12158
26
    case EvalInfo::EM_ConstantExpressionUnevaluated:
12159
      // Reduce it to a constant now.
12160
26
      return Success((Type & 2) ? 
00
: -1, E);
12161
1.26k
    }
12162
12163
0
    llvm_unreachable("unexpected EvalMode");
12164
0
  }
12165
12166
792
  case Builtin::BI__builtin_os_log_format_buffer_size: {
12167
792
    analyze_os_log::OSLogBufferLayout Layout;
12168
792
    analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12169
792
    return Success(Layout.size().getQuantity(), E);
12170
0
  }
12171
12172
78
  case Builtin::BI__builtin_is_aligned: {
12173
78
    APValue Src;
12174
78
    APSInt Alignment;
12175
78
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12176
22
      return false;
12177
56
    if (Src.isLValue()) {
12178
      // If we evaluated a pointer, check the minimum known alignment.
12179
14
      LValue Ptr;
12180
14
      Ptr.setFrom(Info.Ctx, Src);
12181
14
      CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12182
14
      CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12183
      // We can return true if the known alignment at the computed offset is
12184
      // greater than the requested alignment.
12185
14
      assert(PtrAlign.isPowerOfTwo());
12186
14
      assert(Alignment.isPowerOf2());
12187
14
      if (PtrAlign.getQuantity() >= Alignment)
12188
7
        return Success(1, E);
12189
      // If the alignment is not known to be sufficient, some cases could still
12190
      // be aligned at run time. However, if the requested alignment is less or
12191
      // equal to the base alignment and the offset is not aligned, we know that
12192
      // the run-time value can never be aligned.
12193
7
      if (BaseAlignment.getQuantity() >= Alignment &&
12194
7
          
PtrAlign.getQuantity() < Alignment3
)
12195
3
        return Success(0, E);
12196
      // Otherwise we can't infer whether the value is sufficiently aligned.
12197
      // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12198
      //  in cases where we can't fully evaluate the pointer.
12199
4
      Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12200
4
          << Alignment;
12201
4
      return false;
12202
7
    }
12203
42
    assert(Src.isInt());
12204
42
    return Success((Src.getInt() & (Alignment - 1)) == 0 ? 
115
:
027
, E);
12205
42
  }
12206
52
  case Builtin::BI__builtin_align_up: {
12207
52
    APValue Src;
12208
52
    APSInt Alignment;
12209
52
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12210
15
      return false;
12211
37
    if (!Src.isInt())
12212
0
      return Error(E);
12213
37
    APSInt AlignedVal =
12214
37
        APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12215
37
               Src.getInt().isUnsigned());
12216
37
    assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12217
37
    return Success(AlignedVal, E);
12218
37
  }
12219
51
  case Builtin::BI__builtin_align_down: {
12220
51
    APValue Src;
12221
51
    APSInt Alignment;
12222
51
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12223
15
      return false;
12224
36
    if (!Src.isInt())
12225
0
      return Error(E);
12226
36
    APSInt AlignedVal =
12227
36
        APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12228
36
    assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12229
36
    return Success(AlignedVal, E);
12230
36
  }
12231
12232
8
  case Builtin::BI__builtin_bitreverse8:
12233
18
  case Builtin::BI__builtin_bitreverse16:
12234
26
  case Builtin::BI__builtin_bitreverse32:
12235
36
  case Builtin::BI__builtin_bitreverse64: {
12236
36
    APSInt Val;
12237
36
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12238
28
      return false;
12239
12240
8
    return Success(Val.reverseBits(), E);
12241
36
  }
12242
12243
377
  case Builtin::BI__builtin_bswap16:
12244
821
  case Builtin::BI__builtin_bswap32:
12245
1.23k
  case Builtin::BI__builtin_bswap64: {
12246
1.23k
    APSInt Val;
12247
1.23k
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12248
1.16k
      return false;
12249
12250
73
    return Success(Val.byteSwap(), E);
12251
1.23k
  }
12252
12253
103
  case Builtin::BI__builtin_classify_type:
12254
103
    return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12255
12256
18
  case Builtin::BI__builtin_clrsb:
12257
22
  case Builtin::BI__builtin_clrsbl:
12258
28
  case Builtin::BI__builtin_clrsbll: {
12259
28
    APSInt Val;
12260
28
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12261
4
      return false;
12262
12263
24
    return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12264
28
  }
12265
12266
710
  case Builtin::BI__builtin_clz:
12267
1.18k
  case Builtin::BI__builtin_clzl:
12268
2.20k
  case Builtin::BI__builtin_clzll:
12269
2.21k
  case Builtin::BI__builtin_clzs:
12270
2.24k
  case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12271
2.28k
  case Builtin::BI__lzcnt:
12272
2.32k
  case Builtin::BI__lzcnt64: {
12273
2.32k
    APSInt Val;
12274
2.32k
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12275
2.21k
      return false;
12276
12277
    // When the argument is 0, the result of GCC builtins is undefined, whereas
12278
    // for Microsoft intrinsics, the result is the bit-width of the argument.
12279
106
    bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12280
106
                           
BuiltinOp != Builtin::BI__lzcnt91
&&
12281
106
                           
BuiltinOp != Builtin::BI__lzcnt6476
;
12282
12283
106
    if (ZeroIsUndefined && 
!Val61
)
12284
1
      return Error(E);
12285
12286
105
    return Success(Val.countl_zero(), E);
12287
106
  }
12288
12289
6.01k
  case Builtin::BI__builtin_constant_p: {
12290
6.01k
    const Expr *Arg = E->getArg(0);
12291
6.01k
    if (EvaluateBuiltinConstantP(Info, Arg))
12292
1.28k
      return Success(true, E);
12293
4.72k
    if (Info.InConstantContext || 
Arg->HasSideEffects(Info.Ctx)4.41k
) {
12294
      // Outside a constant context, eagerly evaluate to false in the presence
12295
      // of side-effects in order to avoid -Wunsequenced false-positives in
12296
      // a branch on __builtin_constant_p(expr).
12297
373
      return Success(false, E);
12298
373
    }
12299
4.34k
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12300
4.34k
    return false;
12301
4.72k
  }
12302
12303
7.41k
  case Builtin::BI__builtin_is_constant_evaluated: {
12304
7.41k
    const auto *Callee = Info.CurrentCall->getCallee();
12305
7.41k
    if (Info.InConstantContext && 
!Info.CheckingPotentialConstantExpression823
&&
12306
7.41k
        
(252
Info.CallStackDepth == 1252
||
12307
252
         
(152
Info.CallStackDepth == 2152
&&
Callee->isInStdNamespace()42
&&
12308
152
          
Callee->getIdentifier()27
&&
12309
152
          
Callee->getIdentifier()->isStr("is_constant_evaluated")27
))) {
12310
      // FIXME: Find a better way to avoid duplicated diagnostics.
12311
127
      if (Info.EvalStatus.Diag)
12312
94
        Info.report((Info.CallStackDepth == 1)
12313
94
                        ? 
E->getExprLoc()71
12314
94
                        : 
Info.CurrentCall->getCallRange().getBegin()23
,
12315
94
                    diag::warn_is_constant_evaluated_always_true_constexpr)
12316
94
            << (Info.CallStackDepth == 1 ? 
"__builtin_is_constant_evaluated"71
12317
94
                                         : 
"std::is_constant_evaluated"23
);
12318
127
    }
12319
12320
7.41k
    return Success(Info.InConstantContext, E);
12321
4.72k
  }
12322
12323
542
  case Builtin::BI__builtin_ctz:
12324
997
  case Builtin::BI__builtin_ctzl:
12325
1.66k
  case Builtin::BI__builtin_ctzll:
12326
1.67k
  case Builtin::BI__builtin_ctzs: {
12327
1.67k
    APSInt Val;
12328
1.67k
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12329
1.61k
      return false;
12330
57
    if (!Val)
12331
1
      return Error(E);
12332
12333
56
    return Success(Val.countr_zero(), E);
12334
57
  }
12335
12336
22
  case Builtin::BI__builtin_eh_return_data_regno: {
12337
22
    int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12338
22
    Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12339
22
    return Success(Operand, E);
12340
57
  }
12341
12342
2.28k
  case Builtin::BI__builtin_expect:
12343
2.34k
  case Builtin::BI__builtin_expect_with_probability:
12344
2.34k
    return Visit(E->getArg(0));
12345
12346
12
  case Builtin::BI__builtin_ffs:
12347
16
  case Builtin::BI__builtin_ffsl:
12348
20
  case Builtin::BI__builtin_ffsll: {
12349
20
    APSInt Val;
12350
20
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12351
6
      return false;
12352
12353
14
    unsigned N = Val.countr_zero();
12354
14
    return Success(N == Val.getBitWidth() ? 
02
:
N + 112
, E);
12355
20
  }
12356
12357
101
  case Builtin::BI__builtin_fpclassify: {
12358
101
    APFloat Val(0.0);
12359
101
    if (!EvaluateFloat(E->getArg(5), Val, Info))
12360
25
      return false;
12361
76
    unsigned Arg;
12362
76
    switch (Val.getCategory()) {
12363
10
    case APFloat::fcNaN: Arg = 0; break;
12364
10
    case APFloat::fcInfinity: Arg = 1; break;
12365
26
    case APFloat::fcNormal: Arg = Val.isDenormal() ? 
311
:
215
; break;
12366
30
    case APFloat::fcZero: Arg = 4; break;
12367
76
    }
12368
76
    return Visit(E->getArg(Arg));
12369
76
  }
12370
12371
85
  case Builtin::BI__builtin_isinf_sign: {
12372
85
    APFloat Val(0.0);
12373
85
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12374
85
           
Success(68
Val.isInfinity()68
?
(58
Val.isNegative()58
?
-110
:
148
) :
010
, E);
12375
76
  }
12376
12377
77
  case Builtin::BI__builtin_isinf: {
12378
77
    APFloat Val(0.0);
12379
77
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12380
77
           
Success(33
Val.isInfinity()33
?
17
:
026
, E);
12381
76
  }
12382
12383
64
  case Builtin::BI__builtin_isfinite: {
12384
64
    APFloat Val(0.0);
12385
64
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12386
64
           
Success(32
Val.isFinite()32
?
121
:
011
, E);
12387
76
  }
12388
12389
102
  case Builtin::BI__builtin_isnan: {
12390
102
    APFloat Val(0.0);
12391
102
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12392
102
           
Success(34
Val.isNaN()34
?
112
:
022
, E);
12393
76
  }
12394
12395
67
  case Builtin::BI__builtin_isnormal: {
12396
67
    APFloat Val(0.0);
12397
67
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12398
67
           
Success(31
Val.isNormal()31
?
111
:
020
, E);
12399
76
  }
12400
12401
35
  case Builtin::BI__builtin_issubnormal: {
12402
35
    APFloat Val(0.0);
12403
35
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12404
35
           
Success(31
Val.isDenormal()31
?
16
:
025
, E);
12405
76
  }
12406
12407
36
  case Builtin::BI__builtin_iszero: {
12408
36
    APFloat Val(0.0);
12409
36
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12410
36
           
Success(32
Val.isZero()32
?
17
:
025
, E);
12411
76
  }
12412
12413
42
  case Builtin::BI__builtin_issignaling: {
12414
42
    APFloat Val(0.0);
12415
42
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12416
42
           
Success(38
Val.isSignaling()38
?
18
:
030
, E);
12417
76
  }
12418
12419
220
  case Builtin::BI__builtin_isfpclass: {
12420
220
    APSInt MaskVal;
12421
220
    if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12422
0
      return false;
12423
220
    unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12424
220
    APFloat Val(0.0);
12425
220
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12426
220
           
Success(196
(Val.classify() & Test)196
?
197
:
099
, E);
12427
220
  }
12428
12429
18
  case Builtin::BI__builtin_parity:
12430
22
  case Builtin::BI__builtin_parityl:
12431
26
  case Builtin::BI__builtin_parityll: {
12432
26
    APSInt Val;
12433
26
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12434
6
      return false;
12435
12436
20
    return Success(Val.popcount() % 2, E);
12437
26
  }
12438
12439
614
  case Builtin::BI__builtin_popcount:
12440
1.09k
  case Builtin::BI__builtin_popcountl:
12441
1.95k
  case Builtin::BI__builtin_popcountll:
12442
1.98k
  case Builtin::BI__popcnt16: // Microsoft variants of popcount
12443
2.01k
  case Builtin::BI__popcnt:
12444
2.04k
  case Builtin::BI__popcnt64: {
12445
2.04k
    APSInt Val;
12446
2.04k
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12447
1.84k
      return false;
12448
12449
201
    return Success(Val.popcount(), E);
12450
2.04k
  }
12451
12452
60
  case Builtin::BI__builtin_rotateleft8:
12453
129
  case Builtin::BI__builtin_rotateleft16:
12454
201
  case Builtin::BI__builtin_rotateleft32:
12455
292
  case Builtin::BI__builtin_rotateleft64:
12456
304
  case Builtin::BI_rotl8: // Microsoft variants of rotate right
12457
316
  case Builtin::BI_rotl16:
12458
338
  case Builtin::BI_rotl:
12459
360
  case Builtin::BI_lrotl:
12460
373
  case Builtin::BI_rotl64: {
12461
373
    APSInt Val, Amt;
12462
373
    if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12463
373
        
!EvaluateInteger(E->getArg(1), Amt, Info)47
)
12464
326
      return false;
12465
12466
47
    return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12467
373
  }
12468
12469
61
  case Builtin::BI__builtin_rotateright8:
12470
129
  case Builtin::BI__builtin_rotateright16:
12471
196
  case Builtin::BI__builtin_rotateright32:
12472
281
  case Builtin::BI__builtin_rotateright64:
12473
293
  case Builtin::BI_rotr8: // Microsoft variants of rotate right
12474
305
  case Builtin::BI_rotr16:
12475
327
  case Builtin::BI_rotr:
12476
349
  case Builtin::BI_lrotr:
12477
362
  case Builtin::BI_rotr64: {
12478
362
    APSInt Val, Amt;
12479
362
    if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12480
362
        
!EvaluateInteger(E->getArg(1), Amt, Info)47
)
12481
315
      return false;
12482
12483
47
    return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12484
362
  }
12485
12486
1.95k
  case Builtin::BIstrlen:
12487
2.05k
  case Builtin::BIwcslen:
12488
    // A call to strlen is not a constant expression.
12489
2.05k
    if (Info.getLangOpts().CPlusPlus11)
12490
582
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12491
582
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12492
582
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12493
1.47k
    else
12494
1.47k
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12495
2.05k
    [[fallthrough]];
12496
4.47k
  case Builtin::BI__builtin_strlen:
12497
4.58k
  case Builtin::BI__builtin_wcslen: {
12498
    // As an extension, we support __builtin_strlen() as a constant expression,
12499
    // and support folding strlen() to a constant.
12500
4.58k
    uint64_t StrLen;
12501
4.58k
    if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12502
957
      return Success(StrLen, E);
12503
3.62k
    return false;
12504
4.58k
  }
12505
12506
623
  case Builtin::BIstrcmp:
12507
639
  case Builtin::BIwcscmp:
12508
972
  case Builtin::BIstrncmp:
12509
988
  case Builtin::BIwcsncmp:
12510
2.13k
  case Builtin::BImemcmp:
12511
2.16k
  case Builtin::BIbcmp:
12512
2.21k
  case Builtin::BIwmemcmp:
12513
    // A call to strlen is not a constant expression.
12514
2.21k
    if (Info.getLangOpts().CPlusPlus11)
12515
1.40k
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12516
1.40k
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12517
1.40k
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12518
809
    else
12519
809
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12520
2.21k
    [[fallthrough]];
12521
8.72k
  case Builtin::BI__builtin_strcmp:
12522
8.96k
  case Builtin::BI__builtin_wcscmp:
12523
9.36k
  case Builtin::BI__builtin_strncmp:
12524
9.58k
  case Builtin::BI__builtin_wcsncmp:
12525
10.7k
  case Builtin::BI__builtin_memcmp:
12526
11.4k
  case Builtin::BI__builtin_bcmp:
12527
11.6k
  case Builtin::BI__builtin_wmemcmp: {
12528
11.6k
    LValue String1, String2;
12529
11.6k
    if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12530
11.6k
        
!EvaluatePointer(E->getArg(1), String2, Info)3.46k
)
12531
8.26k
      return false;
12532
12533
3.35k
    uint64_t MaxLength = uint64_t(-1);
12534
3.35k
    if (BuiltinOp != Builtin::BIstrcmp &&
12535
3.35k
        
BuiltinOp != Builtin::BIwcscmp3.28k
&&
12536
3.35k
        
BuiltinOp != Builtin::BI__builtin_strcmp3.27k
&&
12537
3.35k
        
BuiltinOp != Builtin::BI__builtin_wcscmp2.74k
) {
12538
2.51k
      APSInt N;
12539
2.51k
      if (!EvaluateInteger(E->getArg(2), N, Info))
12540
36
        return false;
12541
2.47k
      MaxLength = N.getZExtValue();
12542
2.47k
    }
12543
12544
    // Empty substrings compare equal by definition.
12545
3.32k
    if (MaxLength == 0u)
12546
252
      return Success(0, E);
12547
12548
3.06k
    if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12549
3.06k
        
!String2.checkNullPointerForFoldAccess(Info, E, AK_Read)3.01k
||
12550
3.06k
        
String1.Designator.Invalid2.95k
||
String2.Designator.Invalid2.95k
)
12551
114
      return false;
12552
12553
2.95k
    QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12554
2.95k
    QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12555
12556
2.95k
    bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12557
2.95k
                     
BuiltinOp == Builtin::BIbcmp2.80k
||
12558
2.95k
                     
BuiltinOp == Builtin::BI__builtin_memcmp2.79k
||
12559
2.95k
                     
BuiltinOp == Builtin::BI__builtin_bcmp1.96k
;
12560
12561
2.95k
    assert(IsRawByte ||
12562
2.95k
           (Info.Ctx.hasSameUnqualifiedType(
12563
2.95k
                CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12564
2.95k
            Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12565
12566
    // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12567
    // 'char8_t', but no other types.
12568
2.95k
    if (IsRawByte &&
12569
2.95k
        
!(1.60k
isOneByteCharacterType(CharTy1)1.60k
&&
isOneByteCharacterType(CharTy2)1.09k
)) {
12570
      // FIXME: Consider using our bit_cast implementation to support this.
12571
662
      Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12572
662
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12573
662
          << CharTy1 << CharTy2;
12574
662
      return false;
12575
662
    }
12576
12577
10.8k
    
const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) 2.29k
{
12578
10.8k
      return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12579
10.8k
             
handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2)10.4k
&&
12580
10.8k
             
Char1.isInt()10.4k
&&
Char2.isInt()10.4k
;
12581
10.8k
    };
12582
8.92k
    const auto &AdvanceElems = [&] {
12583
8.92k
      return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12584
8.92k
             HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12585
8.92k
    };
12586
12587
2.29k
    bool StopAtNull =
12588
2.29k
        (BuiltinOp != Builtin::BImemcmp && 
BuiltinOp != Builtin::BIbcmp2.14k
&&
12589
2.29k
         
BuiltinOp != Builtin::BIwmemcmp2.13k
&&
12590
2.29k
         
BuiltinOp != Builtin::BI__builtin_memcmp2.11k
&&
12591
2.29k
         
BuiltinOp != Builtin::BI__builtin_bcmp1.62k
&&
12592
2.29k
         
BuiltinOp != Builtin::BI__builtin_wmemcmp1.32k
);
12593
2.29k
    bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12594
2.29k
                  
BuiltinOp == Builtin::BIwcsncmp2.27k
||
12595
2.29k
                  
BuiltinOp == Builtin::BIwmemcmp2.26k
||
12596
2.29k
                  
BuiltinOp == Builtin::BI__builtin_wcscmp2.23k
||
12597
2.29k
                  
BuiltinOp == Builtin::BI__builtin_wcsncmp2.05k
||
12598
2.29k
                  
BuiltinOp == Builtin::BI__builtin_wmemcmp1.86k
;
12599
12600
11.2k
    for (; MaxLength; 
--MaxLength8.92k
) {
12601
10.8k
      APValue Char1, Char2;
12602
10.8k
      if (!ReadCurElems(Char1, Char2))
12603
400
        return false;
12604
10.4k
      if (Char1.getInt().ne(Char2.getInt())) {
12605
1.13k
        if (IsWide) // wmemcmp compares with wchar_t signedness.
12606
332
          return Success(Char1.getInt() < Char2.getInt() ? 
-1264
:
168
, E);
12607
        // memcmp always compares unsigned chars.
12608
802
        return Success(Char1.getInt().ult(Char2.getInt()) ? 
-1494
:
1308
, E);
12609
1.13k
      }
12610
9.31k
      if (StopAtNull && 
!Char1.getInt()5.77k
)
12611
394
        return Success(0, E);
12612
8.92k
      assert(!(StopAtNull && !Char2.getInt()));
12613
8.92k
      if (!AdvanceElems())
12614
0
        return false;
12615
8.92k
    }
12616
    // We hit the strncmp / memcmp limit.
12617
364
    return Success(0, E);
12618
2.29k
  }
12619
12620
434
  case Builtin::BI__atomic_always_lock_free:
12621
811
  case Builtin::BI__atomic_is_lock_free:
12622
1.06k
  case Builtin::BI__c11_atomic_is_lock_free: {
12623
1.06k
    APSInt SizeVal;
12624
1.06k
    if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12625
0
      return false;
12626
12627
    // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12628
    // of two less than or equal to the maximum inline atomic width, we know it
12629
    // is lock-free.  If the size isn't a power of two, or greater than the
12630
    // maximum alignment where we promote atomics, we know it is not lock-free
12631
    // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12632
    // the answer can only be determined at runtime; for example, 16-byte
12633
    // atomics have lock-free implementations on some, but not all,
12634
    // x86-64 processors.
12635
12636
    // Check power-of-two.
12637
1.06k
    CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12638
1.06k
    if (Size.isPowerOfTwo()) {
12639
      // Check against inlining width.
12640
956
      unsigned InlineWidthBits =
12641
956
          Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12642
956
      if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12643
871
        if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12644
871
            
Size == CharUnits::One()695
||
12645
871
            E->getArg(1)->isNullPointerConstant(Info.Ctx,
12646
472
                                                Expr::NPC_NeverValueDependent))
12647
          // OK, we will inline appropriately-aligned operations of this size,
12648
          // and _Atomic(T) is appropriately-aligned.
12649
546
          return Success(1, E);
12650
12651
325
        QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12652
325
          castAs<PointerType>()->getPointeeType();
12653
325
        if (!PointeeType->isIncompleteType() &&
12654
325
            
Info.Ctx.getTypeAlignInChars(PointeeType) >= Size261
) {
12655
          // OK, we will inline operations on this object.
12656
173
          return Success(1, E);
12657
173
        }
12658
325
      }
12659
956
    }
12660
12661
341
    return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12662
201
        
Success(0, E)140
: Error(E);
12663
1.06k
  }
12664
88
  case Builtin::BI__builtin_add_overflow:
12665
133
  case Builtin::BI__builtin_sub_overflow:
12666
316
  case Builtin::BI__builtin_mul_overflow:
12667
330
  case Builtin::BI__builtin_sadd_overflow:
12668
339
  case Builtin::BI__builtin_uadd_overflow:
12669
348
  case Builtin::BI__builtin_uaddl_overflow:
12670
357
  case Builtin::BI__builtin_uaddll_overflow:
12671
366
  case Builtin::BI__builtin_usub_overflow:
12672
375
  case Builtin::BI__builtin_usubl_overflow:
12673
384
  case Builtin::BI__builtin_usubll_overflow:
12674
393
  case Builtin::BI__builtin_umul_overflow:
12675
402
  case Builtin::BI__builtin_umull_overflow:
12676
411
  case Builtin::BI__builtin_umulll_overflow:
12677
420
  case Builtin::BI__builtin_saddl_overflow:
12678
429
  case Builtin::BI__builtin_saddll_overflow:
12679
442
  case Builtin::BI__builtin_ssub_overflow:
12680
451
  case Builtin::BI__builtin_ssubl_overflow:
12681
460
  case Builtin::BI__builtin_ssubll_overflow:
12682
473
  case Builtin::BI__builtin_smul_overflow:
12683
482
  case Builtin::BI__builtin_smull_overflow:
12684
491
  case Builtin::BI__builtin_smulll_overflow: {
12685
491
    LValue ResultLValue;
12686
491
    APSInt LHS, RHS;
12687
12688
491
    QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12689
491
    if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12690
491
        
!EvaluateInteger(E->getArg(1), RHS, Info)55
||
12691
491
        
!EvaluatePointer(E->getArg(2), ResultLValue, Info)55
)
12692
436
      return false;
12693
12694
55
    APSInt Result;
12695
55
    bool DidOverflow = false;
12696
12697
    // If the types don't have to match, enlarge all 3 to the largest of them.
12698
55
    if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12699
55
        
BuiltinOp == Builtin::BI__builtin_sub_overflow39
||
12700
55
        
BuiltinOp == Builtin::BI__builtin_mul_overflow21
) {
12701
45
      bool IsSigned = LHS.isSigned() || 
RHS.isSigned()3
||
12702
45
                      
ResultType->isSignedIntegerOrEnumerationType()2
;
12703
45
      bool AllSigned = LHS.isSigned() && 
RHS.isSigned()42
&&
12704
45
                      
ResultType->isSignedIntegerOrEnumerationType()42
;
12705
45
      uint64_t LHSSize = LHS.getBitWidth();
12706
45
      uint64_t RHSSize = RHS.getBitWidth();
12707
45
      uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12708
45
      uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12709
12710
      // Add an additional bit if the signedness isn't uniformly agreed to. We
12711
      // could do this ONLY if there is a signed and an unsigned that both have
12712
      // MaxBits, but the code to check that is pretty nasty.  The issue will be
12713
      // caught in the shrink-to-result later anyway.
12714
45
      if (IsSigned && !AllSigned)
12715
6
        ++MaxBits;
12716
12717
45
      LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12718
45
      RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12719
45
      Result = APSInt(MaxBits, !IsSigned);
12720
45
    }
12721
12722
    // Find largest int.
12723
55
    switch (BuiltinOp) {
12724
0
    default:
12725
0
      llvm_unreachable("Invalid value for BuiltinOp");
12726
16
    case Builtin::BI__builtin_add_overflow:
12727
20
    case Builtin::BI__builtin_sadd_overflow:
12728
20
    case Builtin::BI__builtin_saddl_overflow:
12729
20
    case Builtin::BI__builtin_saddll_overflow:
12730
20
    case Builtin::BI__builtin_uadd_overflow:
12731
20
    case Builtin::BI__builtin_uaddl_overflow:
12732
20
    case Builtin::BI__builtin_uaddll_overflow:
12733
20
      Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12734
20
                              : 
LHS.uadd_ov(RHS, DidOverflow)0
;
12735
20
      break;
12736
18
    case Builtin::BI__builtin_sub_overflow:
12737
21
    case Builtin::BI__builtin_ssub_overflow:
12738
21
    case Builtin::BI__builtin_ssubl_overflow:
12739
21
    case Builtin::BI__builtin_ssubll_overflow:
12740
21
    case Builtin::BI__builtin_usub_overflow:
12741
21
    case Builtin::BI__builtin_usubl_overflow:
12742
21
    case Builtin::BI__builtin_usubll_overflow:
12743
21
      Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12744
21
                              : 
LHS.usub_ov(RHS, DidOverflow)0
;
12745
21
      break;
12746
11
    case Builtin::BI__builtin_mul_overflow:
12747
14
    case Builtin::BI__builtin_smul_overflow:
12748
14
    case Builtin::BI__builtin_smull_overflow:
12749
14
    case Builtin::BI__builtin_smulll_overflow:
12750
14
    case Builtin::BI__builtin_umul_overflow:
12751
14
    case Builtin::BI__builtin_umull_overflow:
12752
14
    case Builtin::BI__builtin_umulll_overflow:
12753
14
      Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12754
14
                              : 
LHS.umul_ov(RHS, DidOverflow)0
;
12755
14
      break;
12756
55
    }
12757
12758
    // In the case where multiple sizes are allowed, truncate and see if
12759
    // the values are the same.
12760
55
    if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12761
55
        
BuiltinOp == Builtin::BI__builtin_sub_overflow39
||
12762
55
        
BuiltinOp == Builtin::BI__builtin_mul_overflow21
) {
12763
      // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12764
      // since it will give us the behavior of a TruncOrSelf in the case where
12765
      // its parameter <= its size.  We previously set Result to be at least the
12766
      // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12767
      // will work exactly like TruncOrSelf.
12768
45
      APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12769
45
      Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12770
12771
45
      if (!APSInt::isSameValue(Temp, Result))
12772
4
        DidOverflow = true;
12773
45
      Result = Temp;
12774
45
    }
12775
12776
55
    APValue APV{Result};
12777
55
    if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12778
29
      return false;
12779
26
    return Success(DidOverflow, E);
12780
55
  }
12781
46.6k
  }
12782
46.6k
}
12783
12784
/// Determine whether this is a pointer past the end of the complete
12785
/// object referred to by the lvalue.
12786
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12787
719
                                            const LValue &LV) {
12788
  // A null pointer can be viewed as being "past the end" but we don't
12789
  // choose to look at it that way here.
12790
719
  if (!LV.getLValueBase())
12791
339
    return false;
12792
12793
  // If the designator is valid and refers to a subobject, we're not pointing
12794
  // past the end.
12795
380
  if (!LV.getLValueDesignator().Invalid &&
12796
380
      
!LV.getLValueDesignator().isOnePastTheEnd()362
)
12797
344
    return false;
12798
12799
  // A pointer to an incomplete type might be past-the-end if the type's size is
12800
  // zero.  We cannot tell because the type is incomplete.
12801
36
  QualType Ty = getType(LV.getLValueBase());
12802
36
  if (Ty->isIncompleteType())
12803
0
    return true;
12804
12805
  // We're a past-the-end pointer if we point to the byte after the object,
12806
  // no matter what our type or path is.
12807
36
  auto Size = Ctx.getTypeSizeInChars(Ty);
12808
36
  return LV.getLValueOffset() == Size;
12809
36
}
12810
12811
namespace {
12812
12813
/// Data recursive integer evaluator of certain binary operators.
12814
///
12815
/// We use a data recursive algorithm for binary operators so that we are able
12816
/// to handle extreme cases of chained binary operators without causing stack
12817
/// overflow.
12818
class DataRecursiveIntBinOpEvaluator {
12819
  struct EvalResult {
12820
    APValue Val;
12821
    bool Failed = false;
12822
12823
36.2M
    EvalResult() = default;
12824
12825
17.4M
    void swap(EvalResult &RHS) {
12826
17.4M
      Val.swap(RHS.Val);
12827
17.4M
      Failed = RHS.Failed;
12828
17.4M
      RHS.Failed = false;
12829
17.4M
    }
12830
  };
12831
12832
  struct Job {
12833
    const Expr *E;
12834
    EvalResult LHSResult; // meaningful only for binary operator expression.
12835
    enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12836
12837
22.9M
    Job() = default;
12838
69.1k
    Job(Job &&) = default;
12839
12840
91.1k
    void startSpeculativeEval(EvalInfo &Info) {
12841
91.1k
      SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12842
91.1k
    }
12843
12844
  private:
12845
    SpeculativeEvaluationRAII SpecEvalRAII;
12846
  };
12847
12848
  SmallVector<Job, 16> Queue;
12849
12850
  IntExprEvaluator &IntEval;
12851
  EvalInfo &Info;
12852
  APValue &FinalResult;
12853
12854
public:
12855
  DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12856
4.60M
    : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12857
12858
  /// True if \param E is a binary operator that we are going to handle
12859
  /// data recursively.
12860
  /// We handle binary operators that are comma, logical, or that have operands
12861
  /// with integral or enumeration type.
12862
14.4M
  static bool shouldEnqueue(const BinaryOperator *E) {
12863
14.4M
    return E->getOpcode() == BO_Comma || 
E->isLogicalOp()14.4M
||
12864
14.4M
           
(13.0M
E->isPRValue()13.0M
&&
E->getType()->isIntegralOrEnumerationType()13.0M
&&
12865
13.0M
            
E->getLHS()->getType()->isIntegralOrEnumerationType()13.0M
&&
12866
13.0M
            
E->getRHS()->getType()->isIntegralOrEnumerationType()12.8M
);
12867
14.4M
  }
12868
12869
4.60M
  bool Traverse(const BinaryOperator *E) {
12870
4.60M
    enqueue(E);
12871
4.60M
    EvalResult PrevResult;
12872
45.9M
    while (!Queue.empty())
12873
41.3M
      process(PrevResult);
12874
12875
4.60M
    if (PrevResult.Failed) 
return false2.30M
;
12876
12877
2.30M
    FinalResult.swap(PrevResult.Val);
12878
2.30M
    return true;
12879
4.60M
  }
12880
12881
private:
12882
688k
  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12883
688k
    return IntEval.Success(Value, E, Result);
12884
688k
  }
12885
6.10M
  bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12886
6.10M
    return IntEval.Success(Value, E, Result);
12887
6.10M
  }
12888
14.0k
  bool Error(const Expr *E) {
12889
14.0k
    return IntEval.Error(E);
12890
14.0k
  }
12891
0
  bool Error(const Expr *E, diag::kind D) {
12892
0
    return IntEval.Error(E, D);
12893
0
  }
12894
12895
0
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12896
0
    return Info.CCEDiag(E, D);
12897
0
  }
12898
12899
  // Returns true if visiting the RHS is necessary, false otherwise.
12900
  bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12901
                         bool &SuppressRHSDiags);
12902
12903
  bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12904
                  const BinaryOperator *E, APValue &Result);
12905
12906
13.3M
  void EvaluateExpr(const Expr *E, EvalResult &Result) {
12907
13.3M
    Result.Failed = !Evaluate(Result.Val, Info, E);
12908
13.3M
    if (Result.Failed)
12909
3.10M
      Result.Val = APValue();
12910
13.3M
  }
12911
12912
  void process(EvalResult &Result);
12913
12914
22.9M
  void enqueue(const Expr *E) {
12915
22.9M
    E = E->IgnoreParens();
12916
22.9M
    Queue.resize(Queue.size()+1);
12917
22.9M
    Queue.back().E = E;
12918
22.9M
    Queue.back().Kind = Job::AnyExprKind;
12919
22.9M
  }
12920
};
12921
12922
}
12923
12924
bool DataRecursiveIntBinOpEvaluator::
12925
       VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12926
9.63M
                         bool &SuppressRHSDiags) {
12927
9.63M
  if (E->getOpcode() == BO_Comma) {
12928
    // Ignore LHS but note if we could not evaluate it.
12929
3.61k
    if (LHSResult.Failed)
12930
1.80k
      return Info.noteSideEffect();
12931
1.80k
    return true;
12932
3.61k
  }
12933
12934
9.63M
  if (E->isLogicalOp()) {
12935
780k
    bool LHSAsBool;
12936
780k
    if (!LHSResult.Failed && 
HandleConversionToBool(LHSResult.Val, LHSAsBool)689k
) {
12937
      // We were able to evaluate the LHS, see if we can get away with not
12938
      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12939
689k
      if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12940
96.5k
        Success(LHSAsBool, E, LHSResult.Val);
12941
96.5k
        return false; // Ignore RHS
12942
96.5k
      }
12943
689k
    } else {
12944
91.2k
      LHSResult.Failed = true;
12945
12946
      // Since we weren't able to evaluate the left hand side, it
12947
      // might have had side effects.
12948
91.2k
      if (!Info.noteSideEffect())
12949
68
        return false;
12950
12951
      // We can't evaluate the LHS; however, sometimes the result
12952
      // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12953
      // Don't ignore RHS and suppress diagnostics from this arm.
12954
91.1k
      SuppressRHSDiags = true;
12955
91.1k
    }
12956
12957
684k
    return true;
12958
780k
  }
12959
12960
8.85M
  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12961
8.85M
         E->getRHS()->getType()->isIntegralOrEnumerationType());
12962
12963
8.85M
  if (LHSResult.Failed && 
!Info.noteFailure()2.56M
)
12964
825k
    return false; // Ignore RHS;
12965
12966
8.02M
  return true;
12967
8.85M
}
12968
12969
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12970
22
                                    bool IsSub) {
12971
  // Compute the new offset in the appropriate width, wrapping at 64 bits.
12972
  // FIXME: When compiling for a 32-bit target, we should use 32-bit
12973
  // offsets.
12974
22
  assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12975
22
  CharUnits &Offset = LVal.getLValueOffset();
12976
22
  uint64_t Offset64 = Offset.getQuantity();
12977
22
  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12978
22
  Offset = CharUnits::fromQuantity(IsSub ? 
Offset64 - Index646
12979
22
                                         : 
Offset64 + Index6416
);
12980
22
}
12981
12982
bool DataRecursiveIntBinOpEvaluator::
12983
       VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12984
8.71M
                  const BinaryOperator *E, APValue &Result) {
12985
8.71M
  if (E->getOpcode() == BO_Comma) {
12986
3.51k
    if (RHSResult.Failed)
12987
1.04k
      return false;
12988
2.47k
    Result = RHSResult.Val;
12989
2.47k
    return true;
12990
3.51k
  }
12991
12992
8.71M
  if (E->isLogicalOp()) {
12993
684k
    bool lhsResult, rhsResult;
12994
684k
    bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12995
684k
    bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12996
12997
684k
    if (LHSIsOK) {
12998
592k
      if (RHSIsOK) {
12999
591k
        if (E->getOpcode() == BO_LOr)
13000
38.6k
          return Success(lhsResult || rhsResult, E, Result);
13001
553k
        else
13002
553k
          return Success(lhsResult && rhsResult, E, Result);
13003
591k
      }
13004
592k
    } else {
13005
91.1k
      if (RHSIsOK) {
13006
        // We can't evaluate the LHS; however, sometimes the result
13007
        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13008
422
        if (rhsResult == (E->getOpcode() == BO_LOr))
13009
150
          return Success(rhsResult, E, Result);
13010
422
      }
13011
91.1k
    }
13012
13013
92.0k
    return false;
13014
684k
  }
13015
13016
8.02M
  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13017
8.02M
         E->getRHS()->getType()->isIntegralOrEnumerationType());
13018
13019
8.02M
  if (LHSResult.Failed || 
RHSResult.Failed6.28M
)
13020
1.91M
    return false;
13021
13022
6.11M
  const APValue &LHSVal = LHSResult.Val;
13023
6.11M
  const APValue &RHSVal = RHSResult.Val;
13024
13025
  // Handle cases like (unsigned long)&a + 4.
13026
6.11M
  if (E->isAdditiveOp() && 
LHSVal.isLValue()4.03M
&&
RHSVal.isInt()59
) {
13027
20
    Result = LHSVal;
13028
20
    addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13029
20
    return true;
13030
20
  }
13031
13032
  // Handle cases like 4 + (unsigned long)&a
13033
6.11M
  if (E->getOpcode() == BO_Add &&
13034
6.11M
      
RHSVal.isLValue()1.38M
&&
LHSVal.isInt()2
) {
13035
2
    Result = RHSVal;
13036
2
    addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13037
2
    return true;
13038
2
  }
13039
13040
6.11M
  if (E->getOpcode() == BO_Sub && 
LHSVal.isLValue()2.65M
&&
RHSVal.isLValue()39
) {
13041
    // Handle (intptr_t)&&A - (intptr_t)&&B.
13042
39
    if (!LHSVal.getLValueOffset().isZero() ||
13043
39
        !RHSVal.getLValueOffset().isZero())
13044
0
      return false;
13045
39
    const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13046
39
    const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13047
39
    if (!LHSExpr || !RHSExpr)
13048
0
      return false;
13049
39
    const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13050
39
    const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13051
39
    if (!LHSAddrExpr || !RHSAddrExpr)
13052
0
      return false;
13053
    // Make sure both labels come from the same function.
13054
39
    if (LHSAddrExpr->getLabel()->getDeclContext() !=
13055
39
        RHSAddrExpr->getLabel()->getDeclContext())
13056
6
      return false;
13057
33
    Result = APValue(LHSAddrExpr, RHSAddrExpr);
13058
33
    return true;
13059
39
  }
13060
13061
  // All the remaining cases expect both operands to be an integer
13062
6.11M
  if (!LHSVal.isInt() || 
!RHSVal.isInt()6.10M
)
13063
14.0k
    return Error(E);
13064
13065
  // Set up the width and signedness manually, in case it can't be deduced
13066
  // from the operation we're performing.
13067
  // FIXME: Don't do this in the cases where we can deduce it.
13068
6.10M
  APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13069
6.10M
               E->getType()->isUnsignedIntegerOrEnumerationType());
13070
6.10M
  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13071
6.10M
                         RHSVal.getInt(), Value))
13072
350
    return false;
13073
6.10M
  return Success(Value, E, Result);
13074
6.10M
}
13075
13076
41.3M
void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13077
41.3M
  Job &job = Queue.back();
13078
13079
41.3M
  switch (job.Kind) {
13080
22.9M
    case Job::AnyExprKind: {
13081
22.9M
      if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13082
9.67M
        if (shouldEnqueue(Bop)) {
13083
9.63M
          job.Kind = Job::BinOpKind;
13084
9.63M
          enqueue(Bop->getLHS());
13085
9.63M
          return;
13086
9.63M
        }
13087
9.67M
      }
13088
13089
13.3M
      EvaluateExpr(job.E, Result);
13090
13.3M
      Queue.pop_back();
13091
13.3M
      return;
13092
22.9M
    }
13093
13094
9.63M
    case Job::BinOpKind: {
13095
9.63M
      const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13096
9.63M
      bool SuppressRHSDiags = false;
13097
9.63M
      if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13098
922k
        Queue.pop_back();
13099
922k
        return;
13100
922k
      }
13101
8.71M
      if (SuppressRHSDiags)
13102
91.1k
        job.startSpeculativeEval(Info);
13103
8.71M
      job.LHSResult.swap(Result);
13104
8.71M
      job.Kind = Job::BinOpVisitedLHSKind;
13105
8.71M
      enqueue(Bop->getRHS());
13106
8.71M
      return;
13107
9.63M
    }
13108
13109
8.71M
    case Job::BinOpVisitedLHSKind: {
13110
8.71M
      const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13111
8.71M
      EvalResult RHS;
13112
8.71M
      RHS.swap(Result);
13113
8.71M
      Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13114
8.71M
      Queue.pop_back();
13115
8.71M
      return;
13116
9.63M
    }
13117
41.3M
  }
13118
13119
0
  llvm_unreachable("Invalid Job::Kind!");
13120
0
}
13121
13122
namespace {
13123
enum class CmpResult {
13124
  Unequal,
13125
  Less,
13126
  Equal,
13127
  Greater,
13128
  Unordered,
13129
};
13130
}
13131
13132
template <class SuccessCB, class AfterCB>
13133
static bool
13134
EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
13135
107k
                                 SuccessCB &&Success, AfterCB &&DoAfter) {
13136
107k
  assert(!E->isValueDependent());
13137
107k
  assert(E->isComparisonOp() && "expected comparison operator");
13138
107k
  assert((E->getOpcode() == BO_Cmp ||
13139
107k
          E->getType()->isIntegralOrEnumerationType()) &&
13140
107k
         "unsupported binary expression evaluation");
13141
107k
  auto Error = [&](const Expr *E) {
13142
4
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13143
4
    return false;
13144
4
  };
Unexecuted instantiation: ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1&&)::'lambda'(clang::Expr const*)::operator()(clang::Expr const*) const
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1&&)::'lambda'(clang::Expr const*)::operator()(clang::Expr const*) const
Line
Count
Source
13141
4
  auto Error = [&](const Expr *E) {
13142
4
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13143
4
    return false;
13144
4
  };
13145
13146
107k
  bool IsRelational = E->isRelationalOp() || 
E->getOpcode() == BO_Cmp75.2k
;
13147
107k
  bool IsEquality = E->isEqualityOp();
13148
13149
107k
  QualType LHSTy = E->getLHS()->getType();
13150
107k
  QualType RHSTy = E->getRHS()->getType();
13151
13152
107k
  if (LHSTy->isIntegralOrEnumerationType() &&
13153
107k
      
RHSTy->isIntegralOrEnumerationType()740
) {
13154
740
    APSInt LHS, RHS;
13155
740
    bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13156
740
    if (!LHSOK && 
!Info.noteFailure()492
)
13157
216
      return false;
13158
524
    if (!EvaluateInteger(E->getRHS(), RHS, Info) || 
!LHSOK253
)
13159
361
      return false;
13160
163
    if (LHS < RHS)
13161
22
      return Success(CmpResult::Less, E);
13162
141
    if (LHS > RHS)
13163
36
      return Success(CmpResult::Greater, E);
13164
105
    return Success(CmpResult::Equal, E);
13165
141
  }
13166
13167
107k
  if (LHSTy->isFixedPointType() || 
RHSTy->isFixedPointType()106k
) {
13168
248
    APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13169
248
    APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13170
13171
248
    bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13172
248
    if (!LHSOK && 
!Info.noteFailure()62
)
13173
0
      return false;
13174
248
    if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || 
!LHSOK186
)
13175
62
      return false;
13176
186
    if (LHSFX < RHSFX)
13177
51
      return Success(CmpResult::Less, E);
13178
135
    if (LHSFX > RHSFX)
13179
48
      return Success(CmpResult::Greater, E);
13180
87
    return Success(CmpResult::Equal, E);
13181
135
  }
13182
13183
106k
  if (LHSTy->isAnyComplexType() || 
RHSTy->isAnyComplexType()106k
) {
13184
380
    ComplexValue LHS, RHS;
13185
380
    bool LHSOK;
13186
380
    if (E->isAssignmentOp()) {
13187
0
      LValue LV;
13188
0
      EvaluateLValue(E->getLHS(), LV, Info);
13189
0
      LHSOK = false;
13190
380
    } else if (LHSTy->isRealFloatingType()) {
13191
58
      LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13192
58
      if (LHSOK) {
13193
4
        LHS.makeComplexFloat();
13194
4
        LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13195
4
      }
13196
322
    } else {
13197
322
      LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13198
322
    }
13199
380
    if (!LHSOK && 
!Info.noteFailure()290
)
13200
194
      return false;
13201
13202
186
    if (E->getRHS()->getType()->isRealFloatingType()) {
13203
20
      if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || 
!LHSOK2
)
13204
18
        return false;
13205
2
      RHS.makeComplexFloat();
13206
2
      RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13207
166
    } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || 
!LHSOK114
)
13208
78
      return false;
13209
13210
90
    if (LHS.isComplexFloat()) {
13211
69
      APFloat::cmpResult CR_r =
13212
69
        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13213
69
      APFloat::cmpResult CR_i =
13214
69
        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13215
69
      bool IsEqual = CR_r == APFloat::cmpEqual && 
CR_i == APFloat::cmpEqual56
;
13216
69
      return Success(IsEqual ? 
CmpResult::Equal48
:
CmpResult::Unequal21
, E);
13217
69
    } else {
13218
21
      assert(IsEquality && "invalid complex comparison");
13219
21
      bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13220
21
                     
LHS.getComplexIntImag() == RHS.getComplexIntImag()18
;
13221
21
      return Success(IsEqual ? 
CmpResult::Equal18
:
CmpResult::Unequal3
, E);
13222
21
    }
13223
90
  }
13224
13225
106k
  if (LHSTy->isRealFloatingType() &&
13226
106k
      
RHSTy->isRealFloatingType()43.3k
) {
13227
43.3k
    APFloat RHS(0.0), LHS(0.0);
13228
13229
43.3k
    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13230
43.3k
    if (!LHSOK && 
!Info.noteFailure()20.4k
)
13231
11.1k
      return false;
13232
13233
32.2k
    if (!EvaluateFloat(E->getLHS(), LHS, Info) || 
!LHSOK4.17k
)
13234
28.2k
      return false;
13235
13236
4.05k
    assert(E->isComparisonOp() && "Invalid binary operator!");
13237
4.05k
    llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13238
4.05k
    if (!Info.InConstantContext &&
13239
4.05k
        
APFloatCmpResult == APFloat::cmpUnordered76
&&
13240
4.05k
        
E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()4
) {
13241
      // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13242
0
      Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13243
0
      return false;
13244
0
    }
13245
4.05k
    auto GetCmpRes = [&]() {
13246
4.05k
      switch (APFloatCmpResult) {
13247
510
      case APFloat::cmpEqual:
13248
510
        return CmpResult::Equal;
13249
40
      case APFloat::cmpLessThan:
13250
40
        return CmpResult::Less;
13251
3.48k
      case APFloat::cmpGreaterThan:
13252
3.48k
        return CmpResult::Greater;
13253
18
      case APFloat::cmpUnordered:
13254
18
        return CmpResult::Unordered;
13255
4.05k
      }
13256
0
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13257
0
    };
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1&&)::'lambda'()::operator()() const
Line
Count
Source
13245
10
    auto GetCmpRes = [&]() {
13246
10
      switch (APFloatCmpResult) {
13247
4
      case APFloat::cmpEqual:
13248
4
        return CmpResult::Equal;
13249
3
      case APFloat::cmpLessThan:
13250
3
        return CmpResult::Less;
13251
3
      case APFloat::cmpGreaterThan:
13252
3
        return CmpResult::Greater;
13253
0
      case APFloat::cmpUnordered:
13254
0
        return CmpResult::Unordered;
13255
10
      }
13256
0
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13257
0
    };
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1&&)::'lambda'()::operator()() const
Line
Count
Source
13245
4.04k
    auto GetCmpRes = [&]() {
13246
4.04k
      switch (APFloatCmpResult) {
13247
506
      case APFloat::cmpEqual:
13248
506
        return CmpResult::Equal;
13249
37
      case APFloat::cmpLessThan:
13250
37
        return CmpResult::Less;
13251
3.48k
      case APFloat::cmpGreaterThan:
13252
3.48k
        return CmpResult::Greater;
13253
18
      case APFloat::cmpUnordered:
13254
18
        return CmpResult::Unordered;
13255
4.04k
      }
13256
0
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13257
0
    };
13258
4.05k
    return Success(GetCmpRes(), E);
13259
4.05k
  }
13260
13261
63.0k
  if (LHSTy->isPointerType() && 
RHSTy->isPointerType()60.8k
) {
13262
60.8k
    LValue LHSValue, RHSValue;
13263
13264
60.8k
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13265
60.8k
    if (!LHSOK && 
!Info.noteFailure()51.6k
)
13266
11.1k
      return false;
13267
13268
49.7k
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || 
!LHSOK16.8k
)
13269
41.2k
      return false;
13270
13271
    // Reject differing bases from the normal codepath; we special-case
13272
    // comparisons to null.
13273
8.49k
    if (!HasSameBase(LHSValue, RHSValue)) {
13274
965
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13275
437
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13276
437
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13277
437
        Info.FFDiag(E, DiagID)
13278
437
            << (Reversed ? 
RHS33
:
LHS404
) << (Reversed ?
LHS33
:
RHS404
);
13279
437
        return false;
13280
437
      };
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1&&)::'lambda'(unsigned int, bool)::operator()(unsigned int, bool) const
Line
Count
Source
13274
3
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13275
3
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13276
3
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13277
3
        Info.FFDiag(E, DiagID)
13278
3
            << (Reversed ? 
RHS0
: LHS) << (Reversed ?
LHS0
: RHS);
13279
3
        return false;
13280
3
      };
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1&&)::'lambda'(unsigned int, bool)::operator()(unsigned int, bool) const
Line
Count
Source
13274
434
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13275
434
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13276
434
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13277
434
        Info.FFDiag(E, DiagID)
13278
434
            << (Reversed ? 
RHS33
:
LHS401
) << (Reversed ?
LHS33
:
RHS401
);
13279
434
        return false;
13280
434
      };
13281
      // Inequalities and subtractions between unrelated pointers have
13282
      // unspecified or undefined behavior.
13283
965
      if (!IsEquality)
13284
239
        return DiagComparison(
13285
239
            diag::note_constexpr_pointer_comparison_unspecified);
13286
      // A constant address may compare equal to the address of a symbol.
13287
      // The one exception is that address of an object cannot compare equal
13288
      // to a null pointer constant.
13289
      // TODO: Should we restrict this to actual null pointers, and exclude the
13290
      // case of zero cast to pointer type?
13291
726
      if ((!LHSValue.Base && 
!LHSValue.Offset.isZero()74
) ||
13292
726
          (!RHSValue.Base && 
!RHSValue.Offset.isZero()388
))
13293
6
        return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13294
6
                              !RHSValue.Base);
13295
      // It's implementation-defined whether distinct literals will have
13296
      // distinct addresses. In clang, the result of such a comparison is
13297
      // unspecified, so it is not a constant expression. However, we do know
13298
      // that the address of a literal will be non-null.
13299
720
      if ((IsLiteralLValue(LHSValue) || 
IsLiteralLValue(RHSValue)626
) &&
13300
720
          
LHSValue.Base114
&&
RHSValue.Base94
)
13301
35
        return DiagComparison(diag::note_constexpr_literal_comparison);
13302
      // We can't tell whether weak symbols will end up pointing to the same
13303
      // object.
13304
685
      if (IsWeakLValue(LHSValue) || 
IsWeakLValue(RHSValue)593
)
13305
117
        return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13306
117
                              !IsWeakLValue(LHSValue));
13307
      // We can't compare the address of the start of one object with the
13308
      // past-the-end address of another object, per C++ DR1652.
13309
568
      if (LHSValue.Base && 
LHSValue.Offset.isZero()495
&&
13310
568
          
isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)448
)
13311
2
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13312
2
                              true);
13313
566
      if (RHSValue.Base && 
RHSValue.Offset.isZero()274
&&
13314
566
           
isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)271
)
13315
18
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13316
18
                              false);
13317
      // We can't tell whether an object is at the same address as another
13318
      // zero sized object.
13319
548
      if ((RHSValue.Base && 
isZeroSized(LHSValue)256
) ||
13320
548
          
(529
LHSValue.Base529
&&
isZeroSized(RHSValue)456
))
13321
20
        return DiagComparison(
13322
20
            diag::note_constexpr_pointer_comparison_zero_sized);
13323
528
      return Success(CmpResult::Unequal, E);
13324
548
    }
13325
13326
7.53k
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13327
7.53k
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13328
13329
7.53k
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13330
7.53k
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13331
13332
    // C++11 [expr.rel]p3:
13333
    //   Pointers to void (after pointer conversions) can be compared, with a
13334
    //   result defined as follows: If both pointers represent the same
13335
    //   address or are both the null pointer value, the result is true if the
13336
    //   operator is <= or >= and false otherwise; otherwise the result is
13337
    //   unspecified.
13338
    // We interpret this as applying to pointers to *cv* void.
13339
7.53k
    if (LHSTy->isVoidPointerType() && 
LHSOffset != RHSOffset256
&&
IsRelational37
)
13340
8
      Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13341
13342
    // C++11 [expr.rel]p2:
13343
    // - If two pointers point to non-static data members of the same object,
13344
    //   or to subobjects or array elements fo such members, recursively, the
13345
    //   pointer to the later declared member compares greater provided the
13346
    //   two members have the same access control and provided their class is
13347
    //   not a union.
13348
    //   [...]
13349
    // - Otherwise pointer comparisons are unspecified.
13350
7.53k
    if (!LHSDesignator.Invalid && 
!RHSDesignator.Invalid7.39k
&&
IsRelational7.33k
) {
13351
240
      bool WasArrayIndex;
13352
240
      unsigned Mismatch = FindDesignatorMismatch(
13353
240
          getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13354
      // At the point where the designators diverge, the comparison has a
13355
      // specified value if:
13356
      //  - we are comparing array indices
13357
      //  - we are comparing fields of a union, or fields with the same access
13358
      // Otherwise, the result is unspecified and thus the comparison is not a
13359
      // constant expression.
13360
240
      if (!WasArrayIndex && 
Mismatch < LHSDesignator.Entries.size()106
&&
13361
240
          
Mismatch < RHSDesignator.Entries.size()48
) {
13362
48
        const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13363
48
        const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13364
48
        if (!LF && 
!RF4
)
13365
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13366
46
        else if (!LF)
13367
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13368
2
              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13369
2
              << RF->getParent() << RF;
13370
44
        else if (!RF)
13371
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13372
2
              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13373
2
              << LF->getParent() << LF;
13374
42
        else if (!LF->getParent()->isUnion() &&
13375
42
                 LF->getAccess() != RF->getAccess())
13376
4
          Info.CCEDiag(E,
13377
4
                       diag::note_constexpr_pointer_comparison_differing_access)
13378
4
              << LF << LF->getAccess() << RF << RF->getAccess()
13379
4
              << LF->getParent();
13380
48
      }
13381
240
    }
13382
13383
    // The comparison here must be unsigned, and performed with the same
13384
    // width as the pointer.
13385
7.53k
    unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13386
7.53k
    uint64_t CompareLHS = LHSOffset.getQuantity();
13387
7.53k
    uint64_t CompareRHS = RHSOffset.getQuantity();
13388
7.53k
    assert(PtrSize <= 64 && "Unexpected pointer width");
13389
7.53k
    uint64_t Mask = ~0ULL >> (64 - PtrSize);
13390
7.53k
    CompareLHS &= Mask;
13391
7.53k
    CompareRHS &= Mask;
13392
13393
    // If there is a base and this is a relational operator, we can only
13394
    // compare pointers within the object in question; otherwise, the result
13395
    // depends on where the object is located in memory.
13396
7.53k
    if (!LHSValue.Base.isNull() && 
IsRelational6.79k
) {
13397
240
      QualType BaseTy = getType(LHSValue.Base);
13398
240
      if (BaseTy->isIncompleteType())
13399
2
        return Error(E);
13400
238
      CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13401
238
      uint64_t OffsetLimit = Size.getQuantity();
13402
238
      if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13403
2
        return Error(E);
13404
238
    }
13405
13406
7.52k
    if (CompareLHS < CompareRHS)
13407
5.66k
      return Success(CmpResult::Less, E);
13408
1.86k
    if (CompareLHS > CompareRHS)
13409
56
      return Success(CmpResult::Greater, E);
13410
1.80k
    return Success(CmpResult::Equal, E);
13411
1.86k
  }
13412
13413
2.20k
  if (LHSTy->isMemberPointerType()) {
13414
222
    assert(IsEquality && "unexpected member pointer operation");
13415
222
    assert(RHSTy->isMemberPointerType() && "invalid comparison");
13416
13417
222
    MemberPtr LHSValue, RHSValue;
13418
13419
222
    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13420
222
    if (!LHSOK && 
!Info.noteFailure()126
)
13421
64
      return false;
13422
13423
158
    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || 
!LHSOK102
)
13424
74
      return false;
13425
13426
    // If either operand is a pointer to a weak function, the comparison is not
13427
    // constant.
13428
84
    if (LHSValue.getDecl() && 
LHSValue.getDecl()->isWeak()74
) {
13429
8
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13430
8
          << LHSValue.getDecl();
13431
8
      return false;
13432
8
    }
13433
76
    if (RHSValue.getDecl() && 
RHSValue.getDecl()->isWeak()57
) {
13434
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13435
0
          << RHSValue.getDecl();
13436
0
      return false;
13437
0
    }
13438
13439
    // C++11 [expr.eq]p2:
13440
    //   If both operands are null, they compare equal. Otherwise if only one is
13441
    //   null, they compare unequal.
13442
76
    if (!LHSValue.getDecl() || 
!RHSValue.getDecl()66
) {
13443
19
      bool Equal = !LHSValue.getDecl() && 
!RHSValue.getDecl()10
;
13444
19
      return Success(Equal ? 
CmpResult::Equal10
:
CmpResult::Unequal9
, E);
13445
19
    }
13446
13447
    //   Otherwise if either is a pointer to a virtual member function, the
13448
    //   result is unspecified.
13449
57
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13450
18
      if (MD->isVirtual())
13451
3
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13452
57
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13453
18
      if (MD->isVirtual())
13454
6
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13455
13456
    //   Otherwise they compare equal if and only if they would refer to the
13457
    //   same member of the same most derived object or the same subobject if
13458
    //   they were dereferenced with a hypothetical object of the associated
13459
    //   class type.
13460
57
    bool Equal = LHSValue == RHSValue;
13461
57
    return Success(Equal ? 
CmpResult::Equal42
:
CmpResult::Unequal15
, E);
13462
76
  }
13463
13464
1.97k
  if (LHSTy->isNullPtrType()) {
13465
70
    assert(E->isComparisonOp() && "unexpected nullptr operation");
13466
70
    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13467
    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13468
    // are compared, the result is true of the operator is <=, >= or ==, and
13469
    // false otherwise.
13470
70
    LValue Res;
13471
70
    if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13472
70
        
!EvaluatePointer(E->getRHS(), Res, Info)56
)
13473
16
      return false;
13474
54
    return Success(CmpResult::Equal, E);
13475
70
  }
13476
13477
1.90k
  return DoAfter();
13478
1.97k
}
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_1&&)
Line
Count
Source
13135
802
                                 SuccessCB &&Success, AfterCB &&DoAfter) {
13136
802
  assert(!E->isValueDependent());
13137
802
  assert(E->isComparisonOp() && "expected comparison operator");
13138
802
  assert((E->getOpcode() == BO_Cmp ||
13139
802
          E->getType()->isIntegralOrEnumerationType()) &&
13140
802
         "unsupported binary expression evaluation");
13141
802
  auto Error = [&](const Expr *E) {
13142
802
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13143
802
    return false;
13144
802
  };
13145
13146
802
  bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13147
802
  bool IsEquality = E->isEqualityOp();
13148
13149
802
  QualType LHSTy = E->getLHS()->getType();
13150
802
  QualType RHSTy = E->getRHS()->getType();
13151
13152
802
  if (LHSTy->isIntegralOrEnumerationType() &&
13153
802
      
RHSTy->isIntegralOrEnumerationType()740
) {
13154
740
    APSInt LHS, RHS;
13155
740
    bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13156
740
    if (!LHSOK && 
!Info.noteFailure()492
)
13157
216
      return false;
13158
524
    if (!EvaluateInteger(E->getRHS(), RHS, Info) || 
!LHSOK253
)
13159
361
      return false;
13160
163
    if (LHS < RHS)
13161
22
      return Success(CmpResult::Less, E);
13162
141
    if (LHS > RHS)
13163
36
      return Success(CmpResult::Greater, E);
13164
105
    return Success(CmpResult::Equal, E);
13165
141
  }
13166
13167
62
  if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13168
0
    APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13169
0
    APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13170
13171
0
    bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13172
0
    if (!LHSOK && !Info.noteFailure())
13173
0
      return false;
13174
0
    if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13175
0
      return false;
13176
0
    if (LHSFX < RHSFX)
13177
0
      return Success(CmpResult::Less, E);
13178
0
    if (LHSFX > RHSFX)
13179
0
      return Success(CmpResult::Greater, E);
13180
0
    return Success(CmpResult::Equal, E);
13181
0
  }
13182
13183
62
  if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13184
0
    ComplexValue LHS, RHS;
13185
0
    bool LHSOK;
13186
0
    if (E->isAssignmentOp()) {
13187
0
      LValue LV;
13188
0
      EvaluateLValue(E->getLHS(), LV, Info);
13189
0
      LHSOK = false;
13190
0
    } else if (LHSTy->isRealFloatingType()) {
13191
0
      LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13192
0
      if (LHSOK) {
13193
0
        LHS.makeComplexFloat();
13194
0
        LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13195
0
      }
13196
0
    } else {
13197
0
      LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13198
0
    }
13199
0
    if (!LHSOK && !Info.noteFailure())
13200
0
      return false;
13201
13202
0
    if (E->getRHS()->getType()->isRealFloatingType()) {
13203
0
      if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13204
0
        return false;
13205
0
      RHS.makeComplexFloat();
13206
0
      RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13207
0
    } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13208
0
      return false;
13209
13210
0
    if (LHS.isComplexFloat()) {
13211
0
      APFloat::cmpResult CR_r =
13212
0
        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13213
0
      APFloat::cmpResult CR_i =
13214
0
        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13215
0
      bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13216
0
      return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13217
0
    } else {
13218
0
      assert(IsEquality && "invalid complex comparison");
13219
0
      bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13220
0
                     LHS.getComplexIntImag() == RHS.getComplexIntImag();
13221
0
      return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13222
0
    }
13223
0
  }
13224
13225
62
  if (LHSTy->isRealFloatingType() &&
13226
62
      
RHSTy->isRealFloatingType()30
) {
13227
30
    APFloat RHS(0.0), LHS(0.0);
13228
13229
30
    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13230
30
    if (!LHSOK && 
!Info.noteFailure()20
)
13231
2
      return false;
13232
13233
28
    if (!EvaluateFloat(E->getLHS(), LHS, Info) || 
!LHSOK12
)
13234
18
      return false;
13235
13236
10
    assert(E->isComparisonOp() && "Invalid binary operator!");
13237
10
    llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13238
10
    if (!Info.InConstantContext &&
13239
10
        
APFloatCmpResult == APFloat::cmpUnordered4
&&
13240
10
        
E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()0
) {
13241
      // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13242
0
      Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13243
0
      return false;
13244
0
    }
13245
10
    auto GetCmpRes = [&]() {
13246
10
      switch (APFloatCmpResult) {
13247
10
      case APFloat::cmpEqual:
13248
10
        return CmpResult::Equal;
13249
10
      case APFloat::cmpLessThan:
13250
10
        return CmpResult::Less;
13251
10
      case APFloat::cmpGreaterThan:
13252
10
        return CmpResult::Greater;
13253
10
      case APFloat::cmpUnordered:
13254
10
        return CmpResult::Unordered;
13255
10
      }
13256
10
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13257
10
    };
13258
10
    return Success(GetCmpRes(), E);
13259
10
  }
13260
13261
32
  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13262
32
    LValue LHSValue, RHSValue;
13263
13264
32
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13265
32
    if (!LHSOK && 
!Info.noteFailure()24
)
13266
1
      return false;
13267
13268
31
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || 
!LHSOK8
)
13269
23
      return false;
13270
13271
    // Reject differing bases from the normal codepath; we special-case
13272
    // comparisons to null.
13273
8
    if (!HasSameBase(LHSValue, RHSValue)) {
13274
3
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13275
3
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13276
3
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13277
3
        Info.FFDiag(E, DiagID)
13278
3
            << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13279
3
        return false;
13280
3
      };
13281
      // Inequalities and subtractions between unrelated pointers have
13282
      // unspecified or undefined behavior.
13283
3
      if (!IsEquality)
13284
3
        return DiagComparison(
13285
3
            diag::note_constexpr_pointer_comparison_unspecified);
13286
      // A constant address may compare equal to the address of a symbol.
13287
      // The one exception is that address of an object cannot compare equal
13288
      // to a null pointer constant.
13289
      // TODO: Should we restrict this to actual null pointers, and exclude the
13290
      // case of zero cast to pointer type?
13291
0
      if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13292
0
          (!RHSValue.Base && !RHSValue.Offset.isZero()))
13293
0
        return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13294
0
                              !RHSValue.Base);
13295
      // It's implementation-defined whether distinct literals will have
13296
      // distinct addresses. In clang, the result of such a comparison is
13297
      // unspecified, so it is not a constant expression. However, we do know
13298
      // that the address of a literal will be non-null.
13299
0
      if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13300
0
          LHSValue.Base && RHSValue.Base)
13301
0
        return DiagComparison(diag::note_constexpr_literal_comparison);
13302
      // We can't tell whether weak symbols will end up pointing to the same
13303
      // object.
13304
0
      if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13305
0
        return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13306
0
                              !IsWeakLValue(LHSValue));
13307
      // We can't compare the address of the start of one object with the
13308
      // past-the-end address of another object, per C++ DR1652.
13309
0
      if (LHSValue.Base && LHSValue.Offset.isZero() &&
13310
0
          isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13311
0
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13312
0
                              true);
13313
0
      if (RHSValue.Base && RHSValue.Offset.isZero() &&
13314
0
           isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13315
0
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13316
0
                              false);
13317
      // We can't tell whether an object is at the same address as another
13318
      // zero sized object.
13319
0
      if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13320
0
          (LHSValue.Base && isZeroSized(RHSValue)))
13321
0
        return DiagComparison(
13322
0
            diag::note_constexpr_pointer_comparison_zero_sized);
13323
0
      return Success(CmpResult::Unequal, E);
13324
0
    }
13325
13326
5
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13327
5
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13328
13329
5
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13330
5
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13331
13332
    // C++11 [expr.rel]p3:
13333
    //   Pointers to void (after pointer conversions) can be compared, with a
13334
    //   result defined as follows: If both pointers represent the same
13335
    //   address or are both the null pointer value, the result is true if the
13336
    //   operator is <= or >= and false otherwise; otherwise the result is
13337
    //   unspecified.
13338
    // We interpret this as applying to pointers to *cv* void.
13339
5
    if (LHSTy->isVoidPointerType() && 
LHSOffset != RHSOffset0
&&
IsRelational0
)
13340
0
      Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13341
13342
    // C++11 [expr.rel]p2:
13343
    // - If two pointers point to non-static data members of the same object,
13344
    //   or to subobjects or array elements fo such members, recursively, the
13345
    //   pointer to the later declared member compares greater provided the
13346
    //   two members have the same access control and provided their class is
13347
    //   not a union.
13348
    //   [...]
13349
    // - Otherwise pointer comparisons are unspecified.
13350
5
    if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13351
5
      bool WasArrayIndex;
13352
5
      unsigned Mismatch = FindDesignatorMismatch(
13353
5
          getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13354
      // At the point where the designators diverge, the comparison has a
13355
      // specified value if:
13356
      //  - we are comparing array indices
13357
      //  - we are comparing fields of a union, or fields with the same access
13358
      // Otherwise, the result is unspecified and thus the comparison is not a
13359
      // constant expression.
13360
5
      if (!WasArrayIndex && 
Mismatch < LHSDesignator.Entries.size()3
&&
13361
5
          
Mismatch < RHSDesignator.Entries.size()0
) {
13362
0
        const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13363
0
        const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13364
0
        if (!LF && !RF)
13365
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13366
0
        else if (!LF)
13367
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13368
0
              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13369
0
              << RF->getParent() << RF;
13370
0
        else if (!RF)
13371
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13372
0
              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13373
0
              << LF->getParent() << LF;
13374
0
        else if (!LF->getParent()->isUnion() &&
13375
0
                 LF->getAccess() != RF->getAccess())
13376
0
          Info.CCEDiag(E,
13377
0
                       diag::note_constexpr_pointer_comparison_differing_access)
13378
0
              << LF << LF->getAccess() << RF << RF->getAccess()
13379
0
              << LF->getParent();
13380
0
      }
13381
5
    }
13382
13383
    // The comparison here must be unsigned, and performed with the same
13384
    // width as the pointer.
13385
5
    unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13386
5
    uint64_t CompareLHS = LHSOffset.getQuantity();
13387
5
    uint64_t CompareRHS = RHSOffset.getQuantity();
13388
5
    assert(PtrSize <= 64 && "Unexpected pointer width");
13389
5
    uint64_t Mask = ~0ULL >> (64 - PtrSize);
13390
5
    CompareLHS &= Mask;
13391
5
    CompareRHS &= Mask;
13392
13393
    // If there is a base and this is a relational operator, we can only
13394
    // compare pointers within the object in question; otherwise, the result
13395
    // depends on where the object is located in memory.
13396
5
    if (!LHSValue.Base.isNull() && IsRelational) {
13397
5
      QualType BaseTy = getType(LHSValue.Base);
13398
5
      if (BaseTy->isIncompleteType())
13399
0
        return Error(E);
13400
5
      CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13401
5
      uint64_t OffsetLimit = Size.getQuantity();
13402
5
      if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13403
0
        return Error(E);
13404
5
    }
13405
13406
5
    if (CompareLHS < CompareRHS)
13407
1
      return Success(CmpResult::Less, E);
13408
4
    if (CompareLHS > CompareRHS)
13409
1
      return Success(CmpResult::Greater, E);
13410
3
    return Success(CmpResult::Equal, E);
13411
4
  }
13412
13413
0
  if (LHSTy->isMemberPointerType()) {
13414
0
    assert(IsEquality && "unexpected member pointer operation");
13415
0
    assert(RHSTy->isMemberPointerType() && "invalid comparison");
13416
13417
0
    MemberPtr LHSValue, RHSValue;
13418
13419
0
    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13420
0
    if (!LHSOK && !Info.noteFailure())
13421
0
      return false;
13422
13423
0
    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13424
0
      return false;
13425
13426
    // If either operand is a pointer to a weak function, the comparison is not
13427
    // constant.
13428
0
    if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13429
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13430
0
          << LHSValue.getDecl();
13431
0
      return false;
13432
0
    }
13433
0
    if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13434
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13435
0
          << RHSValue.getDecl();
13436
0
      return false;
13437
0
    }
13438
13439
    // C++11 [expr.eq]p2:
13440
    //   If both operands are null, they compare equal. Otherwise if only one is
13441
    //   null, they compare unequal.
13442
0
    if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13443
0
      bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13444
0
      return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13445
0
    }
13446
13447
    //   Otherwise if either is a pointer to a virtual member function, the
13448
    //   result is unspecified.
13449
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13450
0
      if (MD->isVirtual())
13451
0
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13452
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13453
0
      if (MD->isVirtual())
13454
0
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13455
13456
    //   Otherwise they compare equal if and only if they would refer to the
13457
    //   same member of the same most derived object or the same subobject if
13458
    //   they were dereferenced with a hypothetical object of the associated
13459
    //   class type.
13460
0
    bool Equal = LHSValue == RHSValue;
13461
0
    return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13462
0
  }
13463
13464
0
  if (LHSTy->isNullPtrType()) {
13465
0
    assert(E->isComparisonOp() && "unexpected nullptr operation");
13466
0
    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13467
    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13468
    // are compared, the result is true of the operator is <=, >= or ==, and
13469
    // false otherwise.
13470
0
    LValue Res;
13471
0
    if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13472
0
        !EvaluatePointer(E->getRHS(), Res, Info))
13473
0
      return false;
13474
0
    return Success(CmpResult::Equal, E);
13475
0
  }
13476
13477
0
  return DoAfter();
13478
0
}
ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_0&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_1&&)
Line
Count
Source
13135
107k
                                 SuccessCB &&Success, AfterCB &&DoAfter) {
13136
107k
  assert(!E->isValueDependent());
13137
107k
  assert(E->isComparisonOp() && "expected comparison operator");
13138
107k
  assert((E->getOpcode() == BO_Cmp ||
13139
107k
          E->getType()->isIntegralOrEnumerationType()) &&
13140
107k
         "unsupported binary expression evaluation");
13141
107k
  auto Error = [&](const Expr *E) {
13142
107k
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13143
107k
    return false;
13144
107k
  };
13145
13146
107k
  bool IsRelational = E->isRelationalOp() || 
E->getOpcode() == BO_Cmp74.4k
;
13147
107k
  bool IsEquality = E->isEqualityOp();
13148
13149
107k
  QualType LHSTy = E->getLHS()->getType();
13150
107k
  QualType RHSTy = E->getRHS()->getType();
13151
13152
107k
  if (LHSTy->isIntegralOrEnumerationType() &&
13153
107k
      
RHSTy->isIntegralOrEnumerationType()0
) {
13154
0
    APSInt LHS, RHS;
13155
0
    bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13156
0
    if (!LHSOK && !Info.noteFailure())
13157
0
      return false;
13158
0
    if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13159
0
      return false;
13160
0
    if (LHS < RHS)
13161
0
      return Success(CmpResult::Less, E);
13162
0
    if (LHS > RHS)
13163
0
      return Success(CmpResult::Greater, E);
13164
0
    return Success(CmpResult::Equal, E);
13165
0
  }
13166
13167
107k
  if (LHSTy->isFixedPointType() || 
RHSTy->isFixedPointType()106k
) {
13168
248
    APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13169
248
    APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13170
13171
248
    bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13172
248
    if (!LHSOK && 
!Info.noteFailure()62
)
13173
0
      return false;
13174
248
    if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || 
!LHSOK186
)
13175
62
      return false;
13176
186
    if (LHSFX < RHSFX)
13177
51
      return Success(CmpResult::Less, E);
13178
135
    if (LHSFX > RHSFX)
13179
48
      return Success(CmpResult::Greater, E);
13180
87
    return Success(CmpResult::Equal, E);
13181
135
  }
13182
13183
106k
  if (LHSTy->isAnyComplexType() || 
RHSTy->isAnyComplexType()106k
) {
13184
380
    ComplexValue LHS, RHS;
13185
380
    bool LHSOK;
13186
380
    if (E->isAssignmentOp()) {
13187
0
      LValue LV;
13188
0
      EvaluateLValue(E->getLHS(), LV, Info);
13189
0
      LHSOK = false;
13190
380
    } else if (LHSTy->isRealFloatingType()) {
13191
58
      LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13192
58
      if (LHSOK) {
13193
4
        LHS.makeComplexFloat();
13194
4
        LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13195
4
      }
13196
322
    } else {
13197
322
      LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13198
322
    }
13199
380
    if (!LHSOK && 
!Info.noteFailure()290
)
13200
194
      return false;
13201
13202
186
    if (E->getRHS()->getType()->isRealFloatingType()) {
13203
20
      if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || 
!LHSOK2
)
13204
18
        return false;
13205
2
      RHS.makeComplexFloat();
13206
2
      RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13207
166
    } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || 
!LHSOK114
)
13208
78
      return false;
13209
13210
90
    if (LHS.isComplexFloat()) {
13211
69
      APFloat::cmpResult CR_r =
13212
69
        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13213
69
      APFloat::cmpResult CR_i =
13214
69
        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13215
69
      bool IsEqual = CR_r == APFloat::cmpEqual && 
CR_i == APFloat::cmpEqual56
;
13216
69
      return Success(IsEqual ? 
CmpResult::Equal48
:
CmpResult::Unequal21
, E);
13217
69
    } else {
13218
21
      assert(IsEquality && "invalid complex comparison");
13219
21
      bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13220
21
                     
LHS.getComplexIntImag() == RHS.getComplexIntImag()18
;
13221
21
      return Success(IsEqual ? 
CmpResult::Equal18
:
CmpResult::Unequal3
, E);
13222
21
    }
13223
90
  }
13224
13225
106k
  if (LHSTy->isRealFloatingType() &&
13226
106k
      
RHSTy->isRealFloatingType()43.3k
) {
13227
43.3k
    APFloat RHS(0.0), LHS(0.0);
13228
13229
43.3k
    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13230
43.3k
    if (!LHSOK && 
!Info.noteFailure()20.4k
)
13231
11.1k
      return false;
13232
13233
32.2k
    if (!EvaluateFloat(E->getLHS(), LHS, Info) || 
!LHSOK4.16k
)
13234
28.1k
      return false;
13235
13236
4.04k
    assert(E->isComparisonOp() && "Invalid binary operator!");
13237
4.04k
    llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13238
4.04k
    if (!Info.InConstantContext &&
13239
4.04k
        
APFloatCmpResult == APFloat::cmpUnordered72
&&
13240
4.04k
        
E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()4
) {
13241
      // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13242
0
      Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13243
0
      return false;
13244
0
    }
13245
4.04k
    auto GetCmpRes = [&]() {
13246
4.04k
      switch (APFloatCmpResult) {
13247
4.04k
      case APFloat::cmpEqual:
13248
4.04k
        return CmpResult::Equal;
13249
4.04k
      case APFloat::cmpLessThan:
13250
4.04k
        return CmpResult::Less;
13251
4.04k
      case APFloat::cmpGreaterThan:
13252
4.04k
        return CmpResult::Greater;
13253
4.04k
      case APFloat::cmpUnordered:
13254
4.04k
        return CmpResult::Unordered;
13255
4.04k
      }
13256
4.04k
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13257
4.04k
    };
13258
4.04k
    return Success(GetCmpRes(), E);
13259
4.04k
  }
13260
13261
63.0k
  if (LHSTy->isPointerType() && 
RHSTy->isPointerType()60.8k
) {
13262
60.8k
    LValue LHSValue, RHSValue;
13263
13264
60.8k
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13265
60.8k
    if (!LHSOK && 
!Info.noteFailure()51.6k
)
13266
11.1k
      return false;
13267
13268
49.7k
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || 
!LHSOK16.8k
)
13269
41.2k
      return false;
13270
13271
    // Reject differing bases from the normal codepath; we special-case
13272
    // comparisons to null.
13273
8.49k
    if (!HasSameBase(LHSValue, RHSValue)) {
13274
962
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13275
962
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13276
962
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13277
962
        Info.FFDiag(E, DiagID)
13278
962
            << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13279
962
        return false;
13280
962
      };
13281
      // Inequalities and subtractions between unrelated pointers have
13282
      // unspecified or undefined behavior.
13283
962
      if (!IsEquality)
13284
236
        return DiagComparison(
13285
236
            diag::note_constexpr_pointer_comparison_unspecified);
13286
      // A constant address may compare equal to the address of a symbol.
13287
      // The one exception is that address of an object cannot compare equal
13288
      // to a null pointer constant.
13289
      // TODO: Should we restrict this to actual null pointers, and exclude the
13290
      // case of zero cast to pointer type?
13291
726
      if ((!LHSValue.Base && 
!LHSValue.Offset.isZero()74
) ||
13292
726
          (!RHSValue.Base && 
!RHSValue.Offset.isZero()388
))
13293
6
        return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13294
6
                              !RHSValue.Base);
13295
      // It's implementation-defined whether distinct literals will have
13296
      // distinct addresses. In clang, the result of such a comparison is
13297
      // unspecified, so it is not a constant expression. However, we do know
13298
      // that the address of a literal will be non-null.
13299
720
      if ((IsLiteralLValue(LHSValue) || 
IsLiteralLValue(RHSValue)626
) &&
13300
720
          
LHSValue.Base114
&&
RHSValue.Base94
)
13301
35
        return DiagComparison(diag::note_constexpr_literal_comparison);
13302
      // We can't tell whether weak symbols will end up pointing to the same
13303
      // object.
13304
685
      if (IsWeakLValue(LHSValue) || 
IsWeakLValue(RHSValue)593
)
13305
117
        return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13306
117
                              !IsWeakLValue(LHSValue));
13307
      // We can't compare the address of the start of one object with the
13308
      // past-the-end address of another object, per C++ DR1652.
13309
568
      if (LHSValue.Base && 
LHSValue.Offset.isZero()495
&&
13310
568
          
isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)448
)
13311
2
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13312
2
                              true);
13313
566
      if (RHSValue.Base && 
RHSValue.Offset.isZero()274
&&
13314
566
           
isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)271
)
13315
18
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13316
18
                              false);
13317
      // We can't tell whether an object is at the same address as another
13318
      // zero sized object.
13319
548
      if ((RHSValue.Base && 
isZeroSized(LHSValue)256
) ||
13320
548
          
(529
LHSValue.Base529
&&
isZeroSized(RHSValue)456
))
13321
20
        return DiagComparison(
13322
20
            diag::note_constexpr_pointer_comparison_zero_sized);
13323
528
      return Success(CmpResult::Unequal, E);
13324
548
    }
13325
13326
7.52k
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13327
7.52k
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13328
13329
7.52k
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13330
7.52k
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13331
13332
    // C++11 [expr.rel]p3:
13333
    //   Pointers to void (after pointer conversions) can be compared, with a
13334
    //   result defined as follows: If both pointers represent the same
13335
    //   address or are both the null pointer value, the result is true if the
13336
    //   operator is <= or >= and false otherwise; otherwise the result is
13337
    //   unspecified.
13338
    // We interpret this as applying to pointers to *cv* void.
13339
7.52k
    if (LHSTy->isVoidPointerType() && 
LHSOffset != RHSOffset256
&&
IsRelational37
)
13340
8
      Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13341
13342
    // C++11 [expr.rel]p2:
13343
    // - If two pointers point to non-static data members of the same object,
13344
    //   or to subobjects or array elements fo such members, recursively, the
13345
    //   pointer to the later declared member compares greater provided the
13346
    //   two members have the same access control and provided their class is
13347
    //   not a union.
13348
    //   [...]
13349
    // - Otherwise pointer comparisons are unspecified.
13350
7.52k
    if (!LHSDesignator.Invalid && 
!RHSDesignator.Invalid7.38k
&&
IsRelational7.32k
) {
13351
235
      bool WasArrayIndex;
13352
235
      unsigned Mismatch = FindDesignatorMismatch(
13353
235
          getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13354
      // At the point where the designators diverge, the comparison has a
13355
      // specified value if:
13356
      //  - we are comparing array indices
13357
      //  - we are comparing fields of a union, or fields with the same access
13358
      // Otherwise, the result is unspecified and thus the comparison is not a
13359
      // constant expression.
13360
235
      if (!WasArrayIndex && 
Mismatch < LHSDesignator.Entries.size()103
&&
13361
235
          
Mismatch < RHSDesignator.Entries.size()48
) {
13362
48
        const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13363
48
        const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13364
48
        if (!LF && 
!RF4
)
13365
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13366
46
        else if (!LF)
13367
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13368
2
              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13369
2
              << RF->getParent() << RF;
13370
44
        else if (!RF)
13371
2
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13372
2
              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13373
2
              << LF->getParent() << LF;
13374
42
        else if (!LF->getParent()->isUnion() &&
13375
42
                 LF->getAccess() != RF->getAccess())
13376
4
          Info.CCEDiag(E,
13377
4
                       diag::note_constexpr_pointer_comparison_differing_access)
13378
4
              << LF << LF->getAccess() << RF << RF->getAccess()
13379
4
              << LF->getParent();
13380
48
      }
13381
235
    }
13382
13383
    // The comparison here must be unsigned, and performed with the same
13384
    // width as the pointer.
13385
7.52k
    unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13386
7.52k
    uint64_t CompareLHS = LHSOffset.getQuantity();
13387
7.52k
    uint64_t CompareRHS = RHSOffset.getQuantity();
13388
7.52k
    assert(PtrSize <= 64 && "Unexpected pointer width");
13389
7.52k
    uint64_t Mask = ~0ULL >> (64 - PtrSize);
13390
7.52k
    CompareLHS &= Mask;
13391
7.52k
    CompareRHS &= Mask;
13392
13393
    // If there is a base and this is a relational operator, we can only
13394
    // compare pointers within the object in question; otherwise, the result
13395
    // depends on where the object is located in memory.
13396
7.52k
    if (!LHSValue.Base.isNull() && 
IsRelational6.78k
) {
13397
235
      QualType BaseTy = getType(LHSValue.Base);
13398
235
      if (BaseTy->isIncompleteType())
13399
2
        return Error(E);
13400
233
      CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13401
233
      uint64_t OffsetLimit = Size.getQuantity();
13402
233
      if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13403
2
        return Error(E);
13404
233
    }
13405
13406
7.52k
    if (CompareLHS < CompareRHS)
13407
5.66k
      return Success(CmpResult::Less, E);
13408
1.85k
    if (CompareLHS > CompareRHS)
13409
55
      return Success(CmpResult::Greater, E);
13410
1.80k
    return Success(CmpResult::Equal, E);
13411
1.85k
  }
13412
13413
2.20k
  if (LHSTy->isMemberPointerType()) {
13414
222
    assert(IsEquality && "unexpected member pointer operation");
13415
222
    assert(RHSTy->isMemberPointerType() && "invalid comparison");
13416
13417
222
    MemberPtr LHSValue, RHSValue;
13418
13419
222
    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13420
222
    if (!LHSOK && 
!Info.noteFailure()126
)
13421
64
      return false;
13422
13423
158
    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || 
!LHSOK102
)
13424
74
      return false;
13425
13426
    // If either operand is a pointer to a weak function, the comparison is not
13427
    // constant.
13428
84
    if (LHSValue.getDecl() && 
LHSValue.getDecl()->isWeak()74
) {
13429
8
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13430
8
          << LHSValue.getDecl();
13431
8
      return false;
13432
8
    }
13433
76
    if (RHSValue.getDecl() && 
RHSValue.getDecl()->isWeak()57
) {
13434
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13435
0
          << RHSValue.getDecl();
13436
0
      return false;
13437
0
    }
13438
13439
    // C++11 [expr.eq]p2:
13440
    //   If both operands are null, they compare equal. Otherwise if only one is
13441
    //   null, they compare unequal.
13442
76
    if (!LHSValue.getDecl() || 
!RHSValue.getDecl()66
) {
13443
19
      bool Equal = !LHSValue.getDecl() && 
!RHSValue.getDecl()10
;
13444
19
      return Success(Equal ? 
CmpResult::Equal10
:
CmpResult::Unequal9
, E);
13445
19
    }
13446
13447
    //   Otherwise if either is a pointer to a virtual member function, the
13448
    //   result is unspecified.
13449
57
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13450
18
      if (MD->isVirtual())
13451
3
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13452
57
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13453
18
      if (MD->isVirtual())
13454
6
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13455
13456
    //   Otherwise they compare equal if and only if they would refer to the
13457
    //   same member of the same most derived object or the same subobject if
13458
    //   they were dereferenced with a hypothetical object of the associated
13459
    //   class type.
13460
57
    bool Equal = LHSValue == RHSValue;
13461
57
    return Success(Equal ? 
CmpResult::Equal42
:
CmpResult::Unequal15
, E);
13462
76
  }
13463
13464
1.97k
  if (LHSTy->isNullPtrType()) {
13465
70
    assert(E->isComparisonOp() && "unexpected nullptr operation");
13466
70
    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13467
    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13468
    // are compared, the result is true of the operator is <=, >= or ==, and
13469
    // false otherwise.
13470
70
    LValue Res;
13471
70
    if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13472
70
        
!EvaluatePointer(E->getRHS(), Res, Info)56
)
13473
16
      return false;
13474
54
    return Success(CmpResult::Equal, E);
13475
70
  }
13476
13477
1.90k
  return DoAfter();
13478
1.97k
}
13479
13480
802
bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13481
802
  if (!CheckLiteralType(Info, E))
13482
0
    return false;
13483
13484
802
  auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13485
178
    ComparisonCategoryResult CCR;
13486
178
    switch (CR) {
13487
0
    case CmpResult::Unequal:
13488
0
      llvm_unreachable("should never produce Unequal for three-way comparison");
13489
26
    case CmpResult::Less:
13490
26
      CCR = ComparisonCategoryResult::Less;
13491
26
      break;
13492
112
    case CmpResult::Equal:
13493
112
      CCR = ComparisonCategoryResult::Equal;
13494
112
      break;
13495
40
    case CmpResult::Greater:
13496
40
      CCR = ComparisonCategoryResult::Greater;
13497
40
      break;
13498
0
    case CmpResult::Unordered:
13499
0
      CCR = ComparisonCategoryResult::Unordered;
13500
0
      break;
13501
178
    }
13502
    // Evaluation succeeded. Lookup the information for the comparison category
13503
    // type and fetch the VarDecl for the result.
13504
178
    const ComparisonCategoryInfo &CmpInfo =
13505
178
        Info.Ctx.CompCategories.getInfoForType(E->getType());
13506
178
    const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13507
    // Check and evaluate the result as a constant expression.
13508
178
    LValue LV;
13509
178
    LV.set(VD);
13510
178
    if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13511
0
      return false;
13512
178
    return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13513
178
                                   ConstantExprKind::Normal);
13514
178
  };
13515
802
  return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13516
0
    return ExprEvaluatorBaseTy::VisitBinCmp(E);
13517
0
  });
13518
802
}
13519
13520
bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13521
62
    const CXXParenListInitExpr *E) {
13522
62
  return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13523
62
}
13524
13525
4.75M
bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13526
  // We don't support assignment in C. C++ assignments don't get here because
13527
  // assignment is an lvalue in C++.
13528
4.75M
  if (E->isAssignmentOp()) {
13529
129k
    Error(E);
13530
129k
    if (!Info.noteFailure())
13531
1.10k
      return false;
13532
129k
  }
13533
13534
4.75M
  if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13535
4.60M
    return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13536
13537
148k
  assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13538
148k
          !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13539
148k
         "DataRecursiveIntBinOpEvaluator should have handled integral types");
13540
13541
148k
  if (E->isComparisonOp()) {
13542
    // Evaluate builtin binary comparisons by evaluating them as three-way
13543
    // comparisons and then translating the result.
13544
107k
    auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13545
12.5k
      assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13546
12.5k
             "should only produce Unequal for equality comparisons");
13547
12.5k
      bool IsEqual   = CR == CmpResult::Equal,
13548
12.5k
           IsLess    = CR == CmpResult::Less,
13549
12.5k
           IsGreater = CR == CmpResult::Greater;
13550
12.5k
      auto Op = E->getOpcode();
13551
12.5k
      switch (Op) {
13552
0
      default:
13553
0
        llvm_unreachable("unsupported binary operator");
13554
2.45k
      case BO_EQ:
13555
12.0k
      case BO_NE:
13556
12.0k
        return Success(IsEqual == (Op == BO_EQ), E);
13557
92
      case BO_LT:
13558
92
        return Success(IsLess, E);
13559
83
      case BO_GT:
13560
83
        return Success(IsGreater, E);
13561
63
      case BO_LE:
13562
63
        return Success(IsEqual || 
IsLess42
, E);
13563
186
      case BO_GE:
13564
186
        return Success(IsEqual || 
IsGreater166
, E);
13565
12.5k
      }
13566
12.5k
    };
13567
107k
    return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13568
1.90k
      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13569
1.90k
    });
13570
107k
  }
13571
13572
41.6k
  QualType LHSTy = E->getLHS()->getType();
13573
41.6k
  QualType RHSTy = E->getRHS()->getType();
13574
13575
41.6k
  if (LHSTy->isPointerType() && 
RHSTy->isPointerType()41.4k
&&
13576
41.6k
      
E->getOpcode() == BO_Sub41.4k
) {
13577
41.4k
    LValue LHSValue, RHSValue;
13578
13579
41.4k
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13580
41.4k
    if (!LHSOK && 
!Info.noteFailure()41.0k
)
13581
27.5k
      return false;
13582
13583
13.8k
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || 
!LHSOK2.60k
)
13584
13.5k
      return false;
13585
13586
    // Reject differing bases from the normal codepath; we special-case
13587
    // comparisons to null.
13588
321
    if (!HasSameBase(LHSValue, RHSValue)) {
13589
      // Handle &&A - &&B.
13590
27
      if (!LHSValue.Offset.isZero() || 
!RHSValue.Offset.isZero()15
)
13591
12
        return Error(E);
13592
15
      const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13593
15
      const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13594
15
      if (!LHSExpr || 
!RHSExpr11
)
13595
4
        return Error(E);
13596
11
      const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13597
11
      const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13598
11
      if (!LHSAddrExpr || !RHSAddrExpr)
13599
0
        return Error(E);
13600
      // Make sure both labels come from the same function.
13601
11
      if (LHSAddrExpr->getLabel()->getDeclContext() !=
13602
11
          RHSAddrExpr->getLabel()->getDeclContext())
13603
0
        return Error(E);
13604
11
      return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13605
11
    }
13606
294
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13607
294
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13608
13609
294
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13610
294
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13611
13612
    // C++11 [expr.add]p6:
13613
    //   Unless both pointers point to elements of the same array object, or
13614
    //   one past the last element of the array object, the behavior is
13615
    //   undefined.
13616
294
    if (!LHSDesignator.Invalid && 
!RHSDesignator.Invalid244
&&
13617
294
        !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13618
244
                                RHSDesignator))
13619
6
      Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13620
13621
294
    QualType Type = E->getLHS()->getType();
13622
294
    QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13623
13624
294
    CharUnits ElementSize;
13625
294
    if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13626
0
      return false;
13627
13628
    // As an extension, a type may have zero size (empty struct or union in
13629
    // C, array of zero length). Pointer subtraction in such cases has
13630
    // undefined behavior, so is not constant.
13631
294
    if (ElementSize.isZero()) {
13632
27
      Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13633
27
          << ElementType;
13634
27
      return false;
13635
27
    }
13636
13637
    // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13638
    // and produce incorrect results when it overflows. Such behavior
13639
    // appears to be non-conforming, but is common, so perhaps we should
13640
    // assume the standard intended for such cases to be undefined behavior
13641
    // and check for them.
13642
13643
    // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13644
    // overflow in the final conversion to ptrdiff_t.
13645
267
    APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13646
267
    APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13647
267
    APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13648
267
                    false);
13649
267
    APSInt TrueResult = (LHS - RHS) / ElemSize;
13650
267
    APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13651
13652
267
    if (Result.extend(65) != TrueResult &&
13653
267
        
!HandleOverflow(Info, E, TrueResult, E->getType())4
)
13654
4
      return false;
13655
263
    return Success(Result, E);
13656
267
  }
13657
13658
269
  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13659
41.6k
}
13660
13661
/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13662
/// a result as the expression's type.
13663
bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13664
187k
                                    const UnaryExprOrTypeTraitExpr *E) {
13665
187k
  switch(E->getKind()) {
13666
8.90k
  case UETT_PreferredAlignOf:
13667
13.7k
  case UETT_AlignOf: {
13668
13.7k
    if (E->isArgumentType())
13669
13.4k
      return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13670
13.4k
                     E);
13671
321
    else
13672
321
      return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13673
321
                     E);
13674
13.7k
  }
13675
13676
57
  case UETT_VecStep: {
13677
57
    QualType Ty = E->getTypeOfArgument();
13678
13679
57
    if (Ty->isVectorType()) {
13680
54
      unsigned n = Ty->castAs<VectorType>()->getNumElements();
13681
13682
      // The vec_step built-in functions that take a 3-component
13683
      // vector return 4. (OpenCL 1.1 spec 6.11.12)
13684
54
      if (n == 3)
13685
2
        n = 4;
13686
13687
54
      return Success(n, E);
13688
54
    } else
13689
3
      return Success(1, E);
13690
57
  }
13691
13692
173k
  case UETT_SizeOf: {
13693
173k
    QualType SrcTy = E->getTypeOfArgument();
13694
    // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13695
    //   the result is the size of the referenced type."
13696
173k
    if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13697
31
      SrcTy = Ref->getPointeeType();
13698
13699
173k
    CharUnits Sizeof;
13700
173k
    if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13701
184
      return false;
13702
173k
    return Success(Sizeof, E);
13703
173k
  }
13704
47
  case UETT_OpenMPRequiredSimdAlign:
13705
47
    assert(E->isArgumentType());
13706
47
    return Success(
13707
47
        Info.Ctx.toCharUnitsFromBits(
13708
47
                    Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13709
47
            .getQuantity(),
13710
47
        E);
13711
23
  case UETT_VectorElements: {
13712
23
    QualType Ty = E->getTypeOfArgument();
13713
    // If the vector has a fixed size, we can determine the number of elements
13714
    // at compile time.
13715
23
    if (Ty->isVectorType())
13716
8
      return Success(Ty->castAs<VectorType>()->getNumElements(), E);
13717
13718
15
    assert(Ty->isSizelessVectorType());
13719
15
    if (Info.InConstantContext)
13720
15
      Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
13721
15
          << E->getSourceRange();
13722
13723
15
    return false;
13724
15
  }
13725
187k
  }
13726
13727
0
  llvm_unreachable("unknown expr/type trait");
13728
0
}
13729
13730
4.62k
bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13731
4.62k
  CharUnits Result;
13732
4.62k
  unsigned n = OOE->getNumComponents();
13733
4.62k
  if (n == 0)
13734
0
    return Error(OOE);
13735
4.62k
  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13736
9.50k
  for (unsigned i = 0; i != n; 
++i4.88k
) {
13737
4.89k
    OffsetOfNode ON = OOE->getComponent(i);
13738
4.89k
    switch (ON.getKind()) {
13739
68
    case OffsetOfNode::Array: {
13740
68
      const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13741
68
      APSInt IdxResult;
13742
68
      if (!EvaluateInteger(Idx, IdxResult, Info))
13743
15
        return false;
13744
53
      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13745
53
      if (!AT)
13746
0
        return Error(OOE);
13747
53
      CurrentType = AT->getElementType();
13748
53
      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13749
53
      Result += IdxResult.getSExtValue() * ElementSize;
13750
53
      break;
13751
53
    }
13752
13753
4.75k
    case OffsetOfNode::Field: {
13754
4.75k
      FieldDecl *MemberDecl = ON.getField();
13755
4.75k
      const RecordType *RT = CurrentType->getAs<RecordType>();
13756
4.75k
      if (!RT)
13757
0
        return Error(OOE);
13758
4.75k
      RecordDecl *RD = RT->getDecl();
13759
4.75k
      if (RD->isInvalidDecl()) 
return false3
;
13760
4.75k
      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13761
4.75k
      unsigned i = MemberDecl->getFieldIndex();
13762
4.75k
      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13763
4.75k
      Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13764
4.75k
      CurrentType = MemberDecl->getType().getNonReferenceType();
13765
4.75k
      break;
13766
4.75k
    }
13767
13768
0
    case OffsetOfNode::Identifier:
13769
0
      llvm_unreachable("dependent __builtin_offsetof");
13770
13771
71
    case OffsetOfNode::Base: {
13772
71
      CXXBaseSpecifier *BaseSpec = ON.getBase();
13773
71
      if (BaseSpec->isVirtual())
13774
0
        return Error(OOE);
13775
13776
      // Find the layout of the class whose base we are looking into.
13777
71
      const RecordType *RT = CurrentType->getAs<RecordType>();
13778
71
      if (!RT)
13779
0
        return Error(OOE);
13780
71
      RecordDecl *RD = RT->getDecl();
13781
71
      if (RD->isInvalidDecl()) 
return false0
;
13782
71
      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13783
13784
      // Find the base class itself.
13785
71
      CurrentType = BaseSpec->getType();
13786
71
      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13787
71
      if (!BaseRT)
13788
0
        return Error(OOE);
13789
13790
      // Add the offset to the base.
13791
71
      Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13792
71
      break;
13793
71
    }
13794
4.89k
    }
13795
4.89k
  }
13796
4.60k
  return Success(Result, OOE);
13797
4.62k
}
13798
13799
1.39M
bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13800
1.39M
  switch (E->getOpcode()) {
13801
13.0k
  default:
13802
    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13803
    // See C99 6.6p3.
13804
13.0k
    return Error(E);
13805
0
  case UO_Extension:
13806
    // FIXME: Should extension allow i-c-e extension expressions in its scope?
13807
    // If so, we could clear the diagnostic ID.
13808
0
    return Visit(E->getSubExpr());
13809
0
  case UO_Plus:
13810
    // The result is just the value.
13811
0
    return Visit(E->getSubExpr());
13812
1.03M
  case UO_Minus: {
13813
1.03M
    if (!Visit(E->getSubExpr()))
13814
4.63k
      return false;
13815
1.03M
    if (!Result.isInt()) 
return Error(E)0
;
13816
1.03M
    const APSInt &Value = Result.getInt();
13817
1.03M
    if (Value.isSigned() && 
Value.isMinSignedValue()1.02M
&&
E->canOverflow()10
) {
13818
10
      if (Info.checkingForUndefinedBehavior())
13819
3
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13820
3
                                         diag::warn_integer_constant_overflow)
13821
3
            << toString(Value, 10) << E->getType() << E->getSourceRange();
13822
13823
10
      if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13824
10
                          E->getType()))
13825
5
        return false;
13826
10
    }
13827
1.03M
    return Success(-Value, E);
13828
1.03M
  }
13829
22.3k
  case UO_Not: {
13830
22.3k
    if (!Visit(E->getSubExpr()))
13831
5.28k
      return false;
13832
17.0k
    if (!Result.isInt()) 
return Error(E)0
;
13833
17.0k
    return Success(~Result.getInt(), E);
13834
17.0k
  }
13835
324k
  case UO_LNot: {
13836
324k
    bool bres;
13837
324k
    if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13838
49.3k
      return false;
13839
275k
    return Success(!bres, E);
13840
324k
  }
13841
1.39M
  }
13842
1.39M
}
13843
13844
/// HandleCast - This is used to evaluate implicit or explicit casts where the
13845
/// result type is integer.
13846
10.3M
bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13847
10.3M
  const Expr *SubExpr = E->getSubExpr();
13848
10.3M
  QualType DestType = E->getType();
13849
10.3M
  QualType SrcType = SubExpr->getType();
13850
13851
10.3M
  switch (E->getCastKind()) {
13852
0
  case CK_BaseToDerived:
13853
0
  case CK_DerivedToBase:
13854
0
  case CK_UncheckedDerivedToBase:
13855
0
  case CK_Dynamic:
13856
0
  case CK_ToUnion:
13857
0
  case CK_ArrayToPointerDecay:
13858
0
  case CK_FunctionToPointerDecay:
13859
0
  case CK_NullToPointer:
13860
0
  case CK_NullToMemberPointer:
13861
0
  case CK_BaseToDerivedMemberPointer:
13862
0
  case CK_DerivedToBaseMemberPointer:
13863
0
  case CK_ReinterpretMemberPointer:
13864
0
  case CK_ConstructorConversion:
13865
0
  case CK_IntegralToPointer:
13866
0
  case CK_ToVoid:
13867
0
  case CK_VectorSplat:
13868
0
  case CK_IntegralToFloating:
13869
0
  case CK_FloatingCast:
13870
0
  case CK_CPointerToObjCPointerCast:
13871
0
  case CK_BlockPointerToObjCPointerCast:
13872
0
  case CK_AnyPointerToBlockPointerCast:
13873
0
  case CK_ObjCObjectLValueCast:
13874
0
  case CK_FloatingRealToComplex:
13875
0
  case CK_FloatingComplexToReal:
13876
0
  case CK_FloatingComplexCast:
13877
0
  case CK_FloatingComplexToIntegralComplex:
13878
0
  case CK_IntegralRealToComplex:
13879
0
  case CK_IntegralComplexCast:
13880
0
  case CK_IntegralComplexToFloatingComplex:
13881
0
  case CK_BuiltinFnToFnPtr:
13882
0
  case CK_ZeroToOCLOpaqueType:
13883
0
  case CK_NonAtomicToAtomic:
13884
0
  case CK_AddressSpaceConversion:
13885
0
  case CK_IntToOCLSampler:
13886
0
  case CK_FloatingToFixedPoint:
13887
0
  case CK_FixedPointToFloating:
13888
0
  case CK_FixedPointCast:
13889
0
  case CK_IntegralToFixedPoint:
13890
0
  case CK_MatrixCast:
13891
0
    llvm_unreachable("invalid cast kind for integral value");
13892
13893
2.37k
  case CK_BitCast:
13894
2.37k
  case CK_Dependent:
13895
2.37k
  case CK_LValueBitCast:
13896
2.37k
  case CK_ARCProduceObject:
13897
2.37k
  case CK_ARCConsumeObject:
13898
2.37k
  case CK_ARCReclaimReturnedObject:
13899
2.37k
  case CK_ARCExtendBlockObject:
13900
2.37k
  case CK_CopyAndAutoreleaseBlockObject:
13901
2.37k
    return Error(E);
13902
13903
3.61k
  case CK_UserDefinedConversion:
13904
7.38M
  case CK_LValueToRValue:
13905
7.38M
  case CK_AtomicToNonAtomic:
13906
7.72M
  case CK_NoOp:
13907
7.72M
  case CK_LValueToRValueBitCast:
13908
7.72M
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
13909
13910
239
  case CK_MemberPointerToBoolean:
13911
37.2k
  case CK_PointerToBoolean:
13912
228k
  case CK_IntegralToBoolean:
13913
234k
  case CK_FloatingToBoolean:
13914
234k
  case CK_BooleanToSignedIntegral:
13915
234k
  case CK_FloatingComplexToBoolean:
13916
234k
  case CK_IntegralComplexToBoolean: {
13917
234k
    bool BoolResult;
13918
234k
    if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13919
213k
      return false;
13920
21.1k
    uint64_t IntResult = BoolResult;
13921
21.1k
    if (BoolResult && 
E->getCastKind() == CK_BooleanToSignedIntegral13.4k
)
13922
5
      IntResult = (uint64_t)-1;
13923
21.1k
    return Success(IntResult, E);
13924
234k
  }
13925
13926
44
  case CK_FixedPointToIntegral: {
13927
44
    APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13928
44
    if (!EvaluateFixedPoint(SubExpr, Src, Info))
13929
4
      return false;
13930
40
    bool Overflowed;
13931
40
    llvm::APSInt Result = Src.convertToInt(
13932
40
        Info.Ctx.getIntWidth(DestType),
13933
40
        DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13934
40
    if (Overflowed && 
!HandleOverflow(Info, E, Result, DestType)7
)
13935
0
      return false;
13936
40
    return Success(Result, E);
13937
40
  }
13938
13939
28
  case CK_FixedPointToBoolean: {
13940
    // Unsigned padding does not affect this.
13941
28
    APValue Val;
13942
28
    if (!Evaluate(Val, Info, SubExpr))
13943
4
      return false;
13944
24
    return Success(Val.getFixedPoint().getBoolValue(), E);
13945
28
  }
13946
13947
2.38M
  case CK_IntegralCast: {
13948
2.38M
    if (!Visit(SubExpr))
13949
785k
      return false;
13950
13951
1.59M
    if (!Result.isInt()) {
13952
      // Allow casts of address-of-label differences if they are no-ops
13953
      // or narrowing.  (The narrowing case isn't actually guaranteed to
13954
      // be constant-evaluatable except in some narrow cases which are hard
13955
      // to detect here.  We let it through on the assumption the user knows
13956
      // what they are doing.)
13957
17
      if (Result.isAddrLabelDiff())
13958
10
        return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13959
      // Only allow casts of lvalues if they are lossless.
13960
7
      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13961
17
    }
13962
13963
1.59M
    if (Info.Ctx.getLangOpts().CPlusPlus && 
Info.InConstantContext1.46M
&&
13964
1.59M
        
Info.EvalMode == EvalInfo::EM_ConstantExpression689k
&&
13965
1.59M
        
DestType->isEnumeralType()470k
) {
13966
13967
1.92k
      bool ConstexprVar = true;
13968
13969
      // We know if we are here that we are in a context that we might require
13970
      // a constant expression or a context that requires a constant
13971
      // value. But if we are initializing a value we don't know if it is a
13972
      // constexpr variable or not. We can check the EvaluatingDecl to determine
13973
      // if it constexpr or not. If not then we don't want to emit a diagnostic.
13974
1.92k
      if (const auto *VD = dyn_cast_or_null<VarDecl>(
13975
1.92k
              Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13976
193
        ConstexprVar = VD->isConstexpr();
13977
13978
1.92k
      const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13979
1.92k
      const EnumDecl *ED = ET->getDecl();
13980
      // Check that the value is within the range of the enumeration values.
13981
      //
13982
      // This corressponds to [expr.static.cast]p10 which says:
13983
      // A value of integral or enumeration type can be explicitly converted
13984
      // to a complete enumeration type ... If the enumeration type does not
13985
      // have a fixed underlying type, the value is unchanged if the original
13986
      // value is within the range of the enumeration values ([dcl.enum]), and
13987
      // otherwise, the behavior is undefined.
13988
      //
13989
      // This was resolved as part of DR2338 which has CD5 status.
13990
1.92k
      if (!ED->isFixed()) {
13991
208
        llvm::APInt Min;
13992
208
        llvm::APInt Max;
13993
13994
208
        ED->getValueRange(Max, Min);
13995
208
        --Max;
13996
13997
208
        if (ED->getNumNegativeBits() && 
ConstexprVar27
&&
13998
208
            
(27
Max.slt(Result.getInt().getSExtValue())27
||
13999
27
             
Min.sgt(Result.getInt().getSExtValue())18
))
14000
9
          Info.Ctx.getDiagnostics().Report(
14001
9
              E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14002
9
              << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14003
9
              << Max.getSExtValue() << ED;
14004
199
        else if (!ED->getNumNegativeBits() && 
ConstexprVar181
&&
14005
199
                 
Max.ult(Result.getInt().getZExtValue())147
)
14006
23
          Info.Ctx.getDiagnostics().Report(
14007
23
              E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14008
23
              << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14009
23
              << Max.getZExtValue() << ED;
14010
208
      }
14011
1.92k
    }
14012
14013
1.59M
    return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14014
1.59M
                                      Result.getInt()), E);
14015
1.59M
  }
14016
14017
7.64k
  case CK_PointerToIntegral: {
14018
7.64k
    CCEDiag(E, diag::note_constexpr_invalid_cast)
14019
7.64k
        << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14020
14021
7.64k
    LValue LV;
14022
7.64k
    if (!EvaluatePointer(SubExpr, LV, Info))
14023
3.81k
      return false;
14024
14025
3.83k
    if (LV.getLValueBase()) {
14026
      // Only allow based lvalue casts if they are lossless.
14027
      // FIXME: Allow a larger integer size than the pointer size, and allow
14028
      // narrowing back down to pointer width in subsequent integral casts.
14029
      // FIXME: Check integer type's active bits, not its type size.
14030
2.96k
      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14031
31
        return Error(E);
14032
14033
2.93k
      LV.Designator.setInvalid();
14034
2.93k
      LV.moveInto(Result);
14035
2.93k
      return true;
14036
2.96k
    }
14037
14038
868
    APSInt AsInt;
14039
868
    APValue V;
14040
868
    LV.moveInto(V);
14041
868
    if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14042
0
      llvm_unreachable("Can't cast this!");
14043
14044
868
    return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14045
3.83k
  }
14046
14047
25
  case CK_IntegralComplexToReal: {
14048
25
    ComplexValue C;
14049
25
    if (!EvaluateComplex(SubExpr, C, Info))
14050
20
      return false;
14051
5
    return Success(C.getComplexIntReal(), E);
14052
25
  }
14053
14054
13.5k
  case CK_FloatingToIntegral: {
14055
13.5k
    APFloat F(0.0);
14056
13.5k
    if (!EvaluateFloat(SubExpr, F, Info))
14057
8.03k
      return false;
14058
14059
5.46k
    APSInt Value;
14060
5.46k
    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14061
19
      return false;
14062
5.44k
    return Success(Value, E);
14063
5.46k
  }
14064
10.3M
  }
14065
14066
0
  llvm_unreachable("unknown cast resulting in integral value");
14067
0
}
14068
14069
8
bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14070
8
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14071
3
    ComplexValue LV;
14072
3
    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14073
1
      return false;
14074
2
    if (!LV.isComplexInt())
14075
0
      return Error(E);
14076
2
    return Success(LV.getComplexIntReal(), E);
14077
2
  }
14078
14079
5
  return Visit(E->getSubExpr());
14080
8
}
14081
14082
40
bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14083
40
  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14084
2
    ComplexValue LV;
14085
2
    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14086
0
      return false;
14087
2
    if (!LV.isComplexInt())
14088
0
      return Error(E);
14089
2
    return Success(LV.getComplexIntImag(), E);
14090
2
  }
14091
14092
38
  VisitIgnoredValue(E->getSubExpr());
14093
38
  return Success(0, E);
14094
40
}
14095
14096
23.0k
bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14097
23.0k
  return Success(E->getPackLength(), E);
14098
23.0k
}
14099
14100
1.91k
bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14101
1.91k
  return Success(E->getValue(), E);
14102
1.91k
}
14103
14104
bool IntExprEvaluator::VisitConceptSpecializationExpr(
14105
14.2k
       const ConceptSpecializationExpr *E) {
14106
14.2k
  return Success(E->isSatisfied(), E);
14107
14.2k
}
14108
14109
4.80k
bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14110
4.80k
  return Success(E->isSatisfied(), E);
14111
4.80k
}
14112
14113
304
bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14114
304
  switch (E->getOpcode()) {
14115
0
    default:
14116
      // Invalid unary operators
14117
0
      return Error(E);
14118
0
    case UO_Plus:
14119
      // The result is just the value.
14120
0
      return Visit(E->getSubExpr());
14121
304
    case UO_Minus: {
14122
304
      if (!Visit(E->getSubExpr())) 
return false0
;
14123
304
      if (!Result.isFixedPoint())
14124
0
        return Error(E);
14125
304
      bool Overflowed;
14126
304
      APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14127
304
      if (Overflowed && 
!HandleOverflow(Info, E, Negated, E->getType())6
)
14128
0
        return false;
14129
304
      return Success(Negated, E);
14130
304
    }
14131
0
    case UO_LNot: {
14132
0
      bool bres;
14133
0
      if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14134
0
        return false;
14135
0
      return Success(!bres, E);
14136
0
    }
14137
304
  }
14138
304
}
14139
14140
506
bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14141
506
  const Expr *SubExpr = E->getSubExpr();
14142
506
  QualType DestType = E->getType();
14143
506
  assert(DestType->isFixedPointType() &&
14144
506
         "Expected destination type to be a fixed point type");
14145
506
  auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14146
14147
506
  switch (E->getCastKind()) {
14148
303
  case CK_FixedPointCast: {
14149
303
    APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14150
303
    if (!EvaluateFixedPoint(SubExpr, Src, Info))
14151
1
      return false;
14152
302
    bool Overflowed;
14153
302
    APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14154
302
    if (Overflowed) {
14155
8
      if (Info.checkingForUndefinedBehavior())
14156
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14157
0
                                         diag::warn_fixedpoint_constant_overflow)
14158
0
          << Result.toString() << E->getType();
14159
8
      if (!HandleOverflow(Info, E, Result, E->getType()))
14160
0
        return false;
14161
8
    }
14162
302
    return Success(Result, E);
14163
302
  }
14164
60
  case CK_IntegralToFixedPoint: {
14165
60
    APSInt Src;
14166
60
    if (!EvaluateInteger(SubExpr, Src, Info))
14167
12
      return false;
14168
14169
48
    bool Overflowed;
14170
48
    APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14171
48
        Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14172
14173
48
    if (Overflowed) {
14174
10
      if (Info.checkingForUndefinedBehavior())
14175
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14176
0
                                         diag::warn_fixedpoint_constant_overflow)
14177
0
          << IntResult.toString() << E->getType();
14178
10
      if (!HandleOverflow(Info, E, IntResult, E->getType()))
14179
0
        return false;
14180
10
    }
14181
14182
48
    return Success(IntResult, E);
14183
48
  }
14184
32
  case CK_FloatingToFixedPoint: {
14185
32
    APFloat Src(0.0);
14186
32
    if (!EvaluateFloat(SubExpr, Src, Info))
14187
0
      return false;
14188
14189
32
    bool Overflowed;
14190
32
    APFixedPoint Result = APFixedPoint::getFromFloatValue(
14191
32
        Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14192
14193
32
    if (Overflowed) {
14194
0
      if (Info.checkingForUndefinedBehavior())
14195
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14196
0
                                         diag::warn_fixedpoint_constant_overflow)
14197
0
          << Result.toString() << E->getType();
14198
0
      if (!HandleOverflow(Info, E, Result, E->getType()))
14199
0
        return false;
14200
0
    }
14201
14202
32
    return Success(Result, E);
14203
32
  }
14204
2
  case CK_NoOp:
14205
111
  case CK_LValueToRValue:
14206
111
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14207
0
  default:
14208
0
    return Error(E);
14209
506
  }
14210
506
}
14211
14212
1.28k
bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14213
1.28k
  if (E->isPtrMemOp() || E->isAssignmentOp() || 
E->getOpcode() == BO_Comma740
)
14214
551
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14215
14216
737
  const Expr *LHS = E->getLHS();
14217
737
  const Expr *RHS = E->getRHS();
14218
737
  FixedPointSemantics ResultFXSema =
14219
737
      Info.Ctx.getFixedPointSemantics(E->getType());
14220
14221
737
  APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14222
737
  if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14223
12
    return false;
14224
725
  APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14225
725
  if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14226
0
    return false;
14227
14228
725
  bool OpOverflow = false, ConversionOverflow = false;
14229
725
  APFixedPoint Result(LHSFX.getSemantics());
14230
725
  switch (E->getOpcode()) {
14231
119
  case BO_Add: {
14232
119
    Result = LHSFX.add(RHSFX, &OpOverflow)
14233
119
                  .convert(ResultFXSema, &ConversionOverflow);
14234
119
    break;
14235
0
  }
14236
160
  case BO_Sub: {
14237
160
    Result = LHSFX.sub(RHSFX, &OpOverflow)
14238
160
                  .convert(ResultFXSema, &ConversionOverflow);
14239
160
    break;
14240
0
  }
14241
117
  case BO_Mul: {
14242
117
    Result = LHSFX.mul(RHSFX, &OpOverflow)
14243
117
                  .convert(ResultFXSema, &ConversionOverflow);
14244
117
    break;
14245
0
  }
14246
184
  case BO_Div: {
14247
184
    if (RHSFX.getValue() == 0) {
14248
3
      Info.FFDiag(E, diag::note_expr_divide_by_zero);
14249
3
      return false;
14250
3
    }
14251
181
    Result = LHSFX.div(RHSFX, &OpOverflow)
14252
181
                  .convert(ResultFXSema, &ConversionOverflow);
14253
181
    break;
14254
184
  }
14255
105
  case BO_Shl:
14256
145
  case BO_Shr: {
14257
145
    FixedPointSemantics LHSSema = LHSFX.getSemantics();
14258
145
    llvm::APSInt RHSVal = RHSFX.getValue();
14259
14260
145
    unsigned ShiftBW =
14261
145
        LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14262
145
    unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14263
    // Embedded-C 4.1.6.2.2:
14264
    //   The right operand must be nonnegative and less than the total number
14265
    //   of (nonpadding) bits of the fixed-point operand ...
14266
145
    if (RHSVal.isNegative())
14267
6
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14268
139
    else if (Amt != RHSVal)
14269
8
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
14270
8
          << RHSVal << E->getType() << ShiftBW;
14271
14272
145
    if (E->getOpcode() == BO_Shl)
14273
105
      Result = LHSFX.shl(Amt, &OpOverflow);
14274
40
    else
14275
40
      Result = LHSFX.shr(Amt, &OpOverflow);
14276
145
    break;
14277
105
  }
14278
0
  default:
14279
0
    return false;
14280
725
  }
14281
722
  if (OpOverflow || 
ConversionOverflow693
) {
14282
34
    if (Info.checkingForUndefinedBehavior())
14283
15
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14284
15
                                       diag::warn_fixedpoint_constant_overflow)
14285
15
        << Result.toString() << E->getType();
14286
34
    if (!HandleOverflow(Info, E, Result, E->getType()))
14287
0
      return false;
14288
34
  }
14289
722
  return Success(Result, E);
14290
722
}
14291
14292
//===----------------------------------------------------------------------===//
14293
// Float Evaluation
14294
//===----------------------------------------------------------------------===//
14295
14296
namespace {
14297
class FloatExprEvaluator
14298
  : public ExprEvaluatorBase<FloatExprEvaluator> {
14299
  APFloat &Result;
14300
public:
14301
  FloatExprEvaluator(EvalInfo &info, APFloat &result)
14302
386k
    : ExprEvaluatorBaseTy(info), Result(result) {}
14303
14304
10.1k
  bool Success(const APValue &V, const Expr *e) {
14305
10.1k
    Result = V.getFloat();
14306
10.1k
    return true;
14307
10.1k
  }
14308
14309
245
  bool ZeroInitialization(const Expr *E) {
14310
245
    Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14311
245
    return true;
14312
245
  }
14313
14314
  bool VisitCallExpr(const CallExpr *E);
14315
14316
  bool VisitUnaryOperator(const UnaryOperator *E);
14317
  bool VisitBinaryOperator(const BinaryOperator *E);
14318
  bool VisitFloatingLiteral(const FloatingLiteral *E);
14319
  bool VisitCastExpr(const CastExpr *E);
14320
14321
  bool VisitUnaryReal(const UnaryOperator *E);
14322
  bool VisitUnaryImag(const UnaryOperator *E);
14323
14324
  // FIXME: Missing: array subscript of vector, member of vector
14325
};
14326
} // end anonymous namespace
14327
14328
386k
static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14329
386k
  assert(!E->isValueDependent());
14330
386k
  assert(E->isPRValue() && E->getType()->isRealFloatingType());
14331
386k
  return FloatExprEvaluator(Info, Result).Visit(E);
14332
386k
}
14333
14334
static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14335
                                  QualType ResultTy,
14336
                                  const Expr *Arg,
14337
                                  bool SNaN,
14338
3.54k
                                  llvm::APFloat &Result) {
14339
3.54k
  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14340
3.54k
  if (!S) 
return false70
;
14341
14342
3.47k
  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14343
14344
3.47k
  llvm::APInt fill;
14345
14346
  // Treat empty strings as if they were zero.
14347
3.47k
  if (S->getString().empty())
14348
3.43k
    fill = llvm::APInt(32, 0);
14349
43
  else if (S->getString().getAsInteger(0, fill))
14350
3
    return false;
14351
14352
3.47k
  if (Context.getTargetInfo().isNan2008()) {
14353
3.44k
    if (SNaN)
14354
1.66k
      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14355
1.77k
    else
14356
1.77k
      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14357
3.44k
  } else {
14358
    // Prior to IEEE 754-2008, architectures were allowed to choose whether
14359
    // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14360
    // a different encoding to what became a standard in 2008, and for pre-
14361
    // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14362
    // sNaN. This is now known as "legacy NaN" encoding.
14363
35
    if (SNaN)
14364
5
      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14365
30
    else
14366
30
      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14367
35
  }
14368
14369
3.47k
  return true;
14370
3.47k
}
14371
14372
48.5k
bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14373
48.5k
  if (!IsConstantEvaluatedBuiltinCall(E))
14374
16.3k
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
14375
14376
32.2k
  switch (E->getBuiltinCallee()) {
14377
0
  default:
14378
0
    return false;
14379
14380
571
  case Builtin::BI__builtin_huge_val:
14381
1.14k
  case Builtin::BI__builtin_huge_valf:
14382
1.68k
  case Builtin::BI__builtin_huge_vall:
14383
1.68k
  case Builtin::BI__builtin_huge_valf16:
14384
1.69k
  case Builtin::BI__builtin_huge_valf128:
14385
5.18k
  case Builtin::BI__builtin_inf:
14386
8.55k
  case Builtin::BI__builtin_inff:
14387
11.2k
  case Builtin::BI__builtin_infl:
14388
11.2k
  case Builtin::BI__builtin_inff16:
14389
11.2k
  case Builtin::BI__builtin_inff128: {
14390
11.2k
    const llvm::fltSemantics &Sem =
14391
11.2k
      Info.Ctx.getFloatTypeSemantics(E->getType());
14392
11.2k
    Result = llvm::APFloat::getInf(Sem);
14393
11.2k
    return true;
14394
11.2k
  }
14395
14396
605
  case Builtin::BI__builtin_nans:
14397
1.15k
  case Builtin::BI__builtin_nansf:
14398
1.69k
  case Builtin::BI__builtin_nansl:
14399
1.69k
  case Builtin::BI__builtin_nansf16:
14400
1.70k
  case Builtin::BI__builtin_nansf128:
14401
1.70k
    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14402
1.70k
                               true, Result))
14403
36
      return Error(E);
14404
1.66k
    return true;
14405
14406
681
  case Builtin::BI__builtin_nan:
14407
1.28k
  case Builtin::BI__builtin_nanf:
14408
1.83k
  case Builtin::BI__builtin_nanl:
14409
1.84k
  case Builtin::BI__builtin_nanf16:
14410
1.84k
  case Builtin::BI__builtin_nanf128:
14411
    // If this is __builtin_nan() turn this into a nan, otherwise we
14412
    // can't constant fold it.
14413
1.84k
    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14414
1.84k
                               false, Result))
14415
37
      return Error(E);
14416
1.80k
    return true;
14417
14418
5.18k
  case Builtin::BI__builtin_fabs:
14419
10.2k
  case Builtin::BI__builtin_fabsf:
14420
15.3k
  case Builtin::BI__builtin_fabsl:
14421
15.3k
  case Builtin::BI__builtin_fabsf128:
14422
    // The C standard says "fabs raises no floating-point exceptions,
14423
    // even if x is a signaling NaN. The returned value is independent of
14424
    // the current rounding direction mode."  Therefore constant folding can
14425
    // proceed without regard to the floating point settings.
14426
    // Reference, WG14 N2478 F.10.4.3
14427
15.3k
    if (!EvaluateFloat(E->getArg(0), Result, Info))
14428
15.3k
      return false;
14429
14430
15
    if (Result.isNegative())
14431
11
      Result.changeSign();
14432
15
    return true;
14433
14434
98
  case Builtin::BI__arithmetic_fence:
14435
98
    return EvaluateFloat(E->getArg(0), Result, Info);
14436
14437
  // FIXME: Builtin::BI__builtin_powi
14438
  // FIXME: Builtin::BI__builtin_powif
14439
  // FIXME: Builtin::BI__builtin_powil
14440
14441
540
  case Builtin::BI__builtin_copysign:
14442
1.04k
  case Builtin::BI__builtin_copysignf:
14443
1.54k
  case Builtin::BI__builtin_copysignl:
14444
1.55k
  case Builtin::BI__builtin_copysignf128: {
14445
1.55k
    APFloat RHS(0.);
14446
1.55k
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14447
1.55k
        
!EvaluateFloat(E->getArg(1), RHS, Info)36
)
14448
1.51k
      return false;
14449
36
    Result.copySign(RHS);
14450
36
    return true;
14451
1.55k
  }
14452
14453
97
  case Builtin::BI__builtin_fmax:
14454
184
  case Builtin::BI__builtin_fmaxf:
14455
263
  case Builtin::BI__builtin_fmaxl:
14456
287
  case Builtin::BI__builtin_fmaxf16:
14457
294
  case Builtin::BI__builtin_fmaxf128: {
14458
    // TODO: Handle sNaN.
14459
294
    APFloat RHS(0.);
14460
294
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14461
294
        
!EvaluateFloat(E->getArg(1), RHS, Info)96
)
14462
198
      return false;
14463
    // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14464
96
    if (Result.isZero() && 
RHS.isZero()32
&&
Result.isNegative()20
)
14465
10
      Result = RHS;
14466
86
    else if (Result.isNaN() || 
RHS > Result70
)
14467
40
      Result = RHS;
14468
96
    return true;
14469
294
  }
14470
14471
74
  case Builtin::BI__builtin_fmin:
14472
122
  case Builtin::BI__builtin_fminf:
14473
162
  case Builtin::BI__builtin_fminl:
14474
186
  case Builtin::BI__builtin_fminf16:
14475
193
  case Builtin::BI__builtin_fminf128: {
14476
    // TODO: Handle sNaN.
14477
193
    APFloat RHS(0.);
14478
193
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14479
193
        
!EvaluateFloat(E->getArg(1), RHS, Info)116
)
14480
77
      return false;
14481
    // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14482
116
    if (Result.isZero() && 
RHS.isZero()32
&&
RHS.isNegative()20
)
14483
10
      Result = RHS;
14484
106
    else if (Result.isNaN() || 
RHS < Result85
)
14485
45
      Result = RHS;
14486
116
    return true;
14487
193
  }
14488
32.2k
  }
14489
32.2k
}
14490
14491
56
bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14492
56
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14493
54
    ComplexValue CV;
14494
54
    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14495
24
      return false;
14496
30
    Result = CV.FloatReal;
14497
30
    return true;
14498
54
  }
14499
14500
2
  return Visit(E->getSubExpr());
14501
56
}
14502
14503
40
bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14504
40
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14505
24
    ComplexValue CV;
14506
24
    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14507
0
      return false;
14508
24
    Result = CV.FloatImag;
14509
24
    return true;
14510
24
  }
14511
14512
16
  VisitIgnoredValue(E->getSubExpr());
14513
16
  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14514
16
  Result = llvm::APFloat::getZero(Sem);
14515
16
  return true;
14516
40
}
14517
14518
8.17k
bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14519
8.17k
  switch (E->getOpcode()) {
14520
108
  default: return Error(E);
14521
0
  case UO_Plus:
14522
0
    return EvaluateFloat(E->getSubExpr(), Result, Info);
14523
8.07k
  case UO_Minus:
14524
    // In C standard, WG14 N2478 F.3 p4
14525
    // "the unary - raises no floating point exceptions,
14526
    // even if the operand is signalling."
14527
8.07k
    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14528
1.67k
      return false;
14529
6.39k
    Result.changeSign();
14530
6.39k
    return true;
14531
8.17k
  }
14532
8.17k
}
14533
14534
75.6k
bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14535
75.6k
  if (E->isPtrMemOp() || E->isAssignmentOp() || 
E->getOpcode() == BO_Comma41.8k
)
14536
33.8k
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14537
14538
41.8k
  APFloat RHS(0.0);
14539
41.8k
  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14540
41.8k
  if (!LHSOK && 
!Info.noteFailure()26.4k
)
14541
4.85k
    return false;
14542
36.9k
  return EvaluateFloat(E->getRHS(), RHS, Info) && 
LHSOK17.0k
&&
14543
36.9k
         
handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS)14.6k
;
14544
41.8k
}
14545
14546
70.0k
bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14547
70.0k
  Result = E->getValue();
14548
70.0k
  return true;
14549
70.0k
}
14550
14551
193k
bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14552
193k
  const Expr* SubExpr = E->getSubExpr();
14553
14554
193k
  switch (E->getCastKind()) {
14555
152k
  default:
14556
152k
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14557
14558
33.6k
  case CK_IntegralToFloating: {
14559
33.6k
    APSInt IntResult;
14560
33.6k
    const FPOptions FPO = E->getFPFeaturesInEffect(
14561
33.6k
                                  Info.Ctx.getLangOpts());
14562
33.6k
    return EvaluateInteger(SubExpr, IntResult, Info) &&
14563
33.6k
           HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14564
25.5k
                                IntResult, E->getType(), Result);
14565
0
  }
14566
14567
20
  case CK_FixedPointToFloating: {
14568
20
    APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14569
20
    if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14570
0
      return false;
14571
20
    Result =
14572
20
        FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14573
20
    return true;
14574
20
  }
14575
14576
8.00k
  case CK_FloatingCast: {
14577
8.00k
    if (!Visit(SubExpr))
14578
4.21k
      return false;
14579
3.79k
    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14580
3.79k
                                  Result);
14581
8.00k
  }
14582
14583
25
  case CK_FloatingComplexToReal: {
14584
25
    ComplexValue V;
14585
25
    if (!EvaluateComplex(SubExpr, V, Info))
14586
22
      return false;
14587
3
    Result = V.getComplexFloatReal();
14588
3
    return true;
14589
25
  }
14590
193k
  }
14591
193k
}
14592
14593
//===----------------------------------------------------------------------===//
14594
// Complex Evaluation (for float and integer)
14595
//===----------------------------------------------------------------------===//
14596
14597
namespace {
14598
class ComplexExprEvaluator
14599
  : public ExprEvaluatorBase<ComplexExprEvaluator> {
14600
  ComplexValue &Result;
14601
14602
public:
14603
  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14604
4.28k
    : ExprEvaluatorBaseTy(info), Result(Result) {}
14605
14606
39
  bool Success(const APValue &V, const Expr *e) {
14607
39
    Result.setFrom(V);
14608
39
    return true;
14609
39
  }
14610
14611
  bool ZeroInitialization(const Expr *E);
14612
14613
  //===--------------------------------------------------------------------===//
14614
  //                            Visitor Methods
14615
  //===--------------------------------------------------------------------===//
14616
14617
  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14618
  bool VisitCastExpr(const CastExpr *E);
14619
  bool VisitBinaryOperator(const BinaryOperator *E);
14620
  bool VisitUnaryOperator(const UnaryOperator *E);
14621
  bool VisitInitListExpr(const InitListExpr *E);
14622
  bool VisitCallExpr(const CallExpr *E);
14623
};
14624
} // end anonymous namespace
14625
14626
static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14627
4.28k
                            EvalInfo &Info) {
14628
4.28k
  assert(!E->isValueDependent());
14629
4.28k
  assert(E->isPRValue() && E->getType()->isAnyComplexType());
14630
4.28k
  return ComplexExprEvaluator(Info, Result).Visit(E);
14631
4.28k
}
14632
14633
13
bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14634
13
  QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14635
13
  if (ElemTy->isRealFloatingType()) {
14636
10
    Result.makeComplexFloat();
14637
10
    APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14638
10
    Result.FloatReal = Zero;
14639
10
    Result.FloatImag = Zero;
14640
10
  } else {
14641
3
    Result.makeComplexInt();
14642
3
    APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14643
3
    Result.IntReal = Zero;
14644
3
    Result.IntImag = Zero;
14645
3
  }
14646
13
  return true;
14647
13
}
14648
14649
498
bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14650
498
  const Expr* SubExpr = E->getSubExpr();
14651
14652
498
  if (SubExpr->getType()->isRealFloatingType()) {
14653
365
    Result.makeComplexFloat();
14654
365
    APFloat &Imag = Result.FloatImag;
14655
365
    if (!EvaluateFloat(SubExpr, Imag, Info))
14656
0
      return false;
14657
14658
365
    Result.FloatReal = APFloat(Imag.getSemantics());
14659
365
    return true;
14660
365
  } else {
14661
133
    assert(SubExpr->getType()->isIntegerType() &&
14662
133
           "Unexpected imaginary literal.");
14663
14664
133
    Result.makeComplexInt();
14665
133
    APSInt &Imag = Result.IntImag;
14666
133
    if (!EvaluateInteger(SubExpr, Imag, Info))
14667
0
      return false;
14668
14669
133
    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14670
133
    return true;
14671
133
  }
14672
498
}
14673
14674
2.62k
bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14675
14676
2.62k
  switch (E->getCastKind()) {
14677
0
  case CK_BitCast:
14678
0
  case CK_BaseToDerived:
14679
0
  case CK_DerivedToBase:
14680
0
  case CK_UncheckedDerivedToBase:
14681
0
  case CK_Dynamic:
14682
0
  case CK_ToUnion:
14683
0
  case CK_ArrayToPointerDecay:
14684
0
  case CK_FunctionToPointerDecay:
14685
0
  case CK_NullToPointer:
14686
0
  case CK_NullToMemberPointer:
14687
0
  case CK_BaseToDerivedMemberPointer:
14688
0
  case CK_DerivedToBaseMemberPointer:
14689
0
  case CK_MemberPointerToBoolean:
14690
0
  case CK_ReinterpretMemberPointer:
14691
0
  case CK_ConstructorConversion:
14692
0
  case CK_IntegralToPointer:
14693
0
  case CK_PointerToIntegral:
14694
0
  case CK_PointerToBoolean:
14695
0
  case CK_ToVoid:
14696
0
  case CK_VectorSplat:
14697
0
  case CK_IntegralCast:
14698
0
  case CK_BooleanToSignedIntegral:
14699
0
  case CK_IntegralToBoolean:
14700
0
  case CK_IntegralToFloating:
14701
0
  case CK_FloatingToIntegral:
14702
0
  case CK_FloatingToBoolean:
14703
0
  case CK_FloatingCast:
14704
0
  case CK_CPointerToObjCPointerCast:
14705
0
  case CK_BlockPointerToObjCPointerCast:
14706
0
  case CK_AnyPointerToBlockPointerCast:
14707
0
  case CK_ObjCObjectLValueCast:
14708
0
  case CK_FloatingComplexToReal:
14709
0
  case CK_FloatingComplexToBoolean:
14710
0
  case CK_IntegralComplexToReal:
14711
0
  case CK_IntegralComplexToBoolean:
14712
0
  case CK_ARCProduceObject:
14713
0
  case CK_ARCConsumeObject:
14714
0
  case CK_ARCReclaimReturnedObject:
14715
0
  case CK_ARCExtendBlockObject:
14716
0
  case CK_CopyAndAutoreleaseBlockObject:
14717
0
  case CK_BuiltinFnToFnPtr:
14718
0
  case CK_ZeroToOCLOpaqueType:
14719
0
  case CK_NonAtomicToAtomic:
14720
0
  case CK_AddressSpaceConversion:
14721
0
  case CK_IntToOCLSampler:
14722
0
  case CK_FloatingToFixedPoint:
14723
0
  case CK_FixedPointToFloating:
14724
0
  case CK_FixedPointCast:
14725
0
  case CK_FixedPointToBoolean:
14726
0
  case CK_FixedPointToIntegral:
14727
0
  case CK_IntegralToFixedPoint:
14728
0
  case CK_MatrixCast:
14729
0
    llvm_unreachable("invalid cast kind for complex value");
14730
14731
1.78k
  case CK_LValueToRValue:
14732
1.78k
  case CK_AtomicToNonAtomic:
14733
1.78k
  case CK_NoOp:
14734
1.78k
  case CK_LValueToRValueBitCast:
14735
1.78k
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14736
14737
0
  case CK_Dependent:
14738
0
  case CK_LValueBitCast:
14739
0
  case CK_UserDefinedConversion:
14740
0
    return Error(E);
14741
14742
418
  case CK_FloatingRealToComplex: {
14743
418
    APFloat &Real = Result.FloatReal;
14744
418
    if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14745
280
      return false;
14746
14747
138
    Result.makeComplexFloat();
14748
138
    Result.FloatImag = APFloat(Real.getSemantics());
14749
138
    return true;
14750
418
  }
14751
14752
108
  case CK_FloatingComplexCast: {
14753
108
    if (!Visit(E->getSubExpr()))
14754
55
      return false;
14755
14756
53
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14757
53
    QualType From
14758
53
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14759
14760
53
    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14761
53
           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14762
108
  }
14763
14764
0
  case CK_FloatingComplexToIntegralComplex: {
14765
0
    if (!Visit(E->getSubExpr()))
14766
0
      return false;
14767
14768
0
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14769
0
    QualType From
14770
0
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14771
0
    Result.makeComplexInt();
14772
0
    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14773
0
                                To, Result.IntReal) &&
14774
0
           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14775
0
                                To, Result.IntImag);
14776
0
  }
14777
14778
197
  case CK_IntegralRealToComplex: {
14779
197
    APSInt &Real = Result.IntReal;
14780
197
    if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14781
82
      return false;
14782
14783
115
    Result.makeComplexInt();
14784
115
    Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14785
115
    return true;
14786
197
  }
14787
14788
53
  case CK_IntegralComplexCast: {
14789
53
    if (!Visit(E->getSubExpr()))
14790
47
      return false;
14791
14792
6
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14793
6
    QualType From
14794
6
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14795
14796
6
    Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14797
6
    Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14798
6
    return true;
14799
53
  }
14800
14801
61
  case CK_IntegralComplexToFloatingComplex: {
14802
61
    if (!Visit(E->getSubExpr()))
14803
49
      return false;
14804
14805
12
    const FPOptions FPO = E->getFPFeaturesInEffect(
14806
12
                                  Info.Ctx.getLangOpts());
14807
12
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14808
12
    QualType From
14809
12
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14810
12
    Result.makeComplexFloat();
14811
12
    return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14812
12
                                To, Result.FloatReal) &&
14813
12
           HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14814
12
                                To, Result.FloatImag);
14815
61
  }
14816
2.62k
  }
14817
14818
0
  llvm_unreachable("unknown cast resulting in complex value");
14819
0
}
14820
14821
1.93k
bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14822
1.93k
  if (E->isPtrMemOp() || E->isAssignmentOp() || 
E->getOpcode() == BO_Comma1.63k
)
14823
306
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14824
14825
  // Track whether the LHS or RHS is real at the type system level. When this is
14826
  // the case we can simplify our evaluation strategy.
14827
1.63k
  bool LHSReal = false, RHSReal = false;
14828
14829
1.63k
  bool LHSOK;
14830
1.63k
  if (E->getLHS()->getType()->isRealFloatingType()) {
14831
631
    LHSReal = true;
14832
631
    APFloat &Real = Result.FloatReal;
14833
631
    LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14834
631
    if (LHSOK) {
14835
375
      Result.makeComplexFloat();
14836
375
      Result.FloatImag = APFloat(Real.getSemantics());
14837
375
    }
14838
1.00k
  } else {
14839
1.00k
    LHSOK = Visit(E->getLHS());
14840
1.00k
  }
14841
1.63k
  if (!LHSOK && 
!Info.noteFailure()1.02k
)
14842
491
    return false;
14843
14844
1.14k
  ComplexValue RHS;
14845
1.14k
  if (E->getRHS()->getType()->isRealFloatingType()) {
14846
166
    RHSReal = true;
14847
166
    APFloat &Real = RHS.FloatReal;
14848
166
    if (!EvaluateFloat(E->getRHS(), Real, Info) || 
!LHSOK33
)
14849
133
      return false;
14850
33
    RHS.makeComplexFloat();
14851
33
    RHS.FloatImag = APFloat(Real.getSemantics());
14852
974
  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || 
!LHSOK592
)
14853
404
    return false;
14854
14855
603
  assert(!(LHSReal && RHSReal) &&
14856
603
         "Cannot have both operands of a complex operation be real.");
14857
603
  switch (E->getOpcode()) {
14858
0
  default: return Error(E);
14859
355
  case BO_Add:
14860
355
    if (Result.isComplexFloat()) {
14861
274
      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14862
274
                                       APFloat::rmNearestTiesToEven);
14863
274
      if (LHSReal)
14864
243
        Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14865
31
      else if (!RHSReal)
14866
30
        Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14867
30
                                         APFloat::rmNearestTiesToEven);
14868
274
    } else {
14869
81
      Result.getComplexIntReal() += RHS.getComplexIntReal();
14870
81
      Result.getComplexIntImag() += RHS.getComplexIntImag();
14871
81
    }
14872
355
    break;
14873
73
  case BO_Sub:
14874
73
    if (Result.isComplexFloat()) {
14875
61
      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14876
61
                                            APFloat::rmNearestTiesToEven);
14877
61
      if (LHSReal) {
14878
49
        Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14879
49
        Result.getComplexFloatImag().changeSign();
14880
49
      } else 
if (12
!RHSReal12
) {
14881
1
        Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14882
1
                                              APFloat::rmNearestTiesToEven);
14883
1
      }
14884
61
    } else {
14885
12
      Result.getComplexIntReal() -= RHS.getComplexIntReal();
14886
12
      Result.getComplexIntImag() -= RHS.getComplexIntImag();
14887
12
    }
14888
73
    break;
14889
136
  case BO_Mul:
14890
136
    if (Result.isComplexFloat()) {
14891
      // This is an implementation of complex multiplication according to the
14892
      // constraints laid out in C11 Annex G. The implementation uses the
14893
      // following naming scheme:
14894
      //   (a + ib) * (c + id)
14895
124
      ComplexValue LHS = Result;
14896
124
      APFloat &A = LHS.getComplexFloatReal();
14897
124
      APFloat &B = LHS.getComplexFloatImag();
14898
124
      APFloat &C = RHS.getComplexFloatReal();
14899
124
      APFloat &D = RHS.getComplexFloatImag();
14900
124
      APFloat &ResR = Result.getComplexFloatReal();
14901
124
      APFloat &ResI = Result.getComplexFloatImag();
14902
124
      if (LHSReal) {
14903
77
        assert(!RHSReal && "Cannot have two real operands for a complex op!");
14904
77
        ResR = A * C;
14905
77
        ResI = A * D;
14906
77
      } else 
if (47
RHSReal47
) {
14907
5
        ResR = C * A;
14908
5
        ResI = C * B;
14909
42
      } else {
14910
        // In the fully general case, we need to handle NaNs and infinities
14911
        // robustly.
14912
42
        APFloat AC = A * C;
14913
42
        APFloat BD = B * D;
14914
42
        APFloat AD = A * D;
14915
42
        APFloat BC = B * C;
14916
42
        ResR = AC - BD;
14917
42
        ResI = AD + BC;
14918
42
        if (ResR.isNaN() && 
ResI.isNaN()12
) {
14919
12
          bool Recalc = false;
14920
12
          if (A.isInfinity() || B.isInfinity()) {
14921
8
            A = APFloat::copySign(
14922
8
                APFloat(A.getSemantics(), A.isInfinity() ? 
10
: 0), A);
14923
8
            B = APFloat::copySign(
14924
8
                APFloat(B.getSemantics(), B.isInfinity() ? 1 : 
00
), B);
14925
8
            if (C.isNaN())
14926
4
              C = APFloat::copySign(APFloat(C.getSemantics()), C);
14927
8
            if (D.isNaN())
14928
0
              D = APFloat::copySign(APFloat(D.getSemantics()), D);
14929
8
            Recalc = true;
14930
8
          }
14931
12
          if (C.isInfinity() || D.isInfinity()) {
14932
8
            C = APFloat::copySign(
14933
8
                APFloat(C.getSemantics(), C.isInfinity() ? 
10
: 0), C);
14934
8
            D = APFloat::copySign(
14935
8
                APFloat(D.getSemantics(), D.isInfinity() ? 1 : 
00
), D);
14936
8
            if (A.isNaN())
14937
0
              A = APFloat::copySign(APFloat(A.getSemantics()), A);
14938
8
            if (B.isNaN())
14939
0
              B = APFloat::copySign(APFloat(B.getSemantics()), B);
14940
8
            Recalc = true;
14941
8
          }
14942
12
          if (!Recalc && 
(0
AC.isInfinity()0
||
BD.isInfinity()0
||
14943
0
                          AD.isInfinity() || BC.isInfinity())) {
14944
0
            if (A.isNaN())
14945
0
              A = APFloat::copySign(APFloat(A.getSemantics()), A);
14946
0
            if (B.isNaN())
14947
0
              B = APFloat::copySign(APFloat(B.getSemantics()), B);
14948
0
            if (C.isNaN())
14949
0
              C = APFloat::copySign(APFloat(C.getSemantics()), C);
14950
0
            if (D.isNaN())
14951
0
              D = APFloat::copySign(APFloat(D.getSemantics()), D);
14952
0
            Recalc = true;
14953
0
          }
14954
12
          if (Recalc) {
14955
12
            ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14956
12
            ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14957
12
          }
14958
12
        }
14959
42
      }
14960
124
    } else {
14961
12
      ComplexValue LHS = Result;
14962
12
      Result.getComplexIntReal() =
14963
12
        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14964
12
         LHS.getComplexIntImag() * RHS.getComplexIntImag());
14965
12
      Result.getComplexIntImag() =
14966
12
        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14967
12
         LHS.getComplexIntImag() * RHS.getComplexIntReal());
14968
12
    }
14969
136
    break;
14970
136
  case BO_Div:
14971
39
    if (Result.isComplexFloat()) {
14972
      // This is an implementation of complex division according to the
14973
      // constraints laid out in C11 Annex G. The implementation uses the
14974
      // following naming scheme:
14975
      //   (a + ib) / (c + id)
14976
37
      ComplexValue LHS = Result;
14977
37
      APFloat &A = LHS.getComplexFloatReal();
14978
37
      APFloat &B = LHS.getComplexFloatImag();
14979
37
      APFloat &C = RHS.getComplexFloatReal();
14980
37
      APFloat &D = RHS.getComplexFloatImag();
14981
37
      APFloat &ResR = Result.getComplexFloatReal();
14982
37
      APFloat &ResI = Result.getComplexFloatImag();
14983
37
      if (RHSReal) {
14984
16
        ResR = A / C;
14985
16
        ResI = B / C;
14986
21
      } else {
14987
21
        if (LHSReal) {
14988
          // No real optimizations we can do here, stub out with zero.
14989
1
          B = APFloat::getZero(A.getSemantics());
14990
1
        }
14991
21
        int DenomLogB = 0;
14992
21
        APFloat MaxCD = maxnum(abs(C), abs(D));
14993
21
        if (MaxCD.isFinite()) {
14994
18
          DenomLogB = ilogb(MaxCD);
14995
18
          C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14996
18
          D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14997
18
        }
14998
21
        APFloat Denom = C * C + D * D;
14999
21
        ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
15000
21
                      APFloat::rmNearestTiesToEven);
15001
21
        ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
15002
21
                      APFloat::rmNearestTiesToEven);
15003
21
        if (ResR.isNaN() && 
ResI.isNaN()15
) {
15004
15
          if (Denom.isPosZero() && 
(8
!A.isNaN()8
||
!B.isNaN()4
)) {
15005
8
            ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15006
8
            ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15007
8
          } else 
if (7
(7
A.isInfinity()7
||
B.isInfinity()7
) &&
C.isFinite()4
&&
15008
7
                     
D.isFinite()4
) {
15009
4
            A = APFloat::copySign(
15010
4
                APFloat(A.getSemantics(), A.isInfinity() ? 
10
: 0), A);
15011
4
            B = APFloat::copySign(
15012
4
                APFloat(B.getSemantics(), B.isInfinity() ? 1 : 
00
), B);
15013
4
            ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15014
4
            ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15015
4
          } else 
if (3
MaxCD.isInfinity()3
&&
A.isFinite()3
&&
B.isFinite()3
) {
15016
3
            C = APFloat::copySign(
15017
3
                APFloat(C.getSemantics(), C.isInfinity() ? 
11
:
02
), C);
15018
3
            D = APFloat::copySign(
15019
3
                APFloat(D.getSemantics(), D.isInfinity() ? 
12
:
01
), D);
15020
3
            ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15021
3
            ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15022
3
          }
15023
15
        }
15024
21
      }
15025
37
    } else {
15026
2
      if (RHS.getComplexIntReal() == 0 && 
RHS.getComplexIntImag() == 00
)
15027
0
        return Error(E, diag::note_expr_divide_by_zero);
15028
15029
2
      ComplexValue LHS = Result;
15030
2
      APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15031
2
        RHS.getComplexIntImag() * RHS.getComplexIntImag();
15032
2
      Result.getComplexIntReal() =
15033
2
        (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15034
2
         LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15035
2
      Result.getComplexIntImag() =
15036
2
        (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15037
2
         LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15038
2
    }
15039
39
    break;
15040
603
  }
15041
15042
603
  return true;
15043
603
}
15044
15045
38
bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15046
  // Get the operand value into 'Result'.
15047
38
  if (!Visit(E->getSubExpr()))
15048
18
    return false;
15049
15050
20
  switch (E->getOpcode()) {
15051
0
  default:
15052
0
    return Error(E);
15053
0
  case UO_Extension:
15054
0
    return true;
15055
0
  case UO_Plus:
15056
    // The result is always just the subexpr.
15057
0
    return true;
15058
16
  case UO_Minus:
15059
16
    if (Result.isComplexFloat()) {
15060
8
      Result.getComplexFloatReal().changeSign();
15061
8
      Result.getComplexFloatImag().changeSign();
15062
8
    }
15063
8
    else {
15064
8
      Result.getComplexIntReal() = -Result.getComplexIntReal();
15065
8
      Result.getComplexIntImag() = -Result.getComplexIntImag();
15066
8
    }
15067
16
    return true;
15068
4
  case UO_Not:
15069
4
    if (Result.isComplexFloat())
15070
2
      Result.getComplexFloatImag().changeSign();
15071
2
    else
15072
2
      Result.getComplexIntImag() = -Result.getComplexIntImag();
15073
4
    return true;
15074
20
  }
15075
20
}
15076
15077
91
bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15078
91
  if (E->getNumInits() == 2) {
15079
79
    if (E->getType()->isComplexType()) {
15080
57
      Result.makeComplexFloat();
15081
57
      if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15082
1
        return false;
15083
56
      if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15084
0
        return false;
15085
56
    } else {
15086
22
      Result.makeComplexInt();
15087
22
      if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15088
0
        return false;
15089
22
      if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15090
0
        return false;
15091
22
    }
15092
78
    return true;
15093
79
  }
15094
12
  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15095
91
}
15096
15097
322
bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15098
322
  if (!IsConstantEvaluatedBuiltinCall(E))
15099
295
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
15100
15101
27
  switch (E->getBuiltinCallee()) {
15102
18
  case Builtin::BI__builtin_complex:
15103
18
    Result.makeComplexFloat();
15104
18
    if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15105
8
      return false;
15106
10
    if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15107
0
      return false;
15108
10
    return true;
15109
15110
9
  default:
15111
9
    return false;
15112
27
  }
15113
27
}
15114
15115
//===----------------------------------------------------------------------===//
15116
// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15117
// implicit conversion.
15118
//===----------------------------------------------------------------------===//
15119
15120
namespace {
15121
class AtomicExprEvaluator :
15122
    public ExprEvaluatorBase<AtomicExprEvaluator> {
15123
  const LValue *This;
15124
  APValue &Result;
15125
public:
15126
  AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15127
474
      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15128
15129
21
  bool Success(const APValue &V, const Expr *E) {
15130
21
    Result = V;
15131
21
    return true;
15132
21
  }
15133
15134
8
  bool ZeroInitialization(const Expr *E) {
15135
8
    ImplicitValueInitExpr VIE(
15136
8
        E->getType()->castAs<AtomicType>()->getValueType());
15137
    // For atomic-qualified class (and array) types in C++, initialize the
15138
    // _Atomic-wrapped subobject directly, in-place.
15139
8
    return This ? 
EvaluateInPlace(Result, Info, *This, &VIE)7
15140
8
                : 
Evaluate(Result, Info, &VIE)1
;
15141
8
  }
15142
15143
466
  bool VisitCastExpr(const CastExpr *E) {
15144
466
    switch (E->getCastKind()) {
15145
317
    default:
15146
317
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
15147
0
    case CK_NullToPointer:
15148
0
      VisitIgnoredValue(E->getSubExpr());
15149
0
      return ZeroInitialization(E);
15150
149
    case CK_NonAtomicToAtomic:
15151
149
      return This ? 
EvaluateInPlace(Result, Info, *This, E->getSubExpr())29
15152
149
                  : 
Evaluate(Result, Info, E->getSubExpr())120
;
15153
466
    }
15154
466
  }
15155
};
15156
} // end anonymous namespace
15157
15158
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15159
474
                           EvalInfo &Info) {
15160
474
  assert(!E->isValueDependent());
15161
474
  assert(E->isPRValue() && E->getType()->isAtomicType());
15162
474
  return AtomicExprEvaluator(Info, This, Result).Visit(E);
15163
474
}
15164
15165
//===----------------------------------------------------------------------===//
15166
// Void expression evaluation, primarily for a cast to void on the LHS of a
15167
// comma operator
15168
//===----------------------------------------------------------------------===//
15169
15170
namespace {
15171
class VoidExprEvaluator
15172
  : public ExprEvaluatorBase<VoidExprEvaluator> {
15173
public:
15174
10.3k
  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15175
15176
1.59k
  bool Success(const APValue &V, const Expr *e) { return true; }
15177
15178
90
  bool ZeroInitialization(const Expr *E) { return true; }
15179
15180
2.63k
  bool VisitCastExpr(const CastExpr *E) {
15181
2.63k
    switch (E->getCastKind()) {
15182
6
    default:
15183
6
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
15184
2.62k
    case CK_ToVoid:
15185
2.62k
      VisitIgnoredValue(E->getSubExpr());
15186
2.62k
      return true;
15187
2.63k
    }
15188
2.63k
  }
15189
15190
6.78k
  bool VisitCallExpr(const CallExpr *E) {
15191
6.78k
    if (!IsConstantEvaluatedBuiltinCall(E))
15192
6.72k
      return ExprEvaluatorBaseTy::VisitCallExpr(E);
15193
15194
59
    switch (E->getBuiltinCallee()) {
15195
3
    case Builtin::BI__assume:
15196
22
    case Builtin::BI__builtin_assume:
15197
      // The argument is not evaluated!
15198
22
      return true;
15199
15200
37
    case Builtin::BI__builtin_operator_delete:
15201
37
      return HandleOperatorDeleteCall(Info, E);
15202
15203
0
    default:
15204
0
      return false;
15205
59
    }
15206
59
  }
15207
15208
  bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15209
};
15210
} // end anonymous namespace
15211
15212
663
bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15213
  // We cannot speculatively evaluate a delete expression.
15214
663
  if (Info.SpeculativeEvaluationDepth)
15215
0
    return false;
15216
15217
663
  FunctionDecl *OperatorDelete = E->getOperatorDelete();
15218
663
  if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15219
2
    Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15220
2
        << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15221
2
    return false;
15222
2
  }
15223
15224
661
  const Expr *Arg = E->getArgument();
15225
15226
661
  LValue Pointer;
15227
661
  if (!EvaluatePointer(Arg, Pointer, Info))
15228
41
    return false;
15229
620
  if (Pointer.Designator.Invalid)
15230
0
    return false;
15231
15232
  // Deleting a null pointer has no effect.
15233
620
  if (Pointer.isNullPointer()) {
15234
    // This is the only case where we need to produce an extension warning:
15235
    // the only other way we can succeed is if we find a dynamic allocation,
15236
    // and we will have warned when we allocated it in that case.
15237
146
    if (!Info.getLangOpts().CPlusPlus20)
15238
1
      Info.CCEDiag(E, diag::note_constexpr_new);
15239
146
    return true;
15240
146
  }
15241
15242
474
  std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15243
474
      Info, E, Pointer, E->isArrayForm() ? 
DynAlloc::ArrayNew343
:
DynAlloc::New131
);
15244
474
  if (!Alloc)
15245
22
    return false;
15246
452
  QualType AllocType = Pointer.Base.getDynamicAllocType();
15247
15248
  // For the non-array case, the designator must be empty if the static type
15249
  // does not have a virtual destructor.
15250
452
  if (!E->isArrayForm() && 
Pointer.Designator.Entries.size() != 0117
&&
15251
452
      
!hasVirtualDestructor(Arg->getType()->getPointeeType())7
) {
15252
1
    Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15253
1
        << Arg->getType()->getPointeeType() << AllocType;
15254
1
    return false;
15255
1
  }
15256
15257
  // For a class type with a virtual destructor, the selected operator delete
15258
  // is the one looked up when building the destructor.
15259
451
  if (!E->isArrayForm() && 
!E->isGlobalDelete()116
) {
15260
111
    const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15261
111
    if (VirtualDelete &&
15262
111
        
!VirtualDelete->isReplaceableGlobalAllocationFunction()5
) {
15263
1
      Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15264
1
          << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15265
1
      return false;
15266
1
    }
15267
111
  }
15268
15269
450
  if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15270
450
                         (*Alloc)->Value, AllocType))
15271
2
    return false;
15272
15273
448
  if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15274
    // The element was already erased. This means the destructor call also
15275
    // deleted the object.
15276
    // FIXME: This probably results in undefined behavior before we get this
15277
    // far, and should be diagnosed elsewhere first.
15278
0
    Info.FFDiag(E, diag::note_constexpr_double_delete);
15279
0
    return false;
15280
0
  }
15281
15282
448
  return true;
15283
448
}
15284
15285
10.3k
static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15286
10.3k
  assert(!E->isValueDependent());
15287
10.3k
  assert(E->isPRValue() && E->getType()->isVoidType());
15288
10.3k
  return VoidExprEvaluator(Info).Visit(E);
15289
10.3k
}
15290
15291
//===----------------------------------------------------------------------===//
15292
// Top level Expr::EvaluateAsRValue method.
15293
//===----------------------------------------------------------------------===//
15294
15295
36.7M
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15296
36.7M
  assert(!E->isValueDependent());
15297
  // In C, function designators are not lvalues, but we evaluate them as if they
15298
  // are.
15299
36.7M
  QualType T = E->getType();
15300
36.7M
  if (E->isGLValue() || 
T->isFunctionType()33.1M
) {
15301
3.63M
    LValue LV;
15302
3.63M
    if (!EvaluateLValue(E, LV, Info))
15303
2.06M
      return false;
15304
1.57M
    LV.moveInto(Result);
15305
33.1M
  } else if (T->isVectorType()) {
15306
2.32M
    if (!EvaluateVector(E, Result, Info))
15307
2.32M
      return false;
15308
30.8M
  } else if (T->isIntegralOrEnumerationType()) {
15309
30.2M
    if (!IntExprEvaluator(Info, Result).Visit(E))
15310
7.84M
      return false;
15311
30.2M
  } else 
if (585k
T->hasPointerRepresentation()585k
) {
15312
370k
    LValue LV;
15313
370k
    if (!EvaluatePointer(E, LV, Info))
15314
236k
      return false;
15315
134k
    LV.moveInto(Result);
15316
214k
  } else if (T->isRealFloatingType()) {
15317
183k
    llvm::APFloat F(0.0);
15318
183k
    if (!EvaluateFloat(E, F, Info))
15319
117k
      return false;
15320
65.9k
    Result = APValue(F);
15321
65.9k
  } else 
if (31.5k
T->isAnyComplexType()31.5k
) {
15322
2.68k
    ComplexValue C;
15323
2.68k
    if (!EvaluateComplex(E, C, Info))
15324
2.28k
      return false;
15325
403
    C.moveInto(Result);
15326
28.8k
  } else if (T->isFixedPointType()) {
15327
1.84k
    if (!FixedPointExprEvaluator(Info, Result).Visit(E)) 
return false624
;
15328
27.0k
  } else if (T->isMemberPointerType()) {
15329
4.01k
    MemberPtr P;
15330
4.01k
    if (!EvaluateMemberPointer(E, P, Info))
15331
324
      return false;
15332
3.69k
    P.moveInto(Result);
15333
3.69k
    return true;
15334
22.9k
  } else if (T->isArrayType()) {
15335
122
    LValue LV;
15336
122
    APValue &Value =
15337
122
        Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15338
122
    if (!EvaluateArray(E, LV, Value, Info))
15339
62
      return false;
15340
60
    Result = Value;
15341
22.8k
  } else if (T->isRecordType()) {
15342
11.5k
    LValue LV;
15343
11.5k
    APValue &Value =
15344
11.5k
        Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15345
11.5k
    if (!EvaluateRecord(E, LV, Value, Info))
15346
9.29k
      return false;
15347
2.24k
    Result = Value;
15348
11.3k
  } else if (T->isVoidType()) {
15349
10.3k
    if (!Info.getLangOpts().CPlusPlus11)
15350
620
      Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15351
620
        << E->getType();
15352
10.3k
    if (!EvaluateVoid(E, Info))
15353
5.36k
      return false;
15354
10.3k
  } else 
if (1.02k
T->isAtomicType()1.02k
) {
15355
444
    QualType Unqual = T.getAtomicUnqualifiedType();
15356
444
    if (Unqual->isArrayType() || Unqual->isRecordType()) {
15357
11
      LValue LV;
15358
11
      APValue &Value = Info.CurrentCall->createTemporary(
15359
11
          E, Unqual, ScopeKind::FullExpression, LV);
15360
11
      if (!EvaluateAtomic(E, &LV, Value, Info))
15361
7
        return false;
15362
4
      Result = Value;
15363
433
    } else {
15364
433
      if (!EvaluateAtomic(E, nullptr, Result, Info))
15365
321
        return false;
15366
433
    }
15367
577
  } else if (Info.getLangOpts().CPlusPlus11) {
15368
411
    Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15369
411
    return false;
15370
411
  } else {
15371
166
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15372
166
    return false;
15373
166
  }
15374
15375
24.1M
  return true;
15376
36.7M
}
15377
15378
/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15379
/// cases, the in-place evaluation is essential, since later initializers for
15380
/// an object can indirectly refer to subobjects which were initialized earlier.
15381
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15382
3.12M
                            const Expr *E, bool AllowNonLiteralTypes) {
15383
3.12M
  assert(!E->isValueDependent());
15384
15385
3.12M
  if (!AllowNonLiteralTypes && 
!CheckLiteralType(Info, E, &This)2.58M
)
15386
21.2k
    return false;
15387
15388
3.10M
  if (E->isPRValue()) {
15389
    // Evaluate arrays and record types in-place, so that later initializers can
15390
    // refer to earlier-initialized members of the object.
15391
2.90M
    QualType T = E->getType();
15392
2.90M
    if (T->isArrayType())
15393
13.4k
      return EvaluateArray(E, This, Result, Info);
15394
2.89M
    else if (T->isRecordType())
15395
102k
      return EvaluateRecord(E, This, Result, Info);
15396
2.78M
    else if (T->isAtomicType()) {
15397
132
      QualType Unqual = T.getAtomicUnqualifiedType();
15398
132
      if (Unqual->isArrayType() || Unqual->isRecordType())
15399
30
        return EvaluateAtomic(E, &This, Result, Info);
15400
132
    }
15401
2.90M
  }
15402
15403
  // For any other type, in-place evaluation is unimportant.
15404
2.99M
  return Evaluate(Result, Info, E);
15405
3.10M
}
15406
15407
/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15408
/// lvalue-to-rvalue cast if it is an lvalue.
15409
14.7M
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15410
14.7M
  assert(!E->isValueDependent());
15411
15412
14.7M
  if (E->getType().isNull())
15413
0
    return false;
15414
15415
14.7M
  if (!CheckLiteralType(Info, E))
15416
95.7k
    return false;
15417
15418
14.6M
  if (Info.EnableNewConstInterp) {
15419
11.4k
    if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15420
2.13k
      return false;
15421
14.5M
  } else {
15422
14.5M
    if (!::Evaluate(Result, Info, E))
15423
5.76M
      return false;
15424
14.5M
  }
15425
15426
  // Implicit lvalue-to-rvalue cast.
15427
8.84M
  if (E->isGLValue()) {
15428
816k
    LValue LV;
15429
816k
    LV.setFrom(Info.Ctx, Result);
15430
816k
    if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15431
791k
      return false;
15432
816k
  }
15433
15434
  // Check this core constant expression is a constant expression.
15435
8.05M
  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15436
8.05M
                                 ConstantExprKind::Normal) &&
15437
8.05M
         
CheckMemoryLeaks(Info)8.01M
;
15438
8.84M
}
15439
15440
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15441
18.3M
                                 const ASTContext &Ctx, bool &IsConst) {
15442
  // Fast-path evaluations of integer literals, since we sometimes see files
15443
  // containing vast quantities of these.
15444
18.3M
  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15445
8.00M
    Result.Val = APValue(APSInt(L->getValue(),
15446
8.00M
                                L->getType()->isUnsignedIntegerType()));
15447
8.00M
    IsConst = true;
15448
8.00M
    return true;
15449
8.00M
  }
15450
15451
10.3M
  if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15452
349k
    Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15453
349k
    IsConst = true;
15454
349k
    return true;
15455
349k
  }
15456
15457
9.98M
  if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
15458
235k
    if (CE->hasAPValueResult()) {
15459
233k
      Result.Val = CE->getAPValueResult();
15460
233k
      IsConst = true;
15461
233k
      return true;
15462
233k
    }
15463
15464
    // The SubExpr is usually just an IntegerLiteral.
15465
1.53k
    return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15466
235k
  }
15467
15468
  // This case should be rare, but we need to check it before we check on
15469
  // the type below.
15470
9.74M
  if (Exp->getType().isNull()) {
15471
6
    IsConst = false;
15472
6
    return true;
15473
6
  }
15474
15475
9.74M
  return false;
15476
9.74M
}
15477
15478
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15479
6.89M
                                      Expr::SideEffectsKind SEK) {
15480
6.89M
  return (SEK < Expr::SE_AllowSideEffects && 
Result.HasSideEffects952k
) ||
15481
6.89M
         
(6.89M
SEK < Expr::SE_AllowUndefinedBehavior6.89M
&&
Result.HasUndefinedBehavior918k
);
15482
6.89M
}
15483
15484
static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15485
12.0M
                             const ASTContext &Ctx, EvalInfo &Info) {
15486
12.0M
  assert(!E->isValueDependent());
15487
12.0M
  bool IsConst;
15488
12.0M
  if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15489
7.97M
    return IsConst;
15490
15491
4.05M
  return EvaluateAsRValue(Info, E, Result.Val);
15492
12.0M
}
15493
15494
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15495
                          const ASTContext &Ctx,
15496
                          Expr::SideEffectsKind AllowSideEffects,
15497
5.14M
                          EvalInfo &Info) {
15498
5.14M
  assert(!E->isValueDependent());
15499
5.14M
  if (!E->getType()->isIntegralOrEnumerationType())
15500
40.1k
    return false;
15501
15502
5.10M
  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15503
5.10M
      
!ExprResult.Val.isInt()4.63M
||
15504
5.10M
      
hasUnacceptableSideEffect(ExprResult, AllowSideEffects)4.63M
)
15505
468k
    return false;
15506
15507
4.63M
  return true;
15508
5.10M
}
15509
15510
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15511
                                 const ASTContext &Ctx,
15512
                                 Expr::SideEffectsKind AllowSideEffects,
15513
119
                                 EvalInfo &Info) {
15514
119
  assert(!E->isValueDependent());
15515
119
  if (!E->getType()->isFixedPointType())
15516
0
    return false;
15517
15518
119
  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15519
52
    return false;
15520
15521
67
  if (!ExprResult.Val.isFixedPoint() ||
15522
67
      hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15523
0
    return false;
15524
15525
67
  return true;
15526
67
}
15527
15528
/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15529
/// any crazy technique (that has nothing to do with language standards) that
15530
/// we want to.  If this function returns true, it returns the folded constant
15531
/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15532
/// will be applied to the result.
15533
bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15534
6.63M
                            bool InConstantContext) const {
15535
6.63M
  assert(!isValueDependent() &&
15536
6.63M
         "Expression evaluator can't be called on a dependent expression.");
15537
6.63M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15538
6.63M
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15539
6.63M
  Info.InConstantContext = InConstantContext;
15540
6.63M
  return ::EvaluateAsRValue(this, Result, Ctx, Info);
15541
6.63M
}
15542
15543
bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15544
1.13M
                                      bool InConstantContext) const {
15545
1.13M
  assert(!isValueDependent() &&
15546
1.13M
         "Expression evaluator can't be called on a dependent expression.");
15547
1.13M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15548
1.13M
  EvalResult Scratch;
15549
1.13M
  return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15550
1.13M
         
HandleConversionToBool(Scratch.Val, Result)506k
;
15551
1.13M
}
15552
15553
bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15554
                         SideEffectsKind AllowSideEffects,
15555
1.55M
                         bool InConstantContext) const {
15556
1.55M
  assert(!isValueDependent() &&
15557
1.55M
         "Expression evaluator can't be called on a dependent expression.");
15558
1.55M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15559
1.55M
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15560
1.55M
  Info.InConstantContext = InConstantContext;
15561
1.55M
  return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15562
1.55M
}
15563
15564
bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15565
                                SideEffectsKind AllowSideEffects,
15566
119
                                bool InConstantContext) const {
15567
119
  assert(!isValueDependent() &&
15568
119
         "Expression evaluator can't be called on a dependent expression.");
15569
119
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15570
119
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15571
119
  Info.InConstantContext = InConstantContext;
15572
119
  return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15573
119
}
15574
15575
bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15576
                           SideEffectsKind AllowSideEffects,
15577
7.04k
                           bool InConstantContext) const {
15578
7.04k
  assert(!isValueDependent() &&
15579
7.04k
         "Expression evaluator can't be called on a dependent expression.");
15580
15581
7.04k
  if (!getType()->isRealFloatingType())
15582
32
    return false;
15583
15584
7.00k
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15585
7.00k
  EvalResult ExprResult;
15586
7.00k
  if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15587
7.00k
      
!ExprResult.Val.isFloat()1.42k
||
15588
7.00k
      
hasUnacceptableSideEffect(ExprResult, AllowSideEffects)1.42k
)
15589
5.58k
    return false;
15590
15591
1.42k
  Result = ExprResult.Val.getFloat();
15592
1.42k
  return true;
15593
7.00k
}
15594
15595
bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15596
2.18k
                            bool InConstantContext) const {
15597
2.18k
  assert(!isValueDependent() &&
15598
2.18k
         "Expression evaluator can't be called on a dependent expression.");
15599
15600
2.18k
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15601
2.18k
  EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15602
2.18k
  Info.InConstantContext = InConstantContext;
15603
2.18k
  LValue LV;
15604
2.18k
  CheckedTemporaries CheckedTemps;
15605
2.18k
  if (!EvaluateLValue(this, LV, Info) || 
!Info.discardCleanups()344
||
15606
2.18k
      
Result.HasSideEffects344
||
15607
2.18k
      !CheckLValueConstantExpression(Info, getExprLoc(),
15608
344
                                     Ctx.getLValueReferenceType(getType()), LV,
15609
344
                                     ConstantExprKind::Normal, CheckedTemps))
15610
1.97k
    return false;
15611
15612
204
  LV.moveInto(Result.Val);
15613
204
  return true;
15614
2.18k
}
15615
15616
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15617
                                APValue DestroyedValue, QualType Type,
15618
                                SourceLocation Loc, Expr::EvalStatus &EStatus,
15619
763
                                bool IsConstantDestruction) {
15620
763
  EvalInfo Info(Ctx, EStatus,
15621
763
                IsConstantDestruction ? 
EvalInfo::EM_ConstantExpression483
15622
763
                                      : 
EvalInfo::EM_ConstantFold280
);
15623
763
  Info.setEvaluatingDecl(Base, DestroyedValue,
15624
763
                         EvalInfo::EvaluatingDeclKind::Dtor);
15625
763
  Info.InConstantContext = IsConstantDestruction;
15626
15627
763
  LValue LVal;
15628
763
  LVal.set(Base);
15629
15630
763
  if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15631
763
      
EStatus.HasSideEffects492
)
15632
271
    return false;
15633
15634
492
  if (!Info.discardCleanups())
15635
0
    llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15636
15637
492
  return true;
15638
763
}
15639
15640
bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15641
2.43M
                                  ConstantExprKind Kind) const {
15642
2.43M
  assert(!isValueDependent() &&
15643
2.43M
         "Expression evaluator can't be called on a dependent expression.");
15644
2.43M
  bool IsConst;
15645
2.43M
  if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && 
Result.Val.hasValue()609k
)
15646
609k
    return true;
15647
15648
1.82M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15649
1.82M
  EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15650
1.82M
  EvalInfo Info(Ctx, Result, EM);
15651
1.82M
  Info.InConstantContext = true;
15652
15653
  // The type of the object we're initializing is 'const T' for a class NTTP.
15654
1.82M
  QualType T = getType();
15655
1.82M
  if (Kind == ConstantExprKind::ClassTemplateArgument)
15656
441
    T.addConst();
15657
15658
  // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15659
  // represent the result of the evaluation. CheckConstantExpression ensures
15660
  // this doesn't escape.
15661
1.82M
  MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15662
1.82M
  APValue::LValueBase Base(&BaseMTE);
15663
15664
1.82M
  Info.setEvaluatingDecl(Base, Result.Val);
15665
1.82M
  LValue LVal;
15666
1.82M
  LVal.set(Base);
15667
15668
1.82M
  {
15669
    // C++23 [intro.execution]/p5
15670
    // A full-expression is [...] a constant-expression
15671
    // So we need to make sure temporary objects are destroyed after having
15672
    // evaluating the expression (per C++23 [class.temporary]/p4).
15673
1.82M
    FullExpressionRAII Scope(Info);
15674
1.82M
    if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15675
1.82M
        
Result.HasSideEffects1.78M
||
!Scope.destroy()1.78M
)
15676
37.6k
      return false;
15677
1.82M
  }
15678
15679
1.78M
  if (!Info.discardCleanups())
15680
0
    llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15681
15682
1.78M
  if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15683
1.78M
                               Result.Val, Kind))
15684
25.8k
    return false;
15685
1.75M
  if (!CheckMemoryLeaks(Info))
15686
0
    return false;
15687
15688
  // If this is a class template argument, it's required to have constant
15689
  // destruction too.
15690
1.75M
  if (Kind == ConstantExprKind::ClassTemplateArgument &&
15691
1.75M
      
(431
!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15692
431
                            true) ||
15693
431
       
Result.HasSideEffects424
)) {
15694
    // FIXME: Prefix a note to indicate that the problem is lack of constant
15695
    // destruction.
15696
7
    return false;
15697
7
  }
15698
15699
1.75M
  return true;
15700
1.75M
}
15701
15702
bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15703
                                 const VarDecl *VD,
15704
                                 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15705
543k
                                 bool IsConstantInitialization) const {
15706
543k
  assert(!isValueDependent() &&
15707
543k
         "Expression evaluator can't be called on a dependent expression.");
15708
15709
543k
  llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15710
2
    std::string Name;
15711
2
    llvm::raw_string_ostream OS(Name);
15712
2
    VD->printQualifiedName(OS);
15713
2
    return Name;
15714
2
  });
15715
15716
543k
  Expr::EvalStatus EStatus;
15717
543k
  EStatus.Diag = &Notes;
15718
15719
543k
  EvalInfo Info(Ctx, EStatus,
15720
543k
                (IsConstantInitialization && 
Ctx.getLangOpts().CPlusPlus493k
)
15721
543k
                    ? 
EvalInfo::EM_ConstantExpression490k
15722
543k
                    : 
EvalInfo::EM_ConstantFold52.4k
);
15723
543k
  Info.setEvaluatingDecl(VD, Value);
15724
543k
  Info.InConstantContext = IsConstantInitialization;
15725
15726
543k
  if (Info.EnableNewConstInterp) {
15727
1.28k
    auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15728
1.28k
    if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15729
239
      return false;
15730
542k
  } else {
15731
542k
    LValue LVal;
15732
542k
    LVal.set(VD);
15733
15734
542k
    if (!EvaluateInPlace(Value, Info, LVal, this,
15735
542k
                         /*AllowNonLiteralTypes=*/true) ||
15736
542k
        
EStatus.HasSideEffects437k
)
15737
104k
      return false;
15738
15739
    // At this point, any lifetime-extended temporaries are completely
15740
    // initialized.
15741
437k
    Info.performLifetimeExtension();
15742
15743
437k
    if (!Info.discardCleanups())
15744
0
      llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15745
437k
  }
15746
15747
438k
  SourceLocation DeclLoc = VD->getLocation();
15748
438k
  QualType DeclTy = VD->getType();
15749
438k
  return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15750
438k
                                 ConstantExprKind::Normal) &&
15751
438k
         
CheckMemoryLeaks(Info)422k
;
15752
543k
}
15753
15754
bool VarDecl::evaluateDestruction(
15755
332
    SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15756
332
  Expr::EvalStatus EStatus;
15757
332
  EStatus.Diag = &Notes;
15758
15759
  // Only treat the destruction as constant destruction if we formally have
15760
  // constant initialization (or are usable in a constant expression).
15761
332
  bool IsConstantDestruction = hasConstantInitialization();
15762
15763
  // Make a copy of the value for the destructor to mutate, if we know it.
15764
  // Otherwise, treat the value as default-initialized; if the destructor works
15765
  // anyway, then the destruction is constant (and must be essentially empty).
15766
332
  APValue DestroyedValue;
15767
332
  if (getEvaluatedValue() && 
!getEvaluatedValue()->isAbsent()281
)
15768
156
    DestroyedValue = *getEvaluatedValue();
15769
176
  else if (!handleDefaultInitValue(getType(), DestroyedValue))
15770
0
    return false;
15771
15772
332
  if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15773
332
                           getType(), getLocation(), EStatus,
15774
332
                           IsConstantDestruction) ||
15775
332
      
EStatus.HasSideEffects68
)
15776
264
    return false;
15777
15778
68
  ensureEvaluatedStmt()->HasConstantDestruction = true;
15779
68
  return true;
15780
332
}
15781
15782
/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15783
/// constant folded, but discard the result.
15784
2.58M
bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15785
2.58M
  assert(!isValueDependent() &&
15786
2.58M
         "Expression evaluator can't be called on a dependent expression.");
15787
15788
2.58M
  EvalResult Result;
15789
2.58M
  return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15790
2.58M
         
!hasUnacceptableSideEffect(Result, SEK)2.25M
;
15791
2.58M
}
15792
15793
APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15794
294k
                    SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15795
294k
  assert(!isValueDependent() &&
15796
294k
         "Expression evaluator can't be called on a dependent expression.");
15797
15798
294k
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15799
294k
  EvalResult EVResult;
15800
294k
  EVResult.Diag = Diag;
15801
294k
  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15802
294k
  Info.InConstantContext = true;
15803
15804
294k
  bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15805
294k
  (void)Result;
15806
294k
  assert(Result && "Could not evaluate expression");
15807
294k
  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15808
15809
294k
  return EVResult.Val.getInt();
15810
294k
}
15811
15812
APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15813
3.36M
    const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15814
3.36M
  assert(!isValueDependent() &&
15815
3.36M
         "Expression evaluator can't be called on a dependent expression.");
15816
15817
3.36M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15818
3.36M
  EvalResult EVResult;
15819
3.36M
  EVResult.Diag = Diag;
15820
3.36M
  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15821
3.36M
  Info.InConstantContext = true;
15822
3.36M
  Info.CheckingForUndefinedBehavior = true;
15823
15824
3.36M
  bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15825
3.36M
  (void)Result;
15826
3.36M
  assert(Result && "Could not evaluate expression");
15827
3.36M
  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15828
15829
3.36M
  return EVResult.Val.getInt();
15830
3.36M
}
15831
15832
3.86M
void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15833
3.86M
  assert(!isValueDependent() &&
15834
3.86M
         "Expression evaluator can't be called on a dependent expression.");
15835
15836
3.86M
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15837
3.86M
  bool IsConst;
15838
3.86M
  EvalResult EVResult;
15839
3.86M
  if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15840
3.86M
    EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15841
3.86M
    Info.CheckingForUndefinedBehavior = true;
15842
3.86M
    (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15843
3.86M
  }
15844
3.86M
}
15845
15846
38
bool Expr::EvalResult::isGlobalLValue() const {
15847
38
  assert(Val.isLValue());
15848
38
  return IsGlobalLValue(Val.getLValueBase());
15849
38
}
15850
15851
/// isIntegerConstantExpr - this recursive routine will test if an expression is
15852
/// an integer constant expression.
15853
15854
/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15855
/// comma, etc
15856
15857
// CheckICE - This function does the fundamental ICE checking: the returned
15858
// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15859
// and a (possibly null) SourceLocation indicating the location of the problem.
15860
//
15861
// Note that to reduce code duplication, this helper does no evaluation
15862
// itself; the caller checks whether the expression is evaluatable, and
15863
// in the rare cases where CheckICE actually cares about the evaluated
15864
// value, it calls into Evaluate.
15865
15866
namespace {
15867
15868
enum ICEKind {
15869
  /// This expression is an ICE.
15870
  IK_ICE,
15871
  /// This expression is not an ICE, but if it isn't evaluated, it's
15872
  /// a legal subexpression for an ICE. This return value is used to handle
15873
  /// the comma operator in C99 mode, and non-constant subexpressions.
15874
  IK_ICEIfUnevaluated,
15875
  /// This expression is not an ICE, and is not a legal subexpression for one.
15876
  IK_NotICE
15877
};
15878
15879
struct ICEDiag {
15880
  ICEKind Kind;
15881
  SourceLocation Loc;
15882
15883
7.96M
  ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15884
};
15885
15886
}
15887
15888
7.79M
static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15889
15890
766k
static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? 
A766k
:
B117
; }
15891
15892
2.49k
static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15893
2.49k
  Expr::EvalResult EVResult;
15894
2.49k
  Expr::EvalStatus Status;
15895
2.49k
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15896
15897
2.49k
  Info.InConstantContext = true;
15898
2.49k
  if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || 
EVResult.HasSideEffects1.13k
||
15899
2.49k
      
!EVResult.Val.isInt()1.13k
)
15900
1.36k
    return ICEDiag(IK_NotICE, E->getBeginLoc());
15901
15902
1.13k
  return NoDiag();
15903
2.49k
}
15904
15905
10.1M
static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15906
10.1M
  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15907
10.1M
  if (!E->getType()->isIntegralOrEnumerationType())
15908
2.55k
    return ICEDiag(IK_NotICE, E->getBeginLoc());
15909
15910
10.1M
  switch (E->getStmtClass()) {
15911
0
#define ABSTRACT_STMT(Node)
15912
0
#define STMT(Node, Base) case Expr::Node##Class:
15913
0
#define EXPR(Node, Base)
15914
0
#include "clang/AST/StmtNodes.inc"
15915
0
  case Expr::PredefinedExprClass:
15916
0
  case Expr::FloatingLiteralClass:
15917
0
  case Expr::ImaginaryLiteralClass:
15918
0
  case Expr::StringLiteralClass:
15919
1.29k
  case Expr::ArraySubscriptExprClass:
15920
1.29k
  case Expr::MatrixSubscriptExprClass:
15921
1.29k
  case Expr::OMPArraySectionExprClass:
15922
1.29k
  case Expr::OMPArrayShapingExprClass:
15923
1.29k
  case Expr::OMPIteratorExprClass:
15924
5.73k
  case Expr::MemberExprClass:
15925
5.73k
  case Expr::CompoundAssignOperatorClass:
15926
5.74k
  case Expr::CompoundLiteralExprClass:
15927
5.74k
  case Expr::ExtVectorElementExprClass:
15928
5.74k
  case Expr::DesignatedInitExprClass:
15929
5.74k
  case Expr::ArrayInitLoopExprClass:
15930
5.74k
  case Expr::ArrayInitIndexExprClass:
15931
5.74k
  case Expr::NoInitExprClass:
15932
5.74k
  case Expr::DesignatedInitUpdateExprClass:
15933
5.74k
  case Expr::ImplicitValueInitExprClass:
15934
5.74k
  case Expr::ParenListExprClass:
15935
5.74k
  case Expr::VAArgExprClass:
15936
5.74k
  case Expr::AddrLabelExprClass:
15937
5.76k
  case Expr::StmtExprClass:
15938
5.78k
  case Expr::CXXMemberCallExprClass:
15939
5.78k
  case Expr::CUDAKernelCallExprClass:
15940
5.78k
  case Expr::CXXAddrspaceCastExprClass:
15941
5.78k
  case Expr::CXXDynamicCastExprClass:
15942
5.78k
  case Expr::CXXTypeidExprClass:
15943
5.78k
  case Expr::CXXUuidofExprClass:
15944
5.78k
  case Expr::MSPropertyRefExprClass:
15945
5.78k
  case Expr::MSPropertySubscriptExprClass:
15946
5.78k
  case Expr::CXXNullPtrLiteralExprClass:
15947
5.78k
  case Expr::UserDefinedLiteralClass:
15948
5.78k
  case Expr::CXXThisExprClass:
15949
5.78k
  case Expr::CXXThrowExprClass:
15950
5.78k
  case Expr::CXXNewExprClass:
15951
5.78k
  case Expr::CXXDeleteExprClass:
15952
5.78k
  case Expr::CXXPseudoDestructorExprClass:
15953
5.78k
  case Expr::UnresolvedLookupExprClass:
15954
5.78k
  case Expr::TypoExprClass:
15955
5.78k
  case Expr::RecoveryExprClass:
15956
5.78k
  case Expr::DependentScopeDeclRefExprClass:
15957
5.78k
  case Expr::CXXConstructExprClass:
15958
5.78k
  case Expr::CXXInheritedCtorInitExprClass:
15959
5.78k
  case Expr::CXXStdInitializerListExprClass:
15960
5.78k
  case Expr::CXXBindTemporaryExprClass:
15961
5.78k
  case Expr::ExprWithCleanupsClass:
15962
5.78k
  case Expr::CXXTemporaryObjectExprClass:
15963
5.78k
  case Expr::CXXUnresolvedConstructExprClass:
15964
5.78k
  case Expr::CXXDependentScopeMemberExprClass:
15965
5.78k
  case Expr::UnresolvedMemberExprClass:
15966
5.78k
  case Expr::ObjCStringLiteralClass:
15967
5.78k
  case Expr::ObjCBoxedExprClass:
15968
5.78k
  case Expr::ObjCArrayLiteralClass:
15969
5.78k
  case Expr::ObjCDictionaryLiteralClass:
15970
5.78k
  case Expr::ObjCEncodeExprClass:
15971
5.83k
  case Expr::ObjCMessageExprClass:
15972
5.83k
  case Expr::ObjCSelectorExprClass:
15973
5.83k
  case Expr::ObjCProtocolExprClass:
15974
5.92k
  case Expr::ObjCIvarRefExprClass:
15975
5.92k
  case Expr::ObjCPropertyRefExprClass:
15976
5.92k
  case Expr::ObjCSubscriptRefExprClass:
15977
5.92k
  case Expr::ObjCIsaExprClass:
15978
5.92k
  case Expr::ObjCAvailabilityCheckExprClass:
15979
5.92k
  case Expr::ShuffleVectorExprClass:
15980
5.92k
  case Expr::ConvertVectorExprClass:
15981
5.92k
  case Expr::BlockExprClass:
15982
5.92k
  case Expr::NoStmtClass:
15983
5.97k
  case Expr::OpaqueValueExprClass:
15984
5.97k
  case Expr::PackExpansionExprClass:
15985
5.97k
  case Expr::SubstNonTypeTemplateParmPackExprClass:
15986
5.97k
  case Expr::FunctionParmPackExprClass:
15987
5.97k
  case Expr::AsTypeExprClass:
15988
5.97k
  case Expr::ObjCIndirectCopyRestoreExprClass:
15989
5.97k
  case Expr::MaterializeTemporaryExprClass:
15990
6.08k
  case Expr::PseudoObjectExprClass:
15991
6.09k
  case Expr::AtomicExprClass:
15992
6.09k
  case Expr::LambdaExprClass:
15993
6.09k
  case Expr::CXXFoldExprClass:
15994
6.09k
  case Expr::CoawaitExprClass:
15995
6.09k
  case Expr::DependentCoawaitExprClass:
15996
6.09k
  case Expr::CoyieldExprClass:
15997
6.09k
  case Expr::SYCLUniqueStableNameExprClass:
15998
6.09k
  case Expr::CXXParenListInitExprClass:
15999
6.09k
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16000
16001
1
  case Expr::InitListExprClass: {
16002
    // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16003
    // form "T x = { a };" is equivalent to "T x = a;".
16004
    // Unless we're initializing a reference, T is a scalar as it is known to be
16005
    // of integral or enumeration type.
16006
1
    if (E->isPRValue())
16007
1
      if (cast<InitListExpr>(E)->getNumInits() == 1)
16008
1
        return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16009
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16010
1
  }
16011
16012
3
  case Expr::SizeOfPackExprClass:
16013
3
  case Expr::GNUNullExprClass:
16014
15
  case Expr::SourceLocExprClass:
16015
15
    return NoDiag();
16016
16017
22.2k
  case Expr::SubstNonTypeTemplateParmExprClass:
16018
22.2k
    return
16019
22.2k
      CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16020
16021
1.26k
  case Expr::ConstantExprClass:
16022
1.26k
    return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16023
16024
360k
  case Expr::ParenExprClass:
16025
360k
    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16026
230
  case Expr::GenericSelectionExprClass:
16027
230
    return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16028
7.01M
  case Expr::IntegerLiteralClass:
16029
7.01M
  case Expr::FixedPointLiteralClass:
16030
7.47M
  case Expr::CharacterLiteralClass:
16031
7.47M
  case Expr::ObjCBoolLiteralExprClass:
16032
7.47M
  case Expr::CXXBoolLiteralExprClass:
16033
7.47M
  case Expr::CXXScalarValueInitExprClass:
16034
7.47M
  case Expr::TypeTraitExprClass:
16035
7.47M
  case Expr::ConceptSpecializationExprClass:
16036
7.47M
  case Expr::RequiresExprClass:
16037
7.47M
  case Expr::ArrayTypeTraitExprClass:
16038
7.47M
  case Expr::ExpressionTraitExprClass:
16039
7.47M
  case Expr::CXXNoexceptExprClass:
16040
7.47M
    return NoDiag();
16041
3.70k
  case Expr::CallExprClass:
16042
3.70k
  case Expr::CXXOperatorCallExprClass: {
16043
    // C99 6.6/3 allows function calls within unevaluated subexpressions of
16044
    // constant expressions, but they can never be ICEs because an ICE cannot
16045
    // contain an operand of (pointer to) function type.
16046
3.70k
    const CallExpr *CE = cast<CallExpr>(E);
16047
3.70k
    if (CE->getBuiltinCallee())
16048
2.18k
      return CheckEvalInICE(E, Ctx);
16049
1.51k
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16050
3.70k
  }
16051
0
  case Expr::CXXRewrittenBinaryOperatorClass:
16052
0
    return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16053
0
                    Ctx);
16054
447k
  case Expr::DeclRefExprClass: {
16055
447k
    const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16056
447k
    if (isa<EnumConstantDecl>(D))
16057
303k
      return NoDiag();
16058
16059
    // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16060
    // integer variables in constant expressions:
16061
    //
16062
    // C++ 7.1.5.1p2
16063
    //   A variable of non-volatile const-qualified integral or enumeration
16064
    //   type initialized by an ICE can be used in ICEs.
16065
    //
16066
    // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16067
    // that mode, use of reference variables should not be allowed.
16068
143k
    const VarDecl *VD = dyn_cast<VarDecl>(D);
16069
143k
    if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16070
143k
        
!VD->getType()->isReferenceType()266
)
16071
261
      return NoDiag();
16072
16073
143k
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16074
143k
  }
16075
705k
  case Expr::UnaryOperatorClass: {
16076
705k
    const UnaryOperator *Exp = cast<UnaryOperator>(E);
16077
705k
    switch (Exp->getOpcode()) {
16078
23
    case UO_PostInc:
16079
44
    case UO_PostDec:
16080
93
    case UO_PreInc:
16081
721
    case UO_PreDec:
16082
721
    case UO_AddrOf:
16083
1.29k
    case UO_Deref:
16084
1.29k
    case UO_Coawait:
16085
      // C99 6.6/3 allows increment and decrement within unevaluated
16086
      // subexpressions of constant expressions, but they can never be ICEs
16087
      // because an ICE cannot contain an lvalue operand.
16088
1.29k
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16089
2
    case UO_Extension:
16090
850
    case UO_LNot:
16091
862
    case UO_Plus:
16092
701k
    case UO_Minus:
16093
704k
    case UO_Not:
16094
704k
    case UO_Real:
16095
704k
    case UO_Imag:
16096
704k
      return CheckICE(Exp->getSubExpr(), Ctx);
16097
705k
    }
16098
0
    llvm_unreachable("invalid unary operator class");
16099
0
  }
16100
268
  case Expr::OffsetOfExprClass: {
16101
    // Note that per C99, offsetof must be an ICE. And AFAIK, using
16102
    // EvaluateAsRValue matches the proposed gcc behavior for cases like
16103
    // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
16104
    // compliance: we should warn earlier for offsetof expressions with
16105
    // array subscripts that aren't ICEs, and if the array subscripts
16106
    // are ICEs, the value of the offsetof must be an integer constant.
16107
268
    return CheckEvalInICE(E, Ctx);
16108
0
  }
16109
11.2k
  case Expr::UnaryExprOrTypeTraitExprClass: {
16110
11.2k
    const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16111
11.2k
    if ((Exp->getKind() ==  UETT_SizeOf) &&
16112
11.2k
        
Exp->getTypeOfArgument()->isVariableArrayType()9.73k
)
16113
3
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16114
11.2k
    return NoDiag();
16115
11.2k
  }
16116
767k
  case Expr::BinaryOperatorClass: {
16117
767k
    const BinaryOperator *Exp = cast<BinaryOperator>(E);
16118
767k
    switch (Exp->getOpcode()) {
16119
0
    case BO_PtrMemD:
16120
0
    case BO_PtrMemI:
16121
234
    case BO_Assign:
16122
234
    case BO_MulAssign:
16123
234
    case BO_DivAssign:
16124
234
    case BO_RemAssign:
16125
234
    case BO_AddAssign:
16126
234
    case BO_SubAssign:
16127
234
    case BO_ShlAssign:
16128
234
    case BO_ShrAssign:
16129
234
    case BO_AndAssign:
16130
234
    case BO_XorAssign:
16131
234
    case BO_OrAssign:
16132
      // C99 6.6/3 allows assignments within unevaluated subexpressions of
16133
      // constant expressions, but they can never be ICEs because an ICE cannot
16134
      // contain an lvalue operand.
16135
234
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16136
16137
7.00k
    case BO_Mul:
16138
77.9k
    case BO_Div:
16139
78.3k
    case BO_Rem:
16140
316k
    case BO_Add:
16141
522k
    case BO_Sub:
16142
702k
    case BO_Shl:
16143
706k
    case BO_Shr:
16144
706k
    case BO_LT:
16145
707k
    case BO_GT:
16146
707k
    case BO_LE:
16147
707k
    case BO_GE:
16148
712k
    case BO_EQ:
16149
712k
    case BO_NE:
16150
721k
    case BO_And:
16151
721k
    case BO_Xor:
16152
766k
    case BO_Or:
16153
766k
    case BO_Comma:
16154
766k
    case BO_Cmp: {
16155
766k
      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16156
766k
      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16157
766k
      if (Exp->getOpcode() == BO_Div ||
16158
766k
          
Exp->getOpcode() == BO_Rem695k
) {
16159
        // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16160
        // we don't evaluate one.
16161
71.3k
        if (LHSResult.Kind == IK_ICE && 
RHSResult.Kind == IK_ICE70.6k
) {
16162
70.6k
          llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16163
70.6k
          if (REval == 0)
16164
8
            return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16165
70.6k
          if (REval.isSigned() && 
REval.isAllOnes()69.3k
) {
16166
1
            llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16167
1
            if (LEval.isMinSignedValue())
16168
1
              return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16169
1
          }
16170
70.6k
        }
16171
71.3k
      }
16172
766k
      if (Exp->getOpcode() == BO_Comma) {
16173
92
        if (Ctx.getLangOpts().C99) {
16174
          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16175
          // if it isn't evaluated.
16176
86
          if (LHSResult.Kind == IK_ICE && 
RHSResult.Kind == IK_ICE19
)
16177
18
            return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16178
86
        } else {
16179
          // In both C89 and C++, commas in ICEs are illegal.
16180
6
          return ICEDiag(IK_NotICE, E->getBeginLoc());
16181
6
        }
16182
92
      }
16183
766k
      return Worst(LHSResult, RHSResult);
16184
766k
    }
16185
642
    case BO_LAnd:
16186
674
    case BO_LOr: {
16187
674
      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16188
674
      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16189
674
      if (LHSResult.Kind == IK_ICE && 
RHSResult.Kind == IK_ICEIfUnevaluated645
) {
16190
        // Rare case where the RHS has a comma "side-effect"; we need
16191
        // to actually check the condition to see whether the side
16192
        // with the comma is evaluated.
16193
3
        if ((Exp->getOpcode() == BO_LAnd) !=
16194
3
            (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16195
1
          return RHSResult;
16196
2
        return NoDiag();
16197
3
      }
16198
16199
671
      return Worst(LHSResult, RHSResult);
16200
674
    }
16201
767k
    }
16202
0
    llvm_unreachable("invalid binary operator kind");
16203
0
  }
16204
234k
  case Expr::ImplicitCastExprClass:
16205
319k
  case Expr::CStyleCastExprClass:
16206
319k
  case Expr::CXXFunctionalCastExprClass:
16207
319k
  case Expr::CXXStaticCastExprClass:
16208
319k
  case Expr::CXXReinterpretCastExprClass:
16209
319k
  case Expr::CXXConstCastExprClass:
16210
319k
  case Expr::ObjCBridgedCastExprClass: {
16211
319k
    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16212
319k
    if (isa<ExplicitCastExpr>(E)) {
16213
84.5k
      if (const FloatingLiteral *FL
16214
84.5k
            = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16215
39
        unsigned DestWidth = Ctx.getIntWidth(E->getType());
16216
39
        bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16217
39
        APSInt IgnoredVal(DestWidth, !DestSigned);
16218
39
        bool Ignored;
16219
        // If the value does not fit in the destination type, the behavior is
16220
        // undefined, so we are not required to treat it as a constant
16221
        // expression.
16222
39
        if (FL->getValue().convertToInteger(IgnoredVal,
16223
39
                                            llvm::APFloat::rmTowardZero,
16224
39
                                            &Ignored) & APFloat::opInvalidOp)
16225
1
          return ICEDiag(IK_NotICE, E->getBeginLoc());
16226
38
        return NoDiag();
16227
39
      }
16228
84.5k
    }
16229
319k
    switch (cast<CastExpr>(E)->getCastKind()) {
16230
146k
    case CK_LValueToRValue:
16231
146k
    case CK_AtomicToNonAtomic:
16232
146k
    case CK_NonAtomicToAtomic:
16233
201k
    case CK_NoOp:
16234
206k
    case CK_IntegralToBoolean:
16235
311k
    case CK_IntegralCast:
16236
311k
      return CheckICE(SubExpr, Ctx);
16237
7.68k
    default:
16238
7.68k
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16239
319k
    }
16240
319k
  }
16241
24
  case Expr::BinaryConditionalOperatorClass: {
16242
24
    const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16243
24
    ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16244
24
    if (CommonResult.Kind == IK_NotICE) 
return CommonResult6
;
16245
18
    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16246
18
    if (FalseResult.Kind == IK_NotICE) 
return FalseResult0
;
16247
18
    if (CommonResult.Kind == IK_ICEIfUnevaluated) 
return CommonResult0
;
16248
18
    if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16249
18
        
Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 01
)
return NoDiag()0
;
16250
18
    return FalseResult;
16251
18
  }
16252
2.88k
  case Expr::ConditionalOperatorClass: {
16253
2.88k
    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16254
    // If the condition (ignoring parens) is a __builtin_constant_p call,
16255
    // then only the true side is actually considered in an integer constant
16256
    // expression, and it is fully evaluated.  This is an important GNU
16257
    // extension.  See GCC PR38377 for discussion.
16258
2.88k
    if (const CallExpr *CallCE
16259
2.88k
        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16260
82
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16261
41
        return CheckEvalInICE(E, Ctx);
16262
2.84k
    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16263
2.84k
    if (CondResult.Kind == IK_NotICE)
16264
250
      return CondResult;
16265
16266
2.59k
    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16267
2.59k
    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16268
16269
2.59k
    if (TrueResult.Kind == IK_NotICE)
16270
8
      return TrueResult;
16271
2.58k
    if (FalseResult.Kind == IK_NotICE)
16272
8
      return FalseResult;
16273
2.57k
    if (CondResult.Kind == IK_ICEIfUnevaluated)
16274
0
      return CondResult;
16275
2.57k
    if (TrueResult.Kind == IK_ICE && 
FalseResult.Kind == IK_ICE2.57k
)
16276
2.57k
      return NoDiag();
16277
    // Rare case where the diagnostics depend on which side is evaluated
16278
    // Note that if we get here, CondResult is 0, and at least one of
16279
    // TrueResult and FalseResult is non-zero.
16280
1
    if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16281
1
      return FalseResult;
16282
0
    return TrueResult;
16283
1
  }
16284
0
  case Expr::CXXDefaultArgExprClass:
16285
0
    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16286
0
  case Expr::CXXDefaultInitExprClass:
16287
0
    return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16288
3
  case Expr::ChooseExprClass: {
16289
3
    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16290
1
  }
16291
0
  case Expr::BuiltinBitCastExprClass: {
16292
0
    if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16293
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16294
0
    return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16295
0
  }
16296
10.1M
  }
16297
16298
0
  llvm_unreachable("Invalid StmtClass!");
16299
0
}
16300
16301
/// Evaluate an expression as a C++11 integral constant expression.
16302
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
16303
                                                    const Expr *E,
16304
                                                    llvm::APSInt *Value,
16305
3.42M
                                                    SourceLocation *Loc) {
16306
3.42M
  if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16307
9.39k
    if (Loc) 
*Loc = E->getExprLoc()37
;
16308
9.39k
    return false;
16309
9.39k
  }
16310
16311
3.41M
  APValue Result;
16312
3.41M
  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16313
848k
    return false;
16314
16315
2.56M
  if (!Result.isInt()) {
16316
4
    if (Loc) 
*Loc = E->getExprLoc()0
;
16317
4
    return false;
16318
4
  }
16319
16320
2.56M
  if (Value) 
*Value = Result.getInt()2.24M
;
16321
2.56M
  return true;
16322
2.56M
}
16323
16324
bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16325
7.54M
                                 SourceLocation *Loc) const {
16326
7.54M
  assert(!isValueDependent() &&
16327
7.54M
         "Expression evaluator can't be called on a dependent expression.");
16328
16329
7.54M
  ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16330
16331
7.54M
  if (Ctx.getLangOpts().CPlusPlus11)
16332
353k
    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16333
16334
7.18M
  ICEDiag D = CheckICE(this, Ctx);
16335
7.18M
  if (D.Kind != IK_ICE) {
16336
156k
    if (Loc) 
*Loc = D.Loc8
;
16337
156k
    return false;
16338
156k
  }
16339
7.03M
  return true;
16340
7.18M
}
16341
16342
std::optional<llvm::APSInt>
16343
6.81M
Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
16344
6.81M
  if (isValueDependent()) {
16345
    // Expression evaluator can't succeed on a dependent expression.
16346
2.33k
    return std::nullopt;
16347
2.33k
  }
16348
16349
6.80M
  APSInt Value;
16350
16351
6.80M
  if (Ctx.getLangOpts().CPlusPlus11) {
16352
3.06M
    if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16353
2.24M
      return Value;
16354
822k
    return std::nullopt;
16355
3.06M
  }
16356
16357
3.74M
  if (!isIntegerConstantExpr(Ctx, Loc))
16358
144k
    return std::nullopt;
16359
16360
  // The only possible side-effects here are due to UB discovered in the
16361
  // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16362
  // required to treat the expression as an ICE, so we produce the folded
16363
  // value.
16364
3.59M
  EvalResult ExprResult;
16365
3.59M
  Expr::EvalStatus Status;
16366
3.59M
  EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16367
3.59M
  Info.InConstantContext = true;
16368
16369
3.59M
  if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16370
0
    llvm_unreachable("ICE cannot be evaluated!");
16371
16372
3.59M
  return ExprResult.Val.getInt();
16373
3.74M
}
16374
16375
46
bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16376
46
  assert(!isValueDependent() &&
16377
46
         "Expression evaluator can't be called on a dependent expression.");
16378
16379
46
  return CheckICE(this, Ctx).Kind == IK_ICE;
16380
46
}
16381
16382
bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16383
3.41M
                               SourceLocation *Loc) const {
16384
3.41M
  assert(!isValueDependent() &&
16385
3.41M
         "Expression evaluator can't be called on a dependent expression.");
16386
16387
  // We support this checking in C++98 mode in order to diagnose compatibility
16388
  // issues.
16389
3.41M
  assert(Ctx.getLangOpts().CPlusPlus);
16390
16391
  // Build evaluation settings.
16392
3.41M
  Expr::EvalStatus Status;
16393
3.41M
  SmallVector<PartialDiagnosticAt, 8> Diags;
16394
3.41M
  Status.Diag = &Diags;
16395
3.41M
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16396
16397
3.41M
  APValue Scratch;
16398
3.41M
  bool IsConstExpr =
16399
3.41M
      ::EvaluateAsRValue(Info, this, Result ? 
*Result3.41M
:
Scratch37
) &&
16400
      // FIXME: We don't produce a diagnostic for this, but the callers that
16401
      // call us on arbitrary full-expressions should generally not care.
16402
3.41M
      
Info.discardCleanups()2.56M
&&
!Status.HasSideEffects2.56M
;
16403
16404
3.41M
  if (!Diags.empty()) {
16405
848k
    IsConstExpr = false;
16406
848k
    if (Loc) 
*Loc = Diags[0].first10
;
16407
2.56M
  } else if (!IsConstExpr) {
16408
    // FIXME: This shouldn't happen.
16409
64
    if (Loc) 
*Loc = getExprLoc()0
;
16410
64
  }
16411
16412
3.41M
  return IsConstExpr;
16413
3.41M
}
16414
16415
bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16416
                                    const FunctionDecl *Callee,
16417
                                    ArrayRef<const Expr*> Args,
16418
795
                                    const Expr *This) const {
16419
795
  assert(!isValueDependent() &&
16420
795
         "Expression evaluator can't be called on a dependent expression.");
16421
16422
795
  llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16423
0
    std::string Name;
16424
0
    llvm::raw_string_ostream OS(Name);
16425
0
    Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16426
0
                                 /*Qualified=*/true);
16427
0
    return Name;
16428
0
  });
16429
16430
795
  Expr::EvalStatus Status;
16431
795
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16432
795
  Info.InConstantContext = true;
16433
16434
795
  LValue ThisVal;
16435
795
  const LValue *ThisPtr = nullptr;
16436
795
  if (This) {
16437
397
#ifndef NDEBUG
16438
397
    auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16439
397
    assert(MD && "Don't provide `this` for non-methods.");
16440
397
    assert(MD->isImplicitObjectMemberFunction() &&
16441
397
           "Don't provide `this` for methods without an implicit object.");
16442
397
#endif
16443
397
    if (!This->isValueDependent() &&
16444
397
        EvaluateObjectArgument(Info, This, ThisVal) &&
16445
397
        
!Info.EvalStatus.HasSideEffects316
)
16446
316
      ThisPtr = &ThisVal;
16447
16448
    // Ignore any side-effects from a failed evaluation. This is safe because
16449
    // they can't interfere with any other argument evaluation.
16450
397
    Info.EvalStatus.HasSideEffects = false;
16451
397
  }
16452
16453
795
  CallRef Call = Info.CurrentCall->createCall(Callee);
16454
795
  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16455
1.68k
       I != E; 
++I891
) {
16456
891
    unsigned Idx = I - Args.begin();
16457
891
    if (Idx >= Callee->getNumParams())
16458
0
      break;
16459
891
    const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16460
891
    if ((*I)->isValueDependent() ||
16461
891
        
!EvaluateCallArg(PVD, *I, Call, Info)874
||
16462
891
        
Info.EvalStatus.HasSideEffects712
) {
16463
      // If evaluation fails, throw away the argument entirely.
16464
179
      if (APValue *Slot = Info.getParamSlot(Call, PVD))
16465
162
        *Slot = APValue();
16466
179
    }
16467
16468
    // Ignore any side-effects from a failed evaluation. This is safe because
16469
    // they can't interfere with any other argument evaluation.
16470
891
    Info.EvalStatus.HasSideEffects = false;
16471
891
  }
16472
16473
  // Parameter cleanups happen in the caller and are not part of this
16474
  // evaluation.
16475
795
  Info.discardCleanups();
16476
795
  Info.EvalStatus.HasSideEffects = false;
16477
16478
  // Build fake call to Callee.
16479
795
  CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16480
795
                       Call);
16481
  // FIXME: Missing ExprWithCleanups in enable_if conditions?
16482
795
  FullExpressionRAII Scope(Info);
16483
795
  return Evaluate(Value, Info, this) && 
Scope.destroy()747
&&
16484
795
         
!Info.EvalStatus.HasSideEffects746
;
16485
795
}
16486
16487
bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16488
                                   SmallVectorImpl<
16489
229k
                                     PartialDiagnosticAt> &Diags) {
16490
  // FIXME: It would be useful to check constexpr function templates, but at the
16491
  // moment the constant expression evaluator cannot cope with the non-rigorous
16492
  // ASTs which we build for dependent expressions.
16493
229k
  if (FD->isDependentContext())
16494
163k
    return true;
16495
16496
66.4k
  llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16497
1
    std::string Name;
16498
1
    llvm::raw_string_ostream OS(Name);
16499
1
    FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16500
1
                             /*Qualified=*/true);
16501
1
    return Name;
16502
1
  });
16503
16504
66.4k
  Expr::EvalStatus Status;
16505
66.4k
  Status.Diag = &Diags;
16506
16507
66.4k
  EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16508
66.4k
  Info.InConstantContext = true;
16509
66.4k
  Info.CheckingPotentialConstantExpression = true;
16510
16511
  // The constexpr VM attempts to compile all methods to bytecode here.
16512
66.4k
  if (Info.EnableNewConstInterp) {
16513
1.08k
    Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16514
1.08k
    return Diags.empty();
16515
1.08k
  }
16516
16517
65.3k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16518
65.3k
  const CXXRecordDecl *RD = MD ? 
MD->getParent()->getCanonicalDecl()43.1k
:
nullptr22.1k
;
16519
16520
  // Fabricate an arbitrary expression on the stack and pretend that it
16521
  // is a temporary being used as the 'this' pointer.
16522
65.3k
  LValue This;
16523
65.3k
  ImplicitValueInitExpr VIE(RD ? 
Info.Ctx.getRecordType(RD)43.1k
:
Info.Ctx.IntTy22.1k
);
16524
65.3k
  This.set({&VIE, Info.CurrentCall->Index});
16525
16526
65.3k
  ArrayRef<const Expr*> Args;
16527
16528
65.3k
  APValue Scratch;
16529
65.3k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16530
    // Evaluate the call as a constant initializer, to allow the construction
16531
    // of objects of non-literal types.
16532
4.57k
    Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16533
4.57k
    HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16534
60.7k
  } else {
16535
60.7k
    SourceLocation Loc = FD->getLocation();
16536
60.7k
    HandleFunctionCall(
16537
60.7k
        Loc, FD, (MD && 
MD->isImplicitObjectMemberFunction()38.6k
) ?
&This2.24k
:
nullptr58.5k
,
16538
60.7k
        &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
16539
60.7k
        /*ResultSlot=*/nullptr);
16540
60.7k
  }
16541
16542
65.3k
  return Diags.empty();
16543
66.4k
}
16544
16545
bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16546
                                              const FunctionDecl *FD,
16547
                                              SmallVectorImpl<
16548
20.4k
                                                PartialDiagnosticAt> &Diags) {
16549
20.4k
  assert(!E->isValueDependent() &&
16550
20.4k
         "Expression evaluator can't be called on a dependent expression.");
16551
16552
20.4k
  Expr::EvalStatus Status;
16553
20.4k
  Status.Diag = &Diags;
16554
16555
20.4k
  EvalInfo Info(FD->getASTContext(), Status,
16556
20.4k
                EvalInfo::EM_ConstantExpressionUnevaluated);
16557
20.4k
  Info.InConstantContext = true;
16558
20.4k
  Info.CheckingPotentialConstantExpression = true;
16559
16560
  // Fabricate a call stack frame to give the arguments a plausible cover story.
16561
20.4k
  CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
16562
20.4k
                       /*CallExpr=*/nullptr, CallRef());
16563
16564
20.4k
  APValue ResultScratch;
16565
20.4k
  Evaluate(ResultScratch, Info, E);
16566
20.4k
  return Diags.empty();
16567
20.4k
}
16568
16569
bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16570
9.38k
                                 unsigned Type) const {
16571
9.38k
  if (!getType()->isPointerType())
16572
0
    return false;
16573
16574
9.38k
  Expr::EvalStatus Status;
16575
9.38k
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16576
9.38k
  return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16577
9.38k
}
16578
16579
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16580
4.75k
                                  EvalInfo &Info) {
16581
4.75k
  if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16582
0
    return false;
16583
16584
4.75k
  LValue String;
16585
16586
4.75k
  if (!EvaluatePointer(E, String, Info))
16587
2.59k
    return false;
16588
16589
2.16k
  QualType CharTy = E->getType()->getPointeeType();
16590
16591
  // Fast path: if it's a string literal, search the string value.
16592
2.16k
  if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16593
2.16k
          String.getLValueBase().dyn_cast<const Expr *>())) {
16594
645
    StringRef Str = S->getBytes();
16595
645
    int64_t Off = String.Offset.getQuantity();
16596
645
    if (Off >= 0 && 
(uint64_t)Off <= (uint64_t)Str.size()622
&&
16597
645
        
S->getCharByteWidth() == 1599
&&
16598
        // FIXME: Add fast-path for wchar_t too.
16599
645
        
Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)517
) {
16600
517
      Str = Str.substr(Off);
16601
16602
517
      StringRef::size_type Pos = Str.find(0);
16603
517
      if (Pos != StringRef::npos)
16604
42
        Str = Str.substr(0, Pos);
16605
16606
517
      Result = Str.size();
16607
517
      return true;
16608
517
    }
16609
16610
    // Fall through to slow path.
16611
645
  }
16612
16613
  // Slow path: scan the bytes of the string looking for the terminating 0.
16614
16.1k
  
for (uint64_t Strlen = 0; /**/; 1.64k
++Strlen14.5k
) {
16615
16.1k
    APValue Char;
16616
16.1k
    if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16617
16.1k
        
!Char.isInt()15.0k
)
16618
1.12k
      return false;
16619
15.0k
    if (!Char.getInt()) {
16620
522
      Result = Strlen;
16621
522
      return true;
16622
522
    }
16623
14.5k
    if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16624
0
      return false;
16625
14.5k
  }
16626
1.64k
}
16627
16628
bool Expr::EvaluateCharRangeAsString(std::string &Result,
16629
                                     const Expr *SizeExpression,
16630
                                     const Expr *PtrExpression, ASTContext &Ctx,
16631
27
                                     EvalResult &Status) const {
16632
27
  LValue String;
16633
27
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16634
27
  Info.InConstantContext = true;
16635
16636
27
  FullExpressionRAII Scope(Info);
16637
27
  APSInt SizeValue;
16638
27
  if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
16639
2
    return false;
16640
16641
25
  int64_t Size = SizeValue.getExtValue();
16642
16643
25
  if (!::EvaluatePointer(PtrExpression, String, Info))
16644
3
    return false;
16645
16646
22
  QualType CharTy = PtrExpression->getType()->getPointeeType();
16647
95
  for (int64_t I = 0; I < Size; 
++I73
) {
16648
74
    APValue Char;
16649
74
    if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
16650
74
                                        Char))
16651
1
      return false;
16652
16653
73
    APSInt C = Char.getInt();
16654
73
    Result.push_back(static_cast<char>(C.getExtValue()));
16655
73
    if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
16656
0
      return false;
16657
73
  }
16658
21
  if (!Scope.destroy())
16659
0
    return false;
16660
16661
21
  if (!CheckMemoryLeaks(Info))
16662
0
    return false;
16663
16664
21
  return true;
16665
21
}
16666
16667
169
bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16668
169
  Expr::EvalStatus Status;
16669
169
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16670
169
  return EvaluateBuiltinStrLen(this, Result, Info);
16671
169
}